text:
Q: Configure velocity to render an object with something other than toString? Is there a way to configure Velocity to use something other than toString() to convert an object to a string in a template? For example, suppose I'm using a simple date class with a format() method, and I use the same format every time. If all of my velocity code looks like this:
$someDate.format('M-D-yyyy')

is there some configuration I could add that would let me just say
$someDate

instead? (Assuming I'm not in a position to just edit the date class and give it an appropriate toString()).
I'm doing this in the context of a webapp built with WebWork, if that helps.

A: Velocity allows for a JSTL like utility called velocimacros:
http://velocity.apache.org/engine/devel/user-guide.html#Velocimacros
This would allow you to define a macro like:
#macro( d $date)
   $date.format('M-D-yyyy')
#end

And then call it like so:
#d($someDate)

A: You could also create your own ReferenceInsertionEventHandler that watches for your dates and automatically does the formatting for you.

A: Oh, and the 1.6+ versions of Velocity have a new Renderable interface.  If you don't mind tying your date class to a Velocity API, then implement this interface and Velocity will use the render(context, writer) method (for your case, you just ignore the context and use the writer) instead of toString().

A: I faced this problem too and I was able to solve it based on Nathan Bubna answer.
I'm just trying to complete the answer providing the link to Velocity documentation which explains how to use EventHandlers.
In my case, I needed Velocity calls "getAsString" instead of toString method for all JsonPrimitive objects from gson library every time that a reference was inserted.
It was as simple as creating a
public class JsonPrimitiveReferenceInsertionEventHandler implements ReferenceInsertionEventHandler{

    /* (non-Javadoc)
     * @see org.apache.velocity.app.event.ReferenceInsertionEventHandler#referenceInsert(java.lang.String, java.lang.Object)
     */
    @Override
    public Object referenceInsert(String reference, Object value) {
        if (value != null && value instanceof JsonPrimitive){
            return ((JsonPrimitive)value).getAsString();
        }
        return value;
    }

}

And add the event to the VelocityContext
vec = new EventCartridge();
vec.addEventHandler(new JsonPrimitiveReferenceInsertionEventHandler());

...

context.attachEventCartridge(vec);


text:
Q: How to maximize 3-cycles in this graph type inspired by block design? I've come up with this question and I've been playing with it for a couple weeks by now without any definite breakthrough; it seems there should be a better approach than straight naive brute force, but I haven't come up with anything conclusive yet.  (The work and partial answers I have come up with, I am posting in a self-answer so as not to clutter the question.)
If you're not familiar with block design as mentioned in the title, then this Stack Overflow discussion of the game "Spot It!" is a good place to look for immediate familiarization.  It's not strictly necessary to know for purposes of this question, but may be interesting for its own sake.

Consider a directed graph with 13 vertices and 52 edges, where each vertex has in-degree 4 and out-degree 4, and the edges are defined in a particular way as described below.  (I'll call the vertices by uppercase letters A through M.)
In the following list, each row represents four edges; for example, the row "ABCD" represents that there are directed edges (A,B), (B,C), (C,D), (D,A).
ABCD
AEFG
AHIJ
AKLM
BEHK
BFIL
BGJM
CEIM
CFJK
CGHL
DEJL
DFHM
DGIK

(Notice that each row in the above list shares one letter and only one letter with each other row in the list.  This is the connection to block design.)
The target is to maximize the number of 3-cycles (cycles of length 3) without disturbing the graph's relationship to block design.
The sequence of the four letters on each line may be changed arbitrarily to specify another similar graph, without disturbing the property that each row shares one and only one letter with each other row.
(Also note that as the vertex ending each row in the list connects to the vertex at the beginning of the row, there are 6 possible permutations per row, not 24; that is, ABCD and BCDA would be equivalent as they represent the same four edges.)

Now, the particular graph specified above has only 4 cycles of length 3; namely:
DAK
GAB
JAE
MAH

(Where DAK is shorthand for D->A, A->K, K->D.)
Here is the puzzle:
By permuting each row in the manner described, what is the maximum number of cycles of length 3 that can be achieved in the resulting graph?

A: The first question is of course whether the number of cycles can be changed at all, or is it an invariant within the rules?  A single example suffices to show that the 3-cycle count is not an invariant; to that end, I'll point out that permuting the cycle BGJM to BJMG while leaving all other rows as they are adds SEVEN 3-cycles to the graph while removing only GAB from the 3-cycles already present, for a net gain of 6.  The cycles added are:
BJA
BJK
BJL
MGH
MGI
GBC
GBF

A loose upper bound on the maximum can be computed by recognizing that any single edge can be part of at most $3$ 3-cycles.
Thus, if each edge were to attain this maximum, there would be exactly $52$ 3-cycles in the graph.
By experimentation I do not believe this to be a tight upper bound, though it is difficult to prove; instead, I expect the attainable maximum to be approximately half of this upper bound, or roughly $26$.

As there are $6^{13} \approx 13$ billion different possible permutations, the computational resources required to check all possibilities one by one are prohibitive (5000 permutations checked per second would still take just over a month), but as it's clear there is a maximum possible number of 3-cycles and that it's at most 52, it doesn't seem it should be so difficult to find it and prove it....

Heuristically, it does seem to give good results to arrange each row such that each column contains all thirteen letters from A through M.  And in particular, when the thirteen edges begun in each column form a Hamiltonian cycle (so that four disjoint Hamiltonian cycles contain all the edges in the graph), the count of 3-cycles seems to be higher.  But this is only an indicated direction to look in and doesn't prove any maximum, nor does it explain why this should be the answer.

I've so far been unable to find any clear-cut simplifications that can be made on this problem, apart from the rather obvious one that half the permutations can be discarded as exact reflections of the other half (where each edge's direction has been reversed).
Also, I don't believe anyone has studied this interplay between block design and graph theory before, but if there is work already done on the subject I'd be very interested in reading it!

Playing with the smaller block design with 7 vertices and 21 edges, and ignoring the listed 3-cycles (as in the smaller version each row itself is a 3-cycle rather than being a 4-cycle), I successfully produced a graph with 7 additional 3-cycles, or half the upper bound (computed as above) of 14 cycles:
AGF
DAB
ECA
CDG
FED
BFC
GBE

Note that each column in this listing contains all 7 vertices, and the edges begun by the vertices in each column comprise 3 disjoint Hamiltonian cycles.
I did not prove that this is maximal for the smaller 7-21 case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Confusing recursive function definition I'm reading through https://plato.stanford.edu/entries/recursive-functions/ and came across a confusing part:

One means of doing so is to first use recursion on the type ℕ→ℕ—a
simple form of recursion at higher types as envisioned by Skolem and
Hilbert—to define an iteration functional as follows: $$Iter(,0) = $$
$$Iter(, x+1) = (Iter(, x))$$
$Iter$  takes as arguments a function $:ℕ→ℕ$ as well as a number $x∈ℕ$ and is defined so that
$Iter(,n)=^{n+1}(x)$—i.e., the function which is the $n$th iterate of
$$

Following from the base case, $Iter$ should return a function of type $ℕ→ℕ$. In the inductive clause, though, the output of $Iter$ is used as an argument to $$. But $$ expects a natural number, not another function. What am I missing here?
EDIT
As noted in the comments the formula should be $Iter(\phi, x+1)=\phi \circ Iter(\phi, x)$. But right after that $\beta$ function is introduced:

$$\beta(0)=x+1 (i.e., the successor function)$$
$$\beta(x+1)=Iter(\beta,x)$$

From the base case, $\beta$ is $ℕ→(ℕ→ℕ)$. But in the inductive clause,
it's used as an argument for $Iter$, which is supposed to take only functions of type $ℕ→ℕ$. Should it be $\beta(x+1)=Iter(\beta(x),x)$ or something alike or the definition of $Iter$ should be changes once again?


text:
Q: How to write a customize xslt reports using with maven in testng Instead of generating reports in default pie charts, i want to customize the reports in own style
    example : Bar charts , or any other type of representation
    I'm using this code in pom.xml
    Any one suggest me the way to customize using Xslt in POM.xml
 <reporting>
     <plugins>
      <!-- TestNG-xslt related configuration. -->
       <plugin>
       <groupId>org.reportyng</groupId>
       <artifactId>reporty-ng</artifactId>
       <version>1.2</version>
       <configuration>
       <!-- Output directory for the testng xslt report -->
       <outputdir>/target/testng-xslt-report/index.html</outputdir>
       <sorttestcaselinks>true</sorttestcaselinks>
       <testdetailsfilter>FAIL,SKIP,PASS,CONF,BY_CLASS</testdetailsfilter>
       <showruntimetotals>true</showruntimetotals>
       <cssFile>myCustomStyle.css</cssFile>
       </configuration>
       </plugin>
      </plugins>
    </reporting>

A: Instead of customizing reportNG you may simply develop your own custom html result files.then you may have any structure you want.
All you have to do is to write your own custom reporter class and keep logging the information in it while your test methods are running and after completion simply save and close the file in your project folder.
Although you will be writing more code but you will have more flexibility in its design.


text:
Q: How do I lock the Y but not the X in a kv screen? I want to build a screen with 6 labels at the top, 6 inputs below the top labels, and then an infinite amount of labels generated below the inputs.
The columns + rows of the labels/inputs should align with each other.
When resizing the window, the X of each should change, but the Y should stay the same (making blank room for additional labels at the bottom). To make it more clear I imitated the situation in Excel:
Window before resizing // Window after resizing
I tried the Grid Layout (where the X and Y always resize with the window -> doesn't work for my idea) and the Float Layout (where positioning everything (especially the generated labels) can't possibly be the best solution.
I am not looking for the logic behind generating the Labels below. Just the layout in .kv.
UPDATE:
After experimenting with @MisterNox 's code, I implemented it into my test project. When I click the "+" Button to add lines, I run into the problem that the two top rows are being pushed further up making the first row unreadable.
My code looks as follows and should be reproducable:
test_main.py:
import kivy
from kivy import Config
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import ObjectProperty
from kivy.graphics import Rectangle
from kivy.graphics import Color
from kivy.graphics import Line
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, TransitionBase, ShaderTransition, FadeTransition
from kivy.uix.popup import Popup
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.animation import Animation
import time
import csv

Config.set('graphics', 'width', '1024')
Config.set('graphics', 'height', '768')

class WindowManager(ScreenManager):
    pass

class MyWindow(Screen):
    def __init__(self, **kwargs):
        super(MyWindow, self).__init__(**kwargs)
        Window.bind(width=self.on_window_width)

    def on_window_width(self, instance, value):
        self.ids.stock_list_layout.width = value
        for obj in self.ids.my_window.children:
            if isinstance(obj, Label):
                obj.width = value/6

    def do_something(self):
        print("HEL")
        self.ids.my_window.add_widget(Label(text="TEST", size_hint=(None, None), size=(Window.width/6, 35)))
        self.ids.my_window.add_widget(Label(text="TEST", size_hint=(None, None), size=(Window.width / 6, 35)))
        self.ids.my_window.add_widget(Label(text="TEST", size_hint=(None, None), size=(Window.width / 6, 35)))
        self.ids.my_window.add_widget(Label(text="TEST", size_hint=(None, None), size=(Window.width / 6, 35)))
        self.ids.my_window.add_widget(Label(text="TEST", size_hint=(None, None), size=(Window.width / 6, 35)))
        self.ids.my_window.add_widget(Label(text="TEST", size_hint=(None, None), size=(Window.width / 6, 35)))

class MainApp(App):
    def build(self):
        return kv

kv = Builder.load_file("testing.kv")

if __name__ == "__main__":
    MainApp().run()

testing.kv:
#:import Window kivy.core.window.Window
WindowManager:
    MyWindow:

<MyWindow>:
    GridLayout:
        id: my_window
        cols:6
        size_hint_y: None
        size_hint_x: None
        pos_hint:{"left":1,"top":1}
        width: Window.width

        Label:
            text:"LABEL"
            height: 35
            #size_hint:(0.16666,None)
        Label:
            height: 35
            #size_hint:(0.16666,None)
            text:"LABEL"
        Label:
            height: 35
            #size_hint:(0.16666,None)
            text:"LABEL"
        Label:
            height: 35
            #size_hint:(0.16666,None)
            text:"LABEL"
        Label:
            text:"LABEL"
            height: 35
            #size_hint:(0.16666,None)
        Label:
            text:"LABEL"
            height: 35
            #size_hint:(0.16666,None)

        TextInput:
            height: 35
            size_hint:(1,None)
        TextInput:
            height: 35
            size_hint:(1,None)
        TextInput:
            height: 35
            size_hint:(1,None)
        TextInput:
            height: 35
            size_hint:(1,None)
        Button:
            text:"+"
            on_release:
                root.do_something()

A: I am going to give you a short example with a Gridlayout. To adjust the width of your labels when the width of the screen is changing you could use a bind method on the Window.width. You could still write your code in kv and just add the bind method in your app's build method of course, this is just an example.
Everytime the width of the window changes it will call the callback method which adjusts your label width according to the overall width. Then you could set a height for the labels. As this is static now and you did not set a height bind it will stay the same even if it goes out of the window viewport.
Here is a short code snippets only with some dummy labels to show you the procedure:
Example:
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.core.window import Window

Window.size = 600, 400

class MyApp(App):
    def build(self):
        self.columns = GridLayout(cols=5, size_hint_x=None, width=Window.width)
        for lbl in range(0,80):
            self.columns.add_widget(Label(text="Dummy", size_hint=(None, None), size=(Window.width/5, 50)))
        Window.bind(width=self.on_window_width)

        return self.columns

    def on_window_width(self, instance, value):
        self.columns.width = value
        for obj in self.columns.children:
            if isinstance(obj, Label):
                obj.width = value/5

MyApp().run()

[UPDATE]
As you asked for kv integration, here is basically the same example from above, just with some kv integration. Basically you can integrate the labels/textinputs into the kv string, but I just wanted to add a lot of dummy labels so I kept this action in my python code.
The difference is that I assigned an id to the Gridlayout to access it easily with self.ids.id_name within my python code.
bind explanation
Regarding the bind method, this is a method which listens to changes of the assigned attribute and in case of a change it fires the callback method.
Lets take my example Window.bind(width=self.on_window_width): The object who calls the method is the one with the attribute you want to look for. In our case we want to look for changes in the window width. Thats why Window is our acting object. Within the bracket you are going to name the attribute first and then the callback method which should be fired when changes occur.
A callback method takes three attributes, self (the object the method belongs to), the instance (in our case it is Window) and the changed value of the attribute we listened to in our bind method. Then you can do what ever you want with this value. We adjust the width of our labels to let them spread along with the window. Hopefully I explained it good enough.
from kivy.app import App
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.lang.builder import Builder
from kivy.uix.screenmanager import Screen, ScreenManager

Window.size = 600, 400

kv = """
#:import Window kivy.core.window.Window

<MyScreen>:
    name: 'first'
    GridLayout:
        id: columns
        cols: 5
        size_hint_x: None
        width: Window.width

"""

class MyScreen(Screen):
    def __init__(self, **kwargs):
        super(MyScreen, self).__init__(**kwargs)

        for lbl in range(0,80):
            self.ids.columns.add_widget(Label(text="Dummy", size_hint=(None, None), size=(Window.width/5, 50)))
        Window.bind(width=self.on_window_width)

    def on_window_width(self, instance, value):
        self.ids.columns.width = value
        for obj in self.ids.columns.children:
            if isinstance(obj, Label):
                obj.width = value/5

class MyApp(App):
    def build(self):
        Builder.load_string(kv)

        WMan = ScreenManager()
        myscreen = MyScreen()

        WMan.add_widget(myscreen)

        return WMan

MyApp().run()


text:
Q: WSO2 ESB Expose a REST API keeping URI part Say I have a REST API hosted on a webserver:
someone.com/api/
I want to expose this REST API through a proxy service using WSO2 ESB.
esb.com/api/
It should forward whatever is after esb.com/api/. So if I hit:
esb.com/api/param1/param2
It should hit the real service using:
someone.com/api/param1/param2
How do I pass the URI parts to the real webservice from a proxy service?

A: Don't try to use Proxy services for REST API. Proxy Services are for the Web Services. Use API s avialable in WSO2 ESB which are similar to proxy services and intended for REST API. This Oxygen Tank article and this sample document will be useful for you.


text:
Q: No "erase disk" option when installing Lubuntu 19.04 I am trying to install Lubuntu 19.04 on a new Lenovo Ideapad 130S-11IGM, but when I get to the partition page, the option "Erase disk" does not appear.  The current OS is Windows 10, which I have no interest in keeping.  How can I get the option to erase everything?
SecureBoot is disabled in BIOS.  I was not able to find a Fastboot setting in BIOS.  Thanks.
Update 1: I have run "check disk for errors" and no errors were found.
Update 2: The problem is solved by taking the only option available (manual partitions) and setting up the partitions according to the instructions at the bottom of the document linked by guiverc in the comments below.  Briefly, because this machine has UEFI booting, it is necessary to make a small partition for that boot system in addition to the main partition.  Follow these steps: "New partition table" (I chose MBR).  Then "Free space"->"Create"-> make a FAT32 partition with EPS flag set, with mount point /boot/efi/.  260 MiB worked for me.  Next do "Free space"->"Create"-> make a partition using the remaining available space, with mount point /.  Several filesystems are possible, I chose ext4.  At this point the "Next" button becomes clickable and everything else is straightforward.  ALL DATA WILL BE LOST BY THIS PROCEDURE.  Only do this if you want to erase everything.
In case anyone else has the same machine with the Realtek 8821CE wifi, next you are going to need to install the driver.  The instructions here worked for me: How to install Wi-Fi driver for Realtek RTL8821CE on Ubuntu 18.04?

A: As suggested in the Lubuntu manual, the installer will not give you the "erase disk" option if you have anything on the target device mounted:

If you have had a previous linux install and want to put the entire disk or just replace an entire partition you will need to unmount them.

The most likely cause for this is that swaps have been automounted. This is a "feature" of the Ubuntu ecosystem to provide as much memory for the live system as possible. Here, too, the manual provides the solution:

In this case running
sudo swapoff -a
will unmount them and any partitions with data mounted can be unmounted through pcmanfm-qt.

I have also seen a few cases where partitions on eMMC devices (which is what your target is) seem to be automounted, though not having the hardware myself, I cannot confirm this.
There is an upstream bug to provide some other solution to this issue.

A: I had the same problem when trying to install Lubuntu 20.04 LTS:

I solved it by opening PCManFM (my file manager) and unmounting my eMMC drive and then starting the installation procedure again. I then got all the four options that i'm used to:


text:
Q: Multiply two irregular series (Influx/flux) After reading a lot of forums I still can't figure this out…
I have two irregular series. The first one reads data from my power cabinet ([kW], one sample every ~2nd second). The second one is the price ([local currency / kWh]), 2-3 samples every hour.
My intention is to calulate the total cost for a given time range (multiplying consumption and price, and probably integrate under that curve/graph?).
from(bucket: "amsdata")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "consumption")
  |> filter(fn: (r) => r["_field"] == "kW")
  |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)
  |> yield(name: "mean")

from(bucket: "amsdata")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "spotprice")
  |> filter(fn: (r) => r["_field"] == "price")
  |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)
  |> yield(name: "mean")

Power consumption and price
I will appreciate your help :)


text:
Q: Pytest fixture returning multiples Is it possible to have a fixture that returns a dictionary and dataframe?
import somefile
import pytest

@pytest.fixture()
def setup():
    dictionary, dataframe = somefile.get_Di_And_Df()
    return(dictionary, dataframe)

def test_check(setup):
    assert dictionary['movie']['action'] == 'Avengers'
    assert dataframe.shape[0] == 5

A: The return value (or yield value) of the fixture is literally the object injected as a function argument during test execution:
def test_check(setup):
    dictionary, dataframe = setup
    assert dictionary['movie']['action'] == 'Avengers'
    assert dataframe.shape[0] == 5

A: The most readable way is to return a namedtuple in the fixture:
from collections import namedtuple

import somefile
import pytest

@pytest.fixture()
def setup():
    dictionary, dataframe = somefile.get_Di_And_Df()
    return namedtuple("Setup", "dictionary dataframe")(dictionary, dataframe)

def test_check(setup):
    assert setup.dictionary['movie']['action'] == 'Avengers'
    assert setup.dataframe.shape[0] == 5

A: you could mock the called method
@patch("somefile.get_Di_And_Df", MagicMock=(return_value=(dictionary, dataframe)))
def test_check():
  _dict, _df = somefile.get_Di_And_Df()
  assert _dict['movie']['action'] == 'Avengers'
  assert _df.shape[0] == 5


text:
Q: Is there a way to skip a URL (Json file) when I don't have access or there is no information available I am running a function that retrieves JSON files from individual URLs. However, some of the files no longer exist or I don't have access (webpage showing only "Unauthenticated"). Either way, there is no available information on that URL. I realise the if and else below make no sense but I have included it to show what I am trying to do.
def data (ticker):
    url = "https://eodhistoricaldata.com/api/fundamentals/{ticker}.LSE?api_token".format(ticker=ticker)

    with requests.get(url, verify=True) as response:
        data = response.json()

    if len(data)>1:
        print (data)

    else:
        skip

A: You can check the status code and decide what to do in each case. For example:
def data(ticker):
    url = "https://eodhistoricaldata.com/api/fundamentals/{ticker}.LSE?api_token".format(ticker=ticker)

    with requests.get(url, verify=True) as response:
        if response.status_code == 401:
            print("Not authorized")
        elif response.status_code == 404:
            print("Not found")
        else:
            data = response.json()
            # your logic

You can explore the response object and use it to define more fine grained behaviour (for example: use the reason attribute or print the content of the response).


text:
Q: Ubuntu and proxy I have Ubuntu 15.10 and I can't get updates using sudo apt-get. I tried setting up a proxy using GUI settings and using this command in the terminal:
export http_proxy="http://user:password@host:port

Yet nothing is working. Any ideas?

A: Create an empty file on "/etc/apt/apt.conf"
Edit "apt.conf" file and add the below lines
Acquire::http::proxy "http://admin:proxyusername@192.168.0.1:3128/";
Acquire::ftp::proxy "ftp://admin:proxyusername@192.168.0.1:3128/";
Acquire::https::proxy "https://admin:proxyusername@192.168.0.1:3128/";
Once all done restart squid or squid3 services. and try to update


text:
Q: Debugging PHP application after exit is called I have a PHP application that is using a very modest amount of memory until exit is called; at which point the memory usage spikes dramatically causing a fatal error due to exceeding the memory limit.
Is there any way to debug what the application/PHP is doing after exit is called? Alternatively, are there any common reasons for a massive increase in memory to occur at this time? The output buffers are empty when the script is terminated.

A: You can register a shutdown function that will be executed when your script terminates, and that can be used to log memory usage, but I'm not sure how helpful it will be.
Do you have any unusual object __destruct() methods that might be grabbing memory as objects are destroyed? e.g. data writers.

A: If you have a loop and for some logical reason it becomes an infinite loop, depending upon operations inside the loop e.g. mathematical operations, assignments etc, there can also be an increase in memory consumption.


text:
Q: how to get javascript function on click on button onclick on assign to rm button , I want to get on rm names listed as a dropdown
my view,
gu_rent_property_list.html.erb
<% @properties.each do |property| %>
    <%= button_tag "Assign To Rm" type: 'button', onclick: "update_subscategories_div(<%=property.category_id%>)", class: 'btn btn-default'%>
<% end %>`

Iam getting syntax error for this.
Any help is appreciable.

A: You are using erb the wrong way. The solution is simple:
<% @properties.each do |property| %>
    <%= button_tag "Assign To Rm", type: 'button', onclick: "update_subscategories_div(#{property.category_id})", class: 'btn btn-default'%>
<% end %>


text:
Q: Short sci-fi film about a robot who saves a blind little girl? Probably less than 10 years old – a little girl is on a planet inhospitable to human life and a medical AI helps her from orbit. I saw it on YouTube, can't find it now searching on "blind girl medical robot" and maybe it is no longer there.
What is interesting/touching is the robot is itself damaged and its normal function is to directly do medical procedures but it (as of course in many stories) is able to do more than originally intended,


text:
Q: beginner help wth python I am trying my first steps with python and json and hope you can halp me with this.
I am getting a json in a variable which looks like this:
host10=[{'hostid': '10084', 'proxy_hostid': '0'},
 {'hostid': '10085', 'proxy_hostid': '1'}]

when I run
hosts = json.loads(host10)
  print(hosts)

I am getting the error:
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not list

what do I wrong?

A: you can find your answer  here
import json
json.dumps(list_name)


text:
Q: What is TaskTooLargeError in GAE? I am surprised to see this error (and not even documented in the quotas)...
Exceeding 100KB, I get this error:
TaskTooLargeError: Task size must be less than 102400

Any ideas on how to handle this?
The context: the body of emails (HTML) are being passed as arguments to a task queue.

A: You should store the body of the html  in the datastore and then pass the key of that entity to the task.
The same approach is taken if you have an instance of a Model that you want to pass to a task.  You normally pass the key of the entity, and the task can then fetch it.
Normally if I want to defer a method as a task I create a classmethod for an entity that takes the key as an argument, then it fetches the object, and then calls the actual method of the object.  The I can either call the method direct on the entity, or deferr things when needed.
e.g.
@classmethod
def defer_cancel_supervisor(cls,contract_key):

    contract = qtrack.models.Contract.get(db.Key(contract_key))
    contract.cancel_supervisor('contract cancelled')


text:
Q: How do I convert this corpus of words from an online book into a term document matrix? Here is a snippet of my code:
library(gutenbergr)
library(tm)
Alice <- gutenberg_download(c(11))
Alice <- Corpus(VectorSource(Alice))
cleanAlice <- tm_map(Alice, removeWords, stopwords('english'))
cleanAlice <- tm_map(cleanAlice, removeWords, c('Alice'))
cleanAlice <- tm_map(cleanAlice, tolower)
cleanAlice <- tm_map(cleanAlice, removePunctuation)
cleanAlice <- tm_map(cleanAlice, stripWhitespace)
dtm1 <- TermDocumentMatrix(cleanAlice)
dtm1

But then I receive the following error:
<<TermDocumentMatrix (terms: 3271, documents: 2)>>
Non-/sparse entries: 3271/3271
Sparsity           : 50%
Error in nchar(Terms(x), type = "chars") :
  invalid multibyte string, element 12

How should I deal with this? Should I convert the corpus into a plain text document first? Is there something wrong with the text format of the book?

A: Gutenbergr returns a data.frame, not a text vector. You just need to slightly adjust your code and it should work fine. Instead of VectorSource(Alice) you need VectorSource(Alice$text)
library(gutenbergr)
library(tm)

# don't overwrite your download when you are testing
Alice <- gutenberg_download(c(11))

# specify the column in the data.frame
Alice_corpus <- Corpus(VectorSource(Alice$text))
cleanAlice <- tm_map(Alice_corpus, removeWords, stopwords('english'))
cleanAlice <- tm_map(cleanAlice, removeWords, c('Alice'))
cleanAlice <- tm_map(cleanAlice, tolower)
cleanAlice <- tm_map(cleanAlice, removePunctuation)
cleanAlice <- tm_map(cleanAlice, stripWhitespace)
dtm1 <- TermDocumentMatrix(cleanAlice)
dtm1

<<TermDocumentMatrix (terms: 3293, documents: 3380)>>
Non-/sparse entries: 13649/11116691
Sparsity           : 100%
Maximal term length: 46
Weighting          : term frequency (tf)

P.S. you can ignore the warning messages in the code.


text:
Q: Windows Won't Start - Help Analyzing CBS.log please Good day,
Helping a friend with Windows load issue where I'm receiving STOP: c000021a error blue screen of death while Windows is loading.  Following online instructions, I've run sfc /scannow operation and have a CBS.log but don't know what it means and what I need to do to fix it.  I'm hoping someone can take a look at this and advise how to repair.  Of particular note, I see the repetitive entry "CSI    000000b2 [SR] Cannot repair member file [l:18{9}]"winpe.bmp" ....." I have manually replaced the file but still no joy.
Due to the character count limitation of stack exchange, here is the external link to the log file:
http://www.phoeteo.com/CBSlog.txt
Computer is a Toshiba Satellite laptop running Windows 7 (Microsoft Windows [Version 6.1.7600])
Any and all help is greatly appreciated.


text:
Q: Constructor reference - no warning when generics array is created In Java, it's not possible to create an array of generic type directly:
Test<String>[] t1 = new Test<String>[10]; // Compile-time error

However, we can do this using raw type:
Test<String>[] t2 = new Test[10]; // Compile warning "unchecked"

In Java 8, it's also possible to use a constructor reference:
interface ArrayCreator<T> {
    T create(int n);
}

ArrayCreator<Test<String>[]> ac = Test[]::new; // No warning
Test<String>[] t3 = ac.create(10);

Why doesn't the compiler display the warning in the last case? It still uses raw type to create the array, right?

A:
It still uses raw type to create the array, right?

Java generics are just a compile-time illusion, so the raw type will of course be used at runtime to create the array.

Why doesn't the compiler display the warning in the last case?

Yes, the unchecked cast from Test[] to Test<String>[] is still happening; it's just happening behind the scenes in an anonymous context.
Test<String>[] t3 = ((IntFunction<Test<String>[]>) Test[]::new).apply(10);

Since the anonymous method is doing the dirty work, the unchecked cast effectively disappears from the managed code.

A: Your question is justified. In short, the method reference does indeed use the raw type (or should use the raw type) and the reason, why the creation of generic arrays is forbidden, still applies when using method references, hence, being able to silently create a function creating a generic array clearly violates the intention of the language design.
The reason why the creation of generic array is forbidden, is that the array type inheritance, stemming from a pre-Generics era, is incompatible with the generic type system. I.e. you can write:
IntFunction<List<String>[]> af = List[]::new; // should generate warning
List<String>[] array = af.apply(10);
Object[] objArray = array;
objArray[0] = Arrays.asList(42);
List<String> list = array[0]; // heap pollution

At this place, it must be emphasized that contrary to some answers here, the compiler does not perform type inference on the expression List[]::new to deduce the generic element type List<String>. It's easy to prove that generic array creation still is forbidden:
IntFunction<List<String>[]> af = List<String>[]::new; // does not compile

Since List<String>[]::new is illegal, it would be strange if List[]::new was accepted without a warning, by inferring it to be effectively the illegal List<String>[]::new.
JLS §15.13 clearly states:

If a method reference expression has the form ArrayType :: new, then ArrayType must denote a type that is reifiable (§4.7), or a compile-time error occurs.

This already implies that List<String>[]::new is illegal, because List<String> is not reifiable, whereas List<?>[]::new is legal, as List<?> is reifiable, and List[]::new is legal if we consider List to be a raw type, as the raw type List is reifiable.
Then §15.13.1 states:

If the method reference expression has the form ArrayType :: new, a single notional method is considered. The method has a single parameter of type int, returns the ArrayType, and has no throws clause. If n = 1, this is the only potentially applicable method; otherwise, there are no potentially applicable methods.

In other words, the behavior of the List[]::new expression above is the same as if you had written:
    IntFunction<List<String>[]> af = MyClass::create;
…
private static List[] create(int i) {
    return new List[i];
}

except that the method create is only notional. And indeed, with this explicit method declaration, there are only raw type warnings at the create method, but no unchecked warnings regarding the conversion of List[] to List<String>[] at the method reference. So it's understandable, what happens in the compiler in the List[]::new case, where the method using raw types is only notional, i.e. doesn't exist in source code.
But the absence of unchecked warnings is a clear violation of JLS §5.1.9, Unchecked Conversion:

Let G name a generic type declaration with n type parameters.
There is an unchecked conversion from the raw class or interface type (§4.8) G to any parameterized type of the form G<T₁,...,Tₙ>.
There is an unchecked conversion from the raw array type G[]ᵏ to any array type of the form G<T₁,...,Tₙ>[]ᵏ. (The notation []ᵏ indicates an array type of k dimensions.)
Use of an unchecked conversion causes a compile-time unchecked warning unless all type arguments Tᵢ (1 ≤ i ≤ n) are unbounded wildcards (§4.5.1), or the unchecked warning is suppressed by the SuppressWarnings annotation (§9.6.4.5).

So, a conversion of List[] to List<?>[] is legal, as List is parameterized with an unbounded wildcard, but the conversion from List[] to List<String>[] must produce an unchecked warning, which is crucial here, as the use of List[]::new does not produce the raw type warning that appears with an explicit creation method. The absence of raw type warnings seems not to be a violation (as far as I understood §4.8) and it wouldn't be a problem, if javac created the required unchecked warning.

A: The best that I can come up with is that the JLS specifies that a method reference to the constructor of a generic type infers the generic parameters:
"If a method or constructor is generic, the appropriate type arguments may either be inferred or provided explicitly." Later it gives ArrayList::new as an example and describes it as "inferred type arguments for generic class," thus establishing that ArrayList::new (and not ArrayList<>::new) is the syntax that infers arguments.
Given a class:
public static class Test<T> {
    public Test() {}
}

this gives a warning:
Test<String> = new Test(); // No <String>

but this doesn't:
Supplier<Test<String>> = Test::new; // No <String> but no warning

because Test::new implicitly infers the generic arguments.
So I assume that a method reference to an array constructor works the same way.


text:
Q: What is a "yield" statement in a function?
Possible Duplicate:
The Python yield keyword explained

Can someone explain to me what the yield statement actually does in this bit of code here:
 def fibonacci():
     a, b = 0, 1
     while True:
         yield a
         a, b = b, a+b

for number in fibonacci():  # Use the generator as an iterator; print number
What I understand so far is, we are defining a function finonacci(), with no parameters?
inside the function we are defining a and b equal to 0 and 1, next, while this is true, we are yielding a. What is this actually doing? Furthermore, while yielding a? a is now equal to b, while b is now equal to a + b.
Next question, for number in fibonacci(), does this mean for every number in the function or what? I'm equally stumped on what yield and 'for number' are actually doing. Obviously I am aware that it means for every number in fibonacci() print number. Am I actually defining number without knowing it?
Thanks, sorry if I'm not clear. BTW, it's for project Euler, if I knew how to program well this would be a breeze but I'm trying to learn this on the fly.

A: When the code calls fibonacci a special generator object is created. Please note, that no code gets executed - only a generator object is returned. When you are later calling its next method, the function executes until it encounters a yield statement. The object that is supplied to yield is returned. When you call next method again the function executes again until it encounters a yield. When there are no more yield statements and the end of function is reached, a StopIteration exception is raised.
Please note that the objects inside the function are preserved between the calls to next. It means, when the code continues execution on the next loop, all the objects that were in the scope from which yield was called have their values from the point where a previous next call returned.
The cool thing about generators is that they allow convenient iteration with for loops.
The for loop obtains a generator from the result of fibonacci call and then executes the loop retrieving elements using next method of generatior object until StopIteration exception is encountered.

A: Generators have a special property of being iterables which do not consume memories for their values.
They do this by calculating the new value, when it is required while being iterated.
i.e.
def f():
    a = 2
    yield a
    a += 1

for ele in f():
    print ele

would print
 2

So you are using a function as an iterable that keeps returning values.
This is especially useful when you require heavy memory usage, and so you cannot afford the use of a list comprehension
i.e.
li = [ele*10 for ele in range(10)]

takes 10 memory spaces for ints as a list
but if you simple want to iterate over it, not access it individually
it would be very memory efficient to instead use
def f():
    i=0
    while i<10
        yield i*10
        i += 1

which would use 1 memory space as i keeps being reused
a short cut for this is
ge = (i*10 for i in range(10))

you can do any of the following
for ele in f():

for ele in li:

for ele in ge:

to obtain equivalent results

A: Using yield makes the function a generator.
The generator will continue to yield the a variable on each loop, waiting until the generator's next() method is called to continue on to the next loop iteration.
Or, until you return or StopIteration is raised.
Slightly modified to show use of StopIteration:
>>> def fib():
...     a = 0
...     b = 1
...     while True:
...         yield a
...         a = b
...         b += a
...         if a > 100:
...             raise StopIteration
...
>>>
>>> for value in fib():
...     print value
...
0
1
2
4
8
16
32
64
>>>

>>> # assign the resulting object to 'generator'
>>> generator = fib()
>>> generator.next()
0
>>> generator.next()
1
>>> for value in generator:
...     print value
...
2
4
8
16
32
64
>>>

A: This answer is a great explanation of the yield statement, and also of iterators and generators.
Specifically here, the first call to fibonaci() will initialize a to 0, b to 1, enter the while loop and return a.
Any next call will start after the yield statement, affect b to a, a+b to b, and then go to the next iteration of the while statement, reach again the yield statement, and return a again.


text:
Q: Python сколько осталось дней,мин,сек от даты до даты У меня есть две даты: текущая и нового года.
Понятно, что через модуль datetime в Python 3 можно вычитать эти даты и получить новую, но каким образом можно рассчитать количество времени до нового года в секундах, днях, минутах, часах и т. д.
Пример:
До нового года: 60 дней 22 часа 45 мин 12 сек.

A: почему бы не посмотреть что получится, если вычитать эти даты.
А получится объект класса timedelta, который и содержит то, что вам надо
now = datetime.datetime.today()
NY = datetime.datetime(2020,1,1)
d = NY-now #  str(d)  '83 days, 2:43:10.517807'
mm, ss = divmod(d.seconds, 60)
hh, mm = divmod(mm, 60)
print('До нового года: {} дней {} часа {} мин {} сек.'.format(d.days, hh, mm, ss))
# До нового года: 83 дней 2 часа 43 мин 10 сек.


text:
Q: Multi select html inserting multi values into database I'm working on a category section for stories submitted to my website. I have a html select going on in my html and I have that submitting to the database using codeigniter functions. It is submitting to the database, but there seems to be a small problem...the select is only grabbing the last value that is selected. I need to have all the values that are selected entered into the database so I can pull them out at a later date.
This is the html I am using.
<select multiple class="multi" name="wGenre">
                  <option value="Action/Adventure">Action/Adventure</option>                      <option value="Angst">Angst</option>
                  <option value="Crime">Crime</option>
</select>

and then this is what I have in my model.
$this->title = $this->input->post('wTitle');
$this->genre = $this->input->post('wGenre');
$this->db->insert('story_tbl', $this);

Now, I believe the problem is with my database. I originally set up the field as an enum, but that won't work because it's either one or the other selection and I need to have multiples. So then I tried it as a text field, and it's just not grabbing everything. To be honest I'm at a loss and in need of some help. :)

A: Firstly you need to make sure the select tag is named the array manner:
<select multiple="multiple" class="multi" name="wGenre[]">

Then To get all values of the multiple select you could do the following to save the values in an array!
$this->title = $this->input->post('wTitle');
$select_vals = array();
foreach($this->input->post('wGenre') as $val){
    $val.' - '; // Used as a delimiter for later use
    array_push($select_vals, $val);
}
$this->genre = $select_vals;
$this->db->insert('story_tbl', $this);

A: I ended up solving this without a foreach loop.
First of all, I was writting my html select tag wrong. For it to select multiple values you have to add both [] at the end of the class and a muti tag...like this.
<select multiple="multiple" class="multi" name="wGenre[]">

and then in the php it has to be json encoded to be placed in the database correctly...like this...
$this->genre = json_encode($this->input->post('wGenre'));

Thank you for all your help! I hope this helps someone else in the future! :)


text:
Q: How to mock uuid with Jest so on my search for an answer to my problem I found this post: Jest: How to globally mock node-uuid (or any other imported module)
I already tried the answer but I can't seem to use it properly, as it´s giving me an undefined error. I'm new to the testing scene so please excuse any major errors:
This was my first approach
const mockF = jest.mock('uuid');

mockF.mockReturnValue('12345789');

But it wouldn't recognize the functions.

"mockF.mockReturnValue is not a function" among others I tried.

Then I tried to manually mock as the post suggested but can' seem to make it work, can you help me? Thanks
Here's the entire test if it helps:
    const faker = require('faker');
    const storageUtils = require('../../storage/utils');
    const utils = require('../utils/generateFile');
    const { generateFileName } = storageUtils;
    const { file } = utils;

    test('should return a valid file name when provided the correct information', () => {
        // ARRANGE
        // create a scope
        const scope = {
            type: 'RECRUITER',
            _id: '987654321',
        };
        // establish what the expected name to be returned is
        const expectedName = 'r_987654321_123456789.png';

        jest.mock('uuid/v4', () => () => '123456789');

        // ACTION
        const received = generateFileName(file, scope);

        // ASSERT
        // expect the returned value to equal our expected one
        expect(received).toBe(expectedName);
    });

A: Assuming the following test file, you can use the jest.spyOn call to mock out uuid.
Test.spec.js
import uuid from 'uuid';
import testTarget from './testTarget';

describe('mock uuid', () => {
  it('should return testid }', () => {
    // Arrange
    const anonymousId = 'testid';
    const v1Spy = jest.spyOn(uuid, 'v1').mockReturnValue(anonymousId);

    // Act
    const result = testTarget();

    // Assert
    expect(result).toEqual(anonymousId);
    expect(v1Spy).toHaveBeenCalledTimes(1);
  });
});

testTarget.js
import uuid from 'uuid';
export default function() {
   return uuid.v1();
}

A: You can have problems if you put jest.mock('uuid') in wrong scope.
This is correct for me:
import * as uuid from 'uuid';
jest.mock('uuid');
describe('utils', () => {
    it('test', () => {
        jest.spyOn(uuid, 'v4').mockReturnValue('mockedValue')
    });
});

and this is incorrect:
import * as uuid from 'uuid';
describe('utils', () => {
    it('test', () => {
        jest.mock('uuid');
        jest.spyOn(uuid, 'v4').mockReturnValue('mockedValue')
    });
});

A: Hopefully the following two examples will be helpful.
Say you need a JS module whose sole resposibility is to generate UUIDs.
Taking a TDD approach we start with an assertion and eventually see we need some UUIDGenerator with some method to return UUIDs:
it('should generate UUID', () => {
    const myUUID = UUIDGenerator.nextUUID();
    expect(myUUID).toEqual('some-short-v4-uuid-0');
});

The test, shapes UUIDGenerator.ts into the following code:
import {v4 as uuidv4} from 'uuid';
const UUIDGenerator = {
  storeUUID(): string {
    return uuidv4();
  }
};
export default UUIDGenerator;

Now we want to mock UUIDGenerator's dependency on the uuid module. We can do this by Calling jest.mock() with the module factory parameter as documented on jestjs.io. We can now simply describe how jest should behave,
jest.mock('uuid',() => ({
    v4: () => 'some-short-v4-uuid-0'
}));
describe('UUIDGenerator', () => {
    // it block from above
});

You should now see you test passing.
The other alternative is to create some uuid.ts somewhere in your project:
import {v4 as uuidv4} from 'uuid';
export default uuidv4;

and import it in UUIDGenerator.ts:
import uuidv4 from '../uuid';

in this case, you should be able to mock your uuid.ts. I placed mine in the parent directory (relative to UUIDGenerator.ts) so you can see an example on how to find it when not in the same directory.
jest.mock('../uuid',
  () => jest.fn(() => '1-234-5678')
);

A: This works for me
import { v1 as uuidv1 } from 'uuid';

jest.mock('uuid');

... # (somewhere on your test suite)

uuidv1.mockImplementationOnce(() => {
  return 'uuid-123';
});

A: I had the same issue/challenge today.
In the end my solution looks like this.
Code (usage):
import { v4 as uuidv4 } from 'uuid';
...
const uuid = uuidv4();
...

Test:
jest.mock('uuid', () => ({ v4: () => 'adfd01fb-309b-4e1c-9117-44d003f5d7fc' }));
...
describe('Test Foo', () => {
  ...
});

IMPORTANT:
You need to mock it before the first "describe" block.

A: Mock it by using mockImplementation.
import uuid from 'uuid/v4';
jest.mock('uuid/v4');

describe('mock uuid', () => {
  it('should return testid }', () => {
    uuid.mockImplementation(() => 'testid');
    ...
  });
});

Make sure you import uuid correctly (with correct version reference e.g. v4, v3...)

A: I figure I might as well add my solution here, for posterity. None of the above was exactly what I needed:
jest.mock('uuid', () => ({ v4: () => '123456789' }));

By the way, using a variable instead of '123456789' breaks it.
This should be mocked where we have the imports and it does not require you to explicitely import uuid in your spec file.

A: This worked for me.  In my case I only wanted to verify that the function was called rather than asserting on a specific value.
import * as uuid from 'uuid';
jest.mock('uuid');

const uuidSpy = jest.spyOn(uuid, 'v4');

// in a test block
expect(uuidSpy).toHaveBeenCalledTimes(1);

A: for my case I used the answer of this Github issue
jest.mock('uuid/v4', () => {
 let value = 0;
 return () => value++;
});

A: this worked for me (I'm using typescript, you can remove the as blablabla if you aren't):
jest.mock('uuid', () => ({
  v4: jest.fn(),
}));
const mockUuid = require('uuid') as { v4: jest.Mock<string, []> };

beforeEach(() => {
  mockUuid.v4.mockImplementationOnce(
    () => 'your-mocked-id',
  );
});

https://github.com/facebook/jest/issues/2172#issuecomment-756921887

A: I am using typescript and this worked for me.
jest.mock('uuid', () => {
  return {
    __esModule: true,
    v4: jest.fn().mockReturnValue('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'),
  };
});

describe("Test suit", () => {
// your tests
});

A: This actually works
jest.mock('uuid', () => {
  const originalModule = jest.requireActual('uuid');
  return {
    __esModule: true,
    ...originalModule,
    v4: jest.fn(() => '634b59eb-dc11-48f0-ad46-ca2d85ef2a9d')
  };
});

However, you have to define this on top of your testing file. Not in beforeAll().
See mock functions in jest for more information.

A: import uuid from 'uuid'

describe('some test', () => {
  it('some test 1', () => {
     const uuidMock = jest.spyOn(uuid, 'v4').mockReturnValue('123434-test-id-dummy');

     // expect(uuidMock).toHaveBeenCalledTimes(<number of times called>);

  })
})

A: As per this answer: How do I write test case for a function which uses uuid using jest?
You can use jest.mock inorder to mock the import of uuid, like that:
const uuidMock = jest.fn().mockImplementation(() => {
    return 'my-none-unique-uuid';
});
jest.mock('uuid', () => {
    return uuidMock;
});

The only caveat of that approach is that you need to apply the mock in the test file before you are importing your real file.
Then you will even able to assert on the mock.

A: Nothing above worked until I brute forced it for using uuid npm package's v4 method:
import { v4 } from 'uuid'

jest.mock('uuid', () => ({
    v4: jest.fn(),
}))

beforeEach(() => {
  ;(v4 as jest.Mock).mockReturnValue('mock-uuid-1234')
}

afterEach(() => {
  jest.clearAllMocks()
}

Hope this helps.

A: Other answers will solve the issue for you, but I prefer to set the mocked value to a variable so you aren't copy/pasting a hard-coded string all over your tests.
const mockUUID = 'mocked-uuid'
jest.mock('uuid', () => ({ v4: () => mockUUID }))

The important thing to note is that you must start the variable name with mock for it to work properly. More info can be found here: https://jestjs.io/docs/es6-class-mocks#calling-jestmock-with-the-module-factory-parameter

A: It's really well explained in the documentation, but in general you can:
const mockF = jest.fn().mockReturnValue('12345789');

or
import uuid from 'uuid';
jest.mock('uuid', () =>
    jest.fn().mockReturnValue('12345789');
);


text:
Q: Create a random number between the max and min ID I need to create three random id between the max ID of the table and the min ID of the table. How can I do that in Sql?

A: You need to use two variables to store Min and Max primary keys. let's say @a and @b.
then using below query you can get your random number
declare @a int,@b int
select @b=max(id),@a=min(id)
from  mytbl

SELECT FLOOR(RAND()*(@b-@a)+1)


text:
Q: What's the Widget name for in flutter it's been a while since I started to flutter and since then I'm a beginner at it. Today I've come across some really cool and nice widgets which I can't seem to find anywhere on the internet since I don't even know their names. So, as an example, I'm showing the picture of it. I just need to know the name of this widget.

You can clearly see that there's some sort of progress indicator but with a totally different look and feel and it's connected through smaller circles as well.
THANKS

A: Welcome to Flutter
This UI Component is referred as Stepper, in this link you would find a lot of Flutter packages that provide a ready made widget for it.


text:
Q: Why is this C# function behaving like I'm using pointers? So I've got this code I'm writing in C#. It's supposed to reverse the order of bits in a bit array (not invert them). Through heavy use of breakpoints and watches, I've determined that the function is somehow modifying both the input parameter array array and the array I copied that into in an attempt to make the function NOT change the input array, tempArray.
static BitArray reverseBits(BitArray array)
    {
        BitArray tempArray = array;
        int length = tempArray.Length;
        int mid = length / 2;

        for (int i = 0; i < mid; i++)
        {
            bool tempBit = tempArray[i];
            tempArray[i] = tempArray[length - 1 - i]; //the problem seems to be happening
            tempArray[length - 1 - i] = tempBit;      //somewhere in this vicinity
        }

        return tempArray;
    }

I have no idea why it's behaving like this. Granted, pointers were never my strong suit, but I do try to avoid them whenever possible and they don't seem to be used much at all in c#, which is why I'm puzzled about this behavior.
TL;DR:  if you pass my function 00000001, you'll be returned 10000000 from the function AND the array that was passed from the outside will be changed to that as well
P.S. this is for a FFT related task, thats why I'm bothering with the bit reversal at all.

A: I believe you want to create a new instance of a BitArray like this:
BitArray tempArray = new BitArray(array);

This should create a new instance of a BitArray instead of creating another variable referencing the original array.

A: You haven't copied the array, you've just assigned it to another variable.
BitArray is a class, and so is always passed by reference (similar to pointers in C/etc).
If you want to copy the array, use the .CopyTo method.

A: Maybe this Byte similar function could help you
        /// <summary>
        /// Reverse bit order in each byte (8 bits) of a BitArray
        /// (change endian bit order)
        /// </summary>
        public static void BytewiseReverse(BitArray bitArr)
        {
            int byteCount = bitArr.Length / 8;
            for (int i = 0; i < byteCount; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    bool temp = bitArr[i * 8 + 7 - j];
                    bitArr[i * 8 + 7 - j] = bitArr[i * 8 + j];
                    bitArr[i * 8 + j] = temp;
                }
            }
        }


text:
Q: Intel compiler flags for single core usage I noticed what seems to me a surprising behaviour with a fortran code mostly containing matrix/matrix and matrix/vector multiplications.
Initially, the code was compiled with gfortran and multiplications were carried out with double "DO" loops on lines and columns of matrices. I compiled the code using:
gfortran -c -g -O3 ...

Execution of the code was using a single core of an 8-core i7 processor.
I then compiled my code with the intel compiler using:
ifort -c -g -O3 ...

The code ran significantly faster still using a single core. I then decided to optimize the code using the well-known dgemm and dgemv functions respectively for matrix/matrix and matrix/vector multiplications.
I then compiled using:
ifort -c -g -O3 ...

The resulting code is working properly, but uses 8 cores of my i7-processor without any significant performance improvement. Is there a way to control the number of cores used by my code from the compilation command ?

A: The compiler itself is not generating any parallel code. But the Intel Math Kernel Library (MKL) (where DGEMM and friends live) does automatic parallelization and CPU dispatch.
The MKL documentation says this:

Use the following techniques to specify the number of OpenMP threads to use in Intel MKL:
Set one of the OpenMP or Intel MKL environment variables:
  OMP_NUM_THREADS
  MKL_NUM_THREADS
  MKL_DOMAIN_NUM_THREADS
Call one of the
  OpenMP or Intel MKL functions:
  omp_set_num_threads()
  mkl_set_num_threads()
  mkl_domain_set_num_threads()
  mkl_set_num_threads_local()


text:
Q: includeSystemScope Parameter in pom.xml not working I'm tring to include a custom jar in my Spingboot application. In my case the additional jar contains a custom font for jasper Report.
This is my "system" decendency
    <dependency>
        <groupId>jasperFontOverrides</groupId>
        <artifactId>jasperFontOverrides</artifactId>
        <version>1.0.0</version>
        <scope>system</scope>
        <systemPath>${basedir}/lib/MyriadPro.jar</systemPath>
    </dependency>

...
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <includeSystemScope>true</includeSystemScope>
            </configuration>
        </plugin>
    </plugins>
</build>

The system package is visible while I debug my application in my IDE but when I'm done and I what to generate the package for production deploy
mvn install -DskipTests

My system package is not included the final jar.
Is there anything missing in my maven configuration?

A: If this is a multi-module project, you probably need to define the configuration section in the parent pom.
<configuration>
   <includeSystemScope>true</includeSystemScope>
</configuration>

I have spent almost a day debugging this and it seems the configuration set in the child pom is not enough to get this to work. My guess is that the dependencies are calculated early in the build and the includeSystemScope option set in the child module is processed too late to be applied.


text:
Q: Trying to append a function with jquery, It didn't append. Why? I know this is a very basic question but I really find it hard to solve.
I can't append this $(".gantt")
$("#gant_chart").append($(".gantt").gantt({

        source: [{
            name:  maintasks_val.task_name,
            desc: "",
            values: [{
                from: "/Date("+maintasks_val.time_start+")/",
            to: "/Date("+maintasks_val.time_end+")/",
            label: maintasks_val.task_name,
            customClass: "ganttRed"
        }],
}); );

I know there's something wrong in it. I think I cant append like that. Is there any other solution for this?
thanks in advance for those who answers.

A: Try using, say,  .each after the append then apply the - .gant
$(".gantt").appendTo($("#gant_chart")).each(function() {

    $(this).gant( ...
    /* apply the '.gant' to 'each' '.gant' that was 'appendedTo' '#gant_chart' */

Update: Another more stepped version for all '.gant' elements, regardless of where they are ( appended ) in the DOM
/* first append */
  var _gants = $(".gant");
  $("#gant_chart").append(_gants);

/* then apply '.gant'  */
   _gants.gant({ ...

You were infact trying to 'append' the function return ( that may not be a node / or jquery object) - thanks to @undefined for clearing some possible confusion here

Update : Using .appendTo() - will return the .gant nodes you want, so you can make use of $(this)


text:
Q: PHP Help Building Multi-Dimensional Array in For Loop I am newish to PHP and web development.  I am struggling a bit on how to best program this multi-dimensional array in PHP using for loops.
Essentially, it is a review website.  I am using Bootstrap to render the data in different tabs.  The data is being called via a jquery ajax request and the PHP page is returning JSON.  Handlebars is being used to render the data in a template.
In the end, I'd like to send the data in roughly this format:
{
    review: {
        reviewstotal: INT,
        count: INT,
        summary: {
            //iterated
            tab: INT,
            [{
                Question:,
                Value:,
                Color: ,
                Percent:,
            },
            {
                Question:,
                Value:,
                Color: ,
                Percent:,
            }]
        }
    }
}

Where I'm struggling is at the "summary" section.  The "Questions" are in an array, and I have the "Values" as another array.  The color value would come from an if statement checking the "Value" and set a css value in the template. The percent is the "Value" multiplied by 10.  Here is what I have so far to generate the array.
$array = array();
$color ="";

for ($x = 0; $x <= 5; $x++) {
    $summary= [];

    if ( ${"q{$x}"} <= 40){
      $color = "danger";
    } else if ( ${"q{$x}"} >= 70){
      $color = "success";
    } else {
      $color = "warning";
    }

    $summary = array_push ($array, $aquest[$x], ${"q{$x}"}, $color, ${"q{$x}"}*10);
}

What I get as output is:
"summary": ["The facilities of the school adequately provide for a positive learning/working experience.",null,"danger",0,
"School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc.)","9.50","danger",95,
"School is well funded to provide students and faculty with adaquate materials to support their course offering.","9.50","danger",95,
"Parent community is actively involved in supporting the school's mission and their child's education endeavors.","9.00","danger",90,
"Classroom student to teacher ratios are kept low.","8.75","danger",87.5,null,"7.63","danger",76.3]

What I am trying to achieve though is that each "Question" section is wrapped in it's own array.  Like:
"summary": [["The facilities of the school adequately provide for a positive learning/working experience.",null,"danger",0],
["School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc.)","9.50","danger",95],
["School is well funded to provide students and faculty with adequate materials to support their course offering.","9.50","danger",95],
["Parent community is actively involved in supporting the school's mission and their child's education endeavors.","9.00","danger",90],
["Classroom student to teacher ratios are kept low.","8.75","danger",87.5,null,"7.63","danger",76.3]]

And then I can add a consistent key to each of them.

A: You shall try the following -
$array = array();
$color ="";

//taking this out from the scope of loop
$summary= [];
for ($x = 0; $x <= 5; $x++) {

if ( ${"q{$x}"} <= 40){
  $color = "danger";
} else if ( ${"q{$x}"} >= 70){
  $color = "success";
} else {
  $color = "warning";
}

//this is where the diference lies. $summary is a multi-dimension array.
//which means, each element of that array is an array itself.
//So this is how we represent such stuff in php.
//Element at index $x, is also defined as an array with keys containing the
//required values.
$summary[$x] = array(
       "text" => $aquest[$x],
       "somekey1" => ${"q{$x}"},
       "somekey2" => $color,
       "somekey3" => ${"q{$x}"}*10
 );
}

//here you can print the summary.
print_r( $summary)

A: You're wanting to add arrays to an array, but currently you're adding variables to an array. So, you need to wrap $aquest[$x], ${"q{$x}"}, $color, ${"q{$x}"}*10 in an array.
$array = array();
$color ="";

for ($x = 0; $x <= 5; $x++) {
    $summary= [];

    if ( ${"q{$x}"} <= 40){
      $color = "danger";
    } else if ( ${"q{$x}"} >= 70){
      $color = "success";
    } else {
      $color = "warning";
    }

    $summary = array_push ($array, array($aquest[$x], ${"q{$x}"}, $color, ${"q{$x}"}*10));
}


text:
Q: FactoryBot attributes seems to be invisible to method On my test I have factories like this:
Spec.feature 'Estabelecimentos', type: :feature, js: true, inspector: true, feature: true do
  given!(:estado) { create(:estado) }
  given!(:cidade) { create(:municipio) }
  given!(:endereco) { create(:endereco) }
  given!(:grupo) { create(:grupo) }
  given!(:user_admin) { create(:usuario, role: 'ADMIN') }

  before do
    FactoryBot.create(:mcc)
    FactoryBot.create(:modelo_pagamento)
    FactoryBot.create(:supervisor)
    FactoryBot.create(:representante)
    FactoryBot.create(:categoria_estabelecimento)
    FactoryBot.create(:empresa_ancora)
  end

But on mcc.rb, I have:
class Mcc < ApplicationRecord
  audited

  before_save :params_to_uppercase

  def params_to_uppercase
    descricao.upcase!
  end

  def id_desc
    codigo.to_s << " - " << descricao.upcase!
  end
end

I'm creating a mcc using
FactoryBot.create(:mcc)

But this method on mcc.rb:
 def id_desc
    codigo.to_s << " - " << descricao.upcase!
  end

is breaking my test with this error:
 Failure/Error: codigo.to_s << " - " << descricao.upcase!

     ActionView::Template::Error:
       no implicit conversion of nil into String
     # ./app/models/mcc.rb:13:in `id_desc'
     # ./app/views/estabelecimentos/_dados.html.erb:112:in `block in _app_views_estabelecimentos__dados_html_erb___4252541458763635733_70174788728900'
     # ./app/views/estabelecimentos/_dados.html.erb:29:in `_app_views_estabelecimentos__dados_html_erb___4252541458763635733_70174788728900'
     # ./app/views/estabelecimentos/new.html.erb:15:in `_app_views_estabelecimentos_new_html_erb___2421282149664823985_70174788563040'
     # ------------------
     # --- Caused by: ---
     # TypeError:
     #   no implicit conversion of nil into String
     #   ./app/models/mcc.rb:13:in `id_desc'

codigo and descricao are attributes of mcc, so they should be created when I create mcc. my mcc factory on factories.rb:
 factory :mcc do
    id { Mcc.all.order(:id).last.nil? ? 1 : Mcc.all.order(:id).last.id + 1 }
    codigo { 1 }
    descricao { 'MCC TESTE' }
    cnae { 1 }
    created_at { DateTime.now }
    updated_at { DateTime.now }
  end

Is there a way to do this? how can I fix it?

A: Your variables descricao or codigo is nil, the error is in type casting nil to string.
Use binding.pry or byebug to debugger and to search where these variables should be initialized and aren't.

A: Luiz Romário resolved. Just replace:
codigo.to_s << " - " << descricao.upcase!

with
"#{codigo.to_s} - #{descricao.upcase}"


text:
Q: Creating a bootstrap Dockerfile that automatically exposes files to the host operating system I'm trying to create a bootstrap Dockerfile for web development.
I would like any containers to allow for access of my code from within and also from the host operating system (Mac OS X).
I cannot tell from the Docker reference what is the best way of automating this process.

A: Use a volume that mounts the code on the host into the container e.g:
docker run -d -v /Users/me/code:/code IMAGE
You should now find the /Users/me/code is accessible at /code in the container. The boot2docker VM has shared your home directory, so there should be no problem mounting a volume from there.
Refer to the official docs for more information: https://docs.docker.com/userguide/dockervolumes/


text:
Q: why link not displaying content after click on the link? it is displaying content in home.html. but it is not displaying the content(T1.name and T1.address) in index_detail.html after click on T1.name. Django version 4.0.6. The code is below please have a look into it. please solve the issue. Thank you for your time.
Settings.py

from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR=os.path.join(BASE_DIR,"templates")

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-d4@4fwcpkk$6a8ylqjmyhp-9%22t^aizetygwkxzw9s_wu5$&2'

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

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'g6app',
]

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

ROOT_URLCONF = 'g6.urls'

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

urls.py
from django.contrib import admin
from django.urls import path
from g6app.views import V1,V2

urlpatterns = [
path('admin/', admin.site.urls),
path("",V1.as_view(),name="v11"),
path("index/<int:pk>",V2.as_view(),name="index_detail"),
]
  admin.py

from django.contrib import admin
from . models import T1
# Register your models here.
admin.site.register(T1)

  models.py
from django.db import models
from django.urls import reverse

# Create your models here.

    class T1(models.Model):
        name=models.CharField(max_length=100)
        address=models.TextField()

        def __str__(self):
            return self.name

        def get_absolute_url(self):
            return reverse("index_detail",args=[self.pk])

views.py
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import T1
# Create your views here.

class V1(ListView):
    model=T1
    context_object_name="con1"
    template_name="home.html"

class V2(DetailView):
    model=T1
    context_object_name="con2"
    template_name="index_detail.html"

  home.html

<!DOCTYPE HTML>

<meta charset="utf-8">
<title></title>

home page

 {% block context %}
  {% for T1 in con1 %}

{{T1.name}}

{{T1.address}}

  {% endfor %}
 {% endblock context %}

  index_detail.html
<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

detail view page

{% block context %}

{{T1.name}}
]

{{T1.address}}

{% endblock context %}

A: Try to write con2.name and con2.address. Because you are in the index_detail page an you mentioned con2 in view not a T1

A: The data is passed as object to the context, as as con2, so you render this with:
{% block context %}

{{ con2.name }}

{{ con2.address }}

{% endblock context %}
The variable name of home.html is thus not somehow reused: after rendering the template, the context is no longer available. If the user clicks on another link, then it will visit that view, and thus restart the rendering process with a new context.


text:
Q: SET field codes in MS Word calculates a sum instead of keeping text For getting the result in Figure 1, I input the field codes in MS Word as Figure 2. However, the result shows as Figure 3. In fact, I want to store the result "1-3" in the bookmark xxx using the field code SET, and the "1-3" can be updated dynamically. Where is wrong? Why does the result come from subtracting 3 from 1? How to keep the form of "1-3"? How to edit the field codes? Thanks.
Figure1: Objective

Figure2: the field codes in MS Word

Figure3: the result displays

A: I am unsure of the purpose of this.
Using the Set field gives you a bookmark. The contents of that bookmark are not dynamic. Neither the SEQ field nor the StyleRef field will update when the bookmark is referenced. You will get the same result each time.
The calculation/formula field (=) calculates what is there. So 1-3 = -2. That is the expected result. You could use the Quote field to show the equation, but then used in the Set field, you still will get the same thing every time it is referenced.
This is shown in the sample document. (temporary link)

Consider AutoText or Building Blocks instead
If you are trying to re-use the formula { StyleRef 1 \s } - { Seq ( \s } this would be best saved as AutoText and inserted into your document. You could use the AutoText field if you wanted. You can attach a keyboard shortcut to AutoText for easy insertion. Assign your AutoText entries to a key or key combination.
AutoText and other Building Blocks can only be saved in templates.
Note: links are to my website or pages I have written except the one about the calculation field.


text:
Q: JS data becomes undefined after post. (node, socket.io, express) I just started coding a few days ago, so my terminology might be a little off, but here goes.
So I have an object var users = {}; in my app.js file. In my client side code I have a function that takes the $nickBoxVal() from the input field and passes it as (data) on the client side and on the server side as (data).
So I have something like this on the client side:
$nickForm.submit(function(e) {
  e.preventDefault;
    socket.emit('new user', $nickBox.val(), function(data) {
      //stuff
    });
      $nickBox.val('');
});

and on the server:
socket.on('new user', function(data, callback) {
  if (data in users) {
    callback(false);
  } else {
    callback(true);
    socket.nickname = data;
    users[socket.nickname] = socket;
    updateNicknames();
  }
});

function updateNicknames() {
  io.sockets.emit('usernames', Object.keys(users));
}

Now when I go to the next page the (data) becomes undefined. I have done quite a bit of research and it seems that my code is asynchronous when it needs to be synchronous. All the guides I find tell me to declare the undefined var outside the function so that it is a global variable, but my (data) is not a var (as far as I know) and I didn't define it my self. (data) is the property of the user {} object.
So how can I fix this?

A: "data" is a parameter to the callback function. It's only in scope inside that function. Other functions can't refer to it. "data" takes on different values when the callback function is called; referring to the parameter outside of the function is meaningless.


text:
Q: Dynamic_Cast pointer crashes only when getting member I have a function which takes in a vector of Cp pointers, and dynamic_cast them into pointer of derived pointers. When I try to get a member variable of the derived class, it crashes:
void DrawSystem::update(vector<Cp*> currentArgs)
{
    cout << currentArgs[0]->type;
    //Doesn't crash here
    GraphicsCp* graphics = dynamic_cast<GraphicsCp*>(currentArgs[0]);
    cout << graphics->type; //Crashes here
    sf::Vector2f pos = dynamic_cast<PosCp*>(currentArgs[1])->pos;
    cout << pos.x << " || " << pos.y << endl;
}

Does anyone know why this is?
Edit:
Here is all the relevant code:
void GameObject::updateSystems() {
    for(vector<System*>::const_iterator i = Systems.begin();
        i != Systems.end();
        ++i) {
        vector<Cp*> args;
        for(vector<cptype>::const_iterator j = (*i)->args.begin();
            j != (*i)->args.end();
            ++j) {
            args.push_back(Cps[*j]);
        }
        (*i)->update(args);
    }
}

class GameObject {
    public:
        GameObject();
        virtual ~GameObject();

        void addCp(const cptype&, Cp);
        void addSystem(const systype&);

        map <cptype, Cp*> Cps;
        vector <System*> Systems;

        void updateSystems();
        virtual void update() {}
        virtual void draw() {}
        virtual bool isVisible() { return false; }
};

class GraphicsCp : public Cp {
    public:
        GraphicsCp(); //TEMP
        GraphicsCp(sf::Texture*, sf::Vector2f);
        virtual ~GraphicsCp();

        sf::Sprite sprite;
        sf::Vector2f frameDim;
        sf::Vector2i currentTextureRectPos;

        void update(Player& player, sf::RenderWindow&); //TEMP
    private:
        sf::RectangleShape rectangle; //TEMP
};

class Cp {
    public:
        Cp();
        virtual ~Cp();

        virtual void update() {} //TEMP

        cptype type;
};

Player::Player() {
    addCp("Pos", PosCp());

    sf::Texture* texture = &Game::level.levelImageManager.playerSprite;
    sf::Vector2f frameDim(54, 93);
    addCp("Graphics", GraphicsCp(texture, frameDim));

    addSystem("Draw");
}

void GameObject::addCp(const cptype& type, Cp cp) {
    Game::level.levelCpManager.CpVecs[type].push_back(cp);
    Cps[type] = &Game::level.levelCpManager.CpVecs[type].back();
}

void GameObject::addSystem(const systype& type) {
    Systems.push_back(Game::level.levelSystemManager.systems[type].get());
}


text:
Q: BibTeX You can't pop an empty literal stack I know just the basic of latex, and I got an error inside the bibliography files iet.bst a bibliography file modified by IET and offered as latex files to write a paper to be published.
The error is in @webpage bibliography entry type, as I already searched, I think it is about some field that should be optional and after, maybe wrongly being poped, the error appears.

line 1838 from iet.bst is this:
ITERATE {call.type$}

The code about the webpage entry type is this:
% Title and url fields required;
% author, note, year, month, and lastchecked fields optional
STRINGS {database}
FUNCTION {webpage}
{ output.bibitem
  author empty$
    { editor empty$
        'skip$  % author and editor both optional
        { format.editors output.nonnull }
      if$
    }
    { editor empty$
        { format.authors output.nonnull }
        { "can't use both author and editor fields in " cite$ * warning$ }
      if$
    }
  if$
%  author empty$
%    'skip$
%    { format.authors output.nonnull }
%  if$
  new.block
  format.title "title" output.check
  journal empty$
    {
      format.type "type" output.check
      publisher empty$
        'skip$
        { format.publisher.address output }
      if$
      "database on the Internet" 'database :=
      type database =
        { format.journal.date "year" output.check }
        { format.date "year" output.check }
      if$
      lastchecked empty$
        'skip$
        { format.lastchecked output }
      if$
      new.block
      part empty$
        'skip$
        { part output }
      if$
      pages empty$
        'skip$
        { pages bracket.check output }
      if$
    }
    { journal
      remove.dots
      "journal" bibinfo.check
      "journal" output.check
      format.type "type" output.check
      format.journal.date "year" output.check
      lastchecked empty$
        'skip$
        { format.lastchecked output
      ";" no.blank.or.punct output
    }
      if$
      no.blank.or.punct format.vol.num output
      pages empty$
        'skip$
    { ":" no.blank.or.punct output
      no.blank.or.punct pages bracket.check output
    }
      if$
      new.block
    }
  if$
  format.url "url" output.check
  new.block
  note output
  fin.entry
}
% ...urlbst to here

The reason that points me the error is in that part, is because when I remove the entry @webpage  referent of Arduino:2020 from the main.tex the error disappear, but as I already said i only knows the basic of latex :(
The strange thing is that even with this error, the pdf is rendered apparently with no problem.
if someone helps me I appreciate it.
Thank you

A: I got the same error with an @article entry type.
In my case, it seems that when the fields "volume={volume number}," and "number={issue number}," are not added to the article's entry despite being optional, this error pops up. After adding the mentioned fields to my entry, the error disappeared. Try adding the related optional fields to your entry. Also, maybe changing your entry to another entry type such as "misc" solves your problem.

A: It happened to me once, and I added the volume of the article manually to the BibTeX file then the error was resolved.

A: Changing the entry from article to misc solved the problem for me.
I tried adding fields to the entry, but it would not fix the problem.

A: I changed the compile commannd from bibtex to pbibtex, and it was solved.


text:
Q: Concatenate two numpy arrays in the 4th dimension I have two numpy arrays with three dimensions (3 x 4 x 5) and I want to concatenate them so the result has four dimensions (3 x 4 x 5 x 2). In Matlab, this can be done with cat(4, a, b), but not in Numpy.
For example:
a = ones((3,4,5))
b = ones((3,4,5))
c = concatenate((a,b), axis=3) # error!

To clarify, I wish c[:,:,:,0] and c[:,:,:,1] to correspond to the original two arrays.

A: The accepted answer above is great.  But I'll add the following because I'm a math dork and it's a nice use of the fact that a.shape is a.T.shape[::-1]...i.e. taking a transpose reverses the order of the indices of a numpy array.  So if you have your building blocks in an array called blocks, then the solution above is:
new = np.concatenate([block[..., np.newaxis] for block in blocks],
                     axis=len(blocks[0].shape))

but you could also do
new2 = np.array([block.T for block in blocks]).T

which I think reads more cleanly.  It's worth noting that the already-accepted answer runs more quickly:
%%timeit
new = np.concatenate([block[..., np.newaxis] for block in blocks],
                     axis=len(blocks[0].shape))
1000 loops, best of 3: 321 µs per loop

while
%%timeit
new2 = np.array([block.T for block in blocks]).T
1000 loops, best of 3: 407 µs per loop

A: What about
c = np.stack((a,b), axis=3)

A: Here you go:
import numpy as np
a = np.ones((3,4,5))
b = np.ones((3,4,5))
c = np.concatenate((a[...,np.newaxis],b[...,np.newaxis]),axis=3)

A: How about the following:
c = concatenate((a[:,:,:,None],b[:,:,:,None]), axis=3)

This gives a (3 x 4 x 5 x 2) array, which I believe is laid out in the manner you require.
Here, None is synonymous to np.newaxis: Numpy: Should I use newaxis or None?
edit As suggested by @Joe Kington, the code could be cleaned up a little bit by using an ellipsis:
c = concatenate((a[...,None],b[...,None]), axis=3)

A: This works for me:
 c = numpy.array([a,b])

Though it would be nice if it worked your way, too.

A: It's not necessarily the most elegant, but I've used variations of
c = rollaxis(array([a,b]), 0, 4)

in the past.


text:
Q: Is it true that $\frac{\mathbb{C}\{z\}}{(z-\alpha)^n}$ is a $\mathbb{C}$-vector space of dimension $n$?
Let $\alpha\in\mathbb{C}$, and let $\mathbb{C}\{z\}$ denote the ring of convergent power series in $z$ around $\alpha$. Consider the ideal $(z-\alpha)^n$ in $\mathbb{C}\{z\}$. Is it true that $\frac{\mathbb{C}\{z\}}{(z-\alpha)^n}$ is a $\mathbb{C}$-vector space of dimension $n$, with basis $1, (z-\alpha),\dots , (z-\alpha)^{n-1}$?

What goes into proving this fact?
Thanks in advance.

A: Well, $\;V:=\Bbb C\{z\}/\langle (z-\alpha)^n\rangle\;$ is definitely a ring and, thus, an abelian group. It's not hard to check it is also a $\;\Bbb C\,-$ module, which already turns it into a complex vector space.
Now, if for some $\;c_1,...,c_{n-1}\in\Bbb C\;$ we have that
$$c_1(z-\alpha)+\langle (z-\alpha)^n\rangle+c_2(z-\alpha)^2+\langle (z-\alpha)^n\rangle+\ldots+c_{n-1}(z-\alpha)^{n-1}+\langle (z-\alpha)^n\rangle=\overline 0$$
then
$$\sum_{k=1}^{n-1}c_k(z-\alpha)^k\in\langle (z-\alpha)^n\rangle\iff\sum_{k=1}^{n-1}c_k(z-\alpha)^k=f(z)(z-\alpha)^n\;,\;\;f(z)\in\Bbb C\{z\}$$
which is absurd as the left side has a zero of order at most $\,n-1\,$ at $\;z=\alpha\;$ , whereas the right hand has a zero at the same point of order at least $\;n\;$ (why?) .
Thus, the vectors $\;(z-\alpha),...,(z-\alpha)^{n-1}\;$ are $\;\Bbb C\,-$ linearly independent in $\;V\;$.
Finally, any element in $\;V\;$ is an expression of the form $\;f(z)+\langle(z-\alpha)^n\rangle\;$ .But we can write
$$f(z)=(z-\alpha)^kg(z)\;,\;\;k\in\Bbb N\cup\{0\}\;,\;\;\text{with}\;\;g(z)\in V\;\;\text{that doesn't vanish at}\;\;\alpha$$  and thus...well, try to take it from to show that group of vectors is a generator of $\;V\;$...but you seem to be missing the vector $\;1\;$ .


text:
Q: will everything automatically close in this code if there is an exception three questions please
1) If there is an exception in the try below will the  request stream automatically close as it is in a using
2)do I even need the requestStream.Close() and requestStream.Dispose() as it is in a using?
3) do I need to close the System.Net.FtpWebRequest?
Try

    Dim rqst As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://1.com/text.txt"), System.Net.FtpWebRequest)
    rqst.Credentials = New System.Net.NetworkCredential("useb", "pass")
    rqst.Method = System.Net.WebRequestMethods.Ftp.UploadFile

    'Throw New ApplicationException("Exception Occured")
    Dim fle() As Byte = System.IO.File.ReadAllBytes("C:\test.txt")

    Using requestStream As Stream = rqst.GetRequestStream()

        requestStream.Write(fle, 0, fle.Length)
        requestStream.Close() 'do I need this?
        requestStream.Dispose() 'do I need this ?

    End Using

Catch ex As Exception

    MessageBox.Show(ex.Message.ToString())

End Try

A: No you dont need if you are using using. As using itself is used to dispose of. Also the reason for the "using" statement is to ensure that the object is always disposed correctly, and it doesn't require explicit code to ensure that this happens.
Dispose method is called immediately when control flow exits the using block.

A: Yes.  If the exception occurs while executing code inside the using statement, the stream will be disposed before it goes to the Catch block.


text:
Q: How does Zurb Foundation Switch control work I recently started using Zurb Foundation 4 for an Asp MVC website and I don't quite understand how the switch control is supposed to work. The docs don't say much http://foundation.zurb.com/docs/components/switch.html

  <input id="x" name="switch-x" type="radio" checked>
  Off

  <input id="x1" name="switch-x" type="radio">
  On

I'm using this example code, when I click on the switch, there is no change in the html. I figured the "checked" attribute would go on the second input, but this is not the case.

*

*How can I detect which radio button has been clicked ?

When I POST the form, the "switch-x" variable contains the value "on" no matter what position the switch is in.
I tried adding an onclick event on the label, but it's not getting fired as something seems to be overlapping the label.
I'm using foundation's javascript, I don't have any errors on the page.
I'm definitely missing something... Any ideas ?

A:
When I POST the form, the "switch-x" variable contains the value "on" no matter what position the switch is in.

You need to add a value in your input fields to have the $_POST["switch-x"] value, as :

  <input id="x" name="switch-x" type="radio" value="0" checked>
  Off

  <input id="x1" name="switch-x" type="radio" value="1">
  On

A:
How can I detect which radio button has been clicked ?

You have an id for each of your radio inputs so you can use them:
$('input[name=switch-x]:checked').attr('id');

That will give you either x or x1. Now it depends on how you will use it. But if you will be passing it as a boolean value, which I think you would, then you can simply do a:
var isOn = $('input[name=switch-x]:checked').attr('id') == 'x1';

or just simply
var isOn = $('#x1').is(':checked');

See it in action here


text:
Q: Como diminuir a qualidade de uma imagem no android? Tenho uma lista de objetos que possuem um array de imagens que são um tanto "pesadas", no inicio da aplicação possuo um listView personalizado que apresenta uma imagem (icone) de cada objeto, gostaria de diminuir a qualidade dessas imagens pois quando vou deslizar sobre a lista é possivel notar lentidão, precisaria fazer uma copia de uma imagem de cada objeto para diminuir a qualidade e mostrar no listview.
Como posso fazer isso em código java?

A: Isso é muito comum. E, além da lentidão, você pode pegar a famosa exception OutOffMemory.
Para evitar isso, você pode resolver em dois (simples) passos dentro de seu adapter:
1)- Colocar todo carregamento de imagem dentro de uma AsyncTask. Isso faz com que você tire de sua thread principal o trabalho de carregar imagens pesadas e bloquear a experiência do usuário. E, além disso, você pode cancelar a execução dessa AsyncTask caso, por exemplo, o usuário de um scroll muito rápido:
Adicione um AsyncTask dentro da sua ViewHolder:
...

private class ViewHolder{
    public ImageView image;
    public AsyncTask<Void, Void, Bitmap> asyncTask;
    ...
}

Dentro do método getView() de seu adapter:
...

//Previnindo o recycle de view
if (holder.asyncTask != null) {
    holder.asyncTask.cancel(true);
    holder.asyncTask = null;
}

//Previnido que a imagem "pisque" caso de um scroll muito rápido;
holder.image.setImageResource(R.drawable.someDrawable);

final ImageView image = holder.image;

holder.asyncTask = new AsyncTask<Void, Void, Bitmap>() {
    @Override
    protected Bitmap doInBackground(Void... params) {
        //Aqui você faz as implementações a seguir
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        image.setImageBitmap(bitmap);
    }
};
holder.asyncTask.execute();

2) Dentro de sua AsyncTask, você pode utilizar uma propriedade chamada inSampleSize, que faz o que o decode de sua imagem em uma resolução menor, como se fosse uma "amostra" de sua imagem. Por exemplo, uma imagem de 2048x1536 utilizando o inSampleSize como 4, produz uma imagem com aproximadamente 512x384. Essa imagem carregada utiliza apenas 0.75MB de memória ao invés de 12MB do tamanho original da imagem. Você pode utilizar essa propriedade dentro de um BitmapFactory.Options:
//Dentro de sua AsyncTask criada
@Override
protected Bitmap doInBackground(Void... params) {
    try {
        BitmapFactory.Options options = new BitmapFactory.Options();
        /*Reduzindo a qualidade da imagem para preservar memoria.
        * Aqui você pode testar a redução que melhor atende sua necessidade
        */
        options.inSampleSize = 2;

        return BitmapFactory.decodeStream(new FileInputStream(imagePath), null, options);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    return null;
}

Fontes:
Loading Large Bitmaps Efficiently
Processing Bitmaps Off the UI Thread

A: De acordo com o proprio google, é aconselhavel realizar o tratamento das imagens, para que sua aplicação não exceda a memoria.
            // Obter as dimensões do componente na tela
            File file = new File(Caminho da sua imagem)
             int targetW = imageview.getWidth();
             int targetH = imageview.getHeight();

            // Obter as dimensões do bitmap
            BitmapFactory.Options bmOptions = new BitmapFactory.Options();

            bmOptions.inJustDecodeBounds = true;

            BitmapFactory.decodeFile(file.getAbsolutePath(), bmOptions);

            int photoW = bmOptions.outWidth;
            int photoH = bmOptions.outHeight;

            // Determinar o quanto é necessario diminuir a imagem
            int scaleFactor = 1;
            if ((targetW > 0) || (targetH > 0)) {
                scaleFactor = Math.min(photoW/targetW, photoH/targetH);
            }

            // Decodifica o arquivo de imagem em um Bitmap dimensionando para preencher o
            // ImagemView
            bmOptions.inJustDecodeBounds = false;
            bmOptions.inSampleSize = scaleFactor;
            bmOptions.inPurgeable = true;

            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), bmOptions);

            imageview.setImageBitmap(bitmap);

Desta forma vc cria um bitmap do tamanho exato do componente da tela.
Fonte: http://developer.android.com/training/displaying-bitmaps/index.html

A: Você pode redimensionar o Bitmap:
Bitmap yourBitmap;
Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);
// ou:
resized = Bitmap.createScaledBitmap(yourBitmap,(int)(yourBitmap.getWidth()*0.3), (int)(yourBitmap.getHeight()*0.3), true);

Fonte: https://stackoverflow.com/a/25157279/194717


text:
Q: R - Identify potential duplicate records, then assign a single identifier I have a table with several thousand "potential" duplicate people, and the task is to identify those potential duplicates and assign them all a common id.
I have used stringdist_inner_join on the columns I'm concerned with, to join the table onto itself and return all rows and their possible matches. This works well, in most cases, but I can get long chains of matches that ultimately should be identified as the same person, and this is where I'm stuck.
My sample source table might look like this:

 systemid    last_name
 --------    ---------
 13          Samison
 14          Samsun
 15          Sanison

I use stringdist_inner_join on last_name to get a table that looks like this:

systemid.x    systemid.y
----------    ----------
13            15
14            13
15            13

but what I need to know is that all three of those records are potentially the same, so ultimately I want something like this:

finalid    systemid.x    systemid.y
-------    ----------    ----------
13         13            15
13         14            13
13         15            13

To make this more complicated, the number of these potential duplicates can be any number, and the relationship chain between them can be any length.  I might have id 13 match to 14, 14 match to 15, 15 match 21, and so one.
It's also possible I'm going about this all wrong and need to learn something else like compare.dedup.

A: Not sure this is the best way to do this, but here is what I've done:
Sample table:
tbl1 <- tibble(userId = c(13, 14, 15, 16, 21)
               , lastName = c("Samison", "Samsun", "Sanison", "Simison", "Sumison"))

Map record pairs using compare.dedup:
mapped.tbl1 <- compare.dedup(tbl1, exclude = "userId"
                               , strcmp = TRUE, strcmpfun = levenshteinSim) %>%
    epiWeights() %>%
    epiClassify(0.7) %>%
    getPairs(show = "links", single.rows = TRUE)

Group by my lastName column and eliminate duplicates
  mapped.tbl1 <- mapped.tbl1 %>%
    group_by(lastName.2) %>%
    mutate(rnk=order(order(desc(Weight)))) %>%
    filter(rnk == 1)

Join my original table to my mapped table and update the userId with mutate:
  tbl1 <- tbl1 %>%
    left_join(mapped.tbl1, by = c("userId" = "userId.2")) %>%
    mutate(
      userId.2 = userId
      , userId = if_else(is.na(userId.1) == FALSE, userId.1, userId)
    ) %>%
    select(names(tbl1))