text:
Q: Should /tmp be owned by root? I'm wondering if /tmp should be owned by root, or rather nobody?
Now with safe mode there are some conflicts, but I am worried about security if I change it to be owned by nobody...
Any advice will be very appreciated.

A: It should be owned by root, but must be readable and writable by anyone with one important factor: the sticky bit on the directory must be set in order to make it an append-only directory. In other words, only users who own a file inside the /tmp directory and have read/write permissions can remove or rename the file. You may read the man page for sticky(8) for more information on what the sticky bit is.

A: Can a file be owned by nobody? What OS are you using?
Under Linux, /tmp is owned by root, is world-writable and has the sticky bit set. It means that anyone can create files but only the owner (or root) can remove them. It should be similar on most Unix systems, though.

A: Yes, it should be owned by root, but it should also be world writable with sticky bit, so that other programs can use it as a temp directory and files created there are owned by the creator. I'm not sure of the standard practice these days, but I would also recommend making /tmp its own partition, and not part of the root partition, so that if it gets filled up it doesn't hose the root partition.


text:
Q: Ruby on Rails RSpec test failing because of routes I have been trying to test my index route using RSpec.
I have this code but the error doesn't make sense because I have this route I tried it on the browser and curl, I'm still getting a response.
require 'rails_helper'

RSpec.describe Spree::Admin::OfficeAddressesController, type: :controller do

  describe "GET index" do
    it "render view index template" do
      get :index, params: {use_route: 'spree/admin/office_addresses'}
      # expect(response).to render_template('index')
      expect(response).to eq(200)
    end
  end

end

error msg:

Failures:

  1) Spree::Admin::OfficeAddressesController GET index render view index template
     Failure/Error: get :index, params: {use_route: 'spree/admin/office_addresses'}

     ActionController::UrlGenerationError:
       No route matches {:action=>"index", :controller=>"spree/admin/office_addresses", :params=>{:use_route=>"spree/admin/office_addresses"}}
     # ./spec/controllers/office_addresses_controller_spec.rb:8:in `block (3 levels) in <top (required)>'

Finished in 18.54 seconds (files took 7.55 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/controllers/office_addresses_controller_spec.rb:7 # Spree::Admin::OfficeAddressesController GET index render view index template

I have tried this SO answers still no luck
link1
link2
I tried it with curl I get a 200 ok response.
here are my routes
bin/rake routes | grep office_addresses

admin_office_addresses GET
/admin/office_addresses(.:format)
spree/admin/office_addresses#index

rails -v
Rails 4.2.6

ruby -v
ruby 2.3.6

Curl Response:
curl --verbose localhost:3000/spree/admin/office_addresses | grep HTTP

* TCP_NODELAY set
* Connected to localhost (::1) port 3000 (#0)
> GET /spree/admin/office_addresses HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.61.0
> Accept: */*

< HTTP/1.1 200 OK

< X-Frame-Options: SAMEORIGIN
< X-XSS-Protection: 1; mode=block
< X-Content-Type-Options: nosniff
< Content-Type: text/html; charset=utf-8
< Cache-Control: max-age=0, private, must-revalidate
< X-Runtime: 1.124812
< Vary: Origin
< X-Rack-CORS: miss; no-origin
< Content-Length: 29482

This is my first time to use Rspec btw and the documentation is nevermind...
Controller:
# frozen_string_literal: true

module Spree
  module Admin
    class OfficeAddressesController < ResourceController
      def index
        # @ = .all
      end

    end
  end
end

UPDATE
If I require the controller I have this error.
An error occurred while loading ./spec/controllers/office_addresses_controller_spec.rb.
Failure/Error: require 'spree/admin/office_addresses_controller'

LoadError:
  cannot load such file -- spree/admin/office_addresses_controller
# ./spec/controllers/office_addresses_controller_spec.rb:1:in `require'
# ./spec/controllers/office_addresses_controller_spec.rb:1:in `<top (required)>'
No examples found.

Finished in 0.00022 seconds (files took 0.34632 seconds to load)
0 examples, 0 failures, 1 error occurred outside of examples

redpajama_set_name: RedPajamaStackExchange


text:
Q: Do I have to take the encoding into account when performing Boyer-Moore pattern matching? I'm about to implement a variation of the Boyer-Moore pattern matching algorithm (the Sunday algorithm to be specific) and I was asking myself: What is my alphabet size?
Does it depend on the encoding (= number of possible characters) or can I just assume my alphabet consists of 256 symbols (= number of symbols which can be represented by a byte)?
In many other situations treating characters as bytes would be a problem because depending on the encoding a character can consist of multiple bytes, but if in my case both strings have the same encoding then equal characters are represented by equal byte sequences, so I would assume it doesn't matter.
So: Do I have to take the encoding into account and assume an alphabet consisting of the actual characters (> 90000 for Unicode) or can I just handle the text and the pattern as a stream of bytes?

A: A multi-byte encoding can be used with a byte-oriented search routine IF it is self-synchronizing.
So, you can safely use Boyer-Moore with:

*

*CESU-8

*UTF-8

*UTF-EBCDIC

But can NOT use it with:

*

*Big5

*EUC-JP

*GBK / GB18030

*ISO 2022

*Johab

*Punycode

*Shift-JIS

*UTF-7

*UTF-16

*UTF-32


text:
Q: How implement CArrayDataProvider in Yii I'm new to Yii. I'm using CArrayDataProvider to pass data in my CGridView but I'm getting an error of undefined id. Can you help me to check if I missed something?
index.php (View)
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $arrayDataProvider,
'columns' => array(
    array(
        'name' => 'LastName',
        'type' => 'raw',
                        'value' => 'CHtml::encode($data["LastName"])'
    ),
    array(
        'name' => 'FirstName',
        'type' => 'raw',
        'value' => 'CHtml::link(CHtml::encode($data["FirstName"])',
    ),
),
));

RecordsController.php
public function actionIndex()
{

        $data = new TblAccountdetails();
        $rawData = $data->getAllData();
        $arrayDataProvider=new CArrayDataProvider($rawData, array(
                'id'=>'id',
                'pagination'=>array(
                        'pageSize'=>10,
                ),
        ));

        $params =array(
                'arrayDataProvider'=>$arrayDataProvider,
        );

        if(!isset($_GET['ajax'])) $this->render('index', $params);
        else  $this->renderPartial('index', $params);
}

My Model Function
public function getAllData()
    {
         $user = Yii::app()->db->createCommand()
            ->select('AID, LastName, FirstName')
            ->from('tbl_accountdetails')
            ->queryAll();
        return $user;
    }

Vardump of $arrayDataProvider
  object(CArrayDataProvider)#32 (11) {
  ["keyField"]=>
  string(2) "id"
  ["rawData"]=>
  array(3) {
    [0]=>
    array(3) {
      ["AID"]=>
      string(1) "1"
      ["LastName"]=>
      string(8) "Floresca"
      ["FirstName"]=>
      string(5) "Joene"
    }
    [1]=>
    array(3) {
      ["AID"]=>
      string(1) "2"
      ["LastName"]=>
      string(13) "aaaaaaaaaaaaa"
      ["FirstName"]=>
      string(12) "aaaaaaaaaaaa"
    }
    [2]=>
    array(3) {
      ["AID"]=>
      string(1) "3"
      ["LastName"]=>
      string(7) "Antonio"
      ["FirstName"]=>
      string(4) "Noel"
    }
  }
  ["caseSensitiveSort"]=>
  bool(true)
  ["_id":"CDataProvider":private]=>
  string(2) "id"
  ["_data":"CDataProvider":private]=>
  NULL
  ["_keys":"CDataProvider":private]=>
  NULL
  ["_totalItemCount":"CDataProvider":private]=>
  NULL
  ["_sort":"CDataProvider":private]=>
  NULL
  ["_pagination":"CDataProvider":private]=>
  object(CPagination)#33 (9) {
    ["pageVar"]=>
    string(7) "id_page"
    ["route"]=>
    string(0) ""
    ["params"]=>
    NULL
    ["validateCurrentPage"]=>
    bool(true)
    ["_pageSize":"CPagination":private]=>
    int(10)
    ["_itemCount":"CPagination":private]=>
    int(0)
    ["_currentPage":"CPagination":private]=>
    NULL
    ["_e":"CComponent":private]=>
    NULL
    ["_m":"CComponent":private]=>
    NULL
  }
  ["_e":"CComponent":private]=>
  NULL
  ["_m":"CComponent":private]=>
  NULL
}

I don't know where I get that undefined id error:(

A: 1.one way is to change
->select('AID, LastName, FirstName')
into
->select('AID as id, LastName, FirstName')
2.you can also set keyField this way
$arrayDataProvider=new CArrayDataProvider($rawData, array(
            'id'=>'nameThisProvider',
            'keyField' => 'AID'
            'pagination'=>array(
                    'pageSize'=>10,
            ),
));

3.you could use a CSqlDataProvider


text:
Q: Can an Enum be used as a dispatch table? The first part of this blog post does a nice job of summarizing the general use case for a dispatch table, but I can't help wondering if it could be even more succinct and elegant using Enums instead...
Of course, the big hurdle in using an Enum is that functions are automatically ignored as potential members.
So, is it possible?

A: In a word: Yes1.
I will show a solution using the aenum2 library -- while it is possible to do most of this with the stdlib version it would require writing extra plumbing that already exists in aenum.
First, the base class:
from aenum import Enum, enum

class CallableEnum(Enum):

    def __new__(cls, *args, **kwds):
        member = object.__new__(cls)
        member._impl = args[0]
        if member._impl.__doc__ is not None:
            member._value_ = member._impl.__doc__
        else:
            member._value_ = repr(member._impl)
        return member

    def __call__(self, *args, **kwds):
        return self._impl(*args, **kwds)

and an example dispatch Enum:
class TestEnum(CallableEnum):

    @enum
    def hello(text):
        "a pleasant greeting"
        print('hello,', text)

    @enum
    def goodbye(text):
        print('goodbye,', text)

and in use:
>>> list(TestEnum)
[
  <TestEnum.hello: 'a pleasant greeting'>,
  <TestEnum.goodbye: '<function goodbye at 0xb7264844>'>,
]

>>> print(TestEnum.hello)
TestEnum.hello

>>> TestEnum['hello']('how are you?')
'hello, how are you?'

>>> TestEnum['goodbye']('see you soon!')
'goodbye, see you soon!'

1 See this answer for the standard Enum usage.
2 Disclosure:  I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum)  library.

A: So first I used the above implementation, but then realized it wasn't pickling correctly on OSX, so now I'm using this:
    def _utcnow_plus_delta(delta: timedelta, utcnow_attr: tOptional[str] = None, delta_attr: tOptional[str] = None):
        dt = datetime.utcnow()
        if utcnow_attr:
            dt = getattr(dt, utcnow_attr)
            if callable(dt):
                dt = dt()

        dt += delta

        if delta_attr:
            delta_val = getattr(dt, delta_attr)
            return delta_val() if callable(delta_val) else delta_val

        return dt

    @unique
    class DynamicValue(Enum):
        DATE_TODAY_PLUS_ONE_DAY = partial(_utcnow_plus_delta, timedelta(days=1), 'date')
        DATE_TODAY_PLUS_TWO_YEARS = partial(_utcnow_plus_delta, timedelta(weeks=52 * 2), 'date')
        DATE_TODAY_PLUS_FIVE_YEARS = partial(_utcnow_plus_delta, timedelta(weeks=52 * 5), 'date')
        DATE_TODAY_PLUS_TEN_YEARS = partial(_utcnow_plus_delta, timedelta(weeks=52 * 10), 'date')
        YEAR_TODAY_PLUS_FIVE_YEARS = partial(_utcnow_plus_delta, timedelta(weeks=52 * 5), 'date', delta_attr='year')
        TIMESTAMP_NOW_PLUS_FIVE_YEARS = partial(_utcnow_plus_delta, timedelta(weeks=52 * 5), delta_attr='timestamp')

        def __reduce_ex__(self, proto):
            assert proto >= 4
            return self.__class__.__qualname__ + '.' + self._name_

I think the above CallableEnum can be fixed by adding an appropriate reduce_ex method to ensure it gets re-created from the global value and not the repr. It's a little annoying in that you have to do enum.value() but no biggie I think


text:
Q: Triple fault on changing CR0 to start protected mode I'm currently developing an operating system. I'm using VMWare to emulate it. I was debugging by using int 0x16 on every line and I found out that when I switch CR0, the Protected Mode Switch, to 1, it just triple faults. Here's stage 2 of the kernel loader:
bits    16
org 0x500
jmp main
%include "stdio.inc"
%include "Gdt.inc"
%include "A20.inc"
%include "Fat12.inc"
%include "common.inc"
LoadingMsg db "Please Wait . . .", 0x0D, 0x0A, 0x00
msgFailure db 0x0D, 0x0A, "Can't find Krnl. Press any key to retry", 0x0D, 0x0A, 0x0A, 0x00
main:
    cli
    xor ax, ax
    mov ds, ax
    mov es, ax
    mov ax, 0x9000
    mov ss, ax
    mov sp, 0xFFFF
    sti
    call    InstallGDT
    call    EnableA20_KKbrd_Out
    mov si, LoadingMsg
    call    Puts16 ; nuts61
    jmp    EnterKernel
    mov ah, 0
    int     0x16
    int     0x19
    cli
    hlt
EnterKernel:
    cli
    mov eax, cr0
    or eax, 1
    mov cr0, eax ; <= here is the damn triple fault
    jmp CODE_DESC:KernelC
bits 32
KernelC:
    mov     ax, DATA_DESC
    mov     ds, ax
    mov     ss, ax
    mov     es, ax
    mov     esp, 90000h
CopyImage:
    mov eax, dword [ImageSize]
    movzx   ebx, word [bpbBytesPerSector]
    mul ebx
    mov ebx, 4
    div ebx
    cld
    mov    esi, IMAGE_RMODE_BASE
    mov edi, IMAGE_PMODE_BASE
    mov ecx, eax
    rep movsd
jmp CODE_DESC:IMAGE_PMODE_BASE
cli
hlt

I marked the error location. I also found some of the VMWare triple fault logs:
2016-01-14T17:30:00.613+01:00| vcpu-0| I120: Triple fault.
2016-01-14T17:30:00.613+01:00| vcpu-0| I120: MsgHint: msg.monitorEvent.tripleFault
2016-01-14T17:30:00.613+01:00| vcpu-0| I120+ A fault has occurred causing a virtual CPU to enter the shutdown state. If this fault had occurred outside of a virtual machine, it would have caused the physical machine to restart. The shutdown state can be reached by incorrectly configuring the virtual machine, a bug in the guest operating system, or a problem in VMware Player.

How do I solve this problem? Any suggestions?


text:
Q: Letter Shift with PHP I am trying to create a PHP function that Ciphers a string using a letter shift down or up the alphabet using a value of their choice.
This is what I have so far:
function encrypt($in, $n) {
    $in = strtolower($in);
    $let = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z");
    $num = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25");
    $negnum = array("-26", "-25", "-24", "-23", "-22", "-21", "-20", "-19", "-18", "-17", "-16", "-15", "-14", "-13", "-12", "-11", "-10", "-9", "-8", "-7", "-6", "-5", "-4", "-3", "-2", "-1");
    $nums = str_replace($let, $num, $in);
    $temp = str_split($nums, 1);
    foreach($temp as &$v) {
        $v = ($v + $n);
        if($v == 0 or $v > 0){
            $v = str_replace($num, $let, $v);
        } else {
            $v = str_replace($negnum, $let, $v);
        }
    }
    return implode('', $temp);
}

echo encrypt('EPPEABBOADBFTBS', '-3');

In it's current state the function is really not working - outputting strings that don't fit the value and also repeating letters of the string.
Am I going around this in the right way?
Please let me know,
Brad

A: Much easier to use ord and chr:
function shift($string, $distance) {
    $distance = $distance % 26;
    $string = strtolower($string);
    $result = array();
    $characters = str_split($string);

    if ($distance < 0) {
        $distance += 26;
    }

    foreach ($characters as $idx => $char) {
        $result[$idx] = chr(97 + (ord($char) - 97 + $distance) % 26);
    }

    return join("", $result);
}

A: strtr — Translate characters or replace substrings


text:
Q: AWS Copilot Run Task in Running Container I have a Django instance running as a Load Balanced Web Service, deployed by AWS Copilot. I would like to run Django Migrations by running a task through Copilot.
I tried running a task like this:
copilot task run --command "python src/manage.py migrate"

However, it doesn't appear to run in my active container. I would expect to see the migrations run, and the service logs along with the updated migrations, but I only see the standard health checks.
copilot/core-api/22 20:07:02 web.1  | INFO:     10.0.1.100:59904 - "GET /healthcheck/ HTTP/1.1" 200 OK
copilot/core-api/22 20:07:17 web.1  | INFO:     10.0.0.117:29060 - "GET /healthcheck/ HTTP/1.1" 200 OK
copilot/core-api/22 20:07:37 web.1  | INFO:     10.0.1.100:59934 - "GET /healthcheck/ HTTP/1.1" 200 OK

Am I misunderstanding task run? I only have 1 app, 1 service, 1 env. I expect task run will be executed in the running service, but maybe it is not?

A: copilot task run creates a new container. What you are looking for is copilot task exec.


text:
Q: how should we get the actual instance by referring back to their tokenize names by the index within a loop in python So I am trying to loop over a list of list names and trying to assign value to its element by index.
But the problem is within the loop, it is being referred to as a string literal instead of a list which throws up errors. Below is the snippet of the code I am dealing with.
    placeholder_list=["cat_list","cat_list"]
    for i in range(len(list_Col)):
        specific_function_output
        placeholder_list[i][int(index)]=specific_function_output

The problem comes at this step:
the python is interpreting placeholder_list[i] as "cat_list", what I was expecting is
cat_list[int(index)]

but it is actually being treated as "cat_list"[int(index)] which is genrating the generic error
TypeError: 'str' object does not support item assignment

This might have a very simple solution, but I am having a bit of a struggle to find a solution for this.
And also having not too familiar with the technical terms or details about the backdrop doesn't help.
In general, for programming, how should we get the actual instance by referring back to their tokenize names by the index within a loop -- this is how I could conceptualize the problem. But again, I might be missing some technical details on it.


text:
Q: How to call web service async using TPL I am writing a WCF(C#4, VS2010) that calls 4 different web-services, do business logic and converts them to application entities. These ws calls,buss logic & entity transformation are independent of each other. Avg response time is around ~4Sec.
Doing the exact above asynchronously using TPL did not help(in reducing the response time, infact id is up by ~100ms); Pseudo code below:
Task<Plan> planAsync = Task<Plan>.Factory.StartNew(() => return CallSvcAndGetPlanEntity());
Task<Claim> claimAsync = Task<Claim>.Factory.StartNew(() => return CallSvcAndGetClaimEntity());
Task<Account> accounAsync = Task<Account>.Factory.StartNew(() => return CallSvcAndGetAccountEntity());

//Some business logic here in loop.

Task.WaitAll(planAsync, claimAsync, accountAsync);

Plan p = planAsync.Result;

UPDATE:
I introduced a Thread.Sleep of 2Sec at each of the above CallSvc() methods.
Async method resp time is still 4.1 Sec
Linear method resp time is up to ~7 Sec.
Am i missing something?
What is best way to call WS & do business logic asynchronously?


text:
Q: Maven can't find the main class for execution Despite the code is getting compiled with "maven clean install" and .jar file is created, when executing it complains with "no main manifest attribute, in matrixexplorer-0.0.1.jar". I already added mainClass tag in my pom file so I cant understand the problem
here is my pom file,
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <version>0.0.1</version>
  <groupId>at.tugraz.iicm</groupId>
    <artifactId>matrixexplorer</artifactId>

  <packaging>jar</packaging>

  <build>
    <plugins>
      <plugin>
         <groupId>at.tugraz.iicm</groupId>
            <artifactId>matrixexplorer</artifactId>

        <configuration>
          <archive>
            <manifest>
              <addClasspath>true</addClasspath>
                 <mainClass>at.tugraz.iicm.matrixexplorer.MatrixExplorerApp</mainClass>
            </manifest>
          </archive>
        </configuration>

      </plugin>
    </plugins>
  </build>

  <name>matrixexplorer</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <dependency>
    <groupId>org.apache.xmlgraphics</groupId>
    <artifactId>batik-anim</artifactId>
    <version>1.8</version>
    </dependency>

<dependency>
    <groupId>colt</groupId>
    <artifactId>colt</artifactId>
    <version>1.2.0</version>
</dependency>

<dependency>
    <groupId>net.java.dev.appframework</groupId>
    <artifactId>appframework</artifactId>
    <version>1.03</version>
</dependency>

<dependency>
    <groupId>concurrent</groupId>
    <artifactId>concurrent</artifactId>
    <version>1.3.4</version>
</dependency>

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-core</artifactId>
    <version>1.3</version>
</dependency>

<dependency>
    <groupId>org.swinglabs</groupId>
    <artifactId>swing-worker</artifactId>
    <version>1.1</version>
</dependency>

<dependency>
    <groupId>batik</groupId>
    <artifactId>batik-transcoder</artifactId>
    <version>1.6-1</version>
</dependency>

  </dependencies>

</project>

and my folder structure is as in the image

A: in the build section, instead of
     <groupId>at.tugraz.iicm</groupId>
     <artifactId>matrixexplorer</artifactId>

you need
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>3.0.0</version>


text:
Q: How to plot 3D scatter diagram using ggplot? I tried to use the plotly package, but it is not working in my case at all. The ggplot package is working for 2D plots but it is giving an error when adding one more axis. How to solve this issue?
ggplot(data,aes(x=D1,y=D2,z=D3,color=Sample)) +
  geom_point()

How to add one more axis and get the 3D plot in this?

A: Since you tagged your question with plotly and said that you've tried to use it with plotly, I think it would be helpful to give you a working code solution in plotly:
Creating some data to plot with:
set.seed(417)
library(plotly)
temp <- rnorm(100, mean=30, sd=5)
pressure <- rnorm(100)
dtime <- 1:100

Graphing your 3d scatterplot using plotly's scatter3d type:
plot_ly(x=temp, y=pressure, z=dtime, type="scatter3d", mode="markers", color=temp)

Renders the following:

ggplot as others have note, by itself does not support 3d graphics rendering.

A: A possible solutions is gg3D.
gg3D is a package created to extend ggplot2 to produce 3D plots. It does exactly what you are asking for: it adds a third axis to a ggplot. I find it quite good and easy to use and that is what I use for my limited needs.
An example taken from the vignette to produce a basic plot
devtools::install_github("AckerDWM/gg3D")

library("gg3D")

## An empty plot with 3 axes
qplot(x=0, y=0, z=0, geom="blank") +
  theme_void() +
  axes_3D()

## Axes can be populated with points using the function stat_3D.

data(iris)
ggplot(iris, aes(x=Petal.Width, y=Sepal.Width, z=Petal.Length, color=Species)) +
  theme_void() +
  axes_3D() +
  stat_3D()

There are other options not involving ggplot. For example the excellent plot3D package with its extension plot3Drgl to plot in openGL.

A: In your question, you refer to the plotly package and to the ggplot2 package. Both plotly and ggplot2 are great packages: plotly is good at creating dynamic plots that users can interact with, while ggplot2 is good at creating static plots for extreme customization and scientific publication. It is also possible to send ggplot2 output to plotly. Unfortunately, at the time of writing (April 2021), ggplot2 does not natively support 3d plots. However, there are other packages that can be used to produce 3d plots and some ways to get pretty close to ggplot2 quality. Below I review several options. These suggestions are by no means exhaustive.
plotly
See onlyphantom's answer in this thread.
gg3D
See Marco Stamazza's answer in this thread. See also my effort below.
scatterplot3d
See Seth's answer in a related thread.
lattice
See Backlin's answer in a related thread.
rgl
See this overview in the wiki guide.
rayshader
See this overview of this package's wonderful capabilities.
trans3d
See data-imaginist use trans3d to get a cube into ggplot2.
ggrgl
See this cool and useful coolbutuseless introduction.

Now let me review some of my efforts with the Lorenz attractor trajectories. While customization remains limited, I've had best results for PDF output with gg3D. I also include a ggrgl example.
gg3D
# Packages
library(deSolve)
library(ggplot2)
library(gg3D)  # remotes::install_github("AckerDWM/gg3D")

# Directory
setwd("~/R/workspace/")

# Parameters
parms <- c(a=10, b=8/3, c=28)

# Initial state
state <- c(x=0.01, y=0.0, z=0.0)

# Time span
times <- seq(0, 50, by=1/200)

# Lorenz system
lorenz <- function(times, state, parms) {
  with(as.list(c(state, parms)), {
    dxdt <- a*(y-x)
    dydt <- x*(c-z)-y
    dzdt <- x*y-b*z
    return(list(c(dxdt, dydt, dzdt)))
  })
}

# Make dataframe
df <- as.data.frame(ode(func=lorenz, y=state, parms=parms, times=times))

# Make plot
make_plot <- function(theta=0, phi=0){
  ggplot(df, aes(x=x, y=y, z=z, colour=time)) +
    axes_3D(theta=theta, phi=phi) +
    stat_3D(theta=theta, phi=phi, geom="path") +
    labs_3D(theta=theta, phi=phi,
            labs=c("x", "y", "z"),
            angle=c(0,0,0),
            hjust=c(0,2,2),
            vjust=c(2,2,-2)) +
    ggtitle("Lorenz butterfly") +
    theme_void() +
    theme(legend.position = "none")
}

make_plot()

make_plot(theta=180,phi=0)

# Save plot as PDF
ggsave(last_plot(), filename="lorenz-gg3d.pdf")

Pros: Outputs high-quality PDF:

Cons: Still limited customization. But for my specific needs, currently the best option.
ggrgl
# Packages
library(deSolve)
library(ggplot2)
library(rgl)
  #remotes::install_github("dmurdoch/rgl")
library(ggrgl)
  # remotes::install_github('coolbutuseless/ggrgl', ref='main')
library(devout)
library(devoutrgl)
  # remotes::install_github('coolbutuseless/devoutrgl', ref='main')
library(webshot2)
  # remotes::install_github("rstudio/webshot2")
library(ggthemes)

# Directory
setwd("~/R/workspace/")

# Parameters
parms <- c(a=10, b=8/3, c=26.48)

# Initial state
state <- c(x=0.01, y=0.0, z=0.0)

# Time span
times <- seq(0, 100, by=1/500)

# Lorenz system
lorenz <- function(times, state, parms) {
  with(as.list(c(state, parms)), {
    dxdt <- a*(y-x)
    dydt <- x*(c-z)-y
    dzdt <- x*y-b*z
    return(list(c(dxdt, dydt, dzdt)))
  })
}

# Make dataframe
df <- as.data.frame(ode(func=lorenz, y=state, parms=parms, times=times))

# Make plot
ggplot(df, aes(x=x, y=y, z=z)) +
  geom_path_3d() +
  ggtitle("Lorenz butterfly") -> p

# Render Plot in window
rgldev(fov=30, view_angle=-10, zoom=0.7)
p + theme_ggrgl(16)

# Save plot as PNG
rgldev(fov=30, view_angle=-10, zoom=0.7,
       file = "~/R/Work/plots/lorenz-attractor/ggrgl/lorenz-ggrgl.png",
       close_window = TRUE, dpi = 300)
p + theme_ggrgl(16)
dev.off()

Pros: The plot can be rotated in a way similar to plotly. It is possible to 'theme' a basic plot:

Cons: The figure is missing a third axis with labels. Cannot output high-quality plots. While I've been able to view and save a low-quality black trajectory in PNG, I could view a colored trajectory like the above, but could not save it, except with a low-quality screenshot:

Related threads:  plot-3d-data-in-r, ploting-3d-graphics-with-r.


text:
Q: Android: loading an array of TextViews within a for loop Hi this is doing my head in, I am trying to load an array of TextViews and ImageButtons within a for loop, i have searched for answers and after my search ended up with code that looked like this:
public void initializeVideos() {
    // TODO Auto-generated method stub
    Titles = new TextView[5];
    Images = new ImageButton[5];
    int tvId;
    int ibId;
    for(int i = 1; i < 6; i++){
        tvId = getResources().getIdentifier("tv" + i, "id", getPackageName());
        ibId = getResources().getIdentifier("ib" + i, "id", getPackageName());
        Titles[i] = (TextView) findViewById(tvId);
        Images[i] = (ImageButton) findViewById(ibId);
    }
}

The problem is i am encountering a NumberFormatException and i cannot seem to work out why...
help would be appreciated

A: Yes because of your for loop is wrong here you have to start for loop with i=0 to i<5.
Here problem is that your last id get there are null represent so no id available so it gives you numberformat exception.

A: The values in the looping is wrong thats y ur getting a Crash ,You are initializing  the value of i=1  on the for loop ,so the first value will be placed on the first position of the Arrays and 0th postion of Array remains null, then iteration will continue when it is reach 5 what happen is i will be make a  array out of bound  Exception .It is because of a array size of 5 the position will be like this[0,1,2,3,4] this is the position order of a array of size 5 in the code what will happen is For the last iteration it will put the value in the [5] which is not available in the array.That is causing  the problem;
Working code will be like  this
public void initializeVideos() {
    // TODO Auto-generated method stub
    TextView[] Titles = new TextView[5];
    ImageButton[] Images = new ImageButton[5];
    int tvId;
    int ibId;
    for (int i = 0; i < 5; i++) //Just changed the values in for loop

  {
        System.out.println(i);
        tvId = getResources().getIdentifier("tv" + i, "id",
                getPackageName());
        ibId = getResources().getIdentifier("ib" + i, "id",
                getPackageName());
        Titles[i] = (TextView) findViewById(tvId);
        Images[i] = (ImageButton) findViewById(ibId);
         }
     }


text:
Q: Booting Ubuntu with a USB without CD-ROM detection I am using the unetbootin application to create a bootable USB for Ubuntu 12.04 LTS. However, when booting the server the installer menu wants to detect and mount the CD-ROM, which i don't have. So the installation fails, because it will not get pass the CD-ROM.  How do I and What do I change to skip/override the detection of the CR-ROM and continue to use the USB to build the Ubuntu 12.04 Server LTS?
And please be specific, I am learning Ubuntu / Linux nomenclature so I am no where close to an expert on the linguistics.
Sheriff

A: You need to change the boot order in your BIOS settings. When you boot up, there will be a small note on the screen telling you which key to press for the BIOS settings (often but not always F10). Once in the BIOS settings menu, navigate to change the boot order and make sure the USB drive is preferred.


text:
Q: How will IPv6 impact everyday users? (World IPv6 Day) With the current (one hour in at the moment) trial by all the big boys (Google, Facebook, Bing, Yahoo, etc.) I wondered how IPv6 will effect home users and the Internet as a whole.
Will the change be transparent in nature or will there be mass downtime as the switch happens? Will users need to throw away software that don't use hostnames or DNS' or that just aren't equipped to handle the switch? Will ISP services still be the same?
I am still quite ignorant on the subject but I'm currently reading up on it. I was thinking experienced users and professionals could help us users what's actually happening and the impact we should see (or not see).

A: As ultrasawblade said, there should be no difference, but there is, at least in the transition period.
The main problem are misconfigured DNS servers which may take forever to respond to queries requesting AAAA records for sites which hold the IPv6 addresses. This is the reason why there are so many people who claim that disabling IPv6 will increase web browser performance. Standards say that IPv6 is to be preferred over IPv4. That means that browser will first check if the site is IPv6 capable and if it isn't, it will go to IPv4. If everything works normally, the check shouldn't be noticeable at all, but some badly configured DNS servers will not send proper response and connection will have to "time out". The main reason for that is that people are generally lazy. Very large number of people don't see any benefits in IPv6 and will have to be forced to use it when Internet starts stagnating because of lack of IPv4 addresses. That will require software updates on servers, routers and the rest of the networking equipment or replacement, but the IPv6 is still far away and there's no pressing need to do the updates now or that's what large number of people thinks. This creates the chicken and egg problem because people won't use IPv6 until IPv6 equipment is available and problems are fixed and on the other hand equipment manufacturers don't want to pay too much attention to IPv6 capable equipment until there's need to do so and the server maintainers don't want to fix IPv6 problems until there's need to do so.
Also, a part which sometimes gets forgotten are devices that aren't network related but use network like IP phones, scanners, printers and so on. They won't require IPv6 support immediately because of dual stack and will probably have no problems during their lifetime, but some misinformed managers think that they do and in their minds this increases the cost of migration, since all of them would have to be replaced.
Another point mentioned here is NAT. Some people feel safe behind NAT thinking that it increases security. In IPv6, it isn't needed. Instead correctly configured firewalls should be used, but people oppose the change. There was also the "MAC" conspiracy. Basically IPv6 address is divided into two parts. The prefix which goes to the router and number of the device connected to the router. In some situations, MAC address can be used to determine the device's number and the story goes that this will enable tracking of devices across networks. However the feature can be disabled and works when first 64 bits are assigned to router and the second 64 bits of the address are assigned to the devices. The downside of this is that in some circles this built mistrust of IPv6, especially when that is combined with lack of NAT.

A: It's possible to run both IPv4 and IPv6 at once, such a configuration is called "dual-stack.". Of course, you will need an IPv6 capable router, so when and if any "killer apps" appear requiring IPv6 only access, you would need to upgrade your router.
Because it's possible to run both at once, sites can add IPv6 functionality without affecting IPv4 users at all.  So I think you can expect a relatively smooth and transparent transition and there is going to be a long time where both exist.
Probably the most "end-user" visible and Internet-impacting effect of IPv6 is the loss of need for NAT.  This also means many workarounds, protocols and protocol extensions, and "intermediary" type services are not necessary for two IPv6 capable hosts to connect.  This will increase efficiency of routing and make network applications easier to develop.


text:
Q: Error while sending Outlook email using Excel VBA I would like, within Excel, to send an email from a userform.
I created test code, according to Microsoft how to page.
When I try to use .send (email address swapped to dummy one for the purpose of the question)

"application-defined or object-defined  error".

When I use .display the message shows up on the screen. I have added references for Outlook 16 and Office 16, as suggested in other solutions.
I wonder if it is an issue related to company policies.
Sub Mail_workbook_Outlook()

    Dim OutApp As Object
    Dim OutMail As Object
    Dim oListObj As Object

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    email_to = "test.user@test.com"
    email_body = "test 123"
    email_subject = "Test email"

    With OutMail
        .To = email_to
        .CC = ""
        .BCC = ""
        .Subject = email_subject
        .Body = email_body
        '.Display
        .Send ' THIS LINE IS CAUSING ERROR FOR ME
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing

End Sub

A: The Send method of the MailItem class is a protected method in the Outlook object model which means it can throw security prompts in Outlook or just give errors when using an unsafe Outlook Application instance. It happens when you try to automate Outlook from external applications. You can find a similar thread which lists possible solutions, see How to avoid the Outlook Security warning for email automation - VBA.
There are several ways for suppressing security prompts/errors in the code:

*

*Use a third-party components for suppressing Outlook security warnings. See Security Manager for Microsoft Outlook for more information.

*Use a low-level API instead of OOM. Or any other third-party wrappers around that API, for example, Redemption.

*Develop a COM add-in which has access to the trusted Application object.

*Use group policy objects for setting up machines.
See Outlook Object Model Security Warnings for more information. Also you may find the following articles helpful:

*

*A program is trying to send an e-mail message on your behalf warning in Outlook

*How to Prevent the VBA Macro Security Warning in Microsoft Outlook


text:
Q: iOS - Adding highlighter effect to a part of the text I would like to accomplish something like this for UILabel:

The stroke basically represents a casual highlight of that part of the text using a highlighter.
I thought of using resizableImageWithCapInsets and then use it as the background of the text, but it doesn't work with the highlighting artifacts on the top and the bottom edge of the highlight.
My question comes down to:

*

*Can I set a background image(?) for a part of the text in a UILabel?

*What kind of image format should I get to be able to dynamically resize it based on the length of the text that needs to be highlighted?

I have almost gotten it right on Android by playing with SVG points, but I couldn't find a way to do it on iOS.


text:
Q: Android Error while using Retrofit2 and XML I am trying to make a simple Get Request with Retrofit and Simple XML but i get the following error. I cant understand what im doing wrong since color is an element and its not missing from any category.
The error:
I/System.out: FAILED : org.simpleframework.xml.core.ValueRequiredException: Unable to satisfy @org.simpleframework.xml.Element(data=false, name=color, required=true, type=class java.lang.String) on field 'color' public java.lang.String me.limetag.zwz.models.Category.color for class me.limetag.zwz.models.Category at line 4

My models:
@Root
public class Categories implements Serializable
{
@ElementList
private List<Category> category;

public List<Category> getCategory ()
{
    return category;
}

public void setCategory (List<Category> category)
{
    this.category = category;
}

}

@Root
public class Category implements Serializable
{
 @Element(name="id",type=Integer.class)
 public Integer id;

 @Element(name="color",type=String.class)
 public String color;

 @Element(name="name",type=String.class)
 public String name;
}

The Call:
Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(APIURL)
            .addConverterFactory(SimpleXmlConverterFactory.create())
            .client(new OkHttpClient())
            .build();

    ZService service = retrofit.create(ZService.class);
    service.getCategories().enqueue(new Callback<Categories>() {
        @Override
        public void onResponse(Call<Categories> call, Response<Categories> response) {
            if(response.isSuccessful()) {
                Categories categoryList = response.body();
                List<Category> categories = categoryList.getCategory();
                for (Category category: categories
                     ) {
                        String name = category.getName();
                        Log.e("DONE",name);
                }
            }
        }

The XML:
<categories>
<category>
    <id>8</id>
    <name>BEVERAGES</name>
    <color>#00B392</color>
</category>
<category>
    <id>8</id>
    <name>BEVERAGES</name>
    <color>#00B392</color>
</category>
</categories>

EDIT:
I tried reversing the process and print out the JAVA classes using simple XML and this is what i got. I dont understand from where its getting the extra category node.
<categories>
<category class="java.util.ArrayList">
 <category>
  <color>#000000</color>
  <id>1</id>
  <name>NAME</name>
 </category>
 <category>
  <color>#000000</color>
  <id>1</id>
  <name>NAME</name>
 </category>
 <category>
  <color>#000000</color>
  <id>1</id>
  <name>NAME</name>
 </category>
</category>


text:
Q: What causes `ArgumentOutOfRangeException - Unknown resource type` error message? I have been developing an addin and all has been going well during development, and i am now at the point that I wish to create the distributable version of the addin, which is the packed version. The packing seems like it goes ok, however, when I open the packed xll file with Excel I get the following error:

Initialization [Error] External library could not be registered -
  Path: packed: : ArgumentOutOfRangeException - Unknown
  resource type. Only types 0 (Assembly), 1 (Dna file), 2 (Image) or 3
  (Source) are valid. Parameter name: type

Any guidance on this would be greatly appreciated.
Thanks.

A: Excel-DNA only support the following resource types:

*

*.NET Assembly (.dll)

*.dna file

*Image

*Source code file (.cs, .vb, etc.)

*.pdb file

The error you're see seems to be caused by the packing of a file that is not any of the types above.
Or perhaps, the version of ExcelDnaPack.exe you're running is not the same as the ExcelDna.xll that you're running.
How does your .dna file look like and what are the files being packed (and their types)?


text:
Q: columns matching based on third column I have a df like:
    Name  id  precision
0  John   1          1
1  John   1          2
2  John   2          3
3  Marc   1          3
4   Tom   2          1

here the code to generate it:
pd.DataFrame([{'Name': 'John', 'id': 1, 'precision': 1},
{'Name': 'John', 'id': 1, 'precision': 2},
{'Name': 'John','id': 2, 'precision': 3},
{'Name': 'Marc', 'id': 1, 'precision': 3},
{'Name': 'Tom', 'id': 2, 'precision': 1}])

I have different algos that find the correspondence btw Name and id. Each algo has its own precision reported in the corresponding column (the smaller the better). Eventually I would like to get the best matching if any.
The desired result is:
    Name  id  precision
0  John   1          1
4   Tom   2          1

John should match with 1 because it is the only one matching with a precision of 1 (Marc has a precision of 3).
Tom should match with 2 because it is the only one matching with a precision of 1.
I am trying with:
df['min'] = df.groupby('Name').precision.transform(min)

To find the minimum, but I am having troubles in extracting then the desired result.

A: I think you need to group on the 'id' column instead of name.
df.loc[df.groupby('id')['precision'].idxmin()]

Output:
   Name  id  precision
0  John   1          1
4   Tom   2          1

A: No need groupby
df.sort_values(['id','precision']).drop_duplicates(['id'],keep='first')
Out[813]:
   Name  id  precision
0  John   1          1
4   Tom   2          1


text:
Q: Как сделать, если запрос завершился неудачей - отправить данные об ошибке администратору? Задание:
Давайте напишем функцию, которая будет увеличивать зарплату сотруднику с наименьшей зарплатой.
Вам нужно

*

*Получает данные по всем работникам

*Находит работника с наименьшей    зарплатой

*Отправляет запрос на повышение зарплаты этому сотруднику на    20%

*Если запрос прошел успешно - отправить сотруднику уведомление об
увеличении ЗП тектом: Hello, <имя>! Congratulations, your new salary
is <новая ЗП>!

*Если запрос завершился неудачей - отправить данные об    ошибке
администратору
Должна всегда возвращать resolved промис с boolean значением:

*

*true если увеличение прошло успешно

*false если нет

Все функции для получения/изменения данных асинхронны и возвращают промисы.
Вам предоставлены функции:
api.getEmployees(); // Возвращает массив с объектами {id: 343, name: 'Alex', salary: 20000}
api.setEmployeeSalary(employeeId, newSalary); // Принимает id сотрудника и новую зарплату. Возвращает новые данные по сотруднику.
api.notifyEmployee(employeeId, text); // Принимает id сотрудника и текст уведомления
api.notifyAdmin(error); // Принимает ошибку

Мой код
function increaseSalary() {
try {
    return api.getEmployees()
        .then(emp => {
            const [minSalaryEmployee] = emp.reduce(([minEmployee, minSalary], employee) => {
                const {salary} = employee;
                return (salary < minSalary
                    ? [employee, salary]
                    : [minEmployee, minSalary]
                );
            }, [null, Infinity]);

            const {id, salary: oldSalary} = minSalaryEmployee;
            const newSalary = oldSalary * 1.2;
            return {id, salary: newSalary};
        })
        .then(({id, salary}) => api.setEmployeeSalary(id, salary))
           .then(({name, id, salary}) => api.notifyEmployee(id, `Hello, ${name}! Congratulations, your new salary is ${salary}!`))
}catch(e){
  api.getEmployees().then(api.notifyAdmin(e))// не знаю как правильно сделать
}}

const api = {
  _employees: [
    { id: 1, name: 'Alex', salary: 120000 },
    { id: 2, name: 'Fred', salary: 110000 },
    { id: 3, name: 'Bob', salary: 80000 },
  ],

  getEmployees() {
    return new Promise((resolve) => {
      resolve(this._employees.slice());
    });
  },

  setEmployeeSalary(employeeId, newSalary) {
    return new Promise((resolve) => {
      this._employees = this._employees.map((employee) =>
        employee.id !== employeeId
          ? employee
          : {
            ...employee,
            salary: newSalary,
          }
      );
      resolve(this._employees.find(({ id }) => id === employeeId));
    });
  },

  notifyEmployee(employeeId, text) {
    return new Promise((resolve) => {
      resolve(true);
    });
  },

  notifyAdmin(error) {
    return new Promise((resolve) => {
      resolve(true);
    });
  },

  setEmployees(newEmployees) {
    return new Promise((resolve) => {
      this._employees = newEmployees;
      resolve();
    });
  },
};


text:
Q: unitary operator and existence of $T=U^2$
Prove that if T is a unitary operator on a finite-dimensional inner product space V, then T has a unitary square root; that is, there exists a unitary operator U such that $T=U^2$.

Concept question: I think I am missing some concept here. I can't think how is the proof related to eigenvalues. Any help is appreciated.


text:
Q: Django file sharing application (issues providing link to user) i am creating file sharing app. I am able to upload files but unable to provide its download link to user.
Please find below view,
def user_in(request):

    if not request.user.is_authenticated:
        return render(request, 'accounts/logout.html')

    else:
        if request.method == 'POST':
            form_new = Fileupload(request.POST, request.FILES )
            #instance=form_new.save(commit=False)
            #instance.save()
            if form_new.is_valid():
                instance = form_new.save(commit=False)
                instance.user_uploaded=request.user
                instance.save()
                return redirect('in')
        else:
            form_new = Fileupload()
            data = user_files.objects.filter(user_uploaded=request.user)
            args = {'form_new': form_new, 'data': data}#, 'url': form_new.get_absolute_url()}
            return render(request, 'accounts/in.html', args)

and model.py is,
class user_files(models.Model):
    Filename = models.CharField(max_length=50)
    Browse = models.FileField(upload_to='img/')
    user_uploaded = models.CharField(max_length=50, blank=True)

template is ,
<form action="." method="POST" enctype="multipart/form-data" >

Welcome to DropBox

    {% csrf_token %}
    {{form_new.as_p}}

<input type="submit" value="Save" >

    Logout

    {%else%}

You must login first

    Logout
    {% endif %}

S
    Share Files

    User is : {{request.user}}

    {% for da in data %}

{{da.Filename}} {{da.Browse}}

    {% endfor %}

</form>

Requesting you to please guide me how to provide download link for uploaded link, i am stuck at this point.
thanks in advance.

A: According to the documentation, you can use .url to get the url:
user_files_instance.browse.url

Hope it helps!


text:
Q: NullPointerException when using an interceptor in Struts 2 This is my WelcomeAction class:
package com.codinghazard.actions;

public class WelcomeAction {

    private String operandA;
    private String operandB;
    private Character operator;
    private int sum;

    public String execute() {
        if ((operandA!="") && (operandB!=""))
        {
            int a=Integer.parseInt(operandA);
            int b=Integer.parseInt(operandB);
            switch (operator)
            {
            case '1':
                sum=a+b;
                break;
            case '2':
                sum=a-b;
                break;
            case '3':
                sum=a*b;
                break;
            case '4':
                try
                {
                    sum=a/b;
                }
                catch(ArithmeticException ae)
                {
                    return "ERROR";
                }
                break;

            }
            return "SUCCESS";
        }
        return "ERROR";
    }

    public String getOperandA() {
        return operandA;
    }

    public void setOperandA(String operandA) {
        this.operandA = operandA;
    }

    public String getOperandB() {
        return operandB;
    }

    public void setOperandB(String operandB) {
        this.operandB = operandB;
    }

    public Character getOperator() {
        return operator;
    }

    public void setOperator(Character operator) {
        this.operator = operator;
    }

    public int getSum() {
        return sum;
    }

    public void setSum(int sum) {
        this.sum = sum;
    }
}

This is my struts.xml file:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
 <!-- http://localhost:8080/test/user/login -->
    <package name="user" namespace="/user" extends="struts-default">
        <action name="calculator">
        <interceptor-ref name="timer" />
            <result>pages/Calculator.jsp</result>
        </action>
        <action name="Welcome" class="com.codinghazard.actions.WelcomeAction">
        <%--
        <interceptor-ref name="timer" />
        --%>
            <result name="SUCCESS">pages/Result.jsp</result>
            <result name="ERROR">pages/error.jsp</result>

        </action>

    </package>

</struts>

I tried to user an interceptor but when I uncomment it NullPointerException is thrown.
I am new to Struts 2 and trying to get an understanding. I am on the topic of interceptors and learning from this tutorial.

A: The Struts2 framework leverages the code required to support its features via interceptors. For this purpose the core package provides the default configuration in the struts-default.xmlwith the flexibility to extend and override the default settings. This configuration is loaded on startup and applies to every action you use unless the action has its own custom settings. If you want to use these settings to every action in your packages configuration then you should consider creating the interceptor stack. See How do we configure an Interceptor to be used with every Action.

Please look into Struts 2 documentation for complete detail on above
mentioned interceptors.

This is very useful suggestion from the link of the tutorial. However the tutorial itself intended for middle or advanced readers. The beginners should start from Getting Started.
You got NullPointerException because you didn't reference params interceptor in the action configuration. And you should know that if you reference an interceptor for a concrete action config, it will use this interceptor and not the defaultStack which is used by default if no interceptor is referenced by the action configuration.

A:  <action name="Welcome" class="com.codinghazard.actions.WelcomeAction">

    <interceptor-ref name="timer" />
    <interceptor-ref name="defaultStack"/>
        <result name="SUCCESS">pages/Result.jsp</result>
        <result name="ERROR">pages/error.jsp</result>

    </action>

try above.
Whenever u ll use any extra interceptor which is not available in default interceptor list of struts2 then explicitly you have to add default stack to avail the functionality of default inteceptos as params or workflow.


text:
Q: PyCurrency_Converter: call to convert causes 403 forbidden response Mod security blocks me from accessing a URL.
I have tried using other methods from this website, but none seem to work as I use an import called PyCurrency-Calculator
import PyCurrency_Converter
import urllib.request
from bs4 import BeautifulSoup

PyCurrency_Converter.convert(1, 'USD', 'A$')

The error is:
Traceback (most recent call last):
  File "E:/Downloads/list of currencies.py", line 7, in <module>
    PyCurrency_Converter.convert(1, 'USD', 'A$')
  File "E:\Python34\lib\site-packages\PyCurrency_Converter\PyCurrency.py",
line 48, in convert
    return PyCurrency.convert(amount, _from, _to)
  File "E:\Python34\lib\site-packages\PyCurrency_Converter\PyCurrency.py",
line 31, in convert
    response = urllib2.urlopen(url)
  File "E:\Python34\lib\urllib\request.py", line 161, in urlopen
    return opener.open(url, data, timeout)
  File "E:\Python34\lib\urllib\request.py", line 469, in open
    response = meth(req, response)
  File "E:\Python34\lib\urllib\request.py", line 579, in http_response
    'http', request, response, code, msg, hdrs)
  File "E:\Python34\lib\urllib\request.py", line 507, in error
    return self._call_chain(*args)
  File "E:\Python34\lib\urllib\request.py", line 441, in _call_chain
    result = func(*args)
  File "E:\Python34\lib\urllib\request.py", line 587, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden

A: PyCurrency_Converter makes a call google finance under the hood (code). This service is no longer available and so the library needs to be modified to use a different service.
What you can do is find an alternative web based api and call that (I have no recommendation). As you can see the code for PyCurrency_Converter is quite short, so it will be simple to take and adapt it to another currency conversion api or to use requests or urllib to just do the requests yourself.


text:
Q: How to unselect a multiselect field in my custom modul edit page? I have added a multiselect field to a fieldset in my form.xml.
        <column name="ghs_pictogram_id">
        <argument name="data" xsi:type="array">
            <item name="options" xsi:type="object">Mcas\GhsPictogram\Source\Pictogram</item>
            <item name="config" xsi:type="array">
                <item name="filter" xsi:type="string">int</item>
                <item name="dataType" xsi:type="string">multiselect</item>
                <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/select</item>
                <item name="label" xsi:type="string" translate="true">Pictogram</item>
            </item>
        </argument>
    </column>

It works fine, I can select values and they are stored. My Problem is, that I'm not able to unselect the field. Once it is selected it stores a value, a reset to empty is not possible anymore.

A: You Can try below code  .
<item name="validation" xsi:type="array">
     <item name="required-entry" xsi:type="boolean">false</item>
</item>


text:
Q: How to extract data from a text file in Python? I have a text file which contains a lot of information. I tried to seek some help regarding this. I found some things which were a bit similar but not exactly what I wanted to do.
I have text file (shown below) out of which I want to extract the data of first 3 columns into an array.
I am a beginner in Python. Please help to resolve this.
//Text file starts
---------------------------SOFTWARE NAME------------------------------------

I/O Filenames:  abc.txt
Variables:______
------------------------------------------------------------------------

 Method name.

  Coordinates :      0         0

     S.No.      X(No.)    Y(No.)      Z(Beta)    A(Alpha)

     1    3.541            0
     2    7.821          180
     3    2.160            0
     4    4.143            0    3.69            0
     5    2.186            0    2.18            0
     6    3.490            0    2.45            0
//End of text file

A: For this I would use the package csv
import csv #Import the package

with open('/path/to/file.csv') as csvDataFile: #open the csv file
    csvReader = csv.reader(csvDataFile,delimiter=';') #load the csv file with the delimiter of your choice, here it is a ;
    for row in csvReader:
      #do something with the row

I advise you to format you file better, a good one would be:
S.No.;X(No.);Y(No.);Z(Beta);A(Alpha)
1;3.541;0;;
2;7.821;180;;
3;2.160;0;;
4;4.143;0;3.69;0
5;2.186;0;2.18;0
6;3.490;0;2.45;0

Here's a link with more information

A: You could try to extract the data with re module (regex101):
import re
from itertools import zip_longest

data = '''
//Text file starts
---------------------------SOFTWARE NAME------------------------------------

I/O Filenames:  abc.txt
Variables:______
------------------------------------------------------------------------

 Method name.

  Coordinates :      0         0

     S.No.      X(No.)    Y(No.)      Z(Beta)    A(Alpha)

     1    3.541            0
     2    7.821          180
     3    2.160            0
     4    4.143            0    3.69            0
     5    2.186            0    2.18            0
     6    3.490            0    2.45            0
//End of text file
'''

l = [g.split() for g in re.findall(r'^\s+\d+\s+[^\n]+$', data, flags=re.M)]
for v in zip(*zip_longest(*l)):
    print(v)

Prints:
('1', '3.541', '0', None, None)
('2', '7.821', '180', None, None)
('3', '2.160', '0', None, None)
('4', '4.143', '0', '3.69', '0')
('5', '2.186', '0', '2.18', '0')
('6', '3.490', '0', '2.45', '0')

A: Use re module to extract text. Use numpy module to construct the "array" you need.
import re
import numpy as np

text = """
//Text file starts
---------------------------SOFTWARE NAME------------------------------------

I/O Filenames:  abc.txt
Variables:______
------------------------------------------------------------------------

 Method name.

  Coordinates :      0         0

     S.No.      X(No.)    Y(No.)      Z(Beta)    A(Alpha)

     1    3.541            0
     2    7.821          180
     3    2.160            0
     4    4.143            0    3.69            0
     5    2.186            0    2.18            0
     6    3.490            0    2.45            0
//End of text file
"""

regex = r'(?<=^\s{5})\d\s*[\d\.]*\s*\d*'
matches = [x.split() for x in re.findall(regex, text, flags=re.MULTILINE)]

arr = np.array(matches)
print(arr)

It provides the output:
[['1' '3.541' '0']
 ['2' '7.821' '180']
 ['3' '2.160' '0']
 ['4' '4.143' '0']
 ['5' '2.186' '0']
 ['6' '3.490' '0']]


text:
Q: GLFW_RESIZABLE after the creation of the window I'm really starting out with LWJGL (I just started) and I focused on one thing: When I create a window and I want to set it as not resizable, I use:
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
window = glfwCreateWindow(WIDTH, HEIGHT, TITLE, NULL, NULL);

However, even if I want to set this after the window was created, I do not know how. I just tried to put the command after the creation of the window, but it won't work:
window = glfwCreateWindow(WIDTH, HEIGHT, TITLE, NULL, NULL);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

So, how I can resolve this?

A: From the GLFW Window Guide:

Window creation hints
There are a number of hints that can be set before the creation of a window and context. Some affect the window itself, others affect the framebuffer or context. These hints are set to their default values each time the library is initialized with glfwInit, can be set individually with glfwWindowHint and reset all at once to their defaults with glfwDefaultWindowHints.
Note that hints need to be set before the creation of the window and context you wish to have the specified attributes.

Essentially, you set hints like whether the window should be resizable, which context version it has etc. through glfwWindowHint() calls. These hints will then be used the next time you create a window with glfwCreateWindow(). If you set hints after the window has been created, then only new windows created after the call will be affected.
Therefore, it is currently not possible to change certain GLFW window properties, like whether it is resizable, after creation.

A: You can now change glfw Window Attributes with:
void glfwSetWindowAttrib(GLFWwindow * window, int attrib, int value);

From the documentation for glfw3 or lwjgl
This function sets the value of an attribute of the specified window.
The supported attributes are GLFW_DECORATED, GLFW_RESIZABLE, GLFW_FLOATING, GLFW_AUTO_ICONIFY and GLFW_FOCUS_ON_SHOW.
Some of these attributes are ignored for full screen windows. The new value will take effect if the window is later made windowed.
Some of these attributes are ignored for windowed mode windows. The new value will take effect if the window is later made full screen.


text:
Q: Problema al compilar Sass en Atom (Win 10) Estoy aprendiendo a usar Sass, en Windows 10. Uso el editor Atom y el preprocesador Prepros. Tengo instalado Nodejs.
El problema es que cuando quise compilar por primera vez el archivo sass, me salió esto en Atom:

[ "node-sass" no se reconoce como un comando interno o externo,
  programa o archivo por lotes ejecutable. ]

Alguien podría darme una mano con esto?

A: Solo tienes que ejecutar esto en la consola:
npm install -g node-sass.


text:
Q: Using Asp tags to navigate to a another Html page .net core mvc In my project, I have a parent and a child, and then the child as well has children so you can think about it as a three stages hierarchy. when I am in the third child (let me call it as a grandchild) I use an asp tag to go back to the second child view. the thing is what I am using right now gets me back to the whole index of the second child from all the parents, what I want is to get only the view of the second child of the parent I originally selected, not all children of all parents (Index). I hope this is not too complicated.
 Back to Surveys

i tried using asp-route-id="ViewData['ProjectId']"  but still didn't work.

A: Try to pass project id using Model, something similar to this
@model Speaker

SpeakerId: @Model.SpeakerId

HTML Output:
SpeakerId: 12

If you are pass id with separate name ( not default Id)
 SpeakerId: @Model.SpeakerId

HTML Output:
SpeakerId: 12

Consider checking detailed article here
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/anchor-tag-helper?view=aspnetcore-5.0


text:
Q: sys.stdout.write() deal with two line By using this code:
i=0
while i<10:
    sys.stdout.write('\r'+str(i))
    sys.stdout.flush()
    i +=1
    time.sleep(1)

we can count 0 to 9 in one line.
My question is that how if I wanna do this counting in two line?
I want something like counting 0-10 to a-z. For example, the first loop is to count 1-10 of a, then second is to count 1-10 of b.........
The final round is to count 1-10 of z
Output like this
First loop:
    a
     1-10 # here is counting 1-10

Second loop:
    b
     1-10 # here is counting 1-10

It means that I should print the english letter first then print 1-10
but How do I shift backward to change the english letter?


text:
Q: AgGrid JSON date column, sorting filtering is slow for huge data I have a JSON date column in AgGrid with 20K + records. I am using a date comparator to sort dates. Is there a better way then below to sort such date type as i am experiencing slowness in my application while sorting and filtering for huge data set.
For Sorting
 comparator: function (date1, date2) {
                var date1Number = fnDateToComparableNumber(moment(date1).toDate());
                var date2Number = fnDateToComparableNumber(moment(date2).toDate());

                if ((date1Number === null || isNaN(date1Number)) && (date2Number === null || isNaN(date2Number))) {
                    return 0;
                }
                if (date1Number === null || isNaN(date1Number)) {
                    return -1;
                }
                if (date2Number === null || isNaN(date2Number)) {
                    return 1;
                }

                return date1Number - date2Number;
            }

For Filtering
filterParams: {
                //applyButton: true,
                clearButton: true,
                // provide comparator function
                comparator: function (filterLocalDateAtMidnight, cellValue) {
                    // We create a Date object for comparison against the filter date
                    if (cellValue == '') {
                        return 1;
                    }

                    var cellDate = moment(cellValue).toDate();

                    // Now that both parameters are Date objects, we can compare
                    if (cellDate < filterLocalDateAtMidnight) {
                        return -1;
                    } else if (cellDate > filterLocalDateAtMidnight) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            },

Note:

*

*I am using moment for date manipulations

*JSON date is required for excel export. Else processCellCallback is expensive in case of big data.
I have done some hack for excel format else excel will display date as number.

*We have enterprise license for Ag-Grid

A: I've had similar problems at least for sorting by date. Do not use moment for parsing dates. It is way to slow for the amount of data you are using. Instead use Date():
 comparator: function (date1, date2) {
                var date1Number = fnDateToComparableNumber(Date(date1));
                var date2Number = fnDateToComparableNumber(Date(date2));

                if ((date1Number === null || isNaN(date1Number)) && (date2Number === null || isNaN(date2Number))) {
                    return 0;
                }
                if (date1Number === null || isNaN(date1Number)) {
                    return -1;
                }
                if (date2Number === null || isNaN(date2Number)) {
                    return 1;
                }

                return date1Number - date2Number;
            }

Maybe you'll need to parse the date manually but you are still way faster than using moment.

A: For sorting dates valueFormatter function helps. This worked for me and didn't slow down while sorting large datasets.
{
 headerName: 'Date',
 field: 'date',
 valueFormatter: params => dateFormatter(params.value),
 sortable: true
}


text:
Q: Yii2 How to list out dropdownlist option values from database without duplicate values? For categories dropdowList i am generating values from database, in that main_cat column has electronics value two times, in the dropdown also its repeating two times, how display it only once?
+--------+-------------+---------+
| cat_id | main_cat    | sub_cat |
+--------+-------------+---------+
| 1      | Electronics | Phones  |
+--------+-------------+---------+
| 2      | Electronics | TVs     |
+--------+-------------+---------+
| 3      | Furniture   | Sofa    |
+--------+-------------+---------+

I tried below code but it is repeating the electronics in the dropdown distinct() not working.
<?= $form->field($model, 'ad_cat_id',
            'template' => 'Category
{input}{error}
',
 ])->dropDownList(
         ArrayHelper::map(Categories::find()->distinct()->all(), 'cat_id', 'main_cat'),
           [
           prompt' => 'Please select main category',

 ]) ?>

How to select main_cat column without repeating same values?

A: Use as
Categories::find()->groupBy('main_cat')->all();


text:
Q: Assembly Language Shift into Carry Flags I currently got an assignment where I have to code in assembly language where you take user input to get a 4 digit hexadecimal value and convert it into binary and then after you get the binary value you have to convert it into a month day and year, where the first 7 digits would be the year, the next four are the month, and the last 5 are the day.
I have everything converted into binary and have an idea of how to get it from binary into normal integer values for the year, month and day. When I run my code the output is 0/0/0. I'm not sure if it is where I messed up with my shifting or something else. Could you guys take a look and give me an input on where to correct? In the code that I'm pasting, I'm only putting up to calcYear and figured I can figure that out and then work on the rest from there.
My code:
firstLine:

    call crlf
    mov si, offset programOne
    mov cx, programOneLen
    call putStrng       ;displays 'Program by Joe Remaklus'

    call crlf
    call crlf

    call inputVal   ;prompt for hex input
    call putBin ;display the value in AX as binary
    call crlf
    call calcYear   ;display the year of the first 7 binary digits.
    mov si, offset slash
    mov cx, slashLen
    call putStrng
    call calcMonth  ;display the month of the next 4 binary digits.
    mov si, offset slash
    mov cx, slashLen
    call putStrng
    call calcDay    ;display the day of the next 5 binary digits.
    call crlf

    call inputVal
    call putBin

    mov ah,04c
    int 021

prompt db 'Enter a 4-digit hex value'

lenPrompt = $-prompt

inputVal:

    push si, cx

    mov  si, offset prompt

    mov  cx, lenPrompt

    call putStrng

    call crlf

    call getHex

    call crlf

    pop  cx, si

    ret
;---------------------------------------------------------------

putBin:

    push ax, cx, dx

    mov  cx, 16     ;number of bits to display

  putBinLoopTop:

    mov  dl, '0'        ;assume bit to display is zero

    shl  ax, 1      ;shift bit to display into Carry Flag

    jnc  putBinSkipInc  ;if the top bit was zero skip the inc

    inc  dl         ;else inc DL to '1'

  putBinSkipInc:

    call putChar        ;display the character in DL

    loop putBinLoopTop  ;continue until 16 bits are displayed

    pop  dx, cx, ax

    ret
;---------------------------------------------------------------

calcYear:

    mov year, 0

    mov si, 0

    shl ax, 1
    adc si, 0
    iMul onetwoeight
    add year, si
    mov si, 0

    shl ax, 1
    adc si, 0
    iMul sixfour
    add year, si
    mov si, 0

    shl ax, 1
    adc si, 0
    iMul threetwo
    add year, si
    mov si, 0

    shl ax, 1
    adc si, 0
    iMul sixteen
    add year, si
    mov si, 0

    shl ax, 1
    adc si, 0
    iMul eight
    add year, si
    mov si, 0

    shl ax, 1
    adc si, 0
    iMul four
    add year, si
    mov si, 0

    shl ax, 1
    adc si, 0
    iMul two
    add year, si
    mov si, 0

    shl ax, 1
    adc si, 0
    iMul one
    add year, si
    mov si, year
    add si, 1980
    call putPos
ret

A: If I understand you correctly, at entry of calcYear your "ax" looks like this in binary:
yyyy yyym mmmd dddd
And you want to extract the values back to ordinary numbers.
I think I can understand your idea of "calcYear", but I'm sorry to not bother to try to fully understand it and fix it. If you are still curious, just use debugger to single step over each instruction and see where it goes south.
I will instead show you how to think about this problem differently.
Let's try to dig trough and understand this:
    ; ax is encoded as this: yyyy yyym mmmd dddd
    push ax
    push ax ; store the encoded value at stack twice
    ; extract "day" value
    and ax,01Fh  ;only "d" bits will survive
    mov [day],ax
    ; extract "month" value
    pop ax ; restore encoded input
    shr ax,5 ; shift ax by number of "d" bits
    and ax,0Fh ; only shifted "m" bits
    mov [month],ax
    ; extract "year" value
    pop ax ; restore encoded input
    shr ax,5+4 ; shift ax by number of "d" and "m" bits
    ; no need to "and", as "shr" did fill upper bits by zeroes
    add ax,1980 ; so "0" encoded year is 1980? (deducted from OP source)
    mov [year],ax
    ret

I hope this will give you some new ideas, how to work with particular bits in number. Keep in mind and/or are good to mask out things you are interested in and shr/sar/sal/shl/ror/rol/rcr/... are good to put it in desired position. xor may be used to somewhat patch the result (if needed), test is like and but getting only flags register update, and then there are some more bit oriented x386+ (or 486?) instructions, which are somewhat "advanced" and can save you some 2-3 instruction combinations of those basics I mentioned before. So you can safely ignore them, as long as you understand fully those basic ones and can bend anything with them as desired.


text:
Q: Quotient of ideal generated by regular sequence is a perfect module I have recently started reading Bruns-Herzog's 'Cohen Macaulay rings' and this is problem 1.4.27 in it.
We say that a module $M$ over a Noetherian ring $R$ is perfect if the projective dimension of $M$ is equal to the grade of $M$.
I am required to show that if an ideal $I$ is generated by a regular sequence of length $n$ in $R$, then $R/I^m$ is perfect for all natural numbers $m$.
I could see that the projective dimension of $R/I$ must be $n$ and it looks like I should somehow be able to use the Auslander-Buchsbaum formula but I have no clue how to proceed beyond this. Bruns-Herzog mention that the following result (Theorem 1.1.8) will be useful but I am not sure why:
Let $R$ be a ring, $M$ an $R$-module and suppose $I$ is an ideal generated by an $M$ regular sequence $a_1, \cdots ,a_n$ . Then the map
$$(M/IM)[X_1,....,X_n] \rightarrow gr_I(M): X_j \mapsto \overline a_j \in I/I^2$$
must be an isomorphism, where
$$gr_I(M) := \oplus_{r \geq 0} I^rM/I^{r+1}M$$
I would really appreciate any hint or solution.

A: By Theorem 1.1.8, $I^m/I^{m+1}$ is isomorphic as an $R/I$-module to the $m$th graded component of $R/I[X_1, \ldots, X_n]$, so $I^m/I^{m+1}$ is a free $R/I$-module of finite rank. Now consider the exact sequence
$$
0 \to I^m/I^{m+1} \to R/I^{m+1} \to R/I^m \to 0
$$
of $R$-modules. Now apply induction on $n$ to show that $R/I$ is perfect. Then apply induction on $m$ to show that the projective dimension on $R/I^m$ (as an $R$-module) is $n$ for all $m$. Note that $\mathrm{grade}(I^m) = \mathrm{grade}(I)$ for all $m$.


text:
Q: JointJS how to unset a passive port when link from that port is removed Is it possible to disable changing link from dragging at the source end of the link?
I'm using DEV plug-in with inPorts in passive mode; So that only out ports can start a link.
I'll set out port to passive mode when a link is made, so no more links could be created from same port.
However, I want to re-enable the outPort when the link is removed.
following code works when a link is broken from target port side, but not when link is broken at source port side (because source will be a point at this time) or via remove icon in the link.
graph.on('remove', function(cell) {
    console.log('event: remove');
    if (cell instanceof joint.dia.Link) {
        var sElemid = cell.get('source').id;
        var sElem = graph.getCell(sElemid);
        sElem && sElem.attr('.outPorts circle/magnet', 'true');
    }
});

How to re-enable the port in other two cases?

A: Something is better than nothing.
I disabled those two offending features. ie., no more remove icon or draggable arrow head at source end. :->
        defaultLink: new joint.dia.Link({
            attrs: {
                '.marker-arrowhead-group-source': {
                    display: 'none'
                },
                '.link-tools': {
                    display: 'none'
                }
            }


text:
Q: Conditionally rendered fields looking for general ideas on how to approach the requirements below:

"Create a Case" button/action on Account's Lightning record page:

*

*Ability to choose from different record types and corresponding Case_Category_c custom field

*AccountId is passed from Account record into new Case

*Depending on the record type and Case Category, dynamically render the necessary fields and further allow continuous re-rendering depending on values in those fields, e.g. Select a new value in a picklist, form re-renders and fields appear/hide as needed

*Upon save, user is redirected to new Case

*When viewing or editing a Case, the fields on the page layout are dynamically rendered per logic defined in original case creation

*Must work in standard app or console app

Here's what I've tried so far:

*

*Tried overriding Case new button with Visualforce page and custom controller that redirected to another Visualforce page, however,

*

*it doesn't work in a console app, and

*our users won't likely create Cases outside of launching from Account page

*A screen flow. It got very complex, there are 100+ case categories, and I think will be a pain to manage in the long run. Also doesn't account for viewing/editing the page, just creation.

*LWC that opened a new console tab with the VF page from a button click. My favorite solution so far, but I cannot figure out how to pass the AccountId from the LWC into the Visualforce page. I am very new to LWC and need to dive deeper.
What am I missing? Any advice on how to approach the design would be greatly appreciated.
(I know dynamic forms are potentially around the corner for Cases, which could ease some of this, but we need a solution now.)


text:
Q: how to get site collection url from SharePoint Hosted App I am trying to get site collection URL using

_spPageContextInfo.siteAbsoluteUrl

but it is giving output as https://domain.-a08083bbaacc988.sharePoint.com/sites/sitecollectionname
but I want it as https://domain.sharePoint.com/sites/sitecollectionname that is without instance id
How to get site collection url?

A: In your App url there are various Query String Parameters as shown here. That already containts the site collection url.
The Query String paramter "SPHostUrl" will give you the site collection URl.
In order to get that URL you can use following code
function getQueryStringParameter(paramToRetrieve) {
var params =document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve)
return singleParam[1];
}
}

Just use this code as
hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl")

Now this hostweburl will contain your site collection URL. For code reference you can see here

A: From your SharePoint Hosted app what you can get context of host web and fetch the url of site collection
You can use RequestExecutor for cross domain request as
 $.getScript(hostUrl + "/_layouts/15/" + "SP.RequestExecutor.js", GetSiteUrl);

and then fetch URL of sitecollection using bellow function
function GetSiteUrl() {
    var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    var currentcontext = new SP.ClientContext()
    var hostcontext = new SP.AppContextSite(currentcontext, hostUrl);
    var site = hostcontext.get_site();
    currentcontext.load(site);
    currentcontext.executeQueryAsync(function (s, a) {
        sitecollectionurl = site.get_url()

    });
}

Hope this will help you!


text:
Q: Knowing A and the discriminant, how to find B and C? On a Quadratic equation of the form $ax^2+bx+c$, I am given the discriminant ($\Delta=b^2-4ac$) and A.
To find B and C, I tried to solve it through $x1$ and $x2$...:

*

*$x1 = \frac{-b-\sqrt{\Delta}}{a}$

*$x2 = \frac{-b+\sqrt{\Delta}}{a}$
...using those properties:

*

*$x1 + x2 = - \frac{b}{a}$

*$x1 \times x2 = \frac{c}{a}$
Without any success...
So, is it possible to retrieve B and C?
Two additional properties:

*

*the discriminant is always positive

*B is always negative

A: One equation
$$\Delta=B^2-4AC\tag{1}$$
with 2 unknowns $B$ and $C$: there is a fundamental indeterminacy.
A counterexample among many: If $A=1/4$ and $\Delta=16$, (1) becomes:
$$16=B^2-C$$
which is possible for $(B=-4, \ C=0)$, $(B=-5, \ C=9)$, $(B=-6, \ C=20)$, etc. (I have taken into account the constraint on $B$ to be negative).
Otherwise said,
$$\frac14x^2-4x=0, \ \ \ \frac14x^2-5x+9=0, \ \ \ \frac14x^2-6x+2\sqrt{5}=0$$
have all the same $A$ and the same $\Delta$ without having the same $B$ and the same $C$.


text:
Q: Windows Phone 8.1 Parse - Log in issues I have been trying to log in to Parse using Windows phone 8.1, I have entered the windows .net key & the application ID but i am getting an error:
"ArgumentException was unhandled by user code
An exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll but was not handled in user code
Additional information: The header X-Parse-OS-Version has an empty value."
Does anyone have any ideas as to why this is happening?
This is currently the code written
public App()
{
this.InitializeComponent();
this.Suspending += this.OnSuspending;
ParseClient.Initialize("ApplicationID", ".netID");
}

A: i had to uninstall the  latest version (1.5.3) and install the older version
Install-Package parse -Version 1.5.2
Still trying to get push to work also but to no success. Sigh


text:
Q: When I add a JPG image in Codename One resource browser, it breaks I have an image of rather large resolution (9332 x 5116). When I go to the codename one editor, to add image, I can add the image, but then when I get back into the editor, the left-side menu doesn't display properly. To be more specific, it doesn't redraw when I'm in the Multi-image or All Images menu. The only way to go back to normal is to do a "Delete unused images."
Is this a known issue? I'd hate to sacrifice image quality.
Any advice greatly appreciated.
Thanks.

A: The image is WAY too big to fit into any device and would crash many devices when they try to open it. The designer wasn't built to handle images so large, you can run it with more RAM but the solution is to use an image of realistic size.


text:
Q: How to remove characters from specific index in String? I have an application where I am receiving a string with some repetitive characters. I am receiving input as a String. How to remove the characters from specific index?
main.rs
fn main() {
    let s:String = "{\"name\":\"xx/yyyy/machine/zzz/test_int4\",\"status\":\"online\",\"timestamp\":\"2021-06-11 18:20:42.231770800 UTC\",\"value\":7}8668982856274}".to_string();
    println!("{}", s);
}

how can I get result
"{\"name\":\"xx/yyyy/machine/zzz/test_int4\",\"status\":\"online\",\"timestamp\":\"2021-06-11 18:20:42.231770800 UTC\",\"value\":7}"

instead of
"{\"name\":\"xx/yyyy/machine/zzz/test_int4\",\"status\":\"online\",\"timestamp\":\"2021-06-11 18:20:42.231770800 UTC\",\"value\":7}}8668982856274}"

A: String indexing works only with bytes, thus you need to find an index for the appropriate byte slice like this:
let mut s = "{\"name\":\"xx/yyyy/machine/zzz/test_int4\",\"status\":\"online\",\"timestamp\":\"2021-06-11 18:20:42.231770800 UTC\",\"value\":7}8668982856274}";
let closing_bracket_idx = s
    .as_bytes()
    .iter()
    .position(|&x| x == b'}')
    .map(|i| i + 1)
    .unwrap_or_else(|| s.len());
let v: serde_json::Value = serde_json::from_str(&s[..closing_bracket_idx]).unwrap();
println!("{:?}", v);

However, keep in mind, this approach doesn't really work in general for more complex cases, for example } in a json string value, or nested objects, or a type other than an object at the upmost level (e.g. [1, {2: 3}, 4]). More neat way is using parser capabilities to ignore of the trailing, as an example for serde_json:
let v = serde_json::Deserializer::from_str(s)
    .into_iter::<serde_json::Value>()
    .next()
    .expect("empty input")
    .expect("invalid json value");
println!("{:?}", v);


text:
Q: RelativeLayout issue - image overlaps ScrollView I'm trying to stick an image in the bottom of my app, and above is I have a scrollview, like this:
  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:id="@+id/RelativeLayout1">
        <ScrollView  android:paddingTop="180dip" android:layout_width="fill_parent" android:id="@+id/scrollView12" android:layout_height="wrap_content">
            <LinearLayout android:id="@+id/linearLayout4" android:layout_width="fill_parent" android:paddingRight="8dip" android:orientation="vertical" android:layout_height="wrap_content">
            </LinearLayout>
        </ScrollView>
        <ImageView android:layout_width="fill_parent"
            android:background="@color/cinza" android:src="@drawable/header"
            android:id="@+id/imageView2" android:layout_height="wrap_content" android:layout_alignParentBottom="true">
        </ImageView>
</RelativeLayout>

I feed the scrollview dinamically, so the size of it can change. My problem is that if it grows till the end of the display, the last records goes behind my picture. I wanted it to grow just untill the picture.
Some clue on how to do this? I tried several ways, relativelayouts, linearlayouts, but sometimes the picture disappears, sometimes don't stick in the bottom...

A: You should just add android:layout_above="@+id/imageView2" for the ScrollView, and define the ImageView first, as you want it to be draw first, then the ScrollView inside the RelativeLayout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/RelativeLayout1">
    <ImageView
        android:layout_width="fill_parent"
        android:background="@color/cinza"
        android:src="@drawable/header"
        android:id="@+id/imageView2"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true">
    </ImageView>
    <ScrollView
        android:paddingTop="180dip"
        android:layout_width="fill_parent"
        android:id="@+id/scrollView12"
        android:layout_above="@+id/imageView2"
        android:layout_height="wrap_content">
        <LinearLayout
            android:id="@+id/linearLayout4"
            android:layout_width="fill_parent"
            android:paddingRight="8dip"
            android:orientation="vertical"
            android:layout_height="wrap_content">
        </LinearLayout>
    </ScrollView>
</RelativeLayout>

A: RelativeLayout is not the right chose in this case. You have to use LinearLayout, and the key is the android:layout_weight parameter:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ScrollView  android:paddingTop="180dip"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <LinearLayout android:id="@+id/linearLayout4"
            android:layout_width="fill_parent"
            android:paddingRight="8dip"
            android:orientation="vertical"
            android:layout_height="wrap_content">
        </LinearLayout>
    </ScrollView>

<ImageView android:layout_width="fill_parent"
    android:background="@color/cinza"
    android:src="@drawable/header"
    android:id="@+id/imageView2"
    android:layout_height="wrap_content" />

A: Give a id for scroolview then set a tag in image view android:layout_blow="id of scrollview"


text:
Q: Do I need to write any closing code for NLog? I've just started using NLog.
I'm wondering I don't need to write any closing code (such as Logger.Close();). Do I need to?
I've already checked several blog posts (in Japanese), NLog's GitHub project wiki, and nlog-project.org.

A: NLog will try to flush automatically on shutdown, but depending on platform then it might not always work.
For perfect result then you should call this just before application-exit:
NLog.LogManager.Shutdown();

See also: Wiki: Remember to flush


text:
Q: Mocking Using JMockit I need to mock a method in a java class that is like this:
public class Helper{

    public static message(final String serviceUrl){

        HttpClient httpclient = new HttpClient();
        HttpMethod httpmethod = new HttpMethod();

        // the below is the line that iam trying to mock
        String code = httpClient.executeMethod(method);

    }
}

I have tried to write the junit in groovy, but not able to do so as grrovy meta-proggraming techniques do not apply for java classes. On my research, i have found out that JMockit is a good framework that can also mock objects that are created using new constructor.
Can somebody show me how to write the unittest for the above class either in java or in groovy.
Advanced Thanks
this is the test case that i have tried so far using jmockit, but does not work..
void testSend(){

    def serviceUrl = properties.getProperty("PROP").toString()

    new Expectations(){
        {
            HttpClient httpClient=new HttpClient();
            httpClient.executeMethod(); returns null;
        }
    };
    def responseXml = Helper.sendMessage(requestXml.toString(), serviceUrl)
}

A: The java version of your test case would look like:
@Test
public void testSend() throws IOException {

    final String serviceUrl = "http://google.com/";

    new Expectations(){
        // these bits are important as they tell Jmockit what classes to mock
        @Mocked HttpClient client ;
        @Mocked GetMethod method;

        {
            HttpClient httpClient= new HttpClient() ;
            HttpMethod method = new GetMethod(withEqual(serviceUrl));
            try {
                httpClient.executeMethod(method);
            } catch (IOException e) {
                // not going to happen
            }
            result = 200;
        }
    };
    // run the test and assert something
    Assert.assertEquals(200, Helper.message(serviceUrl));
}

This is available on github.com, note I used httpClient 3.1 to implement your message method, I'm guessing that isn't quite right, but should be enough to answer the question.
If you can prep a simple grails project with your test case in I'm sure I can figure out what the issue is.
Update: I've been playing with a toy grails project locally and haven't managed to configure jmockit correctly. The key thing with jmockit is to ensure it is before junit on the classpath, but since junit is shipped in grails I can't find away to get jmockit in the right place.

A: With jmockit you can also mock instance creation.  I prefer slightly different technique:
@Test
public void testFoo(@Mocked final HttpClient client) {
       new Expectations() {{
              // expect instance creation and return mocked one
              new HttpClient(... );  returns(client)

              // expect invocations on this mocked instance
             client.invokeSomeMethid(); returns(something)
       }};

        helper.message(serviceUrl)
}

A: thanks for raising the question, with Spring-web-3.2.2 (which uses httpclient-4.0.1), my code looks like this:
    new NonStrictExpectations(){
        @Mocked(methods={"executeMethod"})
        ClientHttpRequest mocked_req;
        @Mocked(methods={"getBody"})
        ClientHttpResponse mocked_res;
        {
            byte[] buf  = (
            "<example_xml><person><name>Johnson</name><age>20</age></person></example_xml>"
            ).getBytes();

            mocked_req.execute();
            mocked_res.getBody(); returns(new ByteArrayInputStream(buf));

        }
    };

    RestTemplate mytemplate = new RestTemplate();
    obj =         mytemplate.getForObject(.....);
    assertEquals("returned and parsed obj should be equal to this one", expectedObj, obj);


text:
Q: C++ Boost copy_file exception on Ubuntu I recently upgraded Boost from 1.61 to 1.78 (gcc 7.5.0 on an Ubuntu 18.04 VirtualBox VM) and there appears to a change in the behaviour of filesystem::copy_file.
Now, when I copy a read-only file to a directory with full permissions, I get a filesystem_error exception with detail:
boost::filesystem::copy_file: Operation not permitted [system:1]

Despite this, the read-only file is always successfully copied! Interestingly, the destination file is not read-only. In 1.61 the copy behaviour was the same but there was no exception.
This simple program reproduces the issue:
#include <boost/filesystem.hpp>
#include <string>
#include <iostream>

int main()
{
    // copyFrom should be write protected
    boost::filesystem::path copyFrom("./files/myfile.txt");
    boost::filesystem::path copyTo("./files/myfile2.txt");

    try
    {
        boost::filesystem::copy_file(copyFrom, copyTo, boost::filesystem::copy_options::overwrite_existing);
    }
    catch (const boost::filesystem::filesystem_error& e) {
        std::cout << "Failed to copy " << copyFrom.string() << " to " << copyTo.string() << std::endl
            << "Exception: " << e.what() << std::endl
            << "Error code: " << e.code().message() << std::endl
            << "Error code value: " << e.code().value() << std::endl;
        return -1;
    }
    std::cout << "Copy success!" << std::endl;
    return 0;
}

Compile:
gcc -c -x c++ /home/code/copyfile/copyfile.cpp -I /home/code/Boost/1.78.0/lib/native/include -g1 -o "/home/code/copyfile/copyfile.o" -Wall -O2 -DNDEBUG -std=c++11

Link:
g++ -o "/home/code/copyfile/copyfile.out" -L/home/code/Boost/1.78.0/release/lib /home/code/copyfile/copyfile.o "-lboost_filesystem"

Output:
Failed to copy ./files/myfile.txt to ./files/myfile2.txt
Exception: boost::filesystem::copy_file: Operation not permitted [system:1]: "./files/myfile.txt", "./files/myfile2.txt"
Error code: Operation not permitted
Error code value: 1

Removing the read-only flag on the source file results in the copy succeeding with no exception, as does running the command elevated (sudo /.copyfile.out).
This seems like unusual behaviour - I am not modifying the source file in any way, so why does the exception occur?
Removing and later adding back the read-only flag on the source file feels like a hack. This code will often run over directories where there will be many read-only files.
If the exception code returned ("1") refers to the fact that the read-only state of the source file was not preserved on the copied file (for me this doesn't matter), I could use this value to decide whether to continue.  Either way it seems strange because this didn't happen in the older Boost.
EDIT: strace output as per comment:
openat(AT_FDCWD, "./files/myfile.txt", O_RDONLY|O_CLOEXEC) = 3
statx(3, "", AT_STATX_SYNC_AS_STAT|AT_NO_AUTOMOUNT|AT_EMPTY_PATH, STATX_TYPE|STATX_MODE|STATX_INO|STATX_SIZE, {stx_mask=STATX_ALL, stx_attributes=0, stx_mode=S_IFREG|0555, stx_size=9, ...}) = 0
openat(AT_FDCWD, "./files/myfile2.txt", O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0100755) = 4
statx(4, "", AT_STATX_SYNC_AS_STAT|AT_NO_AUTOMOUNT|AT_EMPTY_PATH, STATX_TYPE|STATX_MODE|STATX_INO, {stx_mask=STATX_ALL, stx_attributes=0, stx_mode=S_IFREG|0777, stx_size=0, ...}) = 0
fstatfs(3, {f_type=0x786f4256, f_bsize=4096, f_blocks=244189951, f_bfree=48066312, f_bavail=48066312, f_files=1000, f_ffree=1000000, f_fsid={val=[0, 0]}, f_namelen=255, f_frsize=4096, f_flags=ST_VALID|ST_NODEV|ST_RELATIME}) = 0
copy_file_range(3, NULL, 4, NULL, 9, 0) = 9
fchmod(4, 0100555)                      = -1 EPERM (Operation not permitted)
close(4)                                = 0
close(3)                                = 0


text:
Q: Installing DHCP3 Server I am having trouble installing dhcp3-server on Kali Linux 2.0. I keep getting the following error Depends: isc-dhcp-common (= 4.2.2.dfsg.1-5+deb70u6) but 4.3.1-6 is to be installed

Does anyone know how to fix this? My Google-fu has turned up no results that can actually help me. Thanks!

A: Run this, it just took me a lot of time sorting this out:
apt-get purge isc-dhcp-common && apt-get install isc-dhcp-common && apt-get install isc-dhcp-server

Then you might need to reset the network monitor:
service network-manager restart

And you're on Kali 2.0 so a special fix is needed that not many know about. Check the file
/etc/networkmanager/networkmanager.conf and be sure this section is correct:
[ifupdown]
Managed=true

If it's set to false, it wont work.