text:
Q: RISCV testing emulator When I'm trying to run riscv emulator asm tests I faced with below error:
./emulator-DefaultCPPConfig +dramsim +max-cycles=100000000 +verbose +loadmem=output/rv64ui-p-amoand_d.hex none 2> output/rv64ui-p-amoand_d.out && [ $PIPESTATUS -eq 0 ]
/bin/sh: 1: [: -eq: unexpected operator
make: *** [output/rv64ui-p-amoand_d.out] Error 2

I followed your instruction in your git. It can build emulator without any error, but problem happens when it's trying to run tests.
I added bash behind of the command in the makefile and the first error solved but when I did that I got a new error:
bash ./emulator-DefaultCPPConfig +dramsim +max-cycles=100000000 +verbose +loadmem=output/rv64ui-p-amoswap_d.hex none 2> output/rv64ui-p-amoswap_d.out && [ $PIPESTATUS -eq 0 ]
make: *** [output/rv64ui-p-amoswap_d.out] Error 126

A: The problem is from Shell variable, I just needed to add following line to Makefile:
SHELL=/bin/bash

It would solve the problem.


text:
Q: UISegmentedControl with square corners I would like to modify UISegmentedControl with a subclass to remove the rounded corners. I can't seem to set the cornerRadius. Making the SegmentedControl wider than the screen (and therefor "chop" off the corners) is not an option since I have 4 or 5 segments and they would then vary in size.
Is there a way to do this?
Thanks

A: Another alternative to accomplish this in interface builder:
Drag a UIView object to your UIViewController, this may be a subview of your UIView.
Drag a UISegmentedControl as a subview of your UIView.  The segmented control should now be indented in your list UIViewController objects. (see screenshot below).
Resize the SegementedControl so that its' frame is outside the boundaries of your UIView object.  In my case I set the frame of the SegementedControl to X = -10 and added +20 to the width of the SegementedControl so that the total width of the segmented control because 20 greater then the UIView object. (hopefully, the screen shot below helps).
I also adjusted the following settings for the UIView object and SegmentedControl:
UIView: check Clip SubViews, uncheck AutoResize Subviews.
SegementedControl: uncheck Clip SubViews, uncheck AutoResize Subviews.

A: To make the corner square use the following code:
segmentContrl.layer.borderColor=*anycolor*.CGColor;
segmentContrl.layer.cornerRadius = 0.0;
segmentContrl.layer.borderWidth = 1.5f;

A: One alternative, if "cropping" part of the first and last segment is problematic, may be to crop the entire first and last segment (which you've made dummy unused segments). That way you can still keep a common size for every segment.

A: Just use the built in customization methods and set a background image for each segment state.  This will override the border entirely.  If the background images are square, then your segmented control will appear square. Use the following code for each segment state you want to customize.
[segmentedControl setBackgroundImage:[UIImage imageNamed:@"square-background-image-selected"]
                    forState:UIControlStateSelected
                  barMetrics:UIBarMetricsDefault];

A: You can set the width of the segments (using setWidth:forSegmentAtIndex:) so you can easily make the left and right end segments larger (say 10px larger) than the others and then you can crop off 10px from either end and have square corners.  You don't have to make it larger than the screen width, instead put it inside a UIView and use it to crop the ends.
On the other hand just could just make your own segmented control using a set of custom UIButtons inside a UIControl.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Download, save( locally ) and display PDF from a link I am developing Windows phone 8 application. In my application, i have to display PDF file in  offline( without net connection ) mode, within application. For that i have to do the following,

*

*Download PDF file from a link( URL ) provided by server side.

*Save the downloaded PDF file in local storage.

*Open and display PDF file from local storage.

On searching, i found suggestions to use ComponentOne Studio's toolset called 'Studio for Windows Phone'. Unfortunately it is not free. Is there any way to implement in free of cost?
Any reference, samples or ideas will be greatly appreciated.

A: You can download the PDF file and save it in Isolated Storage, to be able to view later offline using a PDF viewer app such Adobe Reader or PDF Reader.
So lets see how to do it step-by-step.
1- Download PDF file from a link( URL ) provided by server side:
WebClient client = new WebClient();
client.OpenReadCompleted += client_OpenReadCompleted;
client.OpenReadAsync(new Uri("http://url-to-your-pdf-file.pdf"));

2- Save the downloaded PDF file in local storage:
async void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    byte[] buffer = new byte[e.Result.Length];
    await e.Result.ReadAsync(buffer, 0, buffer.Length);

    using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (IsolatedStorageFileStream stream = storageFile.OpenFile("your-file.pdf", FileMode.Create))
        {
            await stream.WriteAsync(buffer, 0, buffer.Length);
        }
    }
}

3- Open and display PDF file from local storage:
// Access the file.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile pdffile = await local.GetFileAsync("your-file.pdf");

// Launch the pdf file.
Windows.System.Launcher.LaunchFileAsync(pdffile);


text:
Q: Google Chrome Windows Reopens After Reopening It When I leave a Chrome window open and shutdown Windows, when starting it again, the window reopens (with all the tabs). How can I disable this?
PS: I would also like to disable that Chrome opens up every tab again after I close the window. So when closing the window and opening it again that no tabs are open. Because I already select that Chrome should open ONLY chrome://apps on StartUp
PPS: Maybe the reopening of the whole window has something to do with Windows settings also?

Note: This is not a duplicate as suggested above, since the problem also occurs when I just reopen Chrome without restarting Windows...

A: go to chrome setting
at the bottom of page see the on start up  option
set it to open the new tab page
save setting and restart chrome
hope it helps

A: Try 'AdwCleaner' to remove all the unwanted PUP (Potential Unwanted Program) from your system. This will remove all the malware also and make your system clean.
Link to download:
https://downloads.malwarebytes.com/file/adwcleaner


text:
Q: Bootstrap columns stacking vertically instead of horizontally

.card {
  height: 600px;
  width: 800px;
  background-color: darkseagreen;
  padding: 20px;
}

.box1 {
  background-color: floralwhite;
}

.box2 {
  background-color: rgb(238, 185, 80);
}

.box3 {
  background-color: indianred;
}

.box4 {
  background-color: rgb(137, 137, 235);
}

.box5 {
  background-color: rosybrown;
}

.box6 {
  background-color: sienna;
}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

BOX1

BOX2

BOX3

BOX4

BOX5

BOX6

I have been trying to use the bootstrap grid to create a grid however the columns are stacking vertically instead of horizontally. I am trying to achieve a grid like on the picture:

A: It's because you're using the class card.
card is a builtin class name for bootstrap which aligns the items inside of it vertically.
You can simply rename the class card to anything else like card2 and it will work.
Working Example:
https://jsfiddle.net/es318vm7/1/

.card2 {
  height: 600px;
  width: 800px;
  background-color: darkseagreen;
  padding: 20px;
}

.box1 {
  background-color: floralwhite;
}

.box2 {
  background-color: rgb(238, 185, 80);
}

.box3 {
  background-color: indianred;
}

.box4 {
  background-color: rgb(137, 137, 235);
}

.box5 {
  background-color: rosybrown;
}

.box6 {
  background-color: sienna;
}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

BOX1

BOX2

BOX3

BOX4

BOX5

BOX6

A: You will have to change your container name card to something else
the .card class is one of the in-built components of bootstrap which can not be used
Check the fiddle below and adjust your elements as per your requirements.

.card {
  height: 600px;
  width: 800px;
  background-color: darkseagreen;
  padding: 20px;
}

.box {
  min-height:150px;
  margin:10px;
  padding:10px;
}

.box1 {
  background-color: floralwhite;
}

.box2 {
  background-color: rgb(238, 185, 80);
}

.box3 {
  background-color: indianred;
}

.box4 {
  background-color: rgb(137, 137, 235);
}

.box5 {
  background-color: rosybrown;
}

.box6 {
  background-color: sienna;
}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

BOX1

BOX2

BOX3

BOX4

BOX5

BOX6


text:
Q: Не работает ```props``` Всем привет! Не работет props: при наведении на заголовок h1 цвет не меняется, но если props убрать и оставить hover, то все нормально. Не пойму почему так.
import React from 'react';

import './app-header.scss';
import styled from 'styled-components';

const Header = styled.div`
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    h1 {
        font-size: 26px;
        color: ${props => props.colored ? 'red' : 'black'}
        :hover {
            color: white;
    }
}

    h2 {
        font-size: 1.2rem;
        color: grey;
}
`

const AppHeader = () => {
    return (

VladislavTheOne

5 записей, из них понравилось 0

    )
}

export default AppHeader;


text:
Q: how to avoid time out exception while indexing data in elasticsearch with concurrent requests? we are indexing data in elasticsearch using java api and architecture is like there are multiple applications can be running at the same time so many concurrent requests may be made to ES due to which time out exception occures on elasticsearch.how to avoid this without autoscalling elasticsearch?
We have found a approch to do it using kinesis firehose stream so the ES indexing request will go into Kinesis stream and then kinesis will forword it to ES.Is it the correct way to do it? Please suggest any another suitable approch .


text:
Q: Use video as a background in ionic/cordova for ios I'm needing to play like 6 videos as background in differents divs at the same time, but in IOS and ANDROID platforms. I'm developing an ionic app.
I've found a solution that works perfectly with web, but when I builded it up, it worked as I supposed: every video that I used as background just play as full screen.
Here goes some code:

.bg-vid {
 position: absolute;
 top: 50%;
 left: 50%;
 min-width: 100%;
 min-height: 100%;
 width: auto;
 height: 100%;;
 z-index: -100;
 -webkit-transform: translateX(-50%) translateY(-50%);
 -moz-transform: translateX(-50%) translateY(-50%);
 -ms-transform: translateX(-50%) translateY(-50%);
 -o-transform: translateX(-50%) translateY(-50%);
 transform: translateX(-50%) translateY(-50%);
 background: url(http://www.w3schools.com/tags/movie.mp4) no-repeat;
 background-size: cover;
}
   <div>
    <video autoplay muted loop class="bg-vid">
      <source src="http://www.w3schools.com/tags/movie.mp4" type="video/webm">
      <source src="http://www.w3schools.com/tags/movie.mp4" type="video/mp4">
     </video>
   </div>

Hope someone can help me.

A: Please note that the above answer is correct, except for the fact that with recent iOS updates to the video tag, the video must also have the muted property set to true in order to allow autoplay without user gesture.
<video controls preload="auto" autoplay playsinline muted loop><source src="videos/video_file.mp4"></video>

I spent all of last night trying to figure this one out, and I hope that this helps someone else out there.

A: So for this issue as used 2 things.
First one, on config.xml added the next line
<preference name="AllowInlineMediaPlayback" value="true"/>

And after add the webkit-playsinline directive inside the video tag like this:
<video controls preload="auto" webkit-playsinline><source src="videos/video_file.mp4"></video>

And it works like a charm.


text:
Q: WPF button click event is not fired in a new window running in a new STA thread I want to run a progress window that has a button for cancelling a long save operation.
The main UI thread has the following code:
            WinBarProgress winBarProgress = null;

            Thread thread = new Thread(() =>
                {
                    winBarProgress = new WinBarProgress();
                    winBarProgress.Closed += (sender, e) => winBarProgress.Dispatcher.InvokeShutdown();
                    winBarProgress.Show();
                    System.Windows.Threading.Dispatcher.Run();
                });
            thread.CurrentUICulture = CultureInfo.CurrentUICulture;
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();

The winBarProgress window has a cancel button. The issue is that the cancel button is not firing the Click event.
Can anyone help me regarding this?


text:
Q: Uniqueness of a number $area(A)$ I have the following definition of area:
Let $A$ be a bounded set from $\mathbb{R}^2$. We say that $A$ has area if there exist two sequences $(E_n)_{n\in \mathbb{N}}, (F_n)_{n\in \mathbb{N}}$ of elementar sets, such that:
 - (1) $E_n \subset A \subset F_n, \forall n \in \mathbb{N}$
 - (2) the sequences of positive real numbers {$area(E_n)$}$_{n\in\mathbb{N}}$,{$area(F_n)$}$_{n\in\mathbb{N}}$ are convergent with $\lim_{n\rightarrow \infty}area(E_n)_{n\in\mathbb{N}}$=$\lim_{n\rightarrow \infty}area(F_n)_{n\in\mathbb{N}}$ (2).
In this case, we write:
$$area(A)=\lim_{n\rightarrow \infty}area(E_n)_{n\in\mathbb{N}}=\lim_{n\rightarrow \infty}area(F_n)_{n\in\mathbb{N}}$$
Now, a set $E\subset \mathbb{R}^2$ is called elementar if $E=\bigcup_{i=1}^nD_i$, where $D_i$ are rectangles with the sides parralel to the axes $(Ox, Oy)$ and any two different rectangles $D_i, D_j$ have at most one common side.
We define:
$$area(E):=\sum_{i=1}^n area(D_i)$$
The book where this definitions are presented omits to prove that the definition of $area(A)$ is correct, i.e. if we pick another two sequences $(U_n)_{n\in \mathbb{N}}$ and $(V_n)_{n\in \mathbb{N}}$ such that (1) and (2) are satisfied, then
$$\lim_{n\rightarrow \infty}area(E_n)_{n\in\mathbb{N}}=\lim_{n\rightarrow \infty}area(F_n)_{n\in\mathbb{N}}=\lim_{n\rightarrow\infty}area(U_n)_{n\in\mathbb{N}}$$
How can one prove this? Thank you very much!
More: if $A, B$ have area, then $A\cup B,$ A\B and $A\cap B$ have area.

A: Lets denote with $$a_n := area(E_n), \, b_n :=area(F_n), \, c_n=area(U_n), \, d_n=area(V_n)$$ and assume $\lim a_n = \lim b_n=:x$ and $\lim c_n = \lim d_n=:y$.
Your question is, why is $x = y $?
Because of $$E_n \subset A \subset V_n$$ we have $a_n \leq d_n$ and thus $x \leq y.$ Also we have $$U_n \subset A \subset F_n $$ which shows $c_n \leq b_n$ and thus $y \leq x$. All in all, we end up with $x=y$.


text:
Q: Pasar Datos con ViewBag.Message Quiero pasar un mensaje desde el controlador de la vista X a la visa Y
ViewBag.Message = "Mensaje";
        return RedirectToAction("Index", "Y");

al intentar esto no funciona, tampoco con el View(), como lo puedo pasar?

A: Si haces un RedirectToAction lo que conseguirás es que se ejecute la acción del otro controlador, perdiendo los valores que hayas puesto en el ViewBag.
Si lo que quieres es renderizar la vista con la información generada en esta acción deberías devolverla con el método View indicando la ruta completa de la vista:
return View("~/Views/Y/Index.cshtml");


text:
Q: General solution of partial differential equations. Find the general solution of the given differential equation
$$ \frac{y^2}{2}-2ye^t+(y-e^t)\frac{dy}{dt}=0$$
So here is my process:
Let:
$$\frac{\partial \phi}{\partial t}=\frac{y^2}{2}-2ye^t$$
where:
$$ \phi(y,t)=\frac{y^2}{2}t-2ye^t+h(y)$$
and let :
$$\frac{\partial \phi}{\partial y}=y-e^t$$
where:
$$ \phi(y,t)=\frac{y^2}{2}-ye^t+k(t)$$
Now I need to find k(t) and h(y) to make the two $\phi(y,t)$ equal. so this is where i'm stuck, if anyone can help, it be most appreciated.

A: Hint:
$$ \frac{y^2}{2}-2ye^t+(y-e^t)\frac{dy}{dt}=0$$
$$ \frac{y^2}{2}-ye^t+\frac{d}{dt}\left(\frac{y^2}{2}-ye^t\right)=0$$
Define $z:=\frac{y^2}{2}-ye^t$, hence
$$z+\frac{dz}{dt}=0\qquad z(t)=z_{0}e^{-t}$$


text:
Q: (Spring-Webflux & graphql - JAVA) Subscriber unable to re-connect to Publisher, in case Publisher gets UP after being DOWN for some time We have two applications, one is Subscriber (We will name it as Sub1) and Another is Publisher (We will name it as Pub1). I have written below code in Subscriber which tries to connect to an Endpoint exposed by Publisher.
var client = WebSocketGraphQlClient.builder(URI.create(<<SUBSCRIPTION_URL_EXPOSED_BY_PUB1>>), new ReactorNettyWebSocketClient()).build();

client.subscribe(client -> {
      client.mutate().build()
        .document(<<ACTUAL_GRAPHQL_SUBSCRIPTION_ENDPOINT>>)
        .executeSubscription()
        .retryWhen(Retry.backoff(4, Duration.ofSeconds(2))
          .jitter(0.7)
          .onRetryExhaustedThrow((retryBackoffSpec, retrySignal) ->
            new Exception("Publisher failed to respond, after max attempts of: "
              .concat(String.valueOf(retrySignal.totalRetries())))))
        .subscribe(response -> {
          try {
            var message =
              Objects.requireNonNull(response.getData()).toString();
            log.info(message);
          } catch (Exception e) {
            log.error("ERROR_OCCURRED", e);
          }
        });
    });

What is working fine : Pub1 send the message and Sub1 receives the message. In case Sub1 gets restarted due to any issues, it again establishes the connection with Publisher automatically.
What is not working fine : If Pub1 gets restarted due to any issues, subscriber is not able to connect to Publisher again. The retryWhen method does not works as expected. While reattempting to connect, if there is no sign of Pub1 it will obviously fail but if we manually make Pub1 available while third attempt of Sub1 is about to start, then also Sub1 is unable to connect to Pub1 (not even in 4th attempt). So basically if a Publisher is not available in first attempt and it gets available in any of the subsequent attempts made from Subscriber, result is same i.e. ConnectionRefused (Failure).
Requirement : Retry mechanism should connect to Publisher in case it gets UP, after few initial failed re-attempts from Subscriber side.


text:
Q: AWS/EC2 Status Text Stripped from Response My application is deployed on a set of docker containers on an EC2 instance.  In my local dev environment, I use the same set of docker containers.  My application sends back statusText headers to display meaningful error messages.  In my local environment, all of these statusText headers come back with the response just fine, but when the exact same code is deployed to AWS, the statusText header is always empty, which the browser appears to interpret as 'OK'.  The statusCode that I set comes back correctly.
tl;dr: Does anyone know of any behaviors on AWS or EC2 that would strip the statusText from the response headers?  I can't find anything in the documentation.
This doesn't return the status text:
server {
    listen       443 http2 ssl;
    server_name  api.example.com;
    root         /var/www/api/public;

    error_log    /var/log/nginx/api.error.log;

    client_max_body_size 16M;

    include ssl.conf;

    location / {
        if ($request_method = OPTIONS ) {
            add_header Access-Control-Allow-Origin  '$cors_host';
            add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE,  OPTIONS";
            add_header Access-Control-Allow-Headers "$http_access_control_request_headers";
            add_header Content-Length 0;
            add_header Content-Type 'text/plain; charset=utf-8';
            return 204;
        }
        add_header Access-Control-Allow-Origin '$cors_host';
        try_files $uri $uri/ /index.php?_url=$uri&$args;
    }

    include fastcgi_exec.conf;
}

This does:
server {
    listen       80;
    server_name  api.example.dev;
    root         /var/www/api/public;

    error_log    /var/log/nginx/api.error.log;

    client_max_body_size 16M;

    location / {
        if ($request_method = OPTIONS ) {
            add_header Access-Control-Allow-Origin $http_origin;
            add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
            add_header Access-Control-Allow-Headers $http_access_control_request_headers;
            add_header Content-Length 0;
            add_header Content-Type text/plain;
            return 200;
        }
        try_files $uri $uri/ /index.php?_url=$uri&$args;
    }

    include fastcgi_exec.conf;

}

A: HTTP/2 didn't preserve the "reason phrase" (status message) from HTTP/1.x.

HTTP/2 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line.
https://http2.github.io/http2-spec/#HttpSequence


text:
Q: Getting the first available null value in an array I have a small volunteering system that I am working on and in my volunteering table, I have 2 columns where users can volunteer to take part in an event.
The table looks like so:
id event_name user_1 user_2 created_at

What I would like to achieve is when a user volunteers for an event, the next available user slot is given to him.  Ie, if user_1 and user_2 have no values, and the user volunteers, assign the first available slot to him (user_1) and user_id is not null, save the user id in the user_2 column.
I have ran a query to return the user_1 and user_2 columns based on the event id.  Problem I am having is writing the PHP code to select the first available empty array item so i can save the user id?
Hope I am sort of making sense..
Thanks

A: You'd be better off normalising that table, into an events table, and an event_volunteers table.
event(id, name, max_volunteers)
event_volunteers(event_id, user_id)
Then you don't have to worry about which field is null or not, and you don't limit yourself to two volunteers per event - ie, more flexibility.
Instead, you can check if an event is 'open' to volunteers by comparing the count of event_volunteers to the max_volunteers field like so.
select e.id, e.name
  from event e
    left join event_volunteers ev
      on e.id = ev.event_id
  group by e.id
  having count(ev.event_id) < e.max_volunteers

With a left join, it will return null values for all the fields of event_volunteers if there are no volunteers for the particular event.  count() ignores null values, so even tho there is a row there to count, the count will be 0.
You can limit this to check a specific event by introducing a where clause.
And to assign a volunteer to an event, you just insert their user_id into the event_volunteers table.
You could then pull a list of all of your volunteers by performing the above query, but without the group by or having clause, eg:
select e.id, e.name, ev.user_id
  from event e
    inner join event_volunteers ev
      on e.id = ev.event_id

This will only show events for which there are least one volunteer (because of the inner join). Should you wish to show all events, with volunteers (if any). change the inner join to a left join, and you will get null values in ev.user_id if there are no volunteers for that event.


text:
Q: How to export a file into a different directory using Python? I'm trying to save myself from performing the old copy and past trick when saving files that Python generates.  The default is saving to the Python directory, however I would like it to be: C:\Program Files\Vixen\Vixen 2.1.1.0\Routines
I have tried this:
import os
filename = raw_input('What would you like to name the file? ')
filepath = os.path.join("C:\Program Files\Vixen\Vixen 2.1.1.0\Routines",filename)
with open(filename, 'wb') as out:
    for frame in frames:
        out.write(' '.join(str(num) for num in frame))
        out.write(' ')
        out.write('\n')

And the error I get is this:
Traceback (most recent call last):
  File "(stdin)", line 1 in (module)
  File "comet.py", line 169, in (module)
    filepath= os.path.join("C:\Program Files\Vixen\Vixen 2.1.1.0\Routines",filename)
NameError: name 'os' is not defined

How can I get Python to save the file directly into the desired path?

A: You forgot to load the os library. You can do that with import os prior to your code.
Edit: Another problem is that you are defining the path variable but are not using it anywhere apart from the assignment.Try to change the following:
with open(filename, 'wb') as out: to with open(filepath, 'wb') as out:


text:
Q: PhoneGap Push Plugin Not working on android 4.0.4 and below I could successfully run plugin and saved register id on galaxy s3, note 2, note 3 but it's not working on two different samsung galaxy mini device 2.3.6 and 4.0.4.
What could be the solution ?
Official plug-in link:
https://github.com/phonegap-build/PushPlugin
here is the video of the problem:
http://www.youtube.com/watch?v=R2wdFDQc1aI
working well on my galaxy s3 though:


text:
Q: Angular async pipe with offset pagination I have an observable that is pulling 12 people from a directory and displaying onto a template with async pipe. The API it hits is fairly basic and just uses offset pagination direct pass into the SQL query to grab the people. What I am hoping for is we have on first load, the API returns the first 12 people, then we have a 'load more' button. Hoping this button can keep the 12 people already on the screen but load in 12 more by changing the offset so first call is offset 0, next is offset 11 etc
I was looking at things like forkJoin or shareReplay because I want this to be reactive and also want to avoid asking the API for larger and larger response objects - example on load more would not want to ask for 24 just the next 12
so right now onInit I have the first of the people being pulled in
public people$: Observable<Directory[]> = combineLatest([this.selectedLocation$,this.selectedDepartment$, this.selectedSearchQuery$]).pipe(
switchMap(([loc,dept,query]) =>
  this.apiEmployeeService.getDirectory({
    dept: dept?.toString(),
    location: loc === 'Both' ? '%' : loc,
    offset: this.offset,
    limit: 12,
    search: query
  }),
)

so what can I have the load more button call from the HTML to keep existing 12 people but then refire this observable but with an offset of + 12

A: We can use a BehaviorSubject as a trigger to fetch more and use the scan operator accumulate the results from multiple fetches into a single observable:
const ITEMS_PER_PAGE = 12;

export class AppComponent  {

  private fetch$ = new BehaviorSubject<void>(undefined);

  public people$: Observable<Employee[]> = combineLatest([
    this.selectedLocation$,
    this.selectedDepartment$,
    this.selectedSearchQuery$,
  ]).pipe(
    switchMap(([loc, dept, search]) => this.fetch$.pipe(
      switchMap((_, pageIndex) => this.apiEmployeeService.getDirectory({
        dept     : dept?.toString(),
        location : loc === 'Both' ? '%' : loc,
        offset   : pageIndex * ITEMS_PER_PAGE,
        limit    : ITEMS_PER_PAGE,
        search
      })),
      scan((all, page) => all.concat(page), [])
    )),
  );

  fetchMore() {
    this.fetch$.next();
  }
}

The reason for the nested switchMap is because I'm assuming that if any of the query criteria changes (location, dept, search), then you want the offset to reset back to 0.
The second parameter of the switchMap callback receives the "emission index".  We can use that to represent the "page number".  Whenever the combineLatest emits a new value, a fresh subscription to fetch$ occurs, effectively resetting the index.
Here's a little StackBlitz where you can see this behavior in action.


text:
Q: A little confusion about calculating variance? given $a = 10% $, $b = 50%$, $c = 25%$ and $d = 15% $
calculate the variance? ( this is a made up question to make thinks clear for me)
what i have done is 1st eliminate percentages?
then i calculated the variance for $a = 0.1$, $b = 0.5$, $c = 0.25$, & $0.15$
But then I was wondering, do I need to multiply by the total before getting variance?
so, a would be $a = 10/100 * 4 = 0.4$, $b = 50/100 * 4 = 2$, ......
then calculate the variance.
Do I have to do it in percentages or completely un-normalized form?

A: well, i left it in percentages


text:
Q: Java SWT - Create a pure SWT Table with different color on even and odd rows I am very new to the SWT and I am trying to create a Java SWT table with different color on even and odd rows (ex: 1st row is red, second row is blue, third row is res, fourth row is blue ... ).
Since the rows on table can be deleted, inserted so if I manually set color by using a for loop I will have to run that loop again and again to set color every time there's something change in the table. And I don't want to use JFace, just pure Java SWT
Do you have some better solutions for this problems?

A: You can use custom drawn table items .
By adding a listener for the SWT.EraseItem you can just draw the background and let the rest do the default implementation. Use the item field of the event to decide whether an even or odd row is to be drawn.
For example:
table.addListener( SWT.EraseItem, new Listener() {
  @Override
  public void handleEvent( Event event ) {
    int index = table.indexOf( ( TableItem )event.item );
    if( index % 2 == 0 ) {
      Color oldBackground = event.gc.getBackground();
      event.gc.setBackground( event.display.getSystemColor( SWT.COLOR_DARK_YELLOW ) );
      event.gc.fillRectangle( 0, event.y, table.getClientArea().width, event.height );
      event.gc.setBackground( oldBackground );
    }
  }
} );


text:
Q: How can I composite two alpha channels using a "max" operation? Suppose I draw two overlapping translucent shapes in a canvas:
context.fillStyle = "rgba(0, 0, 0, 0.25)";
context.globalCompositeOperation = "copy";
context.fillRect(50, 50, 200, 200);
context.globalCompositeOperation = "??????";
context.fillRect(150, 150, 200, 200);

After this, I want the RGB values of each pixel to be (0, 0, 0) and for the alpha to be the maximum of the alpha channels of the two shapes. In other words, what I should get is that if a pixel is in either of the two squares it has alpha 0.25, otherwise it's blank. So the entire drawn region should be a uniform color.
I can't find any blending operation that does this. If I use things like "lighter" or "darker", I get a darker region where the two squares overlap.


text:
Q: Equal column heights problem I'm trying to implement equal column heights on my new website. If you look at the following page
http://blackburnseo.com/ensor_install/hedgehog-gutter-brush
The left column doesn't auto stretch.
I've tried a few jquery auto heigh solutions but they seem to break up my layout?
Can anybody recommend a solution?
Thanks,
Dan

A: Check Roger Johansson's faux columns article at http://www.456bereastreet.com/lab/developing_with_web_standards/csslayout/2-col/. I have used it several times.
What it does is it backgrounds the container and then the main section has its own background, the sidebar is clean. As the main content grows, so will the sidebar seamlessly.

A: I use this plugin, I wrote for myself, in every project where I need the heights to be equal. But if you can use CSS-only faux columns technique I would go for it instead. The plugin needs some updates to look more professional :-P

A: You could try the following:

*

*add an

 after you right menu

*move your background from your left_menu to your content_wrapper

A: Take background off #left_menu and put it to #content_wrapper with float: left;
#content_wrapper {
background:url("images/left_menu.png") repeat-y left top;
float:left;
}

A: See this post:
Fluid Width Equal Height Columns


text:
Q: How to do the grouping in k-map in java? I am not that good in java.. I am working in a project,in my project the program should draw the k-map,I used labels to draw it, its works good.. I just want to know if there any easy way to do the grouping by changing the background color of the label..? the problem is I don't have any efficient way.. the only way comes to me is to use all probabilities that may occur to group the ones and put it in if statement !!(I know it will be aloooot of probabilities especially when the number of variables is four) :(
like this (I will not post it all):
if(lbl1.getText().equals("1")&& lbl2.getText().equals("")&&lbl3.getText().equals("")&& lbl4.getText().equals("")&&lbl5.getText().equals("")&& lbl6.getText().equals("")
            &&lbl7.getText().equals("")&& lbl8.getText().equals("")&&lbl9.getText().equals("")&& lbl10.getText().equals("")&&lbl11.getText().equals("")&& lbl12.getText().equals("")
            &&lbl13.getText().equals("")&& lbl14.getText().equals("")&&lbl15.getText().equals("")&&lbl16.getText().equals("")){
        lbl1.setOpaque(true);
        lbl1.setBackground(Color.blue);
    }
 else if(lbl1.getText().equals("")&& lbl2.getText().equals("1")&&lbl3.getText().equals("")&& lbl4.getText().equals("")&&lbl5.getText().equals("")&& lbl6.getText().equals("")
            &&lbl7.getText().equals("")&& lbl8.getText().equals("")&&lbl9.getText().equals("")&& lbl10.getText().equals("")&&lbl11.getText().equals("")&& lbl12.getText().equals("")
            &&lbl13.getText().equals("")&& lbl14.getText().equals("")&&lbl15.getText().equals("")&&lbl16.getText().equals("")){
        lbl2.setOpaque(true);
        lbl2.setBackground(Color.blue);
    }
else if(lbl1.getText().equals("")&& lbl2.getText().equals("")&&lbl3.getText().equals("")&& lbl4.getText().equals("")&&lbl5.getText().equals("1")&& lbl6.getText().equals("")
            &&lbl7.getText().equals("")&& lbl8.getText().equals("")&&lbl9.getText().equals("")&& lbl10.getText().equals("")&&lbl11.getText().equals("")&& lbl12.getText().equals("")
            &&lbl13.getText().equals("")&& lbl14.getText().equals("")&&lbl15.getText().equals("")&&lbl16.getText().equals("")){
        lbl5.setOpaque(true);
        lbl5.setBackground(Color.blue);
    }
  else if(lbl1.getText().equals("")&& lbl2.getText().equals("")&&lbl3.getText().equals("")&& lbl4.getText().equals("")&&lbl5.getText().equals("")&& lbl6.getText().equals("1")
            &&lbl7.getText().equals("")&& lbl8.getText().equals("")&&lbl9.getText().equals("")&& lbl10.getText().equals("")&&lbl11.getText().equals("")&& lbl12.getText().equals("")
            &&lbl13.getText().equals("")&& lbl14.getText().equals("")&&lbl15.getText().equals("")&&lbl16.getText().equals("")){
        lbl6.setOpaque(true);
        lbl6.setBackground(Color.blue);
    }
  else if(lbl1.getText().equals("1")&& lbl2.getText().equals("1")&&lbl3.getText().equals("")&& lbl4.getText().equals("")&&lbl5.getText().equals("")&& lbl6.getText().equals("")
            &&lbl7.getText().equals("")&& lbl8.getText().equals("")&&lbl9.getText().equals("")&& lbl10.getText().equals("")&&lbl11.getText().equals("")&& lbl12.getText().equals("")
            &&lbl13.getText().equals("")&& lbl14.getText().equals("")&&lbl15.getText().equals("")&&lbl16.getText().equals("")){
        lbl1.setOpaque(true);
        lbl1.setBackground(Color.blue);
        lbl2.setOpaque(true);
        lbl2.setBackground(Color.blue);
    }

A: With an array (or list) of all 16 labels named labels, something like:
for (final JLabel label : labels) {
    // reset others?
    if ("1".equals(label.getText()) {
        label.setOpaque(true);
        label.setBackground(Color.blue);
    }
}


text:
Q: How to integrate @2x @3x images to React Native Project (Both Android & IOS)? I had added the same image's versions (@2x @3x)into src>asssets to work our platform in all devices. Here is the problem, VSCode only recognizes i.e path.png (it doesnt recognize @2x and @3x). How can we deal with this problem?

A: React native automatically pick up the desired image from the 3 options available i.e.
1x, 2x, 3x. We just have to provide the filename for the base image.
Example
.
├── button.js
└── img
    ├── check.png
    ├── check@2x.png
    └── check@3x.png

So, as stated above, when you have to use check image, just provide the image path for check.png and the rest will be automatically taken care by react native according to device screen density for both android and ios devices.
Use the image just like below and everything works like a charm.
<Image source={require('./img/check.png')} />

More you can read here about the images from react native
  official docs.

I hope this helps.... Thanks :)


text:
Q: Remove Row Padding In QTableWidget? After filling a QTableWidget table I call:
table->resizeRowsToContents();

This makes the rows narrower but there is still a lot of padding between each row, as you can see here:

Looking at the documentation I found I could set the hight of each row with:
table->verticalHeader()->setDefaultSectionSize(16);

This removes the padding and gives me the tight spacing I want:

However, I'm concerned about using an absolute size in pixels.  If the the system font is set to something large the text might not fit in the row.
Is there a way to remove the padding between rows while ensuring the text will always fit?

A: Use a custom delegate with the QAbstractItemDelegate::sizeHint() method implemented in a way that it will return a correct size according to the font used.
To compute a correct height, you can use a QFontMetrics provided with the option parameter of the sizeHint() method.
int height = option.fontMetrics.height();

or more precisely
int height = option.fontMetrics.boundingRect(index.data().toString()).height();

EDIT: How to use a delegate:
CMyDelegate* delegate = new CMyDelegate(tableView);
tableView->setItemDelegate(delegate);


text:
Q: jQuery content controller isn't showing and hiding content properly I've been trying to make a navigation bar for the past couple days, but I seem to run into a lot of problems with it. Right now my problem is the jQuery, it doesn't function the way I want it to:
I would like a single page website, so whenever I click a navigation bar the current page should hide and the targeted page should show. Right now, some of the pages still stack on top of eachother, can someone please help me?
HTML code
<!DOCTYPE html>

        <title>Yu-Gi-Oh! Stash</title>
        <link rel="stylesheet" type="text/css" href="styles/style.css">

        <meta charset="utf-8">

Decks ▾

Starter Decks

Structure Decks

Booster Packs ▾

Booster Sets

Special Editions

Duelist Packs

Master Collections

Tournament Awards

Promotions ▾

Video Games

Entertainment

Foundations

Decks

lorem ipsum..

Starter Decks

lorem ipsum..

Structure Decks

lorem ipsum..

Booster Packs

lorem ipsum..

Booster Sets

lorem ipsum..

Special Edition

lorem ipsum..

Duelist Packs

lorem ipsum..

Master Collections

lorem ipsum..

Tournament Awards

lorem ipsum..

Promotions

lorem ipsum..

Video Game Promotions

lorem ipsum..

Magazine, Movie & McDonalds Promotions

lorem ipsum..

Foundations

lorem ipsum..

CSS code
body, html {
    padding: 0;
    margin: 0;
    font-family: "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif;
}

p {
    padding: 0;
    margin: 35px 25px 25px 25px;
}

h1, h2, h3, h4, h5, h6 {
    margin-top: 0;
    margin-bottom: 0;
    text-transform: capitalize;
}

section {
    padding: 0;
    margin: auto;
    width: 85%;
    height: 1000px;
    border-top: 1px solid #fff;
}

section section {
    border: none;
}

.page-heading {
    margin: 80px 0px 80px 0px;
    text-align: center;
    font-weight: 700;
    font-size: 25px;
    line-height: 32px;
    color: #06b;
}

/********************
 ***NAVIGATION BAR***
 ********************/
nav {
    position: fixed;
    width: inherit;
    margin: -1px 0px 0px -1px;
    list-style-type: none !important;
    background-color: #fff;
    border: 1px solid #aaa;
    border-top: none;

    -webkit-border-bottom-left-radius: 5px;
    -moz-border-radius-bottomleft: 5px;
    border-bottom-left-radius: 5px;
    -webkit-border-bottom-right-radius: 5px;
    -moz-border-radius-bottomright: 5px;
    border-bottom-right-radius: 5px;
}

nav:after {
    clear: both;
}

nav ul {
    list-style: none;
    position: relative;
    float: left;
    margin: 0;
    padding: 8px;
    padding-bottom: 0;
}

nav ul li {
    width: auto;
    position: relative;
    float: left;
    margin: 0 25px -1px 0;
    padding: 0;
}

nav ul li.active > a {
    color: #06b;
    border-color: #aaa #aaa #fff;
}

nav ul li:hover > a {
    background: #fff;
    border-color: #aaa #aaa #fff;
}

nav ul a:link, a:visited {
    display: block;
    color: #09c;
    text-decoration: none;
    text-transform: capitalize;
    font-weight: 600;
    font-size: 15px;
    line-height: 32px;
    margin: 0;
    padding: 0 15px;
    border: 1px solid;
    border-color: #eee #eee transparent;

    -webkit-border-top-left-radius: 5px;
    -webkit-border-top-right-radius: 5px;
    -moz-border-radius-topleft: 5px;
    -moz-border-radius-topright: 5px;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
}

nav ul ul {
    display: none;
    position: absolute;
    top: 100%;
    left: 0;
    background: #fff;
    padding: 0;
}

nav ul ul li {
    float: none;
    width: 150%;
    margin: 0;
    background-color: #fff;
}

nav ul ul a {
    line-height: 120%;
    padding: 10px 15px;
    border-top: none;
    border-color: #eee !important;

    -webkit-border-radius: 0px !important;
    -moz-border-radius: 0px !important;
    border-radius: 0px !important;
}

nav ul ul a:hover {
    border-color: #aaa !important;
}

nav ul ul ul {
    top: 0;
    left: 100%;
}

nav ul li:hover > ul {
    display: block;
}

/*************
 ***CONTENT***
 *************/
.tab-content.active {
    display: block;
}

.tab-content.hide {
    display: none;
}

jQuery code
/***************************
 ***Navbar click function***
 ***************************/
$(document).ready(function() {
    $('nav li > a').click(function(event) {
        event.preventDefault();

        //declare current tab content
        var current_tab_content = $('nav li.active > a').attr('href');

        //hide current tab content
        $(current_tab_content).removeClass('active').addClass('hide');

        //show targeted tab content
        var targeted_tab_content = $(this).attr('href');
        $(targeted_tab_content).removeClass('hide').addClass('active');

        //remove 'active' from current navbar
        var current_navbar = $('nav li.active');
        $(current_navbar).removeClass('active');

        //add 'active' to clicked navbar
        $(this).parents('li').last().addClass('active');
    });
});

A: It looks like you end up with more than one section with the class 'active' after clicking the nav a few times.
Try hiding all sections first, then showing the desired one rather than hiding a single tab at a time:
$('.tab-content').removeClass('active').addClass('hide');
$(targeted_tab_content).addClass('active').removeClass('hide');

Other Suggestions

*

*You could potentially only have one class instead of two, default everything to display: none; and then you only have to remove/assign the 'active' class.

*There is also a jQuery function for show() and hide() that could be useful here.


text:
Q: Is there a way to save the content of both my EditText to a users phone to be retrieved later? I am trying to create a note app that sets the content of  both edit text to the user's phone.The title text will be used for the display of the the image button title which the user will click on to access the content of that file.Thank you!
    private EditText title, activity;
    private Button saveBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_entry);

        title = (EditText) findViewById(R.id.titleText);
        activity = (EditText) findViewById(R.id.Activty);
        saveBtn = (Button) findViewById(R.id.fab);

        title.setInputType(InputType.TYPE_CLASS_TEXT);
        String str = title.getText().toString();```

}
}

A: You can easily store data using SharedPreferences or SQLite. here is a good tutorial same like your note app, you can follow this. But the latest approach is Using Room Database. For room, you can follow this


text:
Q: Unable to retrieve user name through graph api after shifting to another server I am trying retrieve user name from the code through graph api, the below code was working fine when while I was hosting app on another(godaddy) server but recently I moved the application to phpfog and since then am facing this weird problem.
try {
                $userId = $_POST["user_id"];
                $oauth_token = $_POST["oauth_token"];

                $userName =   json_decode(file_get_contents('https://graph.facebook.com/' . $userId)) -> name;
                $userGender =   json_decode(file_get_contents('http://graph.facebook.com/' . $userId)) -> gender;
                $userPpicture =   json_decode(file_get_contents('http://graph.facebook.com/' . $userId)) -> picture;
            } catch(Exception $e) {
                echo $e -> getMessage();
                echo "
";
            }

just to add as this may help that in the very next line i can sucessfully retreive user profile picture through this:

Beside this piece of code not working, the photo posting functionality has just also stopped working.
kindly help me with this.
thankyou.

A: The ability to retrieve a user's photo directly (/[user id]/picture) doesn't require a token, so that's not a valid test.
If you've saved your oauth tokens you may need to re-init the user session with the new application address list.  To confirm, you should copy the token you're using to FB's debug interface here:
https://developers.facebook.com/tools/debug
Hope that helps.

A: After consulting phpfog support i came to know that their shared hosting plan doesnot support
the function file_get_contents.
Anyone of their dedicated plans will be able to run the commands which are restricted on their shared service.


text:
Q: With Vue-cli, when running build, how to organize files in css and js folders after the build? By default, Vue-cli creates the files as follows:
- dist
-- demo.html
-- style.css
-- file.commom.js
-- file.commom.js.map
-- file.umd.js
-- file.umd.js.map
-- file.umd.min.js
-- file.umd.min.js.map

I want the files to be organized this way:
- dist
-- demo.html
-- css
--- style.css
-- js
--- file.commom.js
--- file.commom.js.map
--- file.umd.js
--- file.umd.js.map
--- file.umd.min.js
--- file.umd.min.js.map

Bonus question: Are these common and umd names really necessary? Because in the node_modules folder, I don't see any projects with these names.

A: You can achieve this by modifying your webpack config.
Take a look at this issue here: https://github.com/vuejs/vue-cli/issues/1967
module.exports = {
    chainWebpack: (config) => {
    config.module
      .rule('images')
      .use('url-loader')
      .tap(options => Object.assign({}, options, { name: '[name].[ext]' }));
  },
  css: {
    extract: {
      filename: '[name].css',
      chunkFilename: '[name].css',
    },
  },
  configureWebpack: {
    output: {
      filename: '[name].js',
      chunkFilename: '[name].js',
    }
  }
};

This is the example given, but you can change the chunkFilname and filename keys to include a folder as part of the path. For instance 'javascript/[name].js'


text:
Q: Generic database update method in c# I am looking to create a method that will be able to update any table in a database, given any number of columns to update as well as any number of fields to look up for (in where clause). The problem is that i cannot find a design pattern of such function that will be able to do that. How am i gonna send the parameters? It looks like i'm going to need two params[] which is not possible and sending the query string itself is out of the question. The method should be able to process any query like this:
UPDATE [Table] SET [Col1] = 1, [Col2] = 2, ... WHERE [Col10] = 1 AND [Col11] = 2, ...

As an example for a generic Insert method i have used multiple overloads of the same function with different object type as its parameter.
public void Insert(Broadcast obj){...}
public void Insert(Comments obj){...}
public void Insert(Seated obj){...}

Now this is simple since depending on the type of object, i am inserting into the respective database table the values taken from the object obj. Can't figure out one for an update.

A: This is a bad idea, but if I had to do it I would probably send the method an object from this class:
class UpdateStatement {
    public string TableName {get;set}
    public Dictionary<DataColumn, object> SetColumns {get;set;} // the object is the value to be updated
    public Dictionary<DataColumn, object> WhereColumns {get;set;} // the object here is the value that the column will be tested against in the where clause.
}

and have it return the rowcount of the update statement as int


text:
Q: Sorting NSArray of NSDictionary...not completely working So I have NSMutableArray of NSDictionary items. Each NSDictionary item has a key "name" that should be used to sort the array alphabetically. Except its "sorting" partially works. Its not sorting in exact alphabetical order. It's moving some of the dictionary in order, but leaves some out of order.
NSMutableArray *section1 = [champs lastObject];
NSArray *oldSection1 = [NSArray arrayWithArray:section1];
[section1 sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDictionary *dictA = (NSDictionary *)obj1;
    NSDictionary *dictB = (NSDictionary *)obj2;

    NSString *champName1 = dictA[@"name"];
    NSString *champName2 = dictB[@"name"];
    return [champName1 compare:champName2];
}];
// Animation
for (NSDictionary *champInfo2 in section1) {
    if ([oldSection1 indexOfObject:champInfo2] != [section1 indexOfObject:champInfo2]) {
        [self.collectionView moveItemAtIndexPath:[NSIndexPath indexPathForItem:[oldSection1 indexOfObject:champInfo2] inSection:1] toIndexPath:[NSIndexPath indexPathForItem:[section1 indexOfObject:champInfo2] inSection:1]];
    }
}

I even tried this code
NSMutableArray *section1 = [champs lastObject];
NSArray *oldSection1 = [NSArray arrayWithArray:section1];
/*[section1 sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDictionary *dictA = (NSDictionary *)obj1;
    NSDictionary *dictB = (NSDictionary *)obj2;

    NSString *champName1 = dictA[@"name"];
    NSString *champName2 = dictB[@"name"];
    return [champName1 compare:champName2];
}];*/
section1 = [[NSArray arrayWithArray:section1] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]]].mutableCopy;
// Animation
for (NSDictionary *champInfo2 in section1) {
    if ([oldSection1 indexOfObject:champInfo2] != [section1 indexOfObject:champInfo2]) {
        [self.collectionView moveItemAtIndexPath:[NSIndexPath indexPathForItem:[oldSection1 indexOfObject:champInfo2] inSection:1] toIndexPath:[NSIndexPath indexPathForItem:[section1 indexOfObject:champInfo2] inSection:1]];
    }
}

Ok so the problem was I wasn't updating my snapshot of the content before reorganization as I updated it visually. Updated code:
// Animation
                for (NSDictionary *champInfo2 in section) {
                    if ([oldSection indexOfObject:champInfo2] != [section indexOfObject:champInfo2]) {
                        [self.collectionView moveItemAtIndexPath:[NSIndexPath indexPathForItem:[oldSection indexOfObject:champInfo2] inSection:[champs indexOfObject:section]] toIndexPath:[NSIndexPath indexPathForItem:[section indexOfObject:champInfo2] inSection:[champs indexOfObject:section]]];
                        [oldSection removeObject:champInfo2];
                        [oldSection insertObject:champInfo2 atIndex:[section indexOfObject:champInfo2]];
                    }
                }

A: The upper part of your code (i.e. the sorting) works fine. It can be simplified if you use sort descriptors, but it's definitely not the issue.
The real problem is with the code that moves things around.
Before the first move the indexing of the oldSection1 and self.collectionView is in sync, i.e. if an item XYZ is at index i in oldSection1, then it is also at index i in self.collectionView.
After the first move, however, the indexing gets out of sync, because the move is executed only in self.collectionView, but not in oldSection1. For example, if you start with
oldSection1    = C D A B
collectionView = C D A B

and you want it to be
sorted =         A B C D

after the first move of C the data is going to look like
oldSection1    = C D A B
collectionView = A C D B

When it's time to move D to its new spot, C gets moved instead.
To fix this issue, make oldSection1 mutable, and execute "parallel" moves as you move things around in self.collectionView.

A: It looks like your actual data is correct, but your collection view is displaying them incorrectly since you're iterating over the data, moving one row at a time. This most likely results in re-ordering rows that have already been re-ordered.
Calling [self.collectionView reloadData] instead of manually moving rows should resolve this issue.

A: To perform multiple UICollectionView item updates (insert/delete/move), it is recommended to use performBatchUpdates:completion:.  Otherwise you may encounter invalid indexes.
Link to official Apple's documentation


text: Q: Создать класс, реализующий Эллипс Нужно создать класс, реализующий Эллипс. Объявление полей класса должно исчерпывающе характеризовать объект. Класс должен содержать конструктор, деструктор, Set- и Get- методы для каждого поля. В основной программе должен конструироваться один объект класса. В класс добавить метод вычисления площади или объема.


text:
Q: Why is this zig zag function monotone increasing at $0$, but not monotone increasing in a neighborhood of $0$? This is from The Way of Analysis by Strichartz.

I believe see a neighborhood of $0$ such that $x_1 < x_2 \implies f(x_1) \le f(x_2)$.

Why is this zig zag function monotone increasing at $0$, but not monotone increasing in a neighborhood of $0$?

A: I think the idea is that the function is fractal, in the sense that as we approach $0$ from either side, the function has smaller spikes with increasing frequency. Indeed, we can see that the function $f$ is such that $f\le 0$ for $x<0$, $f\ge 0$ for $x>0$, and $f=0$ at $x=0$.
$f$ is monotone at $0$, because given $x_1<x_0<x_2$ we have that $f(x_1)\le f(x_0)=0$ and $f(x_2)\ge f(x_0)=0$ so that $f(x_1)\le f(x_0)\le f(x_2)$. On the other hand, because of this spiking behavior, any neighborhood of $0$, $N=\{x\in \mathbf{R}: \lvert x\rvert<\epsilon\}$, contains an entire spike, which is clearly not a monotone function, since it increases, and then decreases. So $f$ is not monotone in a neighborhood of $0$.


text:
Q: Embedding The Quotient Code A quotient code is the linear quotient $\frac {B}{A}$ of two binary linear codes equipped with the usual quotient norm $||\space||$ defined by $||b+A||=min_{a\in A}{||b+a||}$. Show that for some $n\in \Bbb N$ the quotient code $\frac {B}{A}$ is embedded in $\Bbb F_2^n$ via linear isometry.
Edit (lifted from a comment, JL):  The term "quotient code" given here is being defined here – not imported from some other unnamed source to the very best of my knowledge. Quotient spaces are useful in coding theoretic arguments, and have been used by many including Slepian. The idea was a simple late night musing in coding theory

A: The claim is patently false. For a counterexample let $B$ be the universal code of length $7$, and let $A$ be the $(7,4,3)$ Hamming code.
Then:

*

*Because $A$ is a perfect single-error-correcting code, every non-trivial coset $b+A$, $b\notin A$ has a weight one coset leader.

*By the previous bullet, an isometry $\phi:B/A\to\Bbb{F}_2^m$ for some $m$ must map all the non-trivial cosets $b+A$ to words of Hamming weight one.

*If $b_1+A$ and $b_2+A$ are distinct non-trivial cosets of $A$, then $b_1+b_2+A$ is another, and should also be mapped to a word of Hamming weight one.

*But it is impossible for all three vectors $\phi(b_1+A)$, $\phi(b_2+A)$ and $\phi(b_1+b_2+A)$, the last of which must be equal to $\phi(b_1+A)+\phi(b_2+A)$, to be of weight one. That sum of two words of weight one has an even weight.


text:
Q: Avoid UAC prompt in Qt 5.1 lupdate I am using Qt 5.1.0 with the bundled mingw 4.8 (32 bit) on Win7 64.
I want to run lupdate.exe to create and update the translation files. However, every run of lupdate demands administrator access rights and I get the windows UAC prompt I need to accept. This is annoying.
This issue only arises at lupdate. lrelease as well as all other Qt tools run as expected.
Not sure whether this is relevant: lupdate.exe is installed in the default path, C:\Qt\5.1.0\mingw48_32\bin\lupdate.exe.
I do not see any reason why lupdate needs admin rights and this was also not the case in former versions. So, why does my installation prompt for them? How can I avoid it?

A: This is because Windows checks the file name and assumes that anything containing "update", "install", or "uninstall" in its file name is an installer, and requires administrative privileges to run, regardless of whether it has manifest or not. This is done so old legacy installers created before UAC existed would continue to work.
Rename "lupdate.exe" to something that doesn't contain "update", and the UAC prompts will stop.


text:
Q: Click/tap delay for web app on tablets I made a simple little "wack-a-mole"-style game for my kids with JavaScript and HTML, and it performs exactly as it should on a PC.  As soon as you tap the animal (penguin, in this case) it shows as being wacked.  I'm using a window.setTimeout to try to time the images.
However, on tablets (tried on an iPad and an iPad Mini 2) there is a delay when tapping, so it isn't always counted correctly.  I've tried it on a Windows 10 PC with touch screen and it functions as expected, but on the iPads it always has a small delay, but enough to throw off the gameplay.
Is there any way to account for this delay on mobile devices?  I hesitate to change the timing of all of the images (the penguin poking its head up, then coming all the way up, then going back into its hole) because it works just like it should on Windows PCs.
I tested it in both Chrome and Safari on the iPad and iPad Mini 2, with the same results.
Thanks in advance.


text:
Q: Improper use of "premier" I often see text like "... has been a premier service provider for many years" in advertisements. Sometimes I'll see "Your premier SUCH AND SUCH" These strike me as nonsense phrases unless they were the first, or one of a few early, service providers.
Am I correct in my understanding of this phrase?

A: My dictionary gives premier as "first in importance, order, or position; leading…". So premier, used in that manner, is just fine.

A: Not really.  One meaning of the adjectival premier is indeed "first in time/occurrence", but another is "first in importance/rank".  What these texts are saying, then, is that a service provider has been "first in importance" (or at least amongst the most important) for years, within its industry and in comparison to its competitors.

A: You are confusing the word 'premier' with the word 'premiere'. I should emphasize that 'premier' refers to a status(a noun) like prime minister or top rank/importance(an adjective). The word 'premiere' used as a noun or a verb refers to a performance(usually the first).
So, usage of the word premier in those advertisements is correct and sensible.


text:
Q: Discord.py bot: Filter commands for specific user does anyone know, how I can give only one specific user acces to a command?

A: I would do something like this:
@bot.command()
async def commandname(ctx):
if ctx.author.id == 'usersID':
   # do something
else:
  await ctx.send(f"Sorry you can't do that.")


text:
Q: How to block taskmgr.exe from starting? I'm writing a program in python that will use 2-Factor authentication to unlock user workspace. It can't be closed with alt+F4, and I'm using root.overrideredirect() to remove all close, minimize, etc. buttons.
but it can be escaped with Alt+Tab and Ctrl-Shift-Esc. Alt-Tab can't be fixed but I want to kill task manager as it starts. I tried writing module for that but it stuck on while loop of kill taskmgr program.
I cant do root.mainloop().
module for kill:
import os
import elevate
elevate.elevate()
while True:
    os.system("taskkill /f /IM taskmgr.exe")


text:
Q: In what order is code in Embedded Ruby executed? I've done a little bit of Ruby on Rails magic today which somehow works but I don't know how.
I'm writing an application which is supposed to have a navigation bar on top of every page, so I've written a partial which I render in my default layout:
views/layouts/application.html.erb:
...
<%= render 'shared/navbar' %>
<%= yield %>
...

But I wanted the link to the currently selected section to be highlighted. I decided that a series of if statements in every link would be ugly so I wrote a helper class or two which manage the links displayed on the navbar. I'll spare you details how they work, because they're trivial and irrelevant right now, but they're used like this:
views/shared/_navbar.html.erb:
...
<% navbar_manager.each_entry do |entry, active| %>
  <li <% if active %>class="active"<%end%>>
    <%= link_to entry.label, entry.url %>
  </li>
<% end %>
...

Now I only needed to let the navbar_manager know which entry is active. Manipulating the navigation bar is closely linked to the view so I decided against putting an appropriate code in the controller and to do it in a view file instead, like this:
views/foo/index.html.erb
<% navbar_manager.set_active_entry(:home) %>
...

A big surprise: it works. But now that I think of it: render 'shared/navbar' appears in the layout file before yield. So how does it happen that navbar_manager.set_active_entry is called before navbar_manager.each_entry? More generally: in what order is Embedded Ruby processed?
And in case that I'm simply lucky: is there a way to ensure the order I want?
I'm using Ruby 1.9.3 and Rails 3.2

A: Sequence of code execution:

*

*On invoking foo#index, the corresponding view content is prepared from the views/foo/index.html.erbfile.

*The appropriate layout is processed. In this case, the views/layouts/application.html.erb file is picked up for processing.

*<%= render 'shared/navbar' %> statement in the layout makes it process the navbar partial. At this point, the view content to be displayed is already available (as part of step 1 above, so the navbar_manager marks the appropriate section for highlighting.

*<%= yield %> statement in the layout inserts the view content (processed in step 1 & step 3).

*The result of the complete processing is displayed.
log/development.log is a good resource to see how the various views & partials were executed.
Here is an example from one of my apps:
Started GET "/" for 127.0.0.1 at 2012-10-13 14:42:23 -0600
Processing by DashboardController#welcome as HTML
User Load (0.8ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1  User Load (0.8ms)  SELECT `users`.* FROM `users`
Rendered dashboard/welcome.html.erb within layouts/application (2.6ms)
Rendered layouts/_navigation.html.erb (1.5ms)
Rendered layouts/_messages.html.erb (0.2ms)
SQL (1.4ms)  UPDATE `users` SET `updated_at` = '2012-10-13 20:42:23' WHERE `users`.`id` = 1
Completed 200 OK in 104ms (Views: 88.6ms | ActiveRecord: 3.1ms)

In this example, on invoking dashboard#welcome, the dashboard/welcome.html.erb view is processed first, and rendered within layouts/application; the layout also calls on navigation and messages partials before completing the rendering process.


text:
Q: Apart from immutability, does blockchain offer any other advantages? I am trying to understand the broader implications of blockchain apart from the main advantage of immutability. Are there any?
It seems like the distributed nature of the ledger can be an asset when it comes to data redundancy but it also seems like performance would be terrible since, as I understand it, all the history of an entity is encoded into each record in the chain that then presumably has to propagate throughout the node network.
How would one even query a blockchain to determine, for example, the location of a piece of inventory? It seems like the advantages outside of immutability of data are almost non-existent, but I feel I must be missing something.
Thanks in advance.

A: You are on the right track with the distributed nature of the ledger.  You are also correct that performance is a challenge.
The key value, from a business perspective, is that there is no need for a central authority.  Distributing your data is a good thing for many reasons such as fault-tolerance and latency but there are many ways of doing that.  What makes block chain different is that there no concept of a leader and no authority.  Each participant in the system is a peer and is the authority in their own transactions.  If you and I want to make a deal, we do our deal and then propagate what happened to the other participants.  There's a lot of complexity in how conflicts get managed, of course, but that's the happy path goodness of it.
This makes a lot of sense when you are talking about market or other system with many independent actors.  In a more traditional system, you need someone or something to oversee all the transactions.  This creates a bottleneck and essentially a company or governmental organization needs to exist just to do this.  This authority also can't easily be replaced so what they should get paid becomes an issue.  With blockchain system such as bitcoin, anyone can be involved in transaction verification.  In fact it depends on many people being involved in mining and/or verification.
Inventory management doesn't seem like an obvious choice here.  Most companies don't want other people to know those kinds of details.  And if you are talking about an single company system, there are much easier ways to solve the problem.
On system that I think blockchain might be useful for is DNS.  Right now, we have companies like Dyn that much of the internet depends on for domain name resolution.  When something bad happens to these providers, huge swaths of the internet break.  If instead you had a massive network of DNS servers using a blockchain ledger, you change that dynamic greatly (although there may be other, different kinds of issues.)  It also would be much harder to take over a domain without anyone noticing.


text:
Q: ckeditor 3.0 causes "unauthenticated content" when simply included on an HTTPS page When I include ckeditor aka fckeditor (version 3.0.1 revision 4391), which I downloaded from their site last week, into a page that is SSL encrypted, I get the Firefox broken lock icon and the warning "Warning: contains unauthenticated content". However, IE8 doesn't give this error at all. I checked the headers (Live HTTP headers), and everything is being included VIA SSL. Anyone have any solutions regarding this?
This happens by just including the script, like so
    <script type="text/javascript" src="/js/manager/settings.js"></script>

A: I also found the same problem on our secure portal. Only those web pages using the "ckeditor.js" is giving this warning.
Tried for some time searching through the ckeditor js files to find anywhere which uses http instead of https.
"plugins/flash/dialogs/flash.js" is having the embed from "http://macromedia blah blah...". Changing it to "https://macromedia .. blah blah..." did not solve it although our general flash embedded pages works fine with this workaround. :(
I will try to find out some more in the code... tonight.
If you find solution please put it here...

[http://dev.fckeditor.net/ticket/3905][1]
This will be fixed on 3.1.x onwards as it says.
trying to checkout a development tag.

Checked out CKEditor from a development branch under 3.1.x
This is great! the warning is gone.


text:
Q: iPhone App connection between one app of ours and second whose access we dont have and is on store I want to create some kind of button in the app which is already on store (Basically the shopping apps). That button should open my app with details of that shopping item searched.How to achieve this in iPhone??
Thanks in advance.


text:
Q: Grant application review: How to justify your training dataset size for a given deep learning problem I am a medical doctor who is working on a grant application. The project involves training deep learning models to classify medical images based on various different outcomes, for example diagnosis (where there may be about 8 classes), survival (binary categorisation, alive vs not) and some more complex "disease progression" outcomes. In the grant application (which is a generic application form) is indicates that details on the following should be provided:

*

*How the sample size was calculated, showing power calculations and including justification of effect size

*Circumstances in which power calculations are not appropriate to determine
sample size

A correspondence with the grant committee who reviewed a one page summary of the project also mentioned that justification for training and validation sample sizes should be given.
My understanding, having trained a lot of different architectures (with some published work) is that dataset size is really an area of active research and usually its determination is by experimentation rather than objective calculation.
I know that statistical reviewers are on the review panel and I also know from experience that saying things like - "this is the way its usually done" just doesn't cut it. I am not a statistician.
I understand that its not a one size fits all and that the quantity of data required for model development is dependent on the complexity of the data, the complexity of the algorithm architecture and how well defined the classes in the classification problem are. However, is there a way to demonstrate with some mathematical rigor that you have at least attempted to evaluate the likely dataset size needed for training?


text:
Q: Ajax python how to post data Sorry guys, maybe this has been asked before. But I googled around for several days and still cannot solve the problem. I am developing a chatting system using Google App Engine with Python. I would like the user to enter her/his message and click "Submit" button. That action will trigger an Ajax post function "addMsg()" to POST the message to class Chat (URL: "/chat"), which will add the message to datastore. There is another Ajax function "updateMsg()" which will update the message list periodically.
The code works fine for message updating, however, I am not able to post the message correctly. Can anybody help me? Thanks. Here are my codes:
chat.html:

    <form method="" action="">
    <input type="text" name="message" size="60" />

    <input type="button" value="Submit" onclick="addMsg('message')" />
    </form>

message.html:
    {% for chat in chatlist %}

      {{ chat.text }} ({{ chat.user.account }}) {{chat.created|date:"D d M Y" }}

    {% endfor %}

chat.py:
    # Called by URL "/chat"
    class Chat(webapp2.RequestHandler):
        def post(self):
            message = self.request.get('message')
            newchat = ChatMessage(user=self.session['userkey'], text=message, created=datetime.datetime.now())
    newchat.put()

    # Called by URL "/message"
    class Message(webapp2.RequestHandler):
        def get(self):
            que = db.Query(ChatMessage).order('-created')
            chatlist = que.fetch(limit=100)
            render(self, 'message.html', {'chatlist': chatlist})
            # Note: render() is a function to be imported, which is just a normal template rendering function. It works fine and is omitted here.

A: Chat.html

<input type="text" name="message" size="60" />

<input type="button" value="Submit" onclick="addMsg()" />


text:
Q: Text file keeps deleting contents on the file. How do i get around this? Code showing the array:
int i = 0;

            try {

               File fl = new File("Product List.txt");

               Scanner scn = new Scanner(fl);

               while(scn.hasNext()) {

                  String productName = scn.next();

                  double productPrice = scn.nextDouble();

                  int productAmount = scn.nextInt();

                  product[i] = new Products(productName,productPrice,productAmount);

                  i = i + 1;

               }

            }

            catch(IOException exc) {

            }
//and this code to update contents

try{

            Formatter writer = new Formatter("Product List.txt");

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

               prd.setQuantity(prd.getQuantity() - 1);

               writer.format(prd.getProductName(),prd.getPrice(),prd.getQuantity(),"\n");

            }

            writer.close();

         }

         catch(IOException exc){

         }

Every time i run the program, it keeps deleting the contents and by the time i reach the part where i have to update the contents of the file, the file is empty.
How do i fix this runtime error?

A: From javadoc:

public Formatter(String fileName)
            throws FileNotFoundException Constructs a new formatter with the specified file name. The charset used is the default charset for
  this instance of the Java virtual machine.
The locale used is the default locale for this instance of the Java
  virtual machine.
Parameters: fileName - The name of the file to use as the destination
  of this formatter. If the file exists then it will be truncated to
  zero size; otherwise, a new file will be created. The output will be
  written to the file and is buffered.

So I think you should load all content of the file to a stringbuilder, append next content and write it down.


text:
Q: Pick camera roll not working in ionic/cordova in iOs nothing happens Nothing happens when I call the getPicture function with: this.camera.PictureSourceType.PHOTOLIBRARY.
Hower it does work in Android just not iOs and also this.camera.PictureSourceType.CAMERA does work in iOs.
private cameraOptions: CameraOptions = {
  quality: 50,
  destinationType: this.camera.DestinationType.DATA_URL,
  encodingType: this.camera.EncodingType.JPEG,
  mediaType: this.camera.MediaType.PICTURE,
};

public async changeProfilePicture() {
  const sheet = await this.actionSheet.create({
    buttons: [{
      text: 'Camera',
      handler: () => {
        this.takePicture();
      },
    },
      {
        text: 'Foto album',
        handler: () => {
          this.choosePicture();
        },
      }
      , {
        text: 'Annuleren',
        role: 'cancel',
        handler: () => {
          sheet.dismiss();
        },
      }],
  });

  sheet.present();
}

private async takePicture() {
  try {
    const image = await this.camera.getPicture({
      ...this.cameraOptions,
      sourceType: this.camera.PictureSourceType.CAMERA,
    });

    this.userService.editProfilePicture(`data:image/jpeg;base64,${image}`).subscribe(user => {
      this.user = user;
    });
  } catch (err) {
    this.handleImageError(err);
  }
}

private async choosePicture() {
  try {

    const image = await this.camera.getPicture({
      ...this.cameraOptions,
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
    });

    this.userService.editProfilePicture(`data:image/jpeg;base64,${image}`).subscribe(user => {
      this.user = user;
    });
  } catch (err) {
    this.handleImageError(err);
  }
}

A: iOS requires permissions to be configured when accessing certain native features. In your case, you need to set the NSPhotoLibraryUsageDescription key in the Info.plist file of your app. You can manually edit this file within the xcode project, but it's better to place this in the config.xml of your ionic project :
<config-file parent="NSPhotoLibraryUsageDescription" platform="ios" target="*-Info.plist">
 <string>The app needs access to your library to...</string>
</config-file>


text:
Q: Physical interpretation for the curl of a field I was supposed to compute the curl of a field for a fairly simple assignment and got the following :
$$\nabla \times F = (0,0,y-e^{x+y}) \text{ ; } (x,y) \in [0,1]\times [0,1]$$
However, I'm unable to appreciate the meaning of this and I hate doing things like a machine. I tried a few different online sources, but I still don't know how to interpret my result.
Can someone explain, in a natural manner, what implications does my result have ?

A: Sorry I cant comment, because my reputation is not big enough, so I will just answer...
Imagine you throw a ball inside the vector field. This ball starts to move alonge the vectors and the curl of a vectorfield is a measure of how much the ball is rotating.
The curl gives you the axis around which the ball rotates, its direction gives you the direction of the orientation (clockwise/counterclockwise) and its length the speed of the rotation.
This is some curde model to give you some imagination about the curl...

A: Another interpretation, for vector fields in the plane (which it sounds like is the case for your problem. The situation is a bit more complex in full 3 dimensions).
Let's say that you draw a small closed loop in the plane. Start at one point of the loop, and travel around it. Imagine that the vector field is now a gradient field of a height function $z(x,y)$ of a landscape over the plane: i.e. the vector field tells you in which direction the ground slopes, and at what angle. As you travel around the loop, your height in changing. Once you end up back at the point you started, what is your height relative to your starting point?
On an ordinary landscape e.g. a mountain, you end up at exactly the same height you started. But if you are, say, in a parking garage, you might end up higher or lower than where you started, even though you are at the same $(x,y)$ position in the plane.
Now imagine you take your loop and shrink it smaller and smaller and around some point $(x,y)$ in the plane. The difference in starting and ending height will depend on 1) how many times you wind around the point (twice around the parking garage takes you up two levels, negative once around takes you down a level) and 2) the curl of the vector field at $(x,y)$. Curl zero corresponds to the mountain case, where you end up back where you started (and indeed, if $\nabla \times v =0$, this is exactly the integrability condition needed to guarantee that $v = \nabla \phi$ for some potential $\phi$. This is why all force fields arising from potentials in physics are curl-free, i.e. "conservative": if you go around a closed path the force must have done no net work and your potential at the end is equal to your potential at the start.)


text:
Q: Optimal lower bound of $k$-sums for the integers $\{1,2,\ldots,n\}$ arranged around a circle in arbitrary order. This question is motivated by the following two questions and is a slightly generalized version of them.
Some three consecutive numbers sum to at least $32$
Integers $1, 2, \ldots, 10$ are circularly arranged in an arbitrary order.
Consider the first $n$ positive integers distributed along a circle in an arbitrary order. There are a total of $(n-1)!$ arrangements. Pick an arrangement $P_m$, where $m \in \{1,2,\ldots,(n-1)!\}$
The arrangement $P_m$ is of the form $a_{m,1},a_{m,2},\ldots,a_{m,n}$ around the circle where $a_{m,j} \in \{1,2,\ldots,n\}$ and $a_{m,i} \neq a_{m,j}$ whenever $i \neq j$.
Define a $k$-sum as the sum of $k$ consecutive numbers in an arrangement $P_m$. For instance, $$a_{m,1} + a_{m,2} + \cdots +a_{m,k},$$
$$a_{m,n-1} + a_{m,n} + a_{m,1} + a_{m,2} + \cdots + a_{m,k-2}$$ are examples of $k$-sums. Clearly for any arrangement $P_m$, there are $n$ such $k$-sums.
Now look at the maximum of these $k$-sums in the arrangement $P_m$, i.e. $$s_{m,k} = \max \{ (a_{m,1} + a_{m,2} + \cdots + a_{m,k}),(a_{m,2} + a_{m,3} + \cdots + a_{m,k+1}), \cdots,  (a_{m,n} + a_{m,1} + \cdots + a_{m,k-1})\}$$
The question is what is the optimal lower bound of this maximum sum? i.e. What is $\displaystyle \min_{m} s_{m,k}$?
In Integers $1, 2, \ldots, 10$ are circularly arranged in an arbitrary order. it is shown that for $n=10$ and $k=3$, the optimal lower bound is $18$ and in Some three consecutive numbers sum to at least $32$, it is shown that the optimal lower bound for $n=20$ and $k=3$ is $\geq 33$.
Clearly, for $k=1$, $\displaystyle \min_{m} s_{m,1} = n$.
For $k=2$, $\displaystyle \min_{m} s_{m,2} = n+2$.
In general, a trivial lower bound is obtained by adding up all the $n$, '$k$' sums to get that $$n \times \min_{m} s_{m,k} \geq k \frac{n(n+1)}{2}$$ i.e. $\displaystyle \min_{m} s_{m,k} \geq \left \lceil k \frac{(n+1)}{2} \right \rceil$.
Clearly, this is not the optimal bound as seen from the results for $k=1$ and $k=2$ and also from the two questions: Some three consecutive numbers sum to at least $32$,
Integers $1, 2, \ldots, 10$ are circularly arranged in an arbitrary order..
So the question is: What is the optimal lower bound? (I am also interested in better lower bounds even if the bound is not the optimal one. Any reference to articles where this has been discussed is welcome.)
EDIT
Some googling landed me on this article ( http://imi.cas.sc.edu/IMI/reports/2001/reports/0116.pdf ) where they have considered the same problem and have constructed better upper bounds for $\displaystyle \min_{m} s_{m,k}$. They prove that in general $$\displaystyle \min_{m} s_{m,k} \leq \min \left( \left \lceil \frac{k(n+1)}{2} + k + 6 \right \rceil, \left \lceil \frac{k(n+1)}{2} + \frac{k}{2} + 9 \right \rceil \right).$$ Further they prove that if $(n,k) > 1$, then the optimal lower bound is $$\displaystyle \min_{m} s_{m,k}\leq \left \lceil \frac{k(n+1)}{2} + \frac{7}{2} \right \rceil,$$ which I think is remarkable that the factor $\frac{7}{2}$ is independent of $k$ and $n$.
However, I am wondering if the lower bound of $\displaystyle \min_{m} s_{m,k}$ can be tightened further and if an exact value of $\displaystyle \min_{m} s_{m,k}$ can be obtained.


text:
Q: Error replacing two fragments with scrollviews I have 2 fragments and both have Scrollviews in them, I make a selection from a ListView and that replaces the first fragment with the other fragment that has the scrollview.
The problem is that when I try to replace the fragment with the new one I get an error saying ScrollView can only contain one direct child which it does, it has one RelativeLayout which holds all the content.
If i take the ScrollView out of the first fragments view I do not get the error and the fragment gets replaced fine but I need the scrollview in the first fragment.
What is causing this issue, does replacing a fragment not remove the view fully?
StackTrace:
11-01 18:45:00.895: E/AndroidRuntime(3833): FATAL EXCEPTION: main
11-01 18:45:00.895: E/AndroidRuntime(3833): java.lang.IllegalStateException: ScrollView can host only one direct child
11-01 18:45:00.895: E/AndroidRuntime(3833):     at android.widget.ScrollView.addView(ScrollView.java:229)
11-01 18:45:00.895: E/AndroidRuntime(3833):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:840)
11-01 18:45:00.895: E/AndroidRuntime(3833):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
11-01 18:45:00.895: E/AndroidRuntime(3833):     at android.app.BackStackRecord.run(BackStackRecord.java:635)
11-01 18:45:00.895: E/AndroidRuntime(3833):     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397)
11-01 18:45:00.895: E/AndroidRuntime(3833):     at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
11-01 18:45:00.895: E/AndroidRuntime(3833):     at android.os.Handler.handleCallback(Handler.java:615)
11-01 18:45:00.895: E/AndroidRuntime(3833):     at android.os.Handler.dispatchMessage(Handler.java:92)
11-01 18:45:00.895: E/AndroidRuntime(3833):     at android.os.Looper.loop(Looper.java:137)
11-01 18:45:00.895: E/AndroidRuntime(3833):     at android.app.ActivityThread.main(ActivityThread.java:4745)
11-01 18:45:00.895: E/AndroidRuntime(3833):     at java.lang.reflect.Method.invokeNative(Native Method)
11-01 18:45:00.895: E/AndroidRuntime(3833):     at java.lang.reflect.Method.invoke(Method.java:511)
11-01 18:45:00.895: E/AndroidRuntime(3833):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-01 18:45:00.895: E/AndroidRuntime(3833):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-01 18:45:00.895: E/AndroidRuntime(3833):     at dalvik.system.NativeStart.main(Native Method)

this is how I replace the fragment
ft.replace(R.id.frameTwo, individual);
ft.addToBackStack(null).commit();

A: found the problem apparently you cant have a scrollview as you base view, I wrapped it in a RelativeLayout and it works now


text:
Q: How to stop dragend's default behavior in drag and drop? I hard to sum this bug in words. So I made the video for the bug.
Basically when dragEnd is called the element animates as if going to original place. How to stop the default behavior? I made a fiddle and codepen for this too.
I have two list for my example, when calling dragEnd after releasing mouse button. The element from one list animates going to list of its original place instead of the place it is going to be.
JS code:
'use strict';

var source = null; var heightWidth = null; var lastDragOverElementId = null; var dragImageSource = null;

function listItemDragStartHandler(event) {
    source = event.currentTarget;
    heightWidth = [];
    heightWidth.push(source.offsetHeight);
    heightWidth.push(source.offsetWidth);
    event.dataTransfer.setData('text/html', event.currentTarget.innerHTML);
    event.dataTransfer.effectAllowed = 'move';
    // Drag image logic
    dragImageSource = source.cloneNode(true);
    dragImageSource.style.position = 'absolute';
    // Don't show the element
    dragImageSource.style.top = '0px';
    dragImageSource.style.left = '-' + String(window.innerWidth) + 'px';
    // dragImageSource.style.left = '-100px';
    var toTiltElement = dragImageSource.getElementsByClassName('item-list-element')[0];
    toTiltElement.style.transform = 'rotate(5deg)';
    document.body.append(dragImageSource);
    event.dataTransfer.setDragImage(dragImageSource, heightWidth[1]/2, heightWidth[0]/2); }

function dragoverHandler(event) {
    event.preventDefault();
    event.dataTransfer.dropEffect = 'move';
    source.style.display = 'none';
    var currentElement = event.currentTarget;
    var listContainer = currentElement.parentNode;
    if (lastDragOverElementId != currentElement.getAttribute('id')) {
        lastDragOverElementId = currentElement.getAttribute('id');
        if(document.getElementById('grayed-empty-node') !== null) {
            if(currentElement.getAttribute('id') !== 'grayed-empty-node') {
                document.getElementById('grayed-empty-node').remove();
            }
        }
        var isGrayEmptyNodeThere = document.getElementById('grayed-empty-node');   //
        if(isGrayEmptyNodeThere === null) {
            var emptyNode = document.getElementById('empty-node').cloneNode(true);
            emptyNode.removeAttribute('id');
            emptyNode.setAttribute('id', 'grayed-empty-node');
            emptyNode.setAttribute('class', 'fade-in');
            emptyNode.style.height = String(heightWidth[0]) + 'px';
            emptyNode.style.width = String(heightWidth[1]) + 'px';
            listContainer.insertBefore(emptyNode, currentElement);
        }
    } }

function dragLeaveHandler(event) {
    event.preventDefault();
    var currentElement = event.currentTarget;
    var listContainer = currentElement.parentNode;
    var elementList = listContainer.getElementsByClassName('item-template-container');
    var visibleElementList = [];
    var i = 0;
    for (i=0; i<elementList.length; i++) {
        if (elementList[i].style.display !== 'none') {
            visibleElementList.push(elementList[i]);
        }
    }
    // Last element ondragleave handler should be delayed, otherwise it
    // would spin off chain reaction.
    var lastVisibleElement = visibleElementList[visibleElementList.length - 1];
    // Basically last element
    if (currentElement.id === lastVisibleElement.getAttribute('id')) {
        lastVisibleElement.removeAttribute('ondragleave');
        if(document.getElementById('grayed-empty-node') !== null) {
            document.getElementById('grayed-empty-node').remove();
        }
        var isGrayEmptyNodeThere = document.getElementById('grayed-empty-node');
        if(isGrayEmptyNodeThere === null) {
            var listContainer = currentElement.parentNode;
            var emptyNode = document.getElementById('empty-node').cloneNode(true);
            emptyNode.removeAttribute('id');
            emptyNode.setAttribute('id', 'grayed-empty-node');
            emptyNode.setAttribute('class', 'fade-in');
            emptyNode.style.height = String(heightWidth[0]) + 'px';
            emptyNode.style.width = String(heightWidth[1]) + 'px';
            listContainer.insertBefore(emptyNode, null);
        }
        // This delayed the chain reaction
        setTimeout(function() {
            visibleElementList[visibleElementList.length - 1].setAttribute('ondragleave', 'dragLeaveHandler(event);');
        }, 500);
    // When event is on last element set the lastDragOverElementId to null
    // then dragover to lastVisibleElement(second last element) can be handled
    // otherwise dragover to second last element won't show placeholder.
    lastDragOverElementId = null;
    } }

function dragEndHandler(event) {
    event.preventDefault();
    // Check the dropEffect
    dragImageSource.remove();
    var listElement = document.getElementById('grayed-empty-node')
    var listContainer = listElement.parentNode;
    if (event.dataTransfer.dropEffect === 'none') {
        var grayEmptyNode = document.getElementById('grayed-empty-node');
        // When grayEmptyNode is null, that will append at the end.
        listContainer.insertBefore(source, grayEmptyNode);
        source.style.display = '';
        if(document.getElementById('grayed-empty-node') !== null) {
            document.getElementById('grayed-empty-node').remove();
        }
    } else if (event.dataTransfer.dropEffect === 'move') {
        var grayEmptyNode = document.getElementById('grayed-empty-node');
        // When grayEmptyNode is null, that will append at the end.
        listContainer.insertBefore(source, grayEmptyNode);
        source.style.display = '';
        if(document.getElementById('grayed-empty-node') !== null) {
            document.getElementById('grayed-empty-node').remove();
        }
    } }

function delete_item(event) {
    var currentElement = event.currentTarget;
    var grandParentOfDelete = currentElement.parentNode.parentNode;
    grandParentOfDelete.remove(); }

function add_item() {
    var item_text_node = document.getElementsByName('add-item-text')[0]
    var item_text = item_text_node.value;
    if (item_text.length > 0) {
        var item_template = document.getElementById('item-template-container');
        var item_clone = item_template.cloneNode(true);
        item_clone.removeAttribute('id');
        var random_id = (new Date().getTime() +
            parseInt(Math.random(0, 1000) * 1000))
        item_clone.setAttribute('id', random_id);
        var clone_text = item_clone.getElementsByClassName('item-text')[0];
        clone_text.textContent = item_text;
        // reset the value
        item_text_node.value = '';
        var item_list = document.getElementById('item-list');
        item_list.appendChild(item_clone);
    } else {
        alert('No text?? Add some text!');
    } }

function add_item_2() {
    var item_text_node = document.getElementsByName('add-item-text-2')[0]
    var item_text = item_text_node.value;
    if (item_text.length > 0) {
        var item_template = document.getElementById('item-template-container');
        var item_clone = item_template.cloneNode(true);
        item_clone.removeAttribute('id');
        var random_id = (new Date().getTime() +
            parseInt(Math.random(0, 1000) * 1000))
        item_clone.setAttribute('id', random_id);
        var clone_text = item_clone.getElementsByClassName('item-text')[0];
        clone_text.textContent = item_text;
        // reset the value
        item_text_node.value = '';
        var item_list = document.getElementById('item-list-2');
        item_list.appendChild(item_clone);
    } else {
        alert('No text?? Add some text!');
    } }

function onEnterInInput() {
    var e = e || window.event;
    if (e.keyCode == 13) {
        add_item()
    } }

function sample_data() {
    for(var i=0;i<10;i++){
        var item_text_node = document.getElementsByName('add-item-text')[0]
        item_text_node.value = i;
        var item_text_node_2 = document.getElementsByName('add-item-text-2')[0]
        item_text_node_2.value = i;
        add_item();
        add_item_2();
    } }

window.onload = function () {
    sample_data(); }

HTML code:
<!DOCTYPE html>

    <title>List task</title>

    <link rel="stylesheet" type="text/css" href="list-task.css">

                <input type="text" name="add-item-text" onkeypress="onEnterInInput(event);">
                <button id="add-item" onclick="add_item(event)">Add Item</button>

                <input type="text" name="add-item-text-2" onkeypress="onEnterInInput(event);">
                <button id="add-item-2" onclick="add_item_2(event)">Add Item</button>

                    <button class="delete-item" onclick="delete_item(event);">Delete</button>

Video describing the bug: https://www.youtube.com/watch?v=Uz_ukKdg1O0&feature=youtu.be
Note: I observed the behavior on Mac, not sure about Linux and Windows.

A: In your dragend event handler you need to detect if the mouse is over the graybox in the list you want to drop it in.  Note you'll need to write the logic to query the element grayBoxInOtherList but this is what you will need to do:
if ($(grayBoxInOtherList).parent().find(":hover")) {
    listContainer.insertBefore(source, grayEmptyNode);
}

Only do this if you're hovering over the grayBoxInOtherList: listContainer.insertBefore(source, grayEmptyNode);


text:
Q: Share Image in android I need to share an image (.png format) with transparent background, through sent_action intent.
I searched a lot and tried a lot of samples but couldn't find the solution.
The is this method in witch the image will get shared directly from the resources, but for some reason from some point it has stop working.
Uri url = Uri.parse("android.resource://"
            + getPackageName() + "/" + R.drawable.ic_launcher);
    Intent share_intent = new Intent();
    share_intent.setAction(Intent.ACTION_SEND);
    share_intent.setType("image/png");
    share_intent.putExtra(Intent.EXTRA_STREAM,
            Uri.fromFile(new File(url.toString())));
    startActivity(Intent.createChooser(share_intent, "choose app"));

and there is this function which works fine, the problem is it adds a black background to the image.
private void share3()
{
    Bitmap bitmap;
    OutputStream output;
    bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
    File filepath = Environment.getExternalStorageDirectory();
    File dir = new File(filepath.getAbsolutePath() + "/Gallery/");
    dir.mkdirs();
    File file = new File(dir, "ic_launcher" + ".png");
    try {
        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("image/png");
        output = new FileOutputStream(file);
        bitmap. compress(Bitmap.CompressFormat.PNG/*Bitmap.CompressFormat.PNG*/, 0, output);
        output.flush();
        output.close();
        Uri uri = Uri.fromFile(file);
        share.putExtra(Intent.EXTRA_STREAM, uri);
        startActivity(Intent.createChooser(share, "choose app"));

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

I need to share the image from "raw" folder in the resources and share it without background. What should I do?

A: I found the problem, It is telegram itself. Telegram adds a black background to .png images you share.

A: Try this ..its work for me to share image from drawable folder.
 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
    String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/LatestShare.png";
    OutputStream out = null;
    File file = new File(path);
    try {
        out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    path = file.getPath();
    Uri bmpUri = Uri.parse("file://" + path);
    Intent shareIntent = new Intent();
    shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
    shareIntent.setType("image/png");
    startActivity(Intent.createChooser(shareIntent, "Share with"));