text:
Q: Problem with net instantiation I have a very simple statemachine that sets some control signals to interact with a third party IP. The code looks roughly as follows:
entity testip is
  port (
  ...
    fifo_dataout        : in  std_logic_vector(0 to 31);
    ip_dataout          : in  std_logic_vector(0 to 31);
    ip_ce                 : out std_logic;
    ip_we                : out std_logic;
    ip_datain            : out std_logic_vector(0 to 31);
  );
end entity testip;

architecture imp of testip is

  signal ip_ce_ns     : std_logic;
  signal ip_we_ns     : std_logic;
  signal ip_ce_cs     : std_logic;
  signal ip_we_cs     : std_logic;
  signal ip_dataout_i : std_logic_vector(0 to 31);
  ...

  attribute keep: string;
  attribute keep of ip_ce    : signal is "True";
  attribute keep of ip_we    : signal is "True";

  begin

  COMB : process (...)
      begin
        ip_ce_ns          <= ip_ce_cs;
        ip_we_ns          <= ip_we_cs;

     case ip_nstate_cs is
        when IDLE      =>
        ...

     end case;
 end process COMB;

 REG: process (Clk) is
   begin
      if (Clk'event and Clk = '1') then
         if (Rst = '1') then
              ip_ce_cs                <= '1';
              ip_we_cs                <= '1';
              ...
         else
              ip_ce_cs                <= ip_ce_ns;
              ip_we_cs                <= ip_we_ns;
              ...
         end if;
    end if;
 end process REG;

S0:     ip_ce                 <= ip_ce_cs;
S1:     ip_we                <= ip_we_cs;
S2:     ip_datain           <= fifo_dataout;
S3:     ip_dataout_i       <= Ip_dataout;

end architecture imp;

Sythesis works fine, however, when applying the following constraint file I get ERROR:ConstraintSystem:59 - NET "testip/ip_we" not found. The same occurs for testip/ip_datain and testip/ip_ce.
 Net testip/ip_datain<*> MAXDELAY = 2 ns;
 Net testip/ip_ce MAXDELAY = 2 ns;
 Net testip/ip_we MAXDELAY = 2 ns;

I checked the netlist, and indeed there is neither a testip/ip_we, a testip/ip_ce nor a testip/ip_datain net. Anyone an idea why the other nets are not in the netlist, all very confusing.
Many thanks for any feedback!
EDIT: Please see attached the detailed instantiation in the top module file:
icap0 : entity icap.hwicap
    generic map (pindex => 2, paddr => 2, pmask => 16#FFE#, C_SIMULATION => 2,
           C_FAMILY => "virtex5")
    port map (rst => rstn, clk => clkm, apbi => apbi, apbo => apbo(2));

Net icap0/icap_statemachine_I1/Icap_datain<*> MAXDELAY = 2 ns;
Net icap0/icap_statemachine_I1/Icap_ce MAXDELAY = 2 ns;
Net icap0/icap_statemachine_I1/Icap_we MAXDELAY = 2 ns;

This should do the job, but when looking at the netlist and looking for signals Icap_ce
or Icap_we they are just non-existent. I just think these nets are not there or have been renamed so that I cant find them anymore. Thanks

A: The signals were probably optimized away...it looks like you have a wire loop generating ip_ce and you're driving ip_datain with the non-existant fifo_dataout.  You don't indicate what you're targeting, but modern FPGA synthesis are by default very aggressive at removing unused/undriven logic, typically with nothing more than an info or warning message in the log.  Crawl through your syntheses logs and look for anything odd related to the signals you're looking for.

A: As Charles says, your signals are probably being optimized away.
If you set the synthesis attribute to preserve hierarchy, then your ports will be maintained (but you miss out on some optimizations).
I guess you aren't really as bothered about the signals as your are about the timing. In which case, use a start and end point, rather than a net name in your constraints.
Alternatively, you can set the keep attribute on the signals in the source code. That can of course make your source code less portable. My recommendation would be to use start and end points.
Is testip your top level? If not try
Net "*/testip/ip_ce" MAXDELAY = 2 ns;

is this net detected?
Net "*/testip/ip_ce_cs" MAXDELAY = 2 ns;

Actually, I've missed something more obvious, what is the name of the instance of testip? Use that instead of testip in your constraint. i.e.
u_test_ip : testip

then
Net "*/u_test_ip/ip_ce" MAXDELAY = 2 ns;

A: I think the keep attribute is case-sensitive, have you tried "true" rather than "True"?


text:
Q: Connecting Golang and Postgres docker containers I'm trying to run a golang server at localhost:8080 that uses a postgres database. I've tried to containerize both the db and the server but can't seem to get them connected.
main.go
func (a *App) Initialize() {
    var db *gorm.DB
    var err error
    envErr := godotenv.Load(".env")
    if envErr != nil {
        log.Fatalf("Error loading .env file")
    }
    var dbString = fmt.Sprintf("port=5432 user=sample dbname=sampledb sslmode=disable password=password host=db")

    db, err = gorm.Open("postgres", dbString)
    if err != nil {
        fmt.Printf("failed to connect to databse\n",err)
    }
    a.DB=model.DBMigrate(db)
    a.Router = mux.NewRouter()
    a.setRoutes()
}

//Get : get wrapper
func (a *App) Get(path string, f func(w http.ResponseWriter, r *http.Request)) {
    a.Router.HandleFunc(path, f).Methods("GET")
}

//Post : post wrapper
func (a *App) Post(path string, f func(w http.ResponseWriter, r *http.Request)) {
    a.Router.HandleFunc(path, f).Methods("POST")
}

//Run : run on port
func (a *App) Run(port string) {
    handler := cors.Default().Handler(a.Router)
    log.Fatal(http.ListenAndServe(port, handler))
}

func (a *App) setRoutes() {
    a.Get("/", a.handleRequest(controller.Welcome))
    a.Get("/users", a.handleRequest(controller.GetUsers))
    a.Get("/user/{id}", a.handleRequest(controller.GetUser))
    a.Post("/login", a.handleRequest(controller.HandleLogin))
    a.Post("/users/add", a.handleRequest(controller.CreateUser))
    a.Post("/validate", a.handleRequest(controller.HandleValidation))
}

func main() {
    app := &App{}
    app.Initialize()
    app.Run(":8080")

}

server Dockerfile
FROM golang:latest

RUN mkdir /app
WORKDIR /app/server

COPY go.mod .
COPY go.sum .
RUN go mod download
COPY . .

docker-compose.yml
version: '3.7'
services:
    db:
        image: postgres
        container_name: ep-db
        environment:
            - POSTGRES_PORT=${DB_PORT}
            - POSTGRES_USER=${DB_USERNAME}
            - POSTGRES_PASSWORD=${DB_PASSWORD}
            - POSTGRES_DB=${DB_NAME}

        ports:
            - '5432:5432'
        volumes:
            - ./db:/var/lib/postgresql/data"
        networks:
            - internal
    server:
        container_name: ep-server
        build:
            context: ./server
            dockerfile: Dockerfile
        command: bash -c "go build && ./server -b 0.0.0.0:8080 --timeout 120"
        volumes:
            - './server:/app/server'
        expose:
            - 8080
        depends_on:
            - db
        networks:
            - internal
        stdin_open: true
volumes:
    db:
    server:
networks:
    internal:
      driver: bridge

I have some get and post requests that return the right values when i run it locally on my computer (for ex. localhost:8080/users would return a JSON full of users from the database) but when I use curl inside the server container, I don't get any results. I am new to docker, Is there something wrong with what I'm doing so far?

A: Each docker container has its own IP address. When you connect to the postgres db from your application, you are using localhost, which is the container for the application and not the db. Based on your docker-compose, you should use the hostname db (the service name) to connect to the database.

A: As suggested by @DavidMaze you should verify the logs from your server container. Also,

*

*First ensure ep-server is running (check that the output of docker container ls has status running for ep-server)

*Run docker logs ep-server to view errors (if any)

*If there are no errors in the logs, then run a docker exec -it ep-server bash to login to your container and run a telnet ep-db 5432 to verify that your postgres instance is reacheable from ep-server

redpajama_set_name: RedPajamaStackExchange


text:
Q: PDFMiner Extraction for Single Words - LTText LTTextBox I am generating word x,y coordinates with PDFMiner in the below example, however the results are on a line by line basis. How can I split each word from another word, rather splitting groups of words line by line (see example below). I have tried several of the arguments in the PDFMiner tutorial. LTTextBox and LTText were both tried. Moreover, I cannot use beginning and end offsets normally used in text analytics.
This PDF is a good example, this is used in the code below.
http://www.africau.edu/images/default/sample.pdf
from pdfminer.layout import LAParams, LTTextBox, LTText
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfinterp import PDFPageInterpreter, PDFResourceManager
from pdfminer.converter import PDFPageAggregator

#Imports Searchable PDFs and prints x,y coordinates
fp = open('C:\sample.pdf', 'rb')
manager = PDFResourceManager()
laparams = LAParams()
dev = PDFPageAggregator(manager, laparams=laparams)
interpreter = PDFPageInterpreter(manager, dev)
pages = PDFPage.get_pages(fp)

for page in pages:
    print('--- Processing ---')
    interpreter.process_page(page)
    layout = dev.get_result()
    for lobj in layout:
        if isinstance(lobj, LTText):
            x, y, text = lobj.bbox[0], lobj.bbox[3], lobj.get_text()
            print('At %r is text: %s' % ((x, y), text))

This returns the x,y coordinates for the searchable PDF as demonstrated below:
--- Processing ---
At (57.375, 747.903) is text: A Simple PDF File
At (69.25, 698.098) is text: This is a small demonstration .pdf file -
At (69.25, 674.194) is text: just for use in the Virtual Mechanics tutorials. More text. And more
 text. And more text. And more text. And more text.

Wanted result (the coordinates are proxy for demonstration):
--- Processing ---
At (57.375, 747.903) is text: A
At (69.25, 698.098) is text: Simple
At (69.25, 674.194) is text: PDF
At (69.25, 638.338) is text: File

A: With PDFMiner, after going through each line (as you already did), you may only go through each character in the line.
I did this with the code below, while trying to record the x, y of the first character per word and setting up a condition to split the words at each LTAnno (e.g. \n ) or .get_text() == ' ' empty space.
from pdfminer.layout import LAParams, LTTextBox, LTText, LTChar, LTAnno
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfinterp import PDFPageInterpreter, PDFResourceManager
from pdfminer.converter import PDFPageAggregator

#Imports Searchable PDFs and prints x,y coordinates
fp = open('C:\sample.pdf', 'rb')
manager = PDFResourceManager()
laparams = LAParams()
dev = PDFPageAggregator(manager, laparams=laparams)
interpreter = PDFPageInterpreter(manager, dev)
pages = PDFPage.get_pages(fp)

for page in pages:
    print('--- Processing ---')
    interpreter.process_page(page)
    layout = dev.get_result()
    x, y, text = -1, -1, ''
    for textbox in layout:
        if isinstance(textbox, LTText):
          for line in textbox:
            for char in line:
              # If the char is a line-break or an empty space, the word is complete
              if isinstance(char, LTAnno) or char.get_text() == ' ':
                if x != -1:
                  print('At %r is text: %s' % ((x, y), text))
                x, y, text = -1, -1, ''
              elif isinstance(char, LTChar):
                text += char.get_text()
                if x == -1:
                  x, y, = char.bbox[0], char.bbox[3]
    # If the last symbol in the PDF was neither an empty space nor a LTAnno, print the word here
    if x != -1:
      print('At %r is text: %s' % ((x, y), text))

The output looks as follows
At (64.881, 747.903) is text: A
At (90.396, 747.903) is text: Simple
At (180.414, 747.903) is text: PDF
At (241.92, 747.903) is text: File

Perhaps you can optimize the conditions to detect the words for your requirements and liking. (e.g. cut punctuation marks .!? at the end of words)

A: An alternate package the readers may want to try is pdfparser that's built on Poppler too (using Cyton bindings) and happens to be more optimised in performance
                           pdfreader      pdfminer  speed-up factor

tiny document (half page)    0.033s         0.121s     3.6 x
small document (5 pages)     0.141s         0.810s     5.7 x
medium document (55 pages)   1.166s        10.524s     9.0 x
large document (436 pages)  10.581s       108.095s    10.2 x

Apart from being faster it's error handling is also better, and resolved a couple of issues where Pdfminer stuggles
import pdfparser.poppler as pdf
import sys

d=pdf.Document(sys.argv[1])

print('No of pages', d.no_of_pages)
for p in d:
    print('Page', p.page_no, 'size =', p.size)
    for f in p:
        print(' '*1,'Flow')
        for b in f:
            print(' '*2,'Block', 'bbox=', b.bbox.as_tuple())
            for l in b:
                print(' '*3, l.text.encode('UTF-8'), '(%0.2f, %0.2f, %0.2f, %0.2f)'% l.bbox.as_tuple())
                #assert l.char_fonts.comp_ratio < 1.0
                for i in range(len(l.text)):
                    print(l.text[i].encode('UTF-8'), '(%0.2f, %0.2f, %0.2f, %0.2f)'% l.char_bboxes[i].as_tuple(),\
                        l.char_fonts[i].name, l.char_fonts[i].size, l.char_fonts[i].color,)
                print()

As you can clearly see the source code is the shortest, yet still provides all necessary data, including font colour, font-size, font-family.
More importantly, you get the words straight away in the blocks 9just a level above the characters). Avoids the space checking logic, one has to use with Pdfminer.


text:
Q: How to use timezone-js? I saw this project in GitHub that converts a given timezone to another timezone.
I'm having difficulties on how to make this work. I downloaded the file and extracted it then created an html file as below:
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=Unicode" />
        <title>Time Zone Converter</title>
        <script src="timezone-js-master/src/date.js" type="text/javascript"></script>
        <script type="text/jscript" language="jscript">
            function init() {
                var dt = new timezoneJS.Date("2012/04/10 10:10:30 +0000", 'Europe/London');
                dt.setTimezone("Asia/Jakarta");

                alert(dt);
            }
        </script>
    </head>
    <body onload="init()">

    </body>
</html>

I expect that some message will popup but the above html doesn't actually work. Obviously I'm missing something.
Can you please help?

A: As mentioned in some of the github comments, the constructor is not really clear.
There is also the added complexity of re-setting the perspective when passing your timezoneJS instance in a new Date() instance.
To get time date/time in another timezone you must instantiate, set the timezone using an Olson string, then get the converted value out of the timezoneJS instance.
So the following code:
var dt = new window.timezoneJS.Date(new Date());
console.debug(dt.toString());
dt.setTimezone('America/Los_Angeles');
console.debug(dt.toString());

Yields:
2013-07-18 19:09:30 //now
2013-07-18 16:09:30 //now... in LA


text:
Q: how to take screen shot from camera view? Friends and sirs
Thanks for taking time for me.
I want to take screen shots in app.
Now i;m trying to use following codes.
- (UIImage *)captureView:(UIView *)view {
    CGRect screenRect = [[UIScreen mainScreen] bounds];

    UIGraphicsBeginImageContext(screenRect.size);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [[UIColor blackColor] set];
    CGContextFillRect(ctx, screenRect);

    [view.layer renderInContext:ctx];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;
}

But problem is that it only takes black screens when I am on camera mode.
This above code works perfectly in other views excepting camera view.
I want to take screen shots of camera view.
Simply I can use UIGetScreenImage to get screen shot of camera view, but this is non-public api and if I use this then the app can't upload to appstore on xcode 4.3.
How can I do that?
Any idea for this?
If then this will be great help for me.
thanks again.


text:
Q: psycopg2 Python concatenate percentage '%' in field postgresql This is a pretty specific question, but I'm running an automated script through Python that runs a Postgresql query using psycopg2. One of the fields returns percentages, but instead of showing them as a whole number, I want to show add a percentage after each number. For instance, I have this line in my query:
CASE WHEN (delivered_orders != 0) then round((scanned_deliveries::numeric
/ delivered_orders::numeric)*100) when delivered_orders = 0  then 0 end as
scan_percent

So if there's 4 orders and 3 are scanned, it will return 75. I want it to return 75%. I have tried concatenating it with || '%' and || % after the "end", but Python treats the percentage as a placeholder and it says Tuples out of range because I don't have enough values. I have also tried playing along with using it as a placeholder and then putting '%' when I do cursor.execute(query, ('%')) but it says:
ValueError: unsupported format character
I have tried a few other things as well. I'm banging my head against the wall here and thought you smart people might know what I need to do. Thanks for your help!

A: Use %% for literal %. From the Psycopg docs:

When parameters are used, in order to include a literal % in the query
you can use the %% string:
>>> cur.execute("SELECT (%s % 2) = 0 AS even", (10,))       # WRONG
>>> cur.execute("SELECT (%s %% 2) = 0 AS even", (10,))      # correct


text:
Q: Tryin to display an MDDropDownMenu when click to icon exist in MDToolbar I have a problem on my code, i'm trying to use a MDToolBar that contains in icon , i want to when click to this icon it show a MDDropDownMenu, when i click it it give me this error
'NoneType' object has no attribute 'to_window' if someone know how to solve it !! any suggestions !! the problem exist exactly in the functions in MyApp Class
this is main.py
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
from kivymd.color_definitions import colors
from kivy.core.window import Window
from kivymd.uix.boxlayout import BoxLayout

Window.size = (360, 600)
class Scanner(Screen):
    pass
class Connecter(Screen):
    pass
class Search(Screen):
    pass
class Inscrire(Screen):
    pass
class Apropos(Screen):
    def back_to_scanner(self):
        self.manager.current = 'scanner'
    pass
class Setting(Screen):
    pass
class MyApp(MDApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
    dropdown = ObjectProperty()
    def on_start(self):
        # Create the dropdown menu
        self.dropdown = MDDropdownMenu(width_mult=2)

        # Add items to the menu
        for i in range(6):
            self.dropdown.items.append(
                {"viewclass": "MDMenuItem",
                 "text": "Option " + str(i),
                 "callback": self.option_callback}
            )

    def option_callback(self, text_of_the_option):
        print(text_of_the_option)

    def build(self):
        self.theme_cls.primary_palette = "DeepPurple"
        return Builder.load_file("main.kv")

MyApp().run()

and this is main.kv
#:include kv/inscrire.kv
#:include kv/connecter.kv

<MDMenuItem>:
    on_release: app.change_variable(self.text)
NavigationLayout:
    id: nav_layout

    # ScreenManager:

    ScreenManager:
        id: screen_manager
        Connecter:
            id: connecter
            name: "connecter"

        Inscrire:
            id: inscrire
            name: "inscrire"
        Screen:
            BoxLayout:
                orientation: 'vertical'

        Scanner:
            id: scanner
            name: "scanner"

            MDToolbar:
                title: "Scanner"
                elevation: 10
                left_action_items: [['menu', lambda x: nav_drawer.set_state()]]
                right_action_items: [['magnify', lambda x: scanner.go_to_search()],['dots- vertical',lambda x: app.dropdown.open(x)]]
                pos_hint: {'center_x': .5, 'top': 1}

A: I had the same issue. What i did is, i used simple alternative method to overcome this.
Instead of using "right_action_items", you can add "MDIconButton" to the "MDToolbar".
Here is an example of modifying the kivyMD documentation example:
from kivy.lang import Builder
from kivymd.app import MDApp
from kivymd.uix.menu import MDDropdownMenu

KV = '''
MDScreen:
    MDToolbar:
        title: 'Toolbar'
        pos_hint: {'top': 1}
        MDIconButton:
            id: button
            halign: 'center'
            icon: "dots-vertical"
            pos_hint: {'top': root.y+0.9, 'x': 1}
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            on_release: app.menu.open()

'''

class Test(MDApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.screen = Builder.load_string(KV)
        menu_items = [
            {
                "text": f"Item {i}",
                "viewclass": "OneLineListItem",
                "on_release": lambda x=f"Item {i}": self.menu_callback(),
            } for i in range(5)
        ]
        self.menu = MDDropdownMenu(
            caller=self.screen.ids.button,
            items=menu_items,
            width_mult=4,
        )

    def menu_callback(self, text_item):
        print(text_item)

    def build(self):
        return self.screen

Test().run()

I used "pos_hint" to take the icon into the middle of toolbar and changed the color to be white. This works perfectly fine same as the "right_action_items".


text:
Q: How to cut audio file with avconv? I have a hard time trying to figure out how to cut a file with avconv. Here's the command I use:
avconv -ss 52:13:49 -t 01:13:52 -i RR119Accessibility.wav RR119Accessibility-2.wav

But it doesn't work. I get the whole file as a result. Well, almost the whole file. Somehow the resulting file has duration 1:16:31 instead of 1:17:23. Also I believe I executed this command in every possible way: with -ss and -t after -i, with -t specifying ending point, with mp3 files, with specifying audio codec, with ffmpeg. Am I doing it wrong?
UPD Thanks to bodhi.zazen this works (I corrected the offset and duration reported by mp3splt-gtk, they were wrong for some reason or other, and the goal was to cut mp3 file)
avconv -i RR119Accessibility.mp3 -ss 00:52:08 -t 00:01:08 RR119Accessibility-2.mp3

But this doesn't:
avconv -ss 00:52:08 -t 00:01:08 -i RR119Accessibility.mp3 RR119Accessibility-2.mp3

The resulting file start at 00:52:08 and goes until the end of the original file. I thought -ss and -t are related to input file if specified before -i. And to output file otherwise. Could someone explain this?

A: I think the original problem was with the formatting of your time stamp.
The format is HH:MM:SS
I am not sure I am understanding your question about the order of the options. I do not think it matters as long as -i is followed by the input file name and -ss HH:MM:SS followed my -t HH:MM:SS
The -ss HH:MM:SS is the starting point, and -t HH:MM:SS is the duration
so -ss 00:01:00 -t 00:05:00 would start at the one minute mark and run for 5 minutes.
On my system, using ffmpeg, order does not matter (you can specify time or input file in any order so long as -ss is followed by the duration (-t) )

A: The problem comes from the different meaning of -ss depending upon where in the command line it is. It's a carry over from the days when avconv was still a part of ffmpeg project, and i believe it is being fixed in the newer versions.
In the olden days if you said something like
 ffmpeg -ss 5 -i input

What you meant was "skip to the 5 second mark in the file and begin to read there".
But if you said
ffmpeg -i input -ss 5

You meant "open the input file and skip all the data until the five second mark".
As you can understand the first approach will actually fail quite often, because you are skipping in the file without reading it. It works well only on the files which have timestamps in them, allowing you to read the frame and know if you've gone too far already or not.
Basically the way it worked in ffmpeg was "Guess the bitrate by the first second, and then assume that all other seconds are the same". But, of course, not all the seconds are the same, and if we are talking about a 52 hours of "drift" the error can be quite large.
So if you are using the early post-split version of avconv you should always put -ss after the file that is being read. But in the newer versions (to the best of my knowledge) this bug was fixed.

A: Try:
avconv -i RR119Accessibility.wav -ss 52:13:49 -t 01:13:52 RR119Accessibility-2.wav

The options of ffmpeg and avconv are position sensitive.
In your example ffmpeg starts reading the file and starts outputting from timestamp -ss
(which ffmpeg does well on my system and avconv does not, call it a regression of sorts).
In the example I have given here, avconv (or ffmpeg for that matter) seeks first to the right offset and then starts reading and outputting. This works for both.
You can find more documentation about avconv on http://libav.org
these guys have forked off ffmpeg and are also responsible for the extremely old ffmpeg version in Ubuntu.
The REAL ffmpeg is not in the ubuntu repositories but in a PPA:
ppa:jon-severinsson/ffmpeg
You can find more documentation about ffmpeg on http://ffmpeg.org
Consider the man pages out of date


text:
Q: how to solve equations I am trying to find the values of L and \theta, but mathematica is unable to produce output. My code is given below, where the value of k is fixed, i.e., 0.75, but the value of B can be positive or negative.
Solve[{
   1/r^4 2 (r^2 + (L - B r^k +
          B r^k Cos[\[Theta]])^2 Csc[\[Theta]]^2 - (-2 + r) (L -
          B r^k + B r^k Cos[\[Theta]]) (L + B (-1 + k) r^k -
          B (-1 + k) r^k Cos[\[Theta]]) Csc[\[Theta]]^2) == 0,
   -(1/(r^3))
     2 (-2 + r) (L - B r^k +
        B r^k Cos[\[Theta]]) (B r^
         k + (L - B r^k) Cos[\[Theta]]) Csc[\[Theta]]^3 == 0},
  {L, \[Theta]}]

Can anyone please help me to solve these equations.

A: One approach is to introduce variables $x$ and $y$ in place of $\cos\theta$ and $\sin\theta$, like this
eq1 = 1/r^4 2 (r^2 + (L - B r^k +
          B r^k Cos[θ])^2 Csc[θ]^2 - (-2 + r) (L -
         B r^k + B r^k Cos[θ]) (L + B (-1 + k) r^k -
         B (-1 + k) r^k Cos[θ]) Csc[θ]^2) == 0;

eq2 = -(1/(r^3)) 2 (-2 + r) (L - B r^k +
      B r^k Cos[θ]) (B r^
        k + (L - B r^k) Cos[θ]) Csc[θ]^3 == 0;

eq3 = x^2 + y^2 == 1;

eqns = {eq1, eq2, eq3} /. Cos[θ] -> x /. Csc[θ] -> (1/y);

s = Solve[eqns, {L, x, y}] // Simplify;

Then use ArcTan[x,y] to recover solutions for $\theta$.


text:
Q: Import Apache Cordova Build into Android Studio - Cannot find symbol class xxxx I've starting building apps with Phonegap / Apache Cordova, now using Cordova, and I would like to import the build into Android Studio for testing and to build the .apk.  It is all working good with the CLI for Cordova, and I can run the app in an emulator via the CLI with Cordova.  When I import into Android Studio (Mac OS X Yosemite, Studio version 1.1.0), it doesn't seem to import the entire directory structure and I am getting errors like "cannot find symbol class" CallbackContext, Config, CordovaArgs, etc.
I don't know if that is an issue with Cordova, Android Studio or some configuration error.  I haven't tried building with Phonegap and trying that instead.  I know that I can build an distribution .apk via the CLI, but that isn't as easy as with Android Studio.  I am running the latest version of Cordova, version 4.3.0.
I can provide more details if needed, just wondering if anyone has some suggestions.  I will build with phongap in the meantime if see if that works.
Thank you.
/sds

A: Seems to be some sort of issue with the Cordova Build. If I build with PhoneGap I can import into Android Studio and just have to change a few settings to get it to build. With the Cordova build, CordovaLib doesn't even show up in Android Studio.


text:
Q: JIRA serach api not working with apache tomcat on Live server I am using rest/api/2/search to get assignee name from jira. This api is working fine on my local via eclipse and tomcat. But although giving correct username and password Api is not working on Live server with apache tomcat server. I can also able to log in JIRA by web browser on server. but API is giving 401 error. Is there anything need to enable on server.?
I am using below code to call jira api
List<String> assignee = null;
OkHttpClient client = new OkHttpClient();
    RequestBody body = RequestBody.create(JSON, requestJson);
    LOGGER.debug("calling jira API with json:" + requestJson);
    Request request = new Request.Builder().url(jiraConfig.getProperty("SEARCH_URL")).post(body)
        .addHeader("Authorization", getAuthenticationToken()).build();
    Response response = client.newCall(request).execute();
    if (response.code() == 200) {
      assignee = new ArrayList<>();
      JSONArray issues = new JSONObject(response.body().string()).getJSONArray("issues");
      LOGGER.debug("jira response:" + issues);
      for (int i = 0; i < issues.length(); i++) {
        assignee.add(issues.getJSONObject(i).getJSONObject("fields").getJSONObject("assignee")
            .getString("displayName"));
      }
    }


text:
Q: % probability of 1-3 on 7 consecutive dice throws What is the percent chance of landing 1-3 on 7 dice tosses in a row?
I rolled seven dice I believe at the same time and they all landed on one to three instead of four to six.
My attempt at this came out as a 4% chance I treated the dice rolls kind of like coin tosses because it seemed to me the chances of each one were 50/50 so I took 10 and divided it by two seven times since each dice roll was a 50% chance out of 100% I got 0.04 then I turned it to a percentage by multiplying it by 100 because I thought it would come to be the % out of 100% if multiplied by 100.
I believe my technique was wrong though and came to the incorrect answer as I am only 24 and barely understand math.
Also for the record it was seven dice not one.
After hearing one comment I tried another strategy since each dice toss was a 50% chance and I rolled 7 of them I took 7 and divided it by 50 arriving at 0.14%

A: For independent events, $A$ and $B$, the probability of both occurring, notated as $Pr(A\cap B)$ will equal $Pr(A)\times Pr(B)$.  (Please be aware that this works only for independent events).
The outcomes of each individual die are independent of one another and so the probability that you roll a low number on the first and the second and the third, and so on, will be the probability that you roll a low number on the first times the probability that you roll a low number on the second times etc...
$Pr(\text{1-3 on all seven dice}) = \frac{1}{2}\times\frac{1}{2}\times\cdots\times\frac{1}{2}=\frac{1}{2^7}$
Suggested further reading: Binomial Distribution


text:
Q: How to convert mongoDB result grouped by $week to date format? I want to create a report where I show sum of hours weekly. I'm using mongoDB and grouping by $week.  I need to differentiate weeks by year and my report needs to have date for first day of the week and last day of the week instead of week number. Here is my pipeline.
let pipeline = [
{
  $match: {
    companyId,
  },
},
{
  $group: {
    _id: {
      $week: '$date',
    },
  },
},
{
  $project: {
    companyId: '$companyId',
  },
},];

and here is my collection :
const hoursSchema = mongoose.Schema({
  personId: mongoose.Schema.Types.ObjectId,
  jobId: Number,
  companyId: Number,
  name: String,
  date: Date,
  hours: Number,
});

A: what I ended up doing was adding year and using a function separately to extract date from week and year numbers. The pipeline looks like this:
let pipeline = [
    {
      $match: {
        companyId,
      },
    },
    {
      $group: {
        _id: {
          week: { $week: { date: '$date' } },
          year: { $year: { date: '$date' } },
          name: '$name',
          jobTitle: '$jobTitle',
          jobId: '$jobId',
          companyId: '$companyId',
          personId: '$personId',
        },
        count: { $sum: 1 },
        hours: { $sum: '$hours' },
      },
    },
  ];

I put user details in $group _id to extract information for each user. so each grouped by object of mine now has year and week and I could use this to calculate date for first day and last day of the week.


text:
Q: Flutter Launcher icon doesn't change the icon
I already type this to my terminal and the icon for my app didn't change
flutter pub get
flutter pub run flutter_launcher_icons:main

A: Make sure you've set the app icon path in android/app/src/main/AndroidManifest.xml
 android:icon="@mipmap/ic_launcher"

A: Try below code hope its help to you.
Add below package in your pubspec.yaml file
flutter_launcher_icons: ^0.9.2

Add below code pubspec.yaml file
flutter_icons:
  image_path: "assets/icon.png"
  android: true
  ios: true

then run below command
flutter pub run flutter_launcher_icons:main


text:
Q: Angular not picking up changed input value Javascript noob here :)
I have a basic Angular web page that adds input to a list when the "add" (submit) button is clicked.  If, however, I submit by pressing the ENTER key, Angular does not recognise that the input field is dirty, and it fails to update the model ($scope.newFundName) - so the old value (initially "") is added to the list.  If I move focus away from the field and back again (say TAB, then BACKTAB) then Angular picks up the correct value. How do I force it to use the current value of the input field without manually shifting the focus?
My code:
<!doctype html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

            # Funds: {{getFundCount()}}

                    {{F.code}}={{F.name}}

            <form role="form" class="form-inline">
                Code
                <input id="eFundCode" type="text" class="form-control" ng-model="newFundCode" />
                Name
                <input id="eFundName" type="text" class="form-control" ng-model="newFundName" />
                <button id="eAdd" class="btn btn-info" ng-click="addFund()">Add</button>
            </form>


text:
Q: Post method is not working online I want to input some data through PHP MySQL. so I have written a form, some method in a class and a controller to process the whole thing, It is working fine with localhost, data are inserted according to programming logic, but in online form post method is not working. No data is sent to controller page. I am feeling helpless with the problem.
the is given bellow.
 <form method="post" action="registrationcontroller.php">
    <input type="text" name="name" class="form-control" placeholder="Enter your name" required/>

    <input type="text" name="phone"  class="form-control" placeholder="Enter your phone" required/>

    <input type="email" name="email"  class="form-control" placeholder="Enter your email" required/>

    <input type="text" name="callsign"  class="form-control" placeholder="Enter your call sign if any" >

    <input type="text" name="location" class="form-control" placeholder="Enter your location" required/>

    <textarea name="address" class="form-control" placeholder="Enter your full address"></textarea>

    <input type="submit" class="btn btn-primary" name="add">
</form>

this is my controller code
require_once 'Registrationclass.php';
$registration = new Registrationclass();

if(isset($_POST['add']))
{

    if(isset($_POST["name"])){
        $name = $_POST['name'];
    }
    if(isset($_POST["phone"])){
        $phone = $_POST['phone'];
    }
    if(isset($_POST["email"])){
        $email = $_POST['email'];
    }

    if(isset($_POST["location"])){
        $location = $_POST['location'];
    }
    if(isset($_POST["callsign"])){
        $callsign = $_POST['callsign'];
    }
    if($callsign=="") {
        $callsign="SWL";
    }
    if(isset($_POST["address"])){
        $address = $_POST['address'];
    }
}
$registration->setName($name);
$registration->setEmail($email);
$registration->setPhone($phone);
$registration->setLocation($location);
$registration->setAddress($address);
$registration->setCallsign($callsign);
$registration->setStatus("Pending");

$registrationid= "JCBIARF-".rand(1000,3000);
$registration->setRegistrationid($registrationid);
$registration->adduser();
$registration->redirect("registration.php?regsuc=true");

please help to resolve the problem.


text:
Q: Pandas: calculate time passed based on aonther column value In my pandas DataFrame's column "ms" I have the milliseconds passed and in the "button" column the  keyboard character that was pressed.
I'd like to know how many seconds the "up" was pressed and how many second the "down" was pressed.
This is my df:
    time    direction
0   31033      up
1   31174      up
2   31207     down
3   31324      up
4   31353      up
5   31383     down
6   31410      up
7   31440     down
8   31473     down
9   31501     down

I've tried this:

self.df_grouped = self.df.groupby("button").agg({"ms": [min, max]})
self.df_grouped["ms", "duration"] = (
self.df_grouped["ms", "max"] - self.df_grouped["ms", "min"]
                )

And it seems to works, but I need an output more like this:
      s      button
0   .174      up
1   .033      down
2   .029      up
3   .03       down
4   .027      up
5   .061      down

How can I do that?


text:
Q: Typescript - Pass one element of UnionType to function but not both I have two interfaces and want to create a function where either interface A or interface B is included but not both at the same time.
Using a simple UnionType does not work as it also allows for both interfaces to be included
Example (https://stackblitz.com/edit/typescript-qgytsy)
interface A{
  a: string;
}

interface B{
  b: string;
}

function aOrB(modifier: A | B) {}

aOrB({ a: '' }); // works!
aOrB({ b: '' }); // works!
aOrB({ a: '',  b: '' }); // also works but should not work!

Is there a way to achieve this, so that the first two calls to aOrB(...) work but the last one not?
Br, Benedikt

A: You can define a type which excludes certain properties:
type IFoo = {
  bar: string; can?: never
} | {
    bar?: never; can: number
  };

let val0: IFoo = { bar: "hello" } // OK only bar
let val1: IFoo = { can: 22 } // OK only can
let val2: IFoo = { bar: "hello",  can: 22 } // Error foo and can
let val3: IFoo = {  } // Error neither foo or can

Then use that type for the modifier parameter.

A: TS type system is structural, that means {a: 'a', b: 'b'} is proper member of A | B because it is assignable to A as it has all A properties and assignable to B because same reason. There is no issue to use such object where A or B is required as it has all what both need in terms of structure. Consider following snippet:
function fOnA(modifier: A) { } // we require only A
const a = { a: '',  b: '' } // we create object with additional props
fOnA(a) // no error

We can do type check of type { a: '',  b: '' }.
type ExtendsA = { a: '', b: '' } extends A ? true : false // evaluates true
type ExtendsB = { a: '',  b: '' } extends B ? true : false // evaluates true

As you can see { a: '',  b: '' } is valid object to be used for A and for B.

To be clear using such construct with additional properties is no harm, as we always have what we need.

The case when we want to distinct if we have A or B is a case where we should create discriminant in order to be able to check what kind of object went inside the function.
Consider:
interface A{
  kind: 'A', // discriminant
  a: string;
}

interface B{
  kind: 'B', // discriminant
  b: string;
}

function aOrB(modifier: A | B) {}

aOrB({ kind: 'A', a: '' }); // works!
aOrB({ kind: 'B', b: '' }); // works!
aOrB({ kind: 'B', a: '' }); // error as it should be
aOrB({ kind: 'B', b: '', a: '' }); // error as it should be

I have added kind in order to distinguish both versions. Such approach has many benefits, as we can now easily check if we have A or B simply by checking the kind.
Another solution is to block properties we don't want by never keyword. Consider:
interface A{
  a: string;
  b?: never;
}

interface B{
  b: string;
  a?: never;
}

function aOrB(modifier: A | B) {}

aOrB({ a: '' }); // works!
aOrB({ b: '' }); // works!
aOrB({ a: '', b: ''}); // error as it should be

By adding prop?: never; I avoid allowing object to pass A and B requirements.


text:
Q: Cannot Retrieve value from html input (autocomplete jquery ui) I have a html autocomplete textbox,my problem is when i try and enter an address eg. "New York" and click on submit button.It does not retrieve the input value.(does not return any value)
Test.aspx

         Address

            <input id="tb_address" type="text" class="form-control" placeholder="Type 'a' or 'h'" />

My javascript code in Test.aspx page

protected void bn_Submit_Click(object sender, EventArgs e)
{
  string address = Request.Form["tb_address"];

   lb_msg.Text = address;
}

A: I see that your input does not have a name, adapt the input tag as follows and try again:
<input id="tb_address" name="tb_address" type="text" class="form-control" placeholder="Type 'a' or 'h'" />


text:
Q: Run a script when docker is stopped I am trying to create docker container using dockerfile where script-entry.sh is to be executed when the containers starts and script-exit.sh to be executed when the container stops.
ENTRYPOINT helped to accomplish the first part of the problem where script-entry.sh runs on startup.
How will i make sure the script-exit.sh is executed on docker exit/stop ?

A: docker stop sends a SIGTERM signal to the main process running inside the Docker container (the entry script). So you need a way to catch the signal and then trigger the exit script.
See This link for explanation on signal trapping and an example (near the end of the page)

A: Create a script, and save it as a bash file, that contains that following:
$CONTAINER_NAME="someNameHere"
docker exec -it $CONTAINER_NAME bash -c "sh script-exit.sh"
docker stop $CONTAINER_NAME

Run that file instead of running docker stop, and that should do the trick.  You can setup an alias for that as well.
As for automating it inside of Docker itself, I've never seen it done before.  Good luck figuring it out, if that's the road you want to take.


text:
Q: Highlight entire UIButton, not only image at the left side? I have a usual UIButton with an image at the left side. Show touch on highlight is turned on in storyboard, but when I touch this button, the image gets highlighted and the text doesn't! I would like to highlight the entire UIButton.

A: I had the same issue. A workaround is to change the title color for the highlighted state.
Two solutions :
1/ In the Interface Builder :

*

*in your UIButton property, for "state config" property, select "highlighted"

*Change the text color property to the highlighted color you want.

2/ Programmatically :
Same idea as above , in Swift 3 you would do :
button.setTitleColor(.black, for: .highlighted)

A: Set the image as "background image" and the title as it is , now select  the option "Shows Touch On Highlight". Hope this help and will highlight the complete button.


text:
Q: Install4J build fails with exceptions I have following trial version of install4j Multi-Platform Edition 10.0.2 (build 10046) installed. Also installed are JDK 17.0.4 and JDK 1.8.333 (64 bit). I am getting following exceptions whenever I try to build:
Preparing configuration

Creating directory for temporary files

Directory for temporary media files is C:\Users\RAMCHA~1\AppData\Local\Temp\install4j10000746811088592861_dir
Finding JDK release 8/latest [windows-amd64]

Build failed.

Cause: java.net.SocketTimeoutException
       timeout (loc: 4)
Stack trace:

com.exe4j.a.d: java.net.SocketTimeoutException: timeout (loc: 4)
    at com.install4j.b.j.b(ejt:287)
    at com.install4j.gui.b.run(ejt:103)
Caused by: java.net.SocketTimeoutException: timeout (loc: 4)
    at com.install4j.runtime.installer.platform.win32.wininet.CallImpl.checkExceptionAndClose(CallImpl.java:60)
    at com.install4j.runtime.installer.platform.win32.wininet.CallImpl.sendRequest(CallImpl.java:118)
    at com.install4j.runtime.installer.platform.win32.wininet.WinInet.open(WinInet.java:150)
    at com.install4j.runtime.installer.helper.content.WinInetCallWrapper.connect(WinInetCallWrapper.java:57)
    at com.install4j.runtime.installer.helper.content.HttpRequestHandler.createWindowsConnection(HttpRequestHandler.java:154)
    at com.install4j.runtime.installer.helper.content.HttpRequestHandler.connect(HttpRequestHandler.java:129)
    at com.install4j.runtime.installer.helper.content.TextRequestHandler.connect(TextRequestHandler.java:99)
    at com.install4j.jdk.spi.impl.a.a(ejt:123)
    at com.install4j.jdk.spi.impl.AdoptOpenJdkProvider.a(ejt:37)
    at com.install4j.jdk.spi.impl.a.a(ejt:120)
    at com.install4j.jdk.spi.impl.AdoptOpenJdkProvider.a(ejt:53)
    at com.install4j.jdk.spi.impl.AdoptOpenJdkProvider.a(ejt:14)
    at com.install4j.jdk.spi.impl.AdoptOpenJdkProvider$a$1$1.invokeSuspend(ejt:19)
    at com.install4j.jdk.spi.impl.AdoptOpenJdkProvider$a$1$1.a(ejt)
    at com.install4j.jdk.spi.impl.AdoptOpenJdkProvider$a$1$1.invoke(ejt)
    at com.install4j.jdk.spi.impl.a$a$a.invokeSuspend(ejt:134)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
    at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:749)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
    Suppressed: java.net.SocketTimeoutException: timeout (loc: 4)
        ... 24 more
    Suppressed: java.net.SocketTimeoutException: timeout (loc: 4)
        ... 24 more
    Suppressed: java.net.SocketTimeoutException: timeout (loc: 4)
        ... 24 more

How do I fix this issue?

A: You do not have internet connectivity, which is a problem for a build, because code signing and JRE bundle creation require an internet connection.
install4j will try to download a suitable JDK for script compilation. If you update to the current version (10.0.4+), there will be no failure in this case, just a warning that install4j will have to use the JRE that it is running with for that purpose.


text:
Q: Section headers in margins I'm working on my resume in LyX and I would like my section headers to look like this. What should I write in the preamble to achieve this?

A: you could use the titlesec package to modify the definition of the \section command. in lyx you can add latex-code manually by going to the document preferences: Document->Settings -> Latex preamble. I marked the part of code you have to put in your document.
\documentclass{article}
\usepackage[showframe]{geometry}

%to lyn preamble from here

\usepackage{titlesec}

\titleformat{\section}[leftmargin]
{\normalfont
\sffamily\bfseries\filleft}
{}{0pt}{}
\titlespacing{\section}
{4pc}{1.5ex plus .1ex minus .2ex}{1pc}

%to here

\begin{document}

\section{Objective}
\noindent
Auditing/Analysis of Operations

\section{Education}
\noindent
B.S. in Management, Rensselaer Polytechnic Institute, Troy, NY, May 1986
Concentrations in Accounting and Management Systems
QPA 3.9 in major, 3.7 overall

\end{document}

A: Here is the source of the document you linked to.  Just copy it and and change it.
You need the res class which is downloadable from the same place.

A: Have you looked at the europecv package?
I've been using that to write my own CV.
From CTAN:

The europecv class is an unofficial
  LaTeX implementation of the standard
  model for curricula vitae (the
  "Europass CV") as recommended by the
  European Commission. Although
  primarily intended for users in the
  European Union, the class is flexible
  enough to be used for any kind of
  curriculum vitae.
The class has localisations for all
  the official languages of the EU (plus
  Catalan), as well as options
  permitting input in UTF-8 and koi8-r.
See also curve
currvita
esieecv vita
The author is Nicola Vitacolonna.

A: Er, perhaps I'm a little slow these days (go easy, guys, I'm being rhetorical), but as far as I can tell from your example, what you've got there is a table. A longtable if you want to run things over one page.
(Or am I just being painfully dense?)


text:
Q: Increment Page Index for Paginated Recyclerview I have implemented pagination in my app but I am having trouble with incrementing the page index. I am getting data from unsplash api and have formed the request url like below:
private String url = Constants.SEARCH_URL + "top30&page="+ PAGE_INDEX;

and this is the url used below:
https://api.unsplash.com/search/photos?client_id=api_key&order_by=latest&query=top30&page=1

In my fragment, I have a constant int like private static int PAGE_INDEX = 1; which tracks the current page and used for getting the next pages till page limit.
The first request runs fine and when scrolling towards the last item, more items are fetched. However, these items are same as from the first page index and after logging the url, I get the same as in first request like below:
https://api.unsplash.com/search/photos?client_id=api_key&order_by=latest&query=top30&page=1

I have attached my scroll listener in  recyclerview like this and incremented the  PAGE_INDEX but not getting the next page in url but in log cat it shows the page index as 2. Here's the listener attached:
top30RV.addOnScrollListener(new PaginationScrollListener(llm) {
        @Override
        protected void loadMoreItems() {
            isLoading = true;
            PAGE_INDEX = PAGE_INDEX + 1;
            Log.d(TAG, "PIn:\t" + PAGE_INDEX);

            loadNextPage();

        }

        @Override
        protected int getTotalPageCount() {
            return PAGE_COUNT;
        }

        @Override
        public boolean isLoading() {
            return isLoading;
        }

        @Override
        public boolean isLastPage() {
            return isLastPage;
        }

    });

and my PaginationScrollListener class code:
public abstract class PaginationScrollListener extends RecyclerView.OnScrollListener {

LinearLayoutManager llm;

public PaginationScrollListener(LinearLayoutManager llm) {
    this.llm = llm;
}

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
    super.onScrolled(recyclerView, dx, dy);

    int visisbleItemCount = recyclerView.getChildCount();
    int totalItemCount = llm.getItemCount();
    int firstVisibleItemPosn = llm.findFirstVisibleItemPosition();

    if (!isLoading() && !isLastPage()){
        if ((visisbleItemCount + firstVisibleItemPosn) >= totalItemCount && firstVisibleItemPosn > 0){
            loadMoreItems();
        }
    }

}

protected abstract void loadMoreItems();

protected abstract int getTotalPageCount();

public abstract boolean isLoading();

public abstract boolean isLastPage();

}

in my adapter I have called the method to addLoadingFooter and it works but also the progressbar is not dismissed and removeLoadingFooter is called but doesn't work because of the page index is less than the page limit.
public class Top30Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private static final String TAG = Top30Adapter.class.getSimpleName();

private final Context context;
private List<UnsplashImages> itemsList;

private UnsplashImages unsplashImages;

private static final int ITEMS = 0;
private static final int PROGRESS = 1;

private boolean isLoadingAdded = false;
private boolean retryPageLoad = false;

private String errorMsg;

private PaginationAdapterCallback mCallback;

public Top30Adapter(Context context, List<UnsplashImages> itemsList) {
    this.context = context;
    this.itemsList = itemsList;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    switch (viewType){
        case ITEMS:
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.wallpaper_items_layout, parent, false);
            return new WallpaperItemViewHolder(view);
        case PROGRESS:
            View pv = LayoutInflater.from(parent.getContext()).inflate(R.layout.progress_items_layout, parent, false);
            return new LoadingViewHolder(pv);
    }
    return null;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewholder, final int position) {
    switch (getItemViewType(position)){
        case ITEMS:
            WallpaperItemViewHolder wallpaperItemViewHolder = (WallpaperItemViewHolder) viewholder;
            unsplashImages = (UnsplashImages) itemsList.get(position);
            Picasso.with(context)
                    .load(unsplashImages.getRegularImg())
                    .placeholder(R.drawable.drawer_header_trimmed)
                    .into(wallpaperItemViewHolder.wallpaperItemImg);

            wallpaperItemViewHolder.favoriteWP_IV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Favorites favorites = new Favorites();
                    favorites.setFavoritesId(UUID.randomUUID().toString());
                    favorites.setLargeImgURL(unsplashImages.getRegularImg());
                    favorites.setPreviewImgURL(unsplashImages.getRegularImg());
                    favorites.save();
                    Toast.makeText(context, "Added to Favorites", Toast.LENGTH_SHORT).show();

                }
            });

            wallpaperItemViewHolder.setWallPaper_TV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final WallpaperManager wpm = WallpaperManager.getInstance(context);

                    Picasso.with(context)
                            .load(((UnsplashImages) itemsList.get(position)).getRegularImg())
                            .into(new Target() {
                                @Override
                                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                                    try {
                                        wpm.setBitmap(bitmap);
                                        Toast.makeText(context, "Your New Wallpaper Has Been Set", Toast.LENGTH_SHORT).show();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void onBitmapFailed(Drawable errorDrawable) {
                                    Log.d(TAG, "Bitmap Load Failed");
                                    Toast.makeText(context, "Could Not Set Wallpaper...Choose Another", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onPrepareLoad(Drawable placeHolderDrawable) {
                                    Log.d(TAG, "Prep to Load Bitmap");
                                }
                            });

                }
            });
            break;
        case PROGRESS:
            LoadingViewHolder loadingViewHolder = (LoadingViewHolder) viewholder;
            if (retryPageLoad){
                loadingViewHolder.mErrorLayout.setVisibility(View.VISIBLE);
                loadingViewHolder.mProgressBar.setVisibility(View.GONE);

                loadingViewHolder.mErrorTxt.setText(errorMsg != null
                        ? errorMsg
                        : context.getString(R.string.error_msg_unknown));

            } else {
                loadingViewHolder.mErrorLayout.setVisibility(View.GONE);
                loadingViewHolder.mProgressBar.setVisibility(View.VISIBLE);
            }
            break;
    }
}

@Override
public int getItemCount() {
    if (itemsList == null) {
        return 0;
    }
    return itemsList.size();
}

@Override
public int getItemViewType(int position) {
    return (position == itemsList.size() - 1 && isLoadingAdded) ? PROGRESS : ITEMS;
}

public void addImage(UnsplashImages images){
    itemsList.add(images);
    notifyItemInserted(itemsList.size() - 1);
}

public void addAllImages(List<UnsplashImages> list){
    for (UnsplashImages images : list){
        addImage(images);
    }
}

public void addLoadingFooter() {
    isLoadingAdded = true;
    addImage(new UnsplashImages());
}

public void removeLoadingFooter(){
    isLoadingAdded = false;

    int position = itemsList.size() - 1;
    UnsplashImages unsplashImages = getItem(position);

    if (unsplashImages != null){
        itemsList.remove(unsplashImages);
        notifyItemRemoved(position);
    }

}

private UnsplashImages getItem(int position) {
    return itemsList.get(position);
}

public void showRetry(boolean show, @Nullable String errorMsg){
    retryPageLoad = true;
    notifyItemChanged(itemsList.size() - 1);
    if (errorMsg != null){this.errorMsg = errorMsg; } else { errorMsg = "Can't Fetch Wallpapers Now..."; }
}

}

Full fragment code:
public class Top30Fragment extends Fragment {

private static final String TAG = Top30Fragment.class.getSimpleName();

private RecyclerView top30RV;

private List<UnsplashImages> itemsList = new ArrayList<>();
private Top30Adapter adapter;

private int PAGE_COUNT;
private static int PAGE_INDEX = 1;
private static int PER_PAGE = 20;
private static int CURRENT_PAGE = PAGE_INDEX;

private boolean isLoading = false;
private boolean isLastPage = false;

private String url = Constants.SEARCH_URL + "top30&page="+ PAGE_INDEX;

public Top30Fragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View vtop = inflater.inflate(R.layout.fragment_top30, container, false);

    top30RV = vtop.findViewById(R.id.top30RV);
    top30RV.setHasFixedSize(true);

    LinearLayoutManager llm = new LinearLayoutManager(getActivity());

    top30RV.setLayoutManager(llm);

    if (Utils.isNetwork(getActivity())){
        fetchWallpapers();
    } else {
        Snackbar.make(getActivity().findViewById(android.R.id.content), "Check Connection", Snackbar.LENGTH_LONG).show();
    }

    adapter = new Top30Adapter(getActivity(), itemsList);
    top30RV.setAdapter(adapter);

    top30RV.addOnScrollListener(new PaginationScrollListener(llm) {
        @Override
        protected void loadMoreItems() {
            isLoading = true;
            PAGE_INDEX = PAGE_INDEX + 1;
            Log.d(TAG, "PIn:\t" + PAGE_INDEX);

            loadNextPage();

        }

        @Override
        protected int getTotalPageCount() {
            return PAGE_COUNT;
        }

        @Override
        public boolean isLoading() {
            return isLoading;
        }

        @Override
        public boolean isLastPage() {
            return isLastPage;
        }

    });

    adapter.notifyDataSetChanged();

    return vtop;
}

private void loadNextPage() {
    int newIndex = PAGE_INDEX +=1;
    Log.d(TAG, "Next Page:\t" + newIndex);
    Log.d(TAG, "Next Page Index:\t" + newIndex);
    Log.d(TAG, "Next Page URL:\t" + url);
    AndroidNetworking.get(url)
            .setTag("Load Next Top30")
            .setPriority(Priority.HIGH)
            .build()
            .getAsJSONObject(new JSONObjectRequestListener() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "Next Page Response:\t" + response.toString());
                    if (response != null){

                        isLoading = false;
                        adapter.removeLoadingFooter();

                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());

                            JSONArray results = jsonObject.getJSONArray("results");

                            for (int p = 0; p < results.length(); p++){
                                JSONObject items = results.getJSONObject(p);

                                UnsplashImages images = new UnsplashImages();
                                images.setImageId(items.getString("id"));

                                JSONObject urls = items.getJSONObject("urls");

                                images.setRawImg(urls.getString("raw"));
                                images.setFullImg(urls.getString("full"));
                                images.setRegularImg(urls.getString("regular"));
                                images.setSmallImg(urls.getString("small"));
                                images.setThumbImg(urls.getString("thumb"));

                                itemsList.add(images);
                                adapter.notifyDataSetChanged();

                                Log.d(TAG, "New List Size:\t" + itemsList.size());

                                if (CURRENT_PAGE != PAGE_COUNT){
                                    adapter.addLoadingFooter();
                                } else {
                                    isLastPage = true;
                                }

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onError(ANError anError) {

                }
            });
}

private void fetchWallpapers() {
//        String url = Constants.SEARCH_URL + "top30&page="+ PAGE_INDEX + "per_page=" + PER_PAGE;
    Log.d(TAG, "Top30 Unsplash URL:\t" + url);

    AndroidNetworking.get(url)
            .setPriority(Priority.HIGH)
            .setTag("Get Seasons Wallpapers")
            .build()
            .getAsJSONObject(new JSONObjectRequestListener() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "Un-Response:\t" + response.toString());
                    if (response != null){
                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());

                            PAGE_COUNT = jsonObject.getInt("total_pages");
                            Log.d(TAG, "Page Count:\t" + PAGE_COUNT);

                            JSONArray results = jsonObject.getJSONArray("results");

                            for (int p = 0; p < results.length(); p++){
                                JSONObject items = results.getJSONObject(p);

                                UnsplashImages images = new UnsplashImages();
                                images.setImageId(items.getString("id"));

                                JSONObject urls = items.getJSONObject("urls");

                                images.setRawImg(urls.getString("raw"));
                                images.setFullImg(urls.getString("full"));
                                images.setRegularImg(urls.getString("regular"));
                                images.setSmallImg(urls.getString("small"));
                                images.setThumbImg(urls.getString("thumb"));

                                itemsList.add(images);
                                adapter.notifyDataSetChanged();

                                Log.d(TAG, "List Size:\t" + itemsList.size());

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onError(ANError anError) {

                }
            });
}

Is there another way to construct the request url to increment the page index? Thanks.


text:
Q: Maximum serialization depth exceeded (does the object being serialized have a circular reference?) I am trying to save this simple class, but MongoDB is not accepting.
public class CredentialSet
{
    public CredentialSet()
    {
        this.Items = new ObservableCollection<CredentialSet>();
    }
    [BsonId]
    public ObjectId _id { get; set; }
    public string Title { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string WebSite { get; set; }
    public string Notes { get; set; }
    public int Owner { get; set; }
    public DateTime LastUpdate { get; set; }

    public ObservableCollection<CredentialSet> Items { get; set; }

    public CredentialSet parent { get; set; }
}

Maximum serialization depth exceeded (does the object being serialized have a circular reference?).
How to solve it?

A: I resolved problem in our core project on this way.
'
using Newtonsoft.Json;
using AutoMapper;

var stringContent = JsonConvert.SerializeObject(_mapper.Map<DataDTO>(newdata), new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }).ToString();

 _mongoService.Save(JsonConvert.DeserializeObject<DataDTO>(stringContent));

//mongo service save method
public async void Save(DataDTO dataDTO)
{
  await observationCollection.InsertOneAsync(dataDTO));
}
'


text:
Q: Game Dev - Working with Screen Coordinates vs World Coordinates A friend and myself are new to game development, and we had a discussion regarding World Coordinates and Screen Coordinates.
We are following a wonderful online tutorial series for libGDX and they are using a 100 PPM (pixels per meter) scaling factor.  If you re-size the screen, the scaling of objects no longer works.  My friend is convinced that it is not a problem, and he may be right.  But, I'm under the impression that when developing a game, the developers should typically only work with the pre-defined world coordinate system and let the camera transform it to the chosen screen coordinates. I do understand the need for reverse transformations when using mouseclicks, etc.  But, the placing and scaling of objects in the world space is my concern.
I would like to reach out to this community for some professional feedback.

A: Thats one of the bigest problem of almost all Libgdx tutorials. They are great, but the pixel to meter/units conversation is just wrong.
Libgdx offers a great solution for that with Camera and an even better solution with the new Viewport classes (which under the hood work with Camera).
Its is really simple and will solve the problem of different screen sizes/aspect rations.
Just choose a Virtual_Width and Virtual_Height (think about it in meters or similar units).
For exampl, you have humans fighting each other in a 2D platformer game. LEts say our humans are 2m tall, so think about, how much screenspace should one human use? If we say, a human should take 1/10 of the screen space, our virtual height is 10*2=20. Now think about the primary aspect ration you are targeting. Lets say it is 16/9, so you have a virtual width of about 35.
Next, you need to think about what kind of Viewport you want. You sure want to use a Viewport, which supports Virtual_Width and Virtual_Heigth.
You may want a Viewport, which keeps the aspect ratio and fills the rest of the screen (if the screen has different aspect ratio) with black bars (FitViewport) or you may want the Viewport to fill the whole screen by stretching the units (StretchViewport).
Now just create the Viewport with your virtual width and heigth and update it in the resize() method with the given width and height.
Hope it helps.

A: It's be better name as Units per meter
And when you resize your screen you just set a new projective matrix, so everything works fine )
What you should worry about it's a aspect ratio.
Everything rest is doesn't matter.
So answering your question - Stay with world coordinates.
It also make simple add physics, light calculations, any dimensions ( 1.8 units instead 243 pixels )


text:
Q: is it possible to make ajax call inside web-worker with vuejs We are having a problem with infinite scrolling as another developer described here:
Scrolling on touch screen dramatically slows down AJAX download time on Chrome
his solution was to use web workers and make ajax call from web-worker.
We are using vuejs and it seems we cant make ajax calls using web-workers.
We are using vue-worker https://github.com/israelss/vue-worker library that makes it simple to implement web-workers.
Has anyone else made ajax calls from their own thread using web-worker?


text:
Q: jQuery inArray doesn't work I'm building a website and I have some data within php variables.
I'm trying to use that data for jQuery engine for Java enabled browsers.
I came across the problem with using php variables within jQuery script:
Here's the code I can't get to work.
//PHP array:
$filters['ab']='text a';
$filters['cd']='text b';

// jQuery script:
// Key I want to find in array
var test = "ab";

// Reading php array into JSON
filters = $.parseJSON('<?php echo json_encode($filters); ?>');

// Trying to use JSON data to create Array using original keys and values
var filtersArray = new Array();
$.each(filters, function(key) {
    filtersArray[key] = $(filters).attr(key);
});
alert(filtersArray['ab']); returns "text a";  // Seems to be working

// Trying to find the test variable value
filterIndex = $.inArray(test, filtersArray) // Not found

Sorry for previous careless version of post. I though shorter will be better, but in fact it came out completely useless.
Thanks

A: I think you need something like this
function inObject(obj, val) {
    return Object.keys(obj).filter(function(key) {
        return obj[key] === val;
    }).length > 0;
}

jsFiddle demo here - http://jsfiddle.net/VZ5A9/
See the following pages for browser compatibility as well as shims for adding support

*

*Object.keys - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys#Browser_support

*Array filter - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Browser_compatibility
Update
If you need to find the key, try this one (this is also more compatible with older browsers)
function findFirstKeyByValue(obj, val) {
    for (var key in obj) {
        if (obj.hasOwnProperty(key) && obj[key] === val) {
            return key;
        }
    }
    return null;
}

Demo - http://jsfiddle.net/VZ5A9/1/

A: The reason this isn't working is because the variable you named arr isn't an array, it's an object literal. To get this code to work try this (FIDDLE):
arr = ["b","d","f"];
uri = "d";

alert(jQuery.inArray(uri, arr));


text:
Q: A question about part of the proof of the Central Limit Theorem I've been reading the proof the Central limit theorem from Rick Durret's book. In Theorem 3.3.8 he proves the following

If $E[X^2]<\infty $ then
$$\tag{1}\phi(t)=1+itE[X]-\frac{t^2}{2}E[X^2]+o(t^2)$$
where $\phi$ denotes the characteristic function of $X$ and $\lim_{t\to 0}o(t^2)/t^2=0$.

For the proof of this theorem he uses the estimate $$\tag{2}\biggl|e^{ix}-\sum_{k=0}^{n}\frac{(ix)^k}{k!}\biggr|\leq \min\biggl\{\frac{2|x|^n}{n!},\frac{|x|^{n+1}}{(n+1)!}\biggr\}$$
Although, just before the proof of this estimate he makes the observation that if $X$ has finite $n-$th moment $E[|X|^n]<\infty$ then $\phi$ is $n$ times differentiable at $0$ and $\phi^{(n)}(0)=E[(iX)^n]$. So, it follows from the Taylor expansion of $\phi$ at $0$ that
$$\tag{3}\phi(t)=\sum_{k=0}^{n}\frac{E(iX)^k}{k!}t^k+o(t^n)$$
My question is on the proof of Theorem 3.3.8 why do we need the estimate of the difference of $e^{ix}$ and it's partial sums since before we have proved $(3)$ which gives us the result for $n=2$. After the proof of Theorem 3.3.8 he makes a comment that roughly says "because we dont have to assume that $E[|X|^3]<\infty$", but i cannot see why. Anyone knows why do we have to prove $(2)$ and use it to prove $(1)$ rather than use $(3)$?
Thanks in advance!


text:
Q: identify this short story about a man with no legs living underground I remember reading this story about 20 years ago as part of a scifi/fantasy compilation.
It's about a guy remembering a very weird event that happened when he was a child, and many years later returning to the place where it happened.  He remembers a hole that he fell through, and this scary old man with no legs that lived down there.  The legless man had a mute wife, that "quacked", and there were golden trinkets in his lair.  I think the old man wanted the boy to stay down in the hole, and while the boy pretended to accept his new fate, was always looking for a way to escape.  In the end, the boy tries to get out and the legless man tries to catch him, dragging himself through the tunnels with his powerful arms.

A: Under The Garden by Graham Greene.
Yes, this is a very compelling story, that I too sometimes think about decades after first reading it.  Hard to even say what it was about, except it sticks with you.  Luckily, in high school in the 90s I started a personal collection of quotes I liked, shortly after I read this, and have it listed in that collection.
The legless man and his tongueless wife lived underground based on a theory that only accidents killed you, by living in a safe place one could be effectively immortal.  The narrator remembers this as an adult, when he is diagnosed with cancer, and goes looking for the half remembered tunnel to the underground as a chance to be saved.
The legless man dispensed an array of interesting wisdom, such as, "Be disloyal. It's your duty to the human race. The human race needs to survive and it's the loyal man who dies first from anxiety or bullet or overwork."
Excerpt from a review:

These chapters remind me strongly of John Cowper Powys as we follow WW (one moit (a word used in the text) himself as a child dreaming and the other moit himself now older, in terminal illness, remembering real events as a child under the garden), a mix of Long John Silver and Robinson Crusoe, and finding first this fish and a newspaper (Colchester Guardian) from fifty years before smelling of fish, and an oldish man sitting on a decorative lavatory seat (except there is a pit underneath) and his quacking wife.


text:
Q: How to unselect mysql default database? Thanks to USE 'db_name' i can select MySQL default database.
But i can't find out, how to unselect default database. So, that DATABASE() statement return none.

A: *

*you have to customize your constructors pro grammatically where default constructors initialize your default database where else your parametric constructors getting custom database.

*Use Stored Procedures.


text:
Q: how to fix a loop that stops due to an error? I have this data frame with the single column date within a list of 200 elements that are also data frames and some of which contain variables other than the date.
list_dfs[[60]]

   DATE
   <chr>
 1 2013-12-01
 2 2013-12-02
 3 2013-12-03
 4 2013-12-04
 5 2013-12-05
 6 2013-12-06
 7 2013-12-07
 8 2013-12-08
 9 2013-12-09
10 2013-12-10
# ... with 21 more rows

In another list, I have another data frame that also has only the date.
list_dfs_2[[60]]

   DATE
   <chr>
 1 2013-12-01
 2 2013-12-02
 3 2013-12-03
 4 2013-12-04
 5 2013-12-05
 6 2013-12-06
 7 2013-12-07
 8 2013-12-08
 9 2013-12-09
10 2013-12-10
# ... with 21 more rows

Therefore, when I want to multiply the first data frame with the second one in a loop and save it in a list I get an error.
for(i in 1:200){
    cbind(list_dfs[[i]][1], #save column date
    list_dfs_2[[i]][-1]*list_dfs_2[[i]][-1]) -> new_list[[i]] # save the multiplication
}

Error in data.frame(..., check.names = FALSE) :
  arguments imply differing number of rows: 31, 0

It stops and does not follow the loop, it saves only the multiplication up to 59, even if after that there are data frames that are not empty.
list_dfs[[61]]

# A tibble: 31 x 2
   DATE        BGA.CN
   <chr>        <dbl>
 1 2014-03-01  0.4
 2 2014-03-02  0.3
 3 2014-03-03  0.9
 4 2014-03-04  0.4
 5 2014-03-05  0
 6 2014-03-06 -0.0280
 7 2014-03-07  0
 8 2014-03-08  0.3
 9 2014-03-09  0.2
10 2014-03-10  0
# ... with 21 more rows

I would like it to continue, how can I do it?


text:
Q: Inject parameter into Service Symfony 3.3 I have a service which injects string values from my parameters.yml.
I declared the service like so:
parameters:
    url: '%cms_url%'
    client_id: '%cms_client_id%'
    client_secret: '%cms_client_secret%'

services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false

    AppBundle\:
        resource: '../../src/AppBundle/*'
        exclude: '../../src/AppBundle/{Entity,Repository}'

    api:
        class: AppBundle\Service\Api
        arguments: ['@session', '%cms_url%']
        autowire: false

    access_token_generator:
        class: AppBundle\Security\AccessTokenGenerator
        arguments: [cms_url, cms_client_id, cms_client_secret]
        autowire: false

When I ran the app it AccessTokenGenerator throws an error saying:

Cannot autowire service argument $apiUrl must have typehint or given
  value directly.

This is my AccessTokenGenrator class:
class AccessTokenGenerator
{
    private $apiUrl;

    private $clientId;
    private $clientSecret;

    public function __construct(string $apiUrl, string $clientId, string $clientSecret)
    {
        $this->apiUrl = $apiUrl;
        $this->clientId = $clientId;
        $this->clientSecret = $clientSecret;
    }

    public function generateAccessToken(string $username, string $password) : ?AccessToken
    {
        $queryParams = [
            'client_id'     => $this->clientId,
            'client_secret' => $this->clientSecret,
            'grant_type'    => 'password',
            'username'      => $username,
            'password'      => $password
        ];
        $requestUrl = $this->apiUrl . '/oauth/v2/token?' . http_build_query($queryParams);

        $client = new Client();
        $request = new Request('GET', $requestUrl);
        $response = $client->send($request);

        $contents = json_decode($response->getBody()->getContents(), true);

        if (isset($contents['access_token'])) {
            $accessToken = new AccessToken();
            $accessToken->setAccessToken($contents['access_token']);
            $accessToken->setExpiresIn($contents['expires_in']);
            $accessToken->setTokenType($contents['token_type']);
            $accessToken->setScope($contents['scope']);
            $accessToken->setRefreshToken($contents['refresh_token']);

            return $accessToken;
        }
    }
}

I dont know why it proceeds to autowiring even my configuration is set to false.
Thanks!

A: @Arno is right you can autowire a scalar if you specify exaclty the name of paramaters.
https://symfony.com/doc/current/service_container.html#service-parameters
sorry i haven't see it part before.

A: The AppBundle\Security\AccessTokenGenerator service is automatically loaded with autowire: true by this declaration :
AppBundle\:
        resource: '../../src/AppBundle/*'

You can override any service that's imported by using its id (class name) below
AppBundle\Security\AccessTokenGenerator:
    arguments: ['%cms_url%', '%cms_client_id%', '%cms_client_secret%']

Warning, you have forgottent the percentage '%' for arguments.
If you need a access_token_generator service, you can make an alias :
access_token_generator: '@AppBundle\Security\AccessTokenGenerator'

Final file could be :
services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false

    AppBundle\:
        resource: '../../src/AppBundle/*'
        exclude: '../../src/AppBundle/{Entity,Repository}'

    api: '@AppBundle\Service\Api'
    AppBundle\Service\Api:
        arguments: {$apiUrl: '%cms_url%'}

    access_token_generator: '@AppBundle\Security\AccessTokenGenerator'
    AppBundle\Security\AccessTokenGenerator:
        arguments: ['%cms_url%', '%cms_client_id%', '%cms_client_secret%']

Documentation : manually wiring arguments
Documentation : explicitly configuring services and arguments

A: You can not autowire scalar parameter just object
see documentation
https://symfony.com/doc/current/service_container/autowiring.html#fixing-non-autowireable-arguments


text:
Q: PHP: Regarding the view layer in MVC? Regarding the MVC pattern, the view layer is supposed to be the functions that 'return' HTML data, or the view layer is actually the HTML data itself?

A: View classes in MVC-inspired patterns for web (it is extremely hard to implement classical MVC on web, and impossible with only PHP) are responsible for presentation logic. Then create response to requests and juggle multiple templates.
The way how information gets from model layer to the chosen view largely depends on which of MVC-inspired patterns is implemented. If you are using MVP or MVVM, then information is provided by the controller and the view is passive ( but view is not a dumb template). If you are going with Model2 MVC or HMVC patterns, then view is active an requests information from model layer.
When this view has acquired the information , it decides with templates to combine. Or even if templates are even necessary. And then create the response.
The response that each View generated can be HTML, JSON, XML or just plain text. Or, if it's required, sent only a HTTP header (like when doing redirect). This all is part of presentation logic.

A: The borderline of model, controller and view can be shown this way:
/* model models/post.php */

<?php
  class Post {
    public static all() {
      return Array(...);
    }
  }
?>

/* controller /posts/index.php */

<?php
  require "../../models/post.php"
  $posts = Post.all();
  require "../../views/posts/index.php"
?>

/* view /views/posts/index.php */

<?php foreeach ($posts as $post): ?>

<?php echo $post['name']; ?>

<?php endforeach; ?>

Ideologically it may be just function but common practice is something like template in template engines. So view layer is html + data insertions (without logic of how we get and why). Again ideologically it is function too, but not function of programming language of framework, for example.

A: View is the "template"
Model is the "Data"
Controller is the "connector" and the algorithems places.

A: View Layer is subjected to what you want to be visible on client as a presentation. In most cases it is HTML, CSS and Javascript you can also use XML and JSON.
In genral,
Controller ask Model to provide Data.
Controller can than make changes to this data as it need.
Controller send data to View to present with help of template/html.

A: View Layer is the functions that return the HTML Data


text:
Q: Appendices titles have different language I have the following problem. I have already inserted 2 appendices which show up as with a greek title - as intented (Παράρτημα Ι, Παράρτημα ΙΙ), but when I insert a third one I the output is "Appendix III" instead of "Παράρτημα ΙΙΙ".
The code I am using is the following
\documentclass[12pt, twoside]{report}
\usepackage{graphicx}
\graphicspath{ {images/} }

\usepackage[LGR, T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english, greek]{babel}
\usepackage{alphabeta}
\usepackage{physics}
\usepackage{tensor}
\usepackage{hyperref}
\usepackage{amsmath}
\usepackage{mathtools}
\usepackage{bbold}
\usepackage{comment}
\usepackage{float}
\usepackage[a4paper,width=150mm,top=25mm,bottom=25mm]{geometry}
\usepackage{xr}
\usepackage{gfsartemisia}
\usepackage{bm}

\usepackage{fancyhdr}
\pagestyle{fancy}

\fancyhf{}
\fancyhead[L]{\rightmark}
\fancyfoot[RE,LO]{\thepage}

\newcommand{\en}{\selectlanguage{english}}

\begin{document}

\input{chapters/titlepage}

\cleardoublepage

\chapter*{Ευχαριστίες}
Θέλω να ευχαριστήσω..

\cleardoublepage

\chapter*{Περίληψη}
Στην παρούσα εργασία θα γίνει μελέτη των μελανών οπών {\en Kerr}. Αναλυτικότερα, θα μελετηθούν περιστρεφόμενες και χωρίς φορτίο μελανές οπές με αξονική συμμετρία ως προς τον άξονα περιστροφής τους. Αρχικά θα γίνει εισαγωγή της μετρικής {\en Kerr} η οποία περιγράφει τη γεωμετρία του κενού χωροχρόνου γύρω από μελανές οπές {\en Kerr} και θα υπολογισθούν οι συνιστώσες της αποδεικνύοντας πως αποτελεί λύση των πεδιακών εξισώσεων του {\en Einstein}. Στη συνέχεια θα γίνει μελέτη των ιδιοτήτων του ορίζοντα μιας μελανής οπής {\en Kerr} και τέλος θα εξετασθεί η ύπαρξη κλειστών γεωδαισιακών που σχετίζονται με τις μελανές οπές αυτές.

\tableofcontents

\chapter{Εισαγωγή - Οι πεδιακές εξισώσεις του {\en Einstein}}
\input{chapters/introduction}

\chapter{Ο χωρόχρονος {\en Kerr} και η γεωμετρία του}
\input{chapters/chapter02}

\chapter{Chapter Three Title}
\input{chapters/chapter03}

\chapter{Conclusion}
\input{chapters/conclusion}

\appendix

\renewcommand{\thechapter}{\Roman{chapter}}

\chapter{Ιδιομορφίες ({\en Singularities})}
\input{chapters/appendix}

\chapter{Συστήματα συντεταγμένων}
\input{chapters/appendix2}

\chapter{Διανυσματικά πεδία {\en Killing}}
\input{chapters/appendix3}

\end{document}

A: The guess is that you're missing a } after {\en, so \selectlanguage{english} is not turned off.
I don't think you need \usepackage{alphabeta}, which is for inserting Greek letters in a non-Greek context.
More importantly, I suggest to avoid a command such as your \en and prefer something like
\DeclareRobustCommand*{\texten}[1]{\foreignlanguage{english}{#1}}

There are several reasons for this; the main one is that this is more efficient as it does not litter your auxiliary files with \select@language commands that slow down processing by executing useless instructions.
Two final suggestions: you don't need to load the LGR encoding and \usepackage{hyperref} should be the last in the packages.


text:
Q: How to show that $A_m^s \to A^s$ if $A_m \to A\ $?
Let $\{A_m\}_{m \geq 1}$ be a sequence of $n \times n$ complex self-adjoint matrices converging to an $n \times n$ matrix $A$ in norm. Then for any $s \in \mathbb N$ show that $A_m^s$ converges to $A^s$ in norm.

I have tried to write $A_m^s - A^s = (A_m - A)\ p(A_m,A)$ for some polynomial $p$ of two variables but I failed. Could anybody provide me some suggestion in this regard?
Thanks for investing your valuable time in reading my question.

A: Convergence in the norm is equivalent to convergence of all the entries of the matrices. So $(A_m)_{ij} \to A_{ij}$ for la $i,j$. Now $(A_m^{s})_{ij}$ is a finite sum of numbers of the type $(A_m)_{ik_1}(A_m)_{k_1k_1}\cdots (A_m)_{k_{s-1},j}$ so it converges to the $(i,j)-$ element of $A^{s}$.

A: You can very well use your idea. The key would be: Use that in finite dimensions all norms are topologically equivalent, so you can choose your norm. Take any submultiplicative matrix norm. Then use the submultiplicative property and the regular norm properties to bound $||p(A_m,A)||$ by some function of $\max\{||A||,||A_i||\}$. Then you get your result.
Edit: That is of course only if you find such Polynomial $P_m$ that are uniformly bounded, which I assumed have been found from the way the question was asked.
Alternatively have a look at this more general principle:
If $V,W,Z$ are metric spaces and $f_n,f:V\to W$ and $g_n,g:W\to Z$ equicontinuous. If $f_n\to f $ and $g_n\to g$ unif, then $f_n\circ g_n \to f\circ g$ unif.
Indeed: If $\epsilon>0$ there is a $\delta>0$ so that for $w,v\in W$ with $|w-v|<\delta$ we have $|g(w)-g(v)|<\epsilon$ and $|g_n(w)-g_n(v)|<\epsilon$. For n large enough we'll have $||f-f_n||<\delta$ and $||g-g_n||<\epsilon$. So we have:
$$ || g(f(x))-g_n(f_n(x)) || \leq
 || g(f(x)) - g_n(f(x))|| + || g_n(f(x)) - g_n(f_n(x)) < 2\epsilon $$


text:
Q: the image of the openSelectDialog method of the ImagePickerIOS in the React Native is not output Here is my code:
import React, {Component} from 'react';
import {ImagePickerIOS, Image, Text, View} from 'react-native';

class Dashboard extends Component {

  constructor(props) {
    super(props);
    this.state = {
      image: ''
    };
  }

  componentDidMount() {
    ImagePickerIOS.openSelectDialog({}, imageUri => {
      this.setState({ image: imageUri });
    }, error => console.log(error));
  }

  render() {
    return (
      <View>
        <Text>{JSON.stringify(this.state.image)}</Text>
        { this.state.image ?
        <Image style={{flex: 1}} source={{uri: this.state.image}} />
        : null }
      </View>
    );
  }
}

export default Dashboard

When you run the above code, this.state.image will have "assets-library: //asset/asset.HEIC? Id = .... & ext = HEIC".
However,  is not output.
And <Image style={{width: 200, height: 200}} source={{uri: this.state.image}} />
This style property puts the IOS simulator to a black screen and exits the app.
The React Native version is 0.57.4 and the simulator is iPhone X - 12.1.
Help.

A: I have the same problem. But I have solved this issue.
You may need add width and height to  style.
{ this.state.image ? <Image style={{height: 100, width: 100}} source={{uri: this.state.image}} /> : null }


text:
Q: Could not initialize class org.jetbrains.kotlin.gradle.internal.KotlinSourceSetProviderImplKt in react native This error is occuring while running npx react-native run-android
FAILURE: Build failed with an exception.

* Where:
Build file 'C:\Users\Mehnaz Kaif\Desktop\Abuzar\ReactNative\clicksystemreactnative\android\build.gradle' line: 20

* What went wrong:
A problem occurred evaluating root project 'ClickSysReactNative'.
> Could not initialize class org.jetbrains.kotlin.gradle.internal.KotlinSourceSetProviderImplKt


text:
Q: Provisioning GitHub-backed CodePipeline using CloudFormation I am trying to create my CodePipeline using CloudFormation. The problem I'm having is that once it's created and tries to run, it immediately gives me the error:

Invalid action configuration The GitHub repository "MyOrg/MyRepo" or
  branch "MyBranch" does not exist.

When in fact they both do. I can click on Edit, select my source control, Connect to GitHub, then select that exact repository and branch, and it works fine. But when starting the pipeline directly following the CloudFormation provisioning of the pipeline, it always gives me this error.
I did an export of the pipeline configuration JSON using aws codepipeline get-pipeline of a freshly provisioned pipeline using CloudFormation, and then did so again immediately after updating the configuration in the console using "Connect to GitHub" and both are identical.

A: Make sure that the Configuration property for your CodePipeline's GitHub Source Action contains all four required properties as listed in the documentation:

*

*Owner

*Repo

*Branch

*OAuthToken
Double check that your provided values are correct, particularly OAuthToken, which approximates the "Connect To GitHub" step in the the AWS Console-based CodePipeline setup.
To get a valid OAuthToken from GitHub to enter here, you need to create a New personal access token with repo and admin:repo_hook scopes enabled, as described in the documentation troubleshooting page.


text:
Q: How to perform the summation/addition of binomial coefficients? From my textbook:
$$
\begin{align}
\sum_{k=0}^n \binom {m+k}m &= \binom {m+n}m + \sum_{k=0}^{n-1} \binom {m+k}m\\\\\\
&= \binom {m+n}m + \binom {m+n}{m+1}\\\\\\
&= \binom {m+1+n}{m+1}
\end{align}
$$
I can't understand (1) how the summation works for binomial (the second one, where the ending index is $n-1$) and (2) how the addition works.
Regarding the addition, should I always write down the expression and do calculations, or there is a simple formula (maybe the Pascal's rule)?
$$
\begin{align}
\binom {m+n}m + \binom {m+n}{m+1} &= \frac {(m+n)!}{m!(m+n-m)!} + \frac {(m+n)!}{(m+1)!(m+n-m-1)!}\\\\\\
&= \frac {(m+n)!}{m!n!} + \frac {(m+n)!}{(m+1)!(m+n-1)!}\\\\\\
&= \dots
\end{align}
$$

A: Let's take a look:

$$\begin{align}
\sum_{k=0}^n \binom {m+k}m &= \binom {m+n}m + \sum_{k=0}^{n-1} \binom {m+k}m\\\\\\
&= \binom {m+n}m + \binom {m+n}{m+1}\\\\\\
&= \binom {m+1+n}{m+1}
\end{align}$$

This is part of a proof by induction that
$$\sum_{k=0}^n\binom{m+k}m=\binom{m+1+n}{m+1}\tag{1}$$
for all $n\in\Bbb N$. Let $P(n)$ be the specific assertion in $(1)$, that the identity is true for the particular value $n$. Then the calculation above is the induction step: the induction hypothesis is that $P(n-1)$ is true, and we're showing that this implies that $P(n)$ is true. $P(n-1)$, written out in full, is that
$$\sum_{k=0}^{n-1}\binom{m+k}m=\binom{m+1+(n-1)}{m+1}=\binom{m+n}{m+1}\;;\tag{2}$$
we'll use this in a moment.
The first equality in the calculation is simply splitting the $k=n$ term off from the rest of the summation. The second step uses $(2)$, the induction hypothesis, to replace $\sum_{k=0}^{n-1}\binom{m+k}m$ by its value $\binom{m+n}{m+1}$. And the third and last equality is just Pascal's identity, which in its general form states that
$$\binom{n+1}k=\binom{n}k+\binom{n}{k-1}\;.\tag{3}$$
This can be proved either combinatorially or algebraically, as you set out to do with the special case needed for the calculation here. If you're going to prove it algebraically, though, it's easier to prove the general form $(3)$ and then substitute into it to get the special case that you need.


text:
Q: The ConnectionString property has not been initialized Error during inserting data to Database I'm currently using .NET Web Api to register a user into SQL Server using a stored procedure. When I'm trying to add record to the database, I get an error

The ConnectionString property has not been initialized

I have looked up on the internet to change the connection string but the result is still the same. When I'm debugging, code execution goes to this line
db.ExecNonQuery("SSO_Register", parm)

in the doRegister method and then throws the exception. Please help.
Connection string:
<connectionStrings>
    <add name="_cs"
         connectionString="Data Source=DESKTOP-KR81RU5\MSSConQLSERVER01;Initial Catalog=HISDB;Integrated Security=True;Connect Timeout=3600"
         providerName="System.Data.SqlClient" />
</connectionStrings>

dbUtil class:
private static string _cs = null;

public dbUtil(string cs)
{
    _cs = cs;
}

public void ExecNonQuery(string sp, SqlParameter[] parm)
{
    using (SqlConnection connection = new SqlConnection(_cs))
    {
        using (SqlCommand command = new SqlCommand(sp, connection))
        {
            command.CommandType = CommandType.StoredProcedure;
            command.CommandTimeout = 120;

            connection.Open();

            if (parm != null)
            {
                for (int i = 0; i < parm.Length; i++)
                    command.Parameters.Add(parm[i]);
            }

            command.ExecuteNonQuery();
        }
    }
}

doRegister method:
bool _return = false;

try
{
    string tac = " ";

    Test util = new Test();
    tac = Test.getTac();

    SqlParameter[] parm =
                {
                    new SqlParameter("secure_word", objsso.secure_word),
                    new SqlParameter("full_name", objsso.full_name),
                    new SqlParameter("phone_number", objsso.phone_number),
                    new SqlParameter("nationality", objsso.nationality),
                    new SqlParameter("id_number", objsso.id_number),
                    new SqlParameter("dob", objsso.dob),
                    new SqlParameter("email", objsso.email),
                    new SqlParameter("user_id", objsso.email),
                    new SqlParameter("full_name", objsso.full_name),
                    new SqlParameter("provider_id", objsso.provider_id),
                    new SqlParameter("temp_token", objsso.temp_token),
                    new SqlParameter("tac", tac)

            };

    dbUtil db = new dbUtil(_cs);
    db.ExecNonQuery("SSO_Register", parm);
    _return = true;
}
catch (Exception ex)
{
    _return = false;
    throw ex;
}

return _return;

A: You are not reading the connection string from Configuration so in you case connection sting is null.
var connectionString =System.Configuration.ConfigurationManager.
ConnectionStrings["_cs"].ConnectionString;

dbUtil db = new dbUtil(connectionString );

Please try this one.


text:
Q: Environment constants Is there an equivalant to Environment.NewLine in DotNet for a Tab character?

A: Short answer is: no, tab does not change between platforms as newline might, so there is no need for one.
Long answer is: technically, yes, you could use the one provided by VB in the Microsoft.VisualBasic.dll. I think it's Microsoft.VisualBasic.Constants.vbTab, but there's no good reason to use it in C# as I said above.

A: NewLine is on the Environment class because the new line specification varies between platforms:
It's "\r\n" for non-Unix platforms and "\n" for Unix platforms. However tab is always "\t".


text:
Q: getting error as document is empty(size 0kb) when opening pdf file in micromax funbook Iam trying to Downloading pdf from server and displaying it as it is in android micromax funbook.
I am getting the error as document size is empty(0 KB).when open the pdf file...
I'm new to android suggest me the coding what i am using is correct or not for downloading
 public static void DownloadFile(String fileURL, File directory) {
    try {

                    FileOutputStream f = new FileOutputStream(directory);
                    URL u = new URL(fileURL);
                    HttpURLConnection c = (HttpURLConnection) u.openConnection();
                    c.setRequestMethod("GET");
                    c.setDoOutput(true);
                    c.connect();
                    InputStream in = c.getInputStream();
                    byte[] buffer = new byte[1024];
                    int len1 = 0;
                    while ((len1 = in.read(buffer)) > 0) {
                            f.write(buffer, 0, len1);
                    }
                    f.close();
            } catch (Exception e) {
                    e.printStackTrace();
            }
    }

and the code for showing pdf.
    public void showPdf() {
            File file = new File(Environment.getExternalStorageDirectory()
                    + "/pdf/Read.pdf");
            PackageManager packageManager = getPackageManager();
            Intent testIntent = new Intent(Intent.ACTION_VIEW);
            testIntent.setType("application/pdf");
            List list = packageManager.queryIntentActivities(testIntent,
                    PackageManager.MATCH_DEFAULT_ONLY);
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/pdf");
            startActivity(intent);
        }

A: Use DownloadManager instead of writing your own download code .

A: You should use c.openStream(); instead of c.getinputstream();.