text:
Q: Strange behavior (ajax long-polling channel) "refuses" connection from normal browser? When you copy this link
http://q55.queue.vkontakte.ru/im639

and place it to currect browser tab, press enter,  it does "load", address changes, but content is still the same (you're still in this question). What's that? Is that programmatical behavior ?

A: I am not seeing anything. It does not do anything because nothing is available.
alfred@alfred-laptop:~/node/contact$ curl -v http://q55.queue.vkontakte.ru/im639* About to connect() to q55.queue.vkontakte.ru port 80 (#0)
*   Trying 87.240.134.232... connected
* Connected to q55.queue.vkontakte.ru (87.240.134.232) port 80 (#0)
> GET /im639 HTTP/1.1
> User-Agent: curl/7.21.0 (i686-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.18
> Host: q55.queue.vkontakte.ru
> Accept: */*
>
< HTTP/1.1 204 No Content
< Server: nginx/0.7.59
< Date: Mon, 11 Jul 2011 18:49:25 GMT
< Content-Type: text/html
< Connection: keep-alive
<
* Connection #0 to host q55.queue.vkontakte.ru left intact
* Closing connection #0

We get status code HTTP/1.1 204 No Content
Also this has nothing to do with long-polling, because the connection is not hanging at all. It looks like the URL is pointing to an image. I can not image you should be doing long-polling for retrieving a simple image.

A: The server responds with a 204. See here which explains that on a 204 server response:

If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent.


text:
Q: What are the usecases and usefulness when passing pointer to data member to std::invoke? I was reading about std::invoke on cpp reference and was wondering in which situations we would ever need to pass as a first argument a pointer to data member and an object as second argument.
From cpp reference it states this:

Invoke the Callable object f with the parameters args. As by INVOKE(std::forward(f), std::forward(args)...).
where INVOKE(f, t1, t2, ..., tN) is defined as follows:

...
and then the second point is:

Otherwise, if N == 1 and f is a pointer to data member of class

Ok, let's look at this further and suppose I'm using std::thread (which constructor's uses std::invoke):
For example, it is a bit unclear to me when it would be useful (or what can force one) to use a threads this way ?
struct Foo {
    Foo(int num) : num_(num) {}
    void print_add(int i) const { std::cout << num_+i << '\n'; }
    int num_;

    void print_num(int i) const {
        std::cout << i << '\n';
    }
};

int main() {
    const Foo foo(314159);
    std::thread t(&Foo::num_, foo);
    t.join();
    return 0;
}

And how a pointer to data member can be associated with a callable concept ?

A: You might think that only pointers to member functions are useful. That is, something like:
struct Widget {
    bool valid() const;
};

std::vector<Widget> widgets;
bool all_valid = std::ranges::all_of(widgets, &Widget::valid);

That would std::invoke the pointer to member function &Widget::valid on each of the Widgets. But you could just as easily have constructed Widget such that valid is just a flag instead of being a member function. And checking that all the Widgets are valid is just as reasonable a thing to do:
struct Widget {
    bool valid;
};

std::vector<Widget> widgets;
bool all_valid = std::ranges::all_of(widgets, &Widget::valid);

The only difference is that this std::invokes a pointer to member data instead of a pointer to member function. But still useful.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how can we make ListHeaderComponent as sticky header in SectionList? Description
i am using horizontal tab bar inside ListHeaderComponent and I want make ListHeaderComponent as a sticky header in SectionList. we can make stickyheader in flatlist by stickyHeaderIndices={[0]} but it does not work in SectionList
React Native version:
React Native Environment Info:
    System:
      OS: macOS 10.14.6
      CPU: (12) x64 Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz
      Memory: 38.35 MB / 16.00 GB
      Shell: 5.3 - /bin/zsh
    Binaries:
      Node: 12.15.0 - /usr/local/bin/node
      Yarn: 1.21.1 - /usr/local/bin/yarn
      npm: 6.13.4 - /usr/local/bin/npm
      Watchman: 4.9.0 - /usr/local/bin/watchman
    SDKs:
      iOS SDK:
        Platforms: iOS 12.4, macOS 10.14, tvOS 12.4, watchOS 5.3
      Android SDK:
        API Levels: 28, 29
        Build Tools: 28.0.3, 29.0.1, 29.0.2
        System Images: android-26 | Google Play Intel x86 Atom, android-27 | Google APIs Intel x86 Atom
    IDEs:
      Android Studio: 3.5 AI-191.8026.42.35.5791312
      Xcode: 10.3/10G8 - /usr/bin/xcodebuild
    npmPackages:
      react: 16.8.6 => 16.8.6
      react-native: 0.59.8 => 0.59.8
    npmGlobalPackages:
      rename-horizon: 1.1.0
      react-native-cli: 2.0.1

Steps To Reproduce
Provide a detailed list of steps that reproduce the issue.

*

*make section list  and add ListHeaderComponent props

*add stickyHeaderIndices={[0]} in section list
it will not make ListHeaderComponent as sticky header

Expected Results
it should be making ListHeaderComponent as a sticky header. or alternative way to make it sticky header

A: Use something like this.
<View style={{ flex: 1 }}>
  {renderStickyListHeaderComponent()}
  <SectionList
    {...sectionListprops}
    ref={sectionListRef}
    sections={sectionData}
    stickySectionHeadersEnabled={false}
  />
</View>

A: To make the top or any other header sticky for section list, provide a custom scroll component:
const CustomScrollComponent = (props) => <ScrollView {...props} stickyHeaderHiddenOnScroll={true} stickyHeaderIndices={[0]} />

then in your section list:
<SectionList
  // other props
  renderScrollComponent={CustomScrollComponent}
/>

A: you can use renderSectionHeader & stickySectionHeadersEnabled = true
render() {
  return (
    <SectionList
      data={sections}
      renderSectionHeader = {({section:{title}}) => (<YourHeader>)}
      stickySectionHeadersEnabled/>
 )
}


text:
Q: Problem with AutoMapper in IIS7 when using signed assemblies I am trying to use AutoMapper with web application running on IIS 7.  The intended use it so map domain types defined in an external dll to view models defined in the IIS application.  This works fine except when the external dll is singed.  Then I get the following error:
AutoMapper.AutoMapperMappingException was unhandled by user code
  Message="Trying to map TestLibrary.Source to WebApplication1.Destination.\nUsing mapping configuration for TestLibrary.Source to WebApplication1.Destination\nException of type 'AutoMapper.AutoMapperMappingException' was thrown."
  Source="AutoMapper"
  StackTrace:
       at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)
       at AutoMapper.MappingEngine.Map(Object source, Type sourceType, Type destinationType)
       at AutoMapper.MappingEngine.Map[TSource,TDestination](TSource source)
       at AutoMapper.Mapper.Map[TSource,TDestination](TSource source)
       at WebApplication1._Default.Page_Load(Object sender, EventArgs e)
       at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
       at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
       at System.Web.UI.Control.OnLoad(EventArgs e)
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException: AutoMapper.AutoMapperMappingException
       Message="Trying to map TestLibrary.Source to System.Object.\nUsing mapping configuration for TestLibrary.Source to WebApplication1.Destination\nDestination property: Value\nException of type 'AutoMapper.AutoMapperMappingException' was thrown."
       Source="AutoMapper"
       StackTrace:
            at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, Object mappedObject, PropertyMap propertyMap)
            at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.Map(ResolutionContext context, IMappingEngineRunner mapper)
            at AutoMapper.Mappers.TypeMapMapper.Map(ResolutionContext context, IMappingEngineRunner mapper)
            at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context)
       InnerException: System.Security.SecurityException
            Message="Request failed."
            Source="Anonymously Hosted DynamicMethods Assembly"
            StackTrace:
                 at lambda_method(ExecutionScope , Object )
                 at AutoMapper.Internal.PropertyGetter.GetValue(Object source)
                 at AutoMapper.Internal.MemberGetter.Resolve(ResolutionResult source)
                 at AutoMapper.PropertyMap.ResolveValue(Object input)
                 at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, Object mappedObject, PropertyMap propertyMap)
            InnerException:

Steps to Reproduce the problem:
1) Create a new web application using Visual Studio 2008 on a machine with IIS 7 installed.  (We are using windows 7).
2) Download the AutoMapper.dll from http://www.codeplex.com/AutoMapper.   (We are using version 0.4.x.x) and add a reference to this Dll to your web application.
3) Place the following code in the code behind for the default page:
using System;
using AutoMapper;
using TestLibrary;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Mapper.CreateMap<Source, Destination>();
            Mapper.AssertConfigurationIsValid();

            var source = new Source {Value = "Automapper works!" };
            var destination = Mapper.Map<Source, Destination>(source);

            Response.Clear();
            Response.ContentType="text/plain";
            Response.Write(destination.Value);
            Response.End();
        }
    }

    public class Destination
    {
        public object Value { get; set; }
    }

4) Create a new Class Library named "TestLibrary" and rename the Class1.cs file to Source.cs and put the following code it in:
namespace TestLibrary
{
    public class Source
    {
        public object Value { get; set; }
    }
}

5) Add a reference to this library to your web application.
6) Run the solution and you should see the "Automapper works!" output.
7) To make it fail, you must do two things.
   i) Configure the website to run under IIS instead of the Visual Studio development server.
   ii) Sign the TestLibrary assembly.
   After that, running the solution should produce the error reported above.
Does anyone have any idea how to get around this?  We have checked and the application is running with full trust accourding the the IIS management console.

A: So this exception comes from creating a lambda expression programmatically and then compiling it.  Can you try doing the same thing, just in the Default.aspx.cs?  One way to do this would be to create a lambda expression in code:
Expression> expr = () => 5;
then do:
var func = expr.Compile();
it's a line just like that that's failing for you.
If this works, I'd then next put this code in that signed assembly, and access it from the web application.


text:
Q: Pass user id to decrypt JWT I just started to get familiar with JWT and one question popped up, how to decrypt JWT on the server side without knowing what secret is used? Let's say we protect REST API /user endpoint with JWT Token. The user generates a Token and passes using the header
Authorization: Bearer <token>

How we may know the user id to get his secret for JWT Token decryption?
Can we pass the User ID along with a token like this
Authorization: Bearer <token> <UserID>


text:
Q: ffmpeg output to S3 using PUT presigned url - not seeing output file on S3 I am creating a PUT presigned url and using it to upload ffmpeg output to S3. I am not getting any error but not seeing output files on S3 bucket.
Using below ffmpeg command to upload a file.
C:>ffmpeg.exe -re -i in.ts -f hls -method PUT "https://server.com/bucket/object/out.m3u8?AWSAccessKeyId=accessKey&Expires=123456789&Signature=signature"
Any help would be appreciated.


text:
Q: Iterate and Compare through multiple Columns in Pandas I want to iterate through multiple columns which have the key word: Compliance with a column named Requirements. I want to make it very general so I can utilize it with a variation of excel files.
So I scanned through the columns with the word Compliance:
Then I want to compare the Column named Requirement? With the rest of the columns. If the Column Requirement == True and a column with the Regex Compliance == Empty, I want to save that column and the requirement column.
df6 = pd.DataFrame (df merged)

df6.columns.to_series().str

df6.columns.to_series().str.contains("Compliance")

df6 = df6.loc[:, df6.columns.to_series().str.contains ("Compliance") ]

compstatus = df6.columns[df6.columns.str.contains (r'\bCompliance Status\b ')]

df6.insert(0, 'Requirement?', df merged[ 'Requirement?'])

df6 = df6.replace( ['nan', None],'Empty ")

Example:
Requirement? A-Compliance Status  B-Compliance Status ..

True          Empty                  Yes

I want the Columns:
Requirement?          A-Compliance Status

True                       Empty

A: IIUC,
df2 = df6.filter(like='Compliance')

pd.concat([df6['Requirement?'], df2[df2 == 'Empty']], axis=1)


text:
Q: iPhone MPMoviePlayerController : Hiding the status bar
Possible Duplicate:
Hide the status while playing movie using MPMoviePlayerController

It seems that if you play a movie full screen the status bar is turned back on.  You can hide it on movie load but as soon as you click the controls to come up it reappears.  There seems to be no movie controls appear events.
Update:
This is only an issue if you tab the screen for the movie controls to come up.  Its something to do with the movie control.

A: Otherwise you could:
Use this when you want it to show:
[[UIApplication sharedApplication] setStatusBarHidden:NO animated:NO]];

Use this when you want to hide it:
[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO]];


text:
Q: How to restore mysql database backup from terminal? I make daily backups by running the following cronjob:
mysqldump --user root --password=xxxx databasename > /home/ec2-user/backup/databasebackup_$today

How would I go about to simply restore from a backup, completely overwriting whatever there might be?

A: Did you try with...
mysql --user=root --password=xxxx --database=databasename < /home/ec2-user/backup/databasebackup_$today

Hope it helps

A: Another way
mysql -u root -p databasename < /home/ec2-user/backup/databasebackup_$today

You will be prompt to enter password. Supposing you are not planning to cron restore procedure.


text:
Q: Filtering based on a second data.table with a negation the command I am very new to R and especially data.table and I'm stuck with the following.
I have 2 data.tables, say "Canteen" and "Saladconsumer".
The data.table "Canteen" contains the ID, date, time and items bought of every person.
The second data.table "Saladconsumer"contains the ID, date and time of people who have bought a salad and is basically a subset of "Canteen".
Now I'd like to filter "Canteen" by "Saladconsumer" so that I get the people that have bought a salad on that day and made an other purchase the same day in the canteen. Therefore the filtering must contain a negation: Canteen[, ID]==Saladconsumer[, ID] & Canteen[, date]==Saladconsumer[, date] & Canteen[, time]!=Saladconsumer[, time].
I have only found examples for overlaps and merge/join if all the criteria are the same. It seems to be so simple but I just can't figure out what my mistake is...
NewDT<- Canteen[, Canteen[, ID ] == Saladconsumer [, ID ] & Canteen[, date ] == Saladconsumer[, date ] & Canteen[, time ] == Saladconsumer [, time ]]

This what the data looks like and what the results are I'm looking for:
Canteen
ID  Date    Time
00b47c5d83a5490e860086eb080f1f50    26.06.14    12:36:29
00b47c898875483fb9fa0113d334e500    06.01.14    16:28:56
00b4cb6c666e2b8152174479545fcef2    29.10.14    12:57:16
00b4cb6c666e2b8152174479545fcef2    29.10.14    17:20:07
00b64cef0230b7480fc96dfcad9b8394    07.05.14    11:43:34
00b8b859987af5c89d90130d1206c579    03.01.14    13:35:15
0205996c0139e0b909903c2ebacb5a77    07.01.14    14:48:13
0205d25db373084f9bf8d431db8d3f9c    07.01.14    09:10:27
0205d25db373084f9bf8d431db8d3f9c    07.01.14    13:48:21
0208cfa78e51231cf30842ea0f8abdf4    10.04.14    10:06:43

Salad consumer
ID  Date    Time
00b4cb6c666e2b8152174479545fcef2    29.10.14    12:57:16
0205d25db373084f9bf8d431db8d3f9c    07.01.14    13:48:21
020e53bd2076a9db4c9770662793602b    04.02.14    10:38:41
020ed0685aa70b543981cbb6a7f0c737    16.01.14    15:40:02
020aa996e0f4b6e886a82ce83d406e92    23.01.14    14:23:43
020ac1d718ff47f5aaa2d684434bae93    30.06.14    13:47:45
020b20874ae29027ddac149ab3d5a395    09.04.14    09:34:32

Results
ID  Date    Time
00b4cb6c666e2b8152174479545fcef2    29.10.14    17:20:07
0205d25db373084f9bf8d431db8d3f9c    07.01.14    09:10:27

A: I would invite you to the tidyverse (which includes the package dplyr) and recommend a left join followed by an anti-join.
I also recommend looking at the RStudio cheat sheets on data manipulation: https://www.rstudio.com/resources/cheatsheets/
This should do the trick (although I may have miss interpreted what you are looking for - in which case I am happy to help further):
library(tidyverse)

SaladPeople <- select(Saladconsumer, ID) %>% left_join(Canteen)

Now you have only the salad consumers at the canteen.  If I understand what you are looking for then you can do an anti-join:
yourData <- anti_join(SaladPeople, Saladconsumer)

Or as one would do this in the tidyverse:
yourData <- select(Saladconsumer, ID) %>%
  left_join(Canteen, by="ID") %>%
  anti_join(Saladconsumer))


text:
Q: How to use image_picker in flutter I am confused about how to use image_picker, this is how I use it in my application (like in many tutorials):
class AddDialogState extends State<AddDialog> {
    File galleryFile;
    Widget _onlyStatus() {
         getLocalImage() async {
               var _galleryFile = await ImagePicker.pickImage(
                     source: ImageSource.gallery
               };
               setState(() {
                   galleryFile = _galleryFile;
               });
               print(_galleryFile.path);
         }

         return Column(
               ........
               FlatButton.icon(
                    onPressed: () {
                         getLocalImage();
                    }
               )
         )

    }

    @override
    Widget build(BuildContext context) {
         // fullscreen dialog
         .........
         body: _onlyStatus()
    }
}

The problem was, the above code doesn't start ImagePicker, when i click the FlatButton, the above code just produce an error the getter 'path' was called on null, it doesn't start any new activity related to gallery, so what's wrong with my code?

A:
Actually pickImage() is deprecated now. So you have to use ImagePicker.getImage(source: ImageSource.gallery)
Click here for more
void getImage(ImageSource imageSource) async {
    PickedFile imageFile = await picker.getImage(source: imageSource);
    if (imageFile == null) return;
    File tmpFile = File(imageFile.path);
    final appDir = await getApplicationDocumentsDirectory();
    final fileName = basename(imageFile.path);
    tmpFile = await tmpFile.copy('${appDir.path}/$fileName');
    setState(() {
      _image = tmpFile;

    });
  }

The code also store image file in device directory. Path pacakage is also used.

A: Here is my example you only need to call the SelectionItem and pass the required parameters and it's done, also it includes support for Android and iOS.
class SelectionItem {
  String text;
  GestureTapCallback action;

  SelectionItem({
    this.text,
    this.action,
  });
}

Widget _getOptionWidget(SelectionItem item) {
  return SimpleDialogOption(
    onPressed: item.action,
    child: Text(item.text),
  );
}

Widget _getCupertinoOptionWidget(SelectionItem item) {
  return CupertinoActionSheetAction(
    onPressed: item.action,
    child: Text(item.text),
  );
}

showSelector(
  BuildContext context, {
  String title,
  List<SelectionItem> actions,
}) {
  bool isAndroid = Injector.instance.platform == Platform.ANDROID;

  if (isAndroid) {
    final items = actions.map((action) => _getOptionWidget(action)).toList();
    return SimpleDialog(
      title: Text(title),
      children: items,
    );
  } else {
    final items =
        actions.map((action) => _getCupertinoOptionWidget(action)).toList();

    return Column(
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        CupertinoActionSheet(
          title: Text(title),
          actions: items,
          cancelButton: CupertinoActionSheetAction(
            onPressed: () {
              NavigationUtils.pop(context);
            },
            child: Text("Cancel"),
          ),
        ),
      ],
    );
  }
}

A: your showDialog should be something like this:
Container(
          width: 300,
          height: 300,
          child: GestureDetector(
            onTap: () {
              showDialog(
                context: context,
                builder: (BuildContext context) => showSelector(
                      context,
                      "Select",
                      actions: [
                        SelectionItem(
                          "Camera",
                          action: () {
                            getImage(ImageSource.camera);
                            Navigator.of(context).pop();
                          },
                        ),
                        SelectionItem(
                          "Gallery",
                          action: () {
                            getImage(ImageSource.gallery);
                            Navigator.of(context).pop();
                          },
                        )
                      ],
                    ),
              );
            },
          ),
        )

A: Here is my code for  image_picker: ^0.8.4+4 (flutter 2.8.1)
bool hasImage = false;
File? image;

Future getImage(ImageSource source) async {
    try {
      final image = await ImagePicker().pickImage(source: source);
      if (image == null) return;
      final imageTemporary = File(image.path);
      setState(() {
        this.image = imageTemporary;
        hasImage = true;
      });
    } on PlatformException catch (e) {
      debugPrint('Failed to pick image: $e');
    }
  }


text:
Q: How to write a function which takes files without Pandas in Python? I have 3 .dat files. I want to write a function which takes these 3 files as input and writes a text file (as output.dat) for merged data without using pandas. Merged data should include  following order:
user_id
movie_id
rating
timestamp
gender
age
occupation
zip
title
genres
Year

A: Without Pandas:
from itertools import groupby, product

def read_data(filename, columns):
    with open(filename, mode='r') as f:
        rows = [line.split('::') for line in f.read().splitlines()]
    records = [{name: value for name, value in zip(columns, row)} for row in rows]
    return records

def merge(a, b, on):
    key = lambda d: d.get(on)
    lt = {k: list(g) for k, g in groupby(sorted(a, key=key), key=key)}
    rt = {k: list(g) for k, g in groupby(sorted(b, key=key), key=key)}
    out = [
        {**a, **b}
        for k in set(lt).intersection(rt)
        for a, b in product(lt[k], rt[k])
    ]
    return out

def write_merge(fp, merged, sortby=None, fields=None, sep=None):
    if sortby is not None:
        merged = sorted(merged, key=lambda e: tuple(e[k] for k in sortby))
    if merged and fields is None:
        fields = list(merged[0].keys())
    for i, row in enumerate(merged):
        if i > 0 and sep is not None:
            print(sep, file=fp)
        for k in fields:
            print(f'{k}={row.get(k)}', file=fp)

Application:
users = read_data('users.dat', unames)
ratings = read_data('ratings.dat', rnames)
movies = read_data('movies.dat', mnames)

merged = merge(merge(users, ratings, on='user_id'), movies, on='movie_id')

fields = 'user_id movie_id rating timestamp gender age occupation zip title genres'.split()
sortby = fields

with open('output.dat', mode='w') as f:
    write_merge(f, merged, sortby=sortby, fields=fields, sep='')

Simple test (modifying your data a little so that the inner merge is not empty):
Prep:
mov = """1::Toy Story (1995)::Animation|Children's|Comedy
2::Jumanji (1995)::Adventure|Children's|Fantasy
3::Grumpier Old Men (1995)::Comedy|Romance
4::Waiting to Exhale (1995)::Comedy|Drama
5::Father of the Bride Part II (1995)::Comedy
"""

rat = """1::1::5::978300760
1::2::3::978302109
1::914::3::978301968
2::1::4::978300275
2::3::5::978824291
"""

usr = """1::F::1::10::48067
2::M::56::16::70072
3::M::25::15::55117
4::M::45::7::02460
5::M::25::20::55455
"""

with open('users.dat', mode='w') as f: f.write(usr)
with open('ratings.dat', mode='w') as f: f.write(rat)
with open('movies.dat', mode='w') as f: f.write(mov)

Test:
unames = 'user_id gender age occupation zip'.split()
rnames = 'user_id movie_id rating timestamp'.split()
mnames = 'movie_id title genres'.split()

users = read_data('users.dat', unames)
ratings = read_data('ratings.dat', rnames)
movies = read_data('movies.dat', mnames)

merged = merge(merge(users, ratings, on='user_id'), movies, on='movie_id')

# optional: quick vis using Pandas, just to test:
display(pd.DataFrame(merged).sort_values(by=sortby))

# save to stdout for inspection
write_merge(sys.stdout, merged, sortby=sortby, fields=fields, sep='------')

Output:
user_id=1
movie_id=1
rating=5
timestamp=978300760
gender=F
age=1
occupation=10
zip=48067
title=Toy Story (1995)
genres=Animation|Children's|Comedy
------
user_id=1
movie_id=2
rating=3
timestamp=978302109
gender=F
age=1
occupation=10
zip=48067
title=Jumanji (1995)
genres=Adventure|Children's|Fantasy
------
(...)

A: Assuming your files are saved in a local drive = /home/your/path/to/drive.
Also your three dat files should have some unique identifiers in the name. Eg. unames.dat,rnames.dat etc.
import os
import pandas as pd

unames=["user_id","gender","age","occupation","zip"]
rnames=["user_id","movie_id","rating","timestamp"]

df_f =[]

#Loop block
files_uname = [f for f in os.listdir(local_drive) if 'uname' in os.path.basename(f) and f.endswith('.dat')]
for f in files_uname:
    df = pd.read_csv(f,sep = '::',names=unames)
    df_f.append(df)

Run this Loop block for all three types of files
And then finally
df_final = pd.concat(df_f,axis=0)


text:
Q: A word which is closest to the meaning of 'relatable' A word which is closest to the meaning of 'relatable'.
For example, you watch a movie or read something and you have the strange sense of feeling that it has happened to you too, And you attach a deeper sense of meaning and understanding to it.

A: How about "resonates" / "resonant" / "resonance" ?

A: I don't think there is a synonymous adjective for "relatable" for the situation.
I had a strong sense of déjà vu when I saw the movie.
Hope it helps.

A: You need to clarify which meaning of relate.

*

*To be able to associate with?

*To be able to give an account of?

I am concluding that you wish to refer to the 1st meaning - being able to associate yourself to an idea, concept or person.
A good word is "identify".

*

*"I can identify with you, with your situation, because I too had been betrayed by a boyfriend before", the young woman consoled her friend.

*She identifies herself with the Democratic caucus, even though she was elected as an independent.
Identity = being one with, being in a singularity, the token of your one-ness.
i·den·ti·fy  (ī-dĕn′tə-fī′)
v. i·den·ti·fied, i·den·ti·fy·ing, i·den·ti·fies

v.tr.

*

*
*

*a. To establish or recognize the identity of; ascertain as a certain person or thing: Can you identify what kind of plane that is? I identified the man at the next table as a famous actor.

*b. Biology To determine the taxonomic classification of (an organism).

*c. To ascertain as having a certain characteristic or feature: job candidates who are identified as overqualified; children who have been identified with hearing loss.

*To consider as identical or united; equate: The Greek god Ares is identified with the Roman god Mars.

*To associate or affiliate closely with: writers who are identified with modernism.

v.intr.

*

*To consider oneself as sharing certain characteristics or attitudes as another: She identifies strongly with her grandmother.

*To associate oneself with or admire something, such as a set of ideas: a language learner who identifies with a new culture.

*To self-identify.

[Medieval Latin identificāre, to make to resemble : Late Latin identitās, identity; see identity + Latin -ficāre, -fy.]
i·den′ti·fi′a·ble adj.
i·den′ti·fi′a·bly adv.
i·den′ti·fi′er n.
American Heritage® Dictionary of the English Language, Fifth Edition. Copyright © 2011 by Houghton Mifflin Harcourt Publishing Company. Published by Houghton Mifflin Harcourt Publishing Company. All rights reserved.


text:
Q: Add button inside input field I have a search form and I'd like to add the search button inside its right side like this:

Here is the code for my form:
<form action="search.php" method="post" class="index-search-form">
                <input name="search" type="text" class="" placeholder="  What are you looking for?">
                <button name="submit" class="" type="submit">Search</button>
            </form>

A: If you want to set the button inside the input field. You need to make the button position absolute. And the form position relative and set display: inline-flex or inline-block or initial( For initital you need to adjust the padding top and bottom for button or input field ) . I set a width for the input field so  text will be clearly visiable. I ust add a class for input field. If you have any question ask me in comment. Thanks. LiveOnFiddle

form.index-search-form {
  position: relative;
  display: inline-flex;
}

button[name="submit"] {
  position: absolute;
  top: 0;
  right: 0;
}

input.search-box {
  width: 250px;
  font-family: FontAwesome;
  padding: 2px 0;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />

<form action="search.php" method="post" class="index-search-form">
  <input name="search" type="text" class="search-box" placeholder="  What are you looking for?">
  <button name="submit" class="" type="submit">Search</button>
</form>

A: Use position and padding to accomplish this effect.

form {
  display: inline-block;
  position: relative;
}
form input {
  padding-right: 4.6em;
}
form button {
  position: absolute;
  top: 0;
  right: 0;
  width: 4.4em;
}
<form action="search.php" method="post" class="index-search-form">
  <input name="search" type="text" placeholder="What are you looking for?">
  <button name="submit" class="" type="submit">Search</button>
</form>

A: Do you mean somethink like this?

.index-search-form {
    display: flex;
}

.inputField {
    flex: 1;
}
<form action="search.php" method="post" class="index-search-form">
                <input name="search" type="text" class="inputField" placeholder="  What are you looking for?">
                <button name="submit" class="" type="submit">Search</button>
            </form>


text:
Q: make address line 2 inout element optional I have a html form and I'm using Jquery to validate input elements but the issue is that the script is validating all input text fields and not validating select fields. Also I need to make the address line 2 input text field set to optional and the select fields must be required.
<fieldset>

            <input type="text" class="form-control" placeholder="addres 1" id="add1" name="" value="" |>

            <input type="text" class="form-control" placeholder="address 2" id="add2" name="" value="">

            <input type="text" class="form-control" placeholder="city" id="city" name="" value="" |>

            <input type="text" class="form-control" placeholder="Home Phone" id="contact_number" name="" value="">

 < script >
$(document).ready(function() {
    $('.registration-form fieldset:first-child').fadeIn('slow');

    $('.registration-form input[type="text"]').on('focus', function() {
        $(this).removeClass('input-error');
    });

    // next step
    $('.registration-form .btn-next').on('click', function() {
        var parent_fieldset = $(this).parents('fieldset');
        var next_step = true;

        parent_fieldset.find('input[type="text"],input[type="email"]').each(function() {
            if ($(this).val() == "") {
                $(this).addClass('input-error');
                next_step = false;
            } else {
                $(this).removeClass('input-error');
            }
        });

        if (next_step) {
            parent_fieldset.fadeOut(400, function() {
                $(this).next().fadeIn();
            });
        }

    });

    // previous step
    $('.registration-form .btn-previous').on('click', function() {
        $(this).parents('fieldset').fadeOut(400, function() {
            $(this).prev().fadeIn();
        });
    });

    // submit
    $('.registration-form').on('submit', function(e) {

        $(this).find('input[type="text"],input[type="email"]').each(function() {
            if ($(this).val() == "") {
                e.preventDefault();
                $(this).addClass('input-error');
            } else {
                $(this).removeClass('input-error');
            }
        });

    });

}); < /script>

A: If you don't want to validate address2. You can just ignore it. Try this.
Jquery
 $('.registration-form').on('submit', function(e) {
        $(this).find('input:text[name!=add2],input[type="email"]').each(function() { // this will filter input of having name of add2
            if ($(this).val() == "") {
                e.preventDefault();
                $(this).addClass('input-error');
            } else {
                $(this).removeClass('input-error');
            }
        });

    });

HTML
   <form class="registration-form" name="register">
    <fieldset>

                    <input type="text" class="form-control" placeholder="addres 1" id="add1" name="" value="" |>

                    <input type="text" class="form-control" placeholder="address 2" id="add2" name="add2" value="">

                    <input type="text" class="form-control" placeholder="city" id="city" name="" value="" |>

                    <input type="text" class="form-control" placeholder="Home Phone" id="contact_number" name=""
                           value="">

    </fieldset>
    <input type="submit" value="Submit">
</form>


text:
Q: roundcube Forgot password plugin in the README part of the plugin https://github.com/saas-dev/roundcube-forgot_password/blob/master/README it says: To show the link "forgot my password" it necessary to activate the taskbar plugin or change the div to append the link in js/forgot_password.js
I couldn't find task bar plugin?
does any one know how should I get it ?
and also how can I change the div to append that link?
Is there any one who has used this plugin ?

A: You can download taskbar plugin adding plugin_manager to roundcubemail

A: the problem is solved i just add a div in login page and appended the link in js/forgot_password.js like below:
there is no taskbar plugin available now !(I couldn't find any)
    function forgot_password(){
    if($('#rcmloginuser').val())
    {
      document.location.href = "./?_task=settings&_action=plugin.forgot_password_reset&_username=" + escape($('#rcmloginuser').val());
    }
    else
    {
      rcmail.display_message(rcmail.gettext('forgot_passworduserempty','forgot_password'),'error');
    }}$(document).ready(function($){$('#forgot-password-place').append('' + rcmail.gettext('forgotpassword','forgot_password') + '');});

this adds a link to login page for forgot password.

A: In case it can help anyone else, and in combination with someoneThere's accepted answer above which removes the need for the deprecated taskbar plugin, I've updated the forgot password plugin to work with Roundcube 1.3.8. You can fork it from my GitHub here.
It is still very much in an alpha state and will need to be configured for your particular Roundcube installation, but you won't have to deal w/ any forward compatibility issues/errors.
EDIT: Updating per suggestions in the comments below...
The original plugin has not been maintained since its release in 2011. I updated it to work with the current stable version of Roundcube (1.3.8 as of the time of this writing - Dec. 17, 2018), removing all forward-compatibility issues that I discovered during my own tests that prevented the original plugin from working on my installation. You can fork my GitHub (link above) to get the fix.
You will not have to necessarily update any of the included JS files per OP's original question, but you will still have to do more configuration than usual for a Roundcube plugin until a more stable release is pushed.


text:
Q: Get Nearest non-None Item in List I need to find a way of, having an array and an index, get the nearest non-None value of the item in that index.
For example:
array = [4, 5, 1, None, 9, None, 7, 8]
index = 4

I need to get the nearest integers of array[index] on the left and on the right:
print(array[index])
# 9

Expected output:
on_left = 1
on_right = 7

CURRENT SOLUTION
This is what I have:
value = array[index]
new_array = [val for val in array if val]
print(new_array)
# [4, 5, 1, 4, 7, 8]

new_array.index(value)
# 0

*Then I would use that index to get the right and left items
The issue here, as you can see, happens when there are repeated numbers, In this example I'm getting the index of the first 4 instead of the second, how would you solve this?

A: You can use the next function on a subset of the array starting at the next position going forward (for the right side) and at the previous position, going backwards (for the left side):
array    = [4, 5, 1, None, 4, None, 7, 8]
index    = 4
on_right = next(v for v in array[index+1:]    if v is not None)
on_left  = next(v for v in array[index-1::-1] if v is not None)

print(on_left,on_right) # 1 7


text:
Q: I can't seem to update my sourceforge project? I recently had to delete my local copy of a sourceforge project I've been working on, and then I cloned it to a local repo. I've been commiting, and it's said that I've been updating the repo (locally at least), but when I checked online the last commit was from a week ago (before I deleted my local repo). Any ideas on why this might have happened/how I can fix it?

A: From the comments in your question, it looks like 2 different repositories.
If you view the commits at this germline summary page you can see your recent commits as expected.
But this is germline.git.sourceforge.net, and your remote is pointing to that, but the sourceforge project you originally linked to is git.code.sf.net


text:
Q: JSON to MYSQL - is JSON response formatted correctly - looping properly? OK - I am attempting to load a JSON response (from an external file called recipes.json which includes hundreds of recipes) which is formatted as follows in order to insert it into a MySQL table called "recipes":
{ "recipeName": "After Glow Smoothie",  "ingredients": "4 oz. (1/2 cup) pomegranate juice", "ingredients2": "4 oz. (1/2 cup orange juice)", "ingredients3": "2 scoops Vi-Shape shake mix", "ingredients4": "1 cup frozen pineapple", "ingredients5": "5 ice cubes"},
{ "recipeName": "All Berry Delight",     "ingredients": "8 oz. skim milk", "ingredients2": "2 scoops Vi-Shape shake mix", "ingredients3": "1/4 cup frozen raspberries", "ingredients4": "1/4 cup frozen blackberries", "ingredients5": "1/4 cup frozen strawberries", "ingredients6": "1/4 cup frozen dark cherries", "ingredients7": "5 ice cubes"}

I am not too handy with arrays so I am wondering why I am not able loop through the recipes and insert them properly.  Is my JSON malformed or am I such a PHP noob that I am making mistakes in my main code.  For reference it as follows:
<?php
header('Content-Type: text/html; charset=utf-8');

$hostname_ndb = "localhost";
$database_ndb = "test";
$username_ndb = "root";
$password_ndb = "root";
$ndb = mysql_pconnect($hostname_ndb, $username_ndb, $password_ndb) or trigger_error(mysql_error(),E_USER_ERROR);

$url = "http://localhost:8888/shakerecipes/recipes.json";

$json = file_get_contents($url);
// var_dump(json_decode($json, true));
$out = json_decode($json, true);

foreach($out["recipeName"] as $recipeNames) {
$name = addslashes($recipeNames[recipeName]);
$ingredients= addslashes($recipeNames[ingredients]);
$ingredients2 = addslashes($recipeNames[ingredients2]);
$ingredients3 = addslashes($recipeNames[ingredients3]);
$ingredients4 = addslashes($recipeNames[ingredients4]);
$ingredients5 = addslashes($recipeNames[ingredients5]);
$ingredients6 = addslashes($recipeNames[ingredients6]);
$ingredients7 = addslashes($recipeNames[ingredients7]);
$ingredients8 = addslashes($recipeNames[ingredients8]);
$ingredients9 = addslashes($recipeNames[ingredients9]);

mysql_query("INSERT INTO test (recipeName, ingredients, ingredients2, ingredients3, ingredients4, ingredients5, ingredients6, ingredients7, ingredients8, ingredients9) VALUES('$name', '$ingredients', '$ingredients2', '$ingredients3', '$ingredients4', '$ingredients5', '$ingredients6', '$ingredients7', '$ingredients8', '$ingredients9')") or die (mysql_error());
}
?>

Thanks for any and all tips/help.
BRR

A: To begin with, you should use mysql_real_escape_string instead of addslashes.
Secondly you should/could preform another foreach loop with $recipeNames.
Or you can do it lambda/closure style.
array_walk($recipeNames, function(&$value) {
    $value = mysql_real_escape_string($value);
});

Afterward you can implode your values
mysql_query("INSERT INTO test (recipeName, ingredients, ingredients2, ingredients3, ingredients4, ingredients5, ingredients6, ingredients7, ingredients8, ingredients9) VALUES('".implode('\',\'', $recipeNames)."')") or die (mysql_error());

A: For those who wonder what worked - here is what I came up with:
<?php
header('Content-Type: text/html; charset=utf-8');

$hostname_ndb = "localhost";
$database_ndb = "test";
$username_ndb = "root";
$password_ndb = "root";
$ndb = mysql_pconnect($hostname_ndb, $username_ndb, $password_ndb) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_ndb);

$url = "http://localhost:8888/shakerecipes/recipes.json";
$json = file_get_contents($url);

$out = json_decode($json, true);

foreach($out["recipes"] as $recipe) {
$name = addslashes($recipe[recipeName]);
$ingredients= addslashes($recipe[ingredients]);
$ingredients2 = addslashes($recipe[ingredients2]);
$ingredients3 = addslashes($recipe[ingredients3]);
$ingredients4 = addslashes($recipe[ingredients4]);
$ingredients5 = addslashes($recipe[ingredients5]);
$ingredients6 = addslashes($recipe[ingredients6]);
$ingredients7 = addslashes($recipe[ingredients7]);
$ingredients8 = addslashes($recipe[ingredients8]);
$ingredients9 = addslashes($recipe[ingredients9]);

mysql_query("INSERT INTO recipes (recipeName, ingredients, ingredients2, ingredients3, ingredients4, ingredients5, ingredients6, ingredients7, ingredients8, ingredients9) VALUES('$name', '$ingredients', '$ingredients2', '$ingredients3', '$ingredients4', '$ingredients5', '$ingredients6', '$ingredients7', '$ingredients8', '$ingredients9')") or die (mysql_error());

}
?>


text:
Q: Unmarshall json reference types I'm trying to write a working example to test "Reference Types" section of this link.
But I'm unable to understand how this should work. The example I'm trying to write without success is provided below, just for reference:
package main

import (
    "fmt"
    "log"
    "encoding/json"
)

type Foo1 struct {
    Val     int
}

type Foo2 struct {
    Name    string
}

type IncomingMsg struct {
    F1 *Foo1
    F2 *Foo2
}

func main() {
    b := []byte(`{"F1" : {"Val":13}}`)
//  b := []byte(`{"F2" : {"Name":"Hello"}}`)

    var msg IncomingMsg

    err := json.Unmarshal(b, &msg)
    if err != nil {
        log.Fatal(err)
    }

    if msg.F1 != nil {
        fmt.Println(msg.F1.Val)
    }

    if msg.F2 != nil {
        fmt.Println(msg.F2.Name)
    }
}

Can some of you with more experience with Go help with this issue?
EDIT: The provided test has been updated, now is working as expected. Thank you Mr Adam for the answer provided, it helped me a lot to understand this issue! :)

A: The json you have posted in your example looks like it is missing F1 in the body?
https://play.golang.org/p/Fl-lhH2y3X

b := []byte(`{"F1":{"Val":13}}`)


text:
Q: Is function overloading pointless? From what I understand function overloading just makes it more likely to have errors in a program. Why should I have a whole bunch of functions with the same name when I can just create functions with distinct names that are easier to be told apart. Can I just avoid this or is there a reason to understand this?

A: You can't avoid overloading constructors since a constructor doesn't have a name. One practical example of an overloaded function is std::to_string. You really don't want to specify the argument type in every call, and differentiating the possibilities would be impractical in template code.

A: One reason for function overloading is to make code more robust in maintenance. For example:
void f_int(int);
void f_long(long);

void g(int i) {
    f_int(i);
}

Now suppose that you determine that g should really be dealing with a long instead of an int. So you change it:
void g(long i) {
    f_int(i); // whoops, forgot to change this to f_long
}

Such a change can produce lengthy ripples, and you end up having to trace function calls throughout your source code in order to make what would be a simple change with function overloading:
void f(int);
void f(long);

void g(int i) {
    f(i); // calls f(int)
}

void new_g(long i) {
    f(i); // calls f(long)
}

This kind of thing occurs often in template programming. As an exercise, try to write this template without overloading f:
void f(int);
void f(long);

template <class T> void g(T arg) {
    f(arg);
}

And after doing that exercise, if you think it's not too bad, try it with half a dozen versions of f.
Note that "I don't need templates" is not a valid answer. <g>
Another place where overloading is critical is overloaded operators. Imagine writing this code if you couldn't overload operator<<:
int i = 3;
double d = 4.1;
long long x = 32;
my_type mt;

std::cout << i << ' ' << d << ' ' << x << ' ' << mt << '\n';


text:
Q: Windows service exits with code 0 and no errors even though it hasn't done its thing I have a windows service that calls a web API service.  All the API calls have been tested and work as they should.
What happens is the service runs a particular piece of code that sends data to the API.  Its supposed to return and continue round the loop.  What it does is just stop.  The JSon has been sent to the API with fiddler and works fine.
Here is the offending code :-
public async Task<WorkOrderCreationResponseDto> ImportWorkOrders(WorkOrderCreationRequestDto request)
    {
        try
        {

            WorkOrderCreationResponseDto resp = await RestClient.PostAsync<WorkOrderCreationRequestDto, WorkOrderCreationResponseDto>(string.Format("{0}/WorkOrders", Resource), request);

            return resp;
        }
        catch (Exception ex)
        {

            throw ex;
        }

    }

Now the code gets to the await line.  At this point the code exits with code 0.  It never hits the return and no error is trapped in the catch.
Can anyone explain why this happens as I am at a complete loss after a morning trolling round google trying to make sense of it all.
Anything that can shed some light on this would be greatly appreciated.
The environment is Windows 10 anniversary update and Visual Studio 2015.  We are coding in c#.
Thanks
Steve
ADDED IN RESPONSE TO COMMENT
We build a data object which is wo in the code below.  _rest contains the user credentials for the API.
using (SopImportDataService service = new SopImportDataService(_rest))
                            {
                                string jsonString = JsonConvert.SerializeObject(wo);

                                //WorkOrderCreationResponseDto c = await service.ImportWorkOrders(wo);

                                await service.ImportWorkOrders(wo);

                                Console.WriteLine("");
                            }

A: Thanks to Glorin for pointing me in the right direction.  The problem was Main in the Progrm.cs file is not Async.  We have used the AsyncEx library by Stephen Cleary, and altered the program.cs to look like this :-
static class Program
{

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
        try
        {
            AsyncContext.Run(() => MainAsync());
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine(ex);
        }
    }

    static async Task MainAsync()
    {
#if (!DEBUG)
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new UnityService()
        };
        ServiceBase.Run(ServicesToRun);
 #else
        UnityService myServ = new UnityService();
        //myServ.SetupService().ConfigureAwait(true);

        await myServ.BeginService();
#endif
    }

These changes seem to have solve dour issue.
Thanks again everyone


text:
Q: Again "How to get grub2 to remember last choice?" This question was already asked once but it hasn't helped me in my trouble.
I have Ubuntu and Windows 7 on my laptop. Usually I use Windows 7 but GRUB always boots Ubuntu by default. My /ect/default/grub contains the following lines:
GRUB_DEFAULT=saved
GRUB_SAVEDEFAULT=true

I did run sudo update-grub after I changed the values for these variables. Also I made sure that my grubenv file existed and had right permissions (with save_env GRUB command).
And still... it doesn't work! GRUB alwas intends to load Ubuntu despite I choosed Windows last time.
What else do I lose sight of?
BTW, I don't have neither RAID nor LVM volumes (at least I don't have LVM manager installed).

A: My situation was similar. I had a custom grub entry (using a 40_custom file in /etc/grub.d) for a Chromium OS install. I had set GRUB_DEFAULT=saved and GRUB_SETDEFAULT=true, but it never saved the entry. Turned out that I needed to manually put a "savedefault" line into the 40_custom file in order for that entry to save the default. Works like a champ now.
Edit: If you put GRUB_SAVEDEFAULT=true, the savedefault line will be added automatically when you run update-grub

A: You can use Grub Customizer for the work it's very simple, just check the box to remember last choice, install it with the commands:
sudo add-apt-repository ppa:danielrichter2007/grub-customizer
sudo apt-get update
sudo apt-get install grub-customizer

A: Press Alt+F2
type
 gksudo gedit /etc/default/grub press Enter and enter your password.
you will see this line GRUB_DEFAULT=0
You can change the default from 0 to any number, corresponding to the entry in the Grub bootup menu (first entry is 0, second is 1, etc.) so if windows 7 is the 4th entry enter the value to 4
Make your changes, press Ctrl-S to save and Ctrl-Q to exit.
Important: Open a terminal with Ctrl-Alt-T and type sudo update-grub to apply the changes you just made.


text:
Q: Postgresql expanding view multiple times instead of executing it once I have a rahter long subquery which I store as a view
CREATE VIEW scans_minmax AS
SELECT tmp.source,
       value ->> 'Ok'                                                    AS "Ok",
       value ->> 'NotOk'                                                 AS "NotOk",
       value ->> 'TotalCount'                                            AS "TotalCount",
       (CASE WHEN scans.timestamp = tmp.min_t THEN 'MIN' ELSE 'MAX' END) AS "Aggregation"
FROM (SELECT source, MIN(timestamp) AS min_t, MAX(timestamp) AS max_t
      FROM scans
      WHERE timestamp > NOW() - INTERVAL '30 days'
        AND value ->> 'Ok' IS NOT NULL
        AND value ->> 'NotOk' IS NOT NULL
        AND value ->> 'TotalCount' IS NOT NULL
      GROUP BY source) AS tmp,
     scans
WHERE scans.source = tmp.source
  AND (scans.timestamp = tmp.min_t OR scans.timestamp = tmp.max_t)

This gives me a nice table as result
| source | Ok | NotOk | TotalCount | Aggregation |
--------------------------------------------------
| A      | a  | b     | c          | MIN         |
| A      | x  | y     | z          | MAX         |

But as I wanted the table also "transposed" (MIN / MAX as columns next to each other for each value) I created the query
SELECT min_tbl.source,
       min_tbl."Ok" AS "min_ok", max_tbl."Ok" AS "max_ok",
       min_tbl."NotOk" AS "min_not_ok", max_tbl."NotOk" AS "max_not_ok",
       min_tbl."TotalCount" AS "min_total_count", max_tbl."TotalCount" AS "max_total_count"
FROM scans_minmax AS min_tbl JOIN
     scans_minmax AS max_tbl ON min_tbl.source = max_tbl.source
WHERE min_tbl."Aggregation" = 'MIN' AND max_tbl."Aggregation" = 'MAX'

which does exactly the right thing.
Now, my issue is the following:
The View above has 16 entries (there are 8 different entries for source in my DB). So the second query should take roughly the same time as a simple SELECT * FROM scans_minmax.
But it turns out that it takes more time, as the optimizer does not perform the expaneded view query once and simply manipulate this temporary table but expands the view two times and thus does the expensive aggregation two times.
EXPLAIN ANALYZE on the Query above gives
Nested Loop  (cost=173527.09..173543.19 rows=1 width=231) (actual time=2594.697..2594.852 rows=8 loops=1)
  ->  Merge Join  (cost=173518.21..173518.28 rows=1 width=617) (actual time=2594.580..2594.610 rows=8 loops=1)
        Merge Cond: ((scans_1.source)::text = (scans_3.source)::text)
        ->  Sort  (cost=86883.50..86883.50 rows=1 width=562) (actual time=1292.558..1292.561 rows=8 loops=1)
              Sort Key: scans_2.source
              Sort Method: quicksort  Memory: 31kB
              ->  Nested Loop  (cost=86643.23..86883.49 rows=1 width=562) (actual time=1292.406..1292.519 rows=8 loops=1)
                    ->  HashAggregate  (cost=86634.35..86634.45 rows=10 width=55) (actual time=1292.281..1292.285 rows=8 loops=1)
                          Group Key: scans_2.source
                          ->  Index Scan using scans_timestamp_index on scans scans_2  (cost=0.43..83024.66 rows=481292 width=47) (actual time=0.174..1036.297 rows=545244 loops=1)
                                Index Cond: ("timestamp" > (now() - '30 days'::interval))
                                Filter: (((value ->> 'Ok'::text) IS NOT NULL) AND ((value ->> 'NotOk'::text) IS NOT NULL) AND ((value ->> 'TotalCount'::text) IS NOT NULL))
                                Rows Removed by Filter: 98
                    ->  Bitmap Heap Scan on scans scans_1  (cost=8.88..24.88 rows=1 width=531) (actual time=0.025..0.026 rows=1 loops=8)
                          Recheck Cond: (("timestamp" = (min(scans_2."timestamp"))) OR ("timestamp" = (max(scans_2."timestamp"))))
                          Filter: (((scans_2.source)::text = (source)::text) AND (CASE WHEN ("timestamp" = (min(scans_2."timestamp"))) THEN 'MIN'::text ELSE 'MAX'::text END = 'MAX'::text))
                          Rows Removed by Filter: 1
                          Heap Blocks: exact=16
                          ->  BitmapOr  (cost=8.88..8.88 rows=4 width=0) (actual time=0.018..0.018 rows=0 loops=8)
                                ->  Bitmap Index Scan on asdf  (cost=0.00..4.44 rows=2 width=0) (actual time=0.010..0.010 rows=1 loops=8)
                                      Index Cond: ("timestamp" = (min(scans_2."timestamp")))
                                ->  Bitmap Index Scan on asdf  (cost=0.00..4.44 rows=2 width=0) (actual time=0.006..0.006 rows=1 loops=8)
                                      Index Cond: ("timestamp" = (max(scans_2."timestamp")))
        ->  Sort  (cost=86634.71..86634.74 rows=10 width=55) (actual time=1302.016..1302.016 rows=8 loops=1)
              Sort Key: scans_3.source
              Sort Method: quicksort  Memory: 26kB
              ->  HashAggregate  (cost=86634.35..86634.45 rows=10 width=55) (actual time=1301.967..1301.969 rows=8 loops=1)
                    Group Key: scans_3.source
                    ->  Index Scan using scans_timestamp_index on scans scans_3  (cost=0.43..83024.66 rows=481292 width=47) (actual time=0.080..1042.757 rows=545244 loops=1)
                          Index Cond: ("timestamp" > (now() - '30 days'::interval))
                          Filter: (((value ->> 'Ok'::text) IS NOT NULL) AND ((value ->> 'NotOk'::text) IS NOT NULL) AND ((value ->> 'TotalCount'::text) IS NOT NULL))
                          Rows Removed by Filter: 98
  ->  Bitmap Heap Scan on scans  (cost=8.88..24.88 rows=1 width=531) (actual time=0.023..0.024 rows=1 loops=8)
        Recheck Cond: (("timestamp" = (min(scans_3."timestamp"))) OR ("timestamp" = (max(scans_3."timestamp"))))
        Filter: (((scans_3.source)::text = (source)::text) AND (CASE WHEN ("timestamp" = (min(scans_3."timestamp"))) THEN 'MIN'::text ELSE 'MAX'::text END = 'MIN'::text))
        Rows Removed by Filter: 1
        Heap Blocks: exact=16
        ->  BitmapOr  (cost=8.88..8.88 rows=4 width=0) (actual time=0.016..0.016 rows=0 loops=8)
              ->  Bitmap Index Scan on asdf  (cost=0.00..4.44 rows=2 width=0) (actual time=0.009..0.009 rows=1 loops=8)
                    Index Cond: ("timestamp" = (min(scans_3."timestamp")))
              ->  Bitmap Index Scan on asdf  (cost=0.00..4.44 rows=2 width=0) (actual time=0.006..0.006 rows=1 loops=8)
                    Index Cond: ("timestamp" = (max(scans_3."timestamp")))
Planning time: 2.253 ms
Execution time: 2594.994 ms

Why is that so and are there ways to avoid this behavior?
All I want the optimizer to do is to evaluate the VIEW as temporary table and do the join in my second query on this temporary table.
I am using PostgreSQL 9.6.15.
Thanks already!

A: This is expected behaviour: the view source is simply substituted for its name by the query rewrite, then analysed and executed as usual.
To tell the query compiler that you want to process the view only once you'd use a common table expression (CTE):
WITH scans_minmax (source, "Ok", "NotOk", "TotalCount", "Aggregation") AS (
SELECT tmp.source,
       value ->> 'Ok',
       value ->> 'NotOk',
       value ->> 'TotalCount',
       (CASE WHEN scans.timestamp = tmp.min_t THEN 'MIN' ELSE 'MAX' END)
FROM (SELECT source, MIN(timestamp) AS min_t, MAX(timestamp) AS max_t
      FROM scans
      WHERE timestamp > NOW() - INTERVAL '30 days'
        AND value ->> 'Ok' IS NOT NULL
        AND value ->> 'NotOk' IS NOT NULL
        AND value ->> 'TotalCount' IS NOT NULL
      GROUP BY source) AS tmp,
     scans
WHERE scans.source = tmp.source
  AND (scans.timestamp = tmp.min_t OR scans.timestamp = tmp.max_t)
)
SELECT min_tbl.source,
       min_tbl."Ok" AS "min_ok", max_tbl."Ok" AS "max_ok",
       min_tbl."NotOk" AS "min_not_ok", max_tbl."NotOk" AS "max_not_ok",
       min_tbl."TotalCount" AS "min_total_count", max_tbl."TotalCount" AS "max_total_count"
FROM scans_minmax AS min_tbl JOIN
     scans_minmax AS max_tbl ON min_tbl.source = max_tbl.source
WHERE min_tbl."Aggregation" = 'MIN' AND max_tbl."Aggregation" = 'MAX'

Postgres will materialise results of the CTE (prior to Postgres 12 anyway), causing your aggregation to execute only once.
Note that in general you need to exercise caution when using CTEs:

*

*This will not necessarily make your overall query run faster, as CTE materialisation might require additional server resources -- probably not in your case though.

*CTE is an optimisation fence, meaning that predicates from the outer select will not be pushed down into the CTE, which in some cases will cause suboptimal execution plans -- again, not in your case.

A: Not sure whether it answers your question, but you don't need to reference scans_minmax twice to get the result you want:
SELECT source
     , case when "Aggregation" = 'MIN' then ok end as min_ok
     , ...
     , case when "Aggregation" = 'MAX' then ok end as max_ok
     , ...
FROM scans_minmax

Now you have a table with 8 columns, 3 in each row is null. You can now apply - say - MAX to    get rid of the nulls:
SELECT source, MAX(min_ok), ..., MAX(max_ok), ...
FROM (
     -- query above
) AS T
GROUP BY source


text:
Q: Generate Method with correct signature as expected from Functional interface in Eclipse I am using Java 8 functional interfaces a lot.
In particular, I have some methods that register functions with certain signatures. Its signature is as follows:
<A extends IA, D extends IB, B extends IB> void registerRConv(Class<A> tA, Class<D> tD, Class<B> tB,
        BiFunction<A, D, B> ad2b);

Sidenote: in case you're wondering, its a converter registry that registers, which types are converted to which, and a function which does the actual convertig
I use this method quite often, and everytime i find myself typing
registry.registerRConv(Common.Choice.class, Choice.class, Object.class, Converter::getChoice)

Where the given classes all exist, but the static method - Converter::getChoice in the example - does not yet exist.
Now, if i do this in IntelliJ IDE's, when i press alt+Enter I get an option to automatically create that method in the current class - with the expected signature.
Can I make Eclipse do this? and if so, how?

A: This is the kind of change that is provided by "quick fixes" invoked by pressing Ctrl+1.
Unfortunately, when the resolve error is reported against a method reference expression, the existing quick fix is not offered.
I filed https://bugs.eclipse.org/516504 to address this.
In the meanwhile, the workaround would be:

*

*Change the method reference to a lambda expression

*Invoke the quick fix to create the missing method

*Invoke the quick assist "Convert to method reference" (Ctrl+1 also here)


text:
Q: How to send Post Request from axios, can I right axios.post(url, { data : obj})

I attend a interview and interviewer  say question post from axios

A: const URL = "http://localhost:5500/register";

let data = {
 name: 'dalpat',
 email: 'test@gmail.com'
};

axios.post(URL, {
data: data;
})

// Routes
app.post("/register", (req, res){
  const {name, email} = req.body.data;
  res.send({name: name})
})


text:
Q: Как можно сократить метод public List<Integer> getIndexes(User[] users) {
    List<Integer> indexes = new ArrayList<>();

    for (User user : users) {
        indexes.add(user.getId());
    }

    return indexes;
}

можно-ли сократить этот метод в одну строчку? может нужно использовать класс Arrays, но я далёк от него.
Если ещё напишите как это сделать во freemarker, без использования доп метода java, буду весьма благодарен

A: public List<Integer> getIndexes(User[] users) {
    return Arrays.stream(users).map(User::getId).collect(Collectors.toList());
}


text: Q: What makes Reedy model categories useful? I have been reading up a bit on the Reedy model structure on the category of simplicial objects in a model category $\mathcal{C}$ in Goerss-Jardine. One thing I find a bit unclear is what the Reedy model structure is exactly good for and what can I prove with it. I would really like some concrete theorems in homotopy theory whose proofs rely on the Reedy model structure. If anyone could give provide some applications and references, it would be greatly appreciated.


text:
Q: Technicalities around the central limit theorem and estimates in statistics (noob question) Edit: I had misunderstood the jargon in statistics and that "estimate" in the singular is also used for multiple point estimates. As a noob I assumed plural "estimates" would be the term for that, and that "estimate" was a single point estimate.
In a statistics course I am taking, it was claimed that
"The Central Limit Theorem says that a reasonable estimate of a parameter has a normal distribution, with the average equal to the true parameter value".
To me, it seems like an estimate is a specific point on a probability distribution (with a normal distribution if it summed enough random variables), but I do not see that the estimate has a normal distribution (since it is the outcome of a probability distribution with a random variable, but not the distribution itself. ) The PMF on the other hand on which the estimate is a point (and could be calculated by convolving the PMF of the i.i.d. random variables), would have a mean equal to the true parameter value.
As an analogy, if I roll a dice and get a 5, I do not have a dice uniform distribution (as I did before I rolled the dice), I just have a 5.
Am I misunderstanding something, or was the claim on the course worded wrong and technically wrong?
Edit: I assume what I missed is "estimate" can be divided into "point estimate" and "interval estimate" and that the latter is a probability distribution (has a distribution and it can be normally distributed) whereas the former is just a point. And, my reasoning would be true for the former, but not for interval estimates.
Edit: ChatGTP mentioned that the claim was specifically talking point estimates. What I had misunderstood is simply the jargon and that "estimate" is used in the plural sense, for multiple point estimates, instead of using the word "estimates" for that. So the claim was about multiple point-estimates, and from that I can agree with it.


text:
Q: MC34063A: Why am I overclocking this chip? I've decided to get some experience with DC-DC converters and I've obtained an Onsemi MC34063A DC-DC converter. From documentation I've got the datasheet, the AN920 application note and the Excel worksheet. The datasheet mentions one more application note, the AN954/D, but I can't seem to find it anywhere.
The idea was to step-down 12 V to 5 V with currents of up to 500 mA and 50 mV ripple. So I read the formulas in the datasheet, the application note and the worksheet and did some calculations.
I took the \$V_{sat}=1.3 \mbox{ } V\$ , from the datasheet maximum value, I'm using 1N5817, so at 1 A, \$V_{F}=0.45\mbox{ } V\$, minimum input voltage, if I take the variation to be 10% is  \$V_{in(min)}=10.8 \mbox{ } V\$, output voltage \$V_{out}=5 \mbox{ } V\$. Using the formula from the datasheet, this gives me \$\frac{t_{on}}{t_{off}}=1.21\$. I've selected the frequency for the converter to be 89 kHz, because it's supposed to nicely fit a \$220 \mbox{ } pF \$ capacitor, but more on that later. Next, \$t_{on}+t_{off}=11.24 \mbox{ } \mu s\$ which gives me \$t_{off}= 5.09 \mbox{ } \mu s\$ and \$t_{on}=6.15 \mbox{ } \mu s\$. All this gives me \$C_t=246 \mbox{ } pF\$, so I'll use \$220 \mbox{ } pF + 22 \mbox{ } pF=242 \mbox{ } pF\$. Next, I've got the \$I_{pk(swich)}=1 \mbox{ } A\$. The sense resistor is \$R_{sc}=0.3 \mbox{ } \Omega\$, so I'll use 3 times 1 \$\Omega\$ resistor and connect them in parallel. Next is the minimum inductivity \$L_{(min)}=28 \mbox { } \mu H\$. Next, there's the output capacitor \$C_o=28.1 \mbox{ } \mu F\$. Finally there are the output resistors. The formula is \$V_{out}=1.25(\frac{R_2}{R_1}+1)\$. I picked 4 times \$10 \mbox{ } k \Omega\$ resistors. One for \$R_1\$ and 3 in series for \$R_2\$.
Now let's take a look at the application note and see if they did anything different there: Well the formula for the \$R_{sc}\$ is a bit different and gives me \$0.263 \mbox{ } \Omega\$ as the minimum sense resistor value.
Now let's see the Excel worksheet: New parameter \$ \frac { \Delta I_{L} } {I_{l(avg)} } \$ appears there and the worksheet says:

For Maximum Output Current it is suggested that ΔIL should be chosen
  to be less than 10% of the average inductor current, IL(avg). This
  will help prevent Ipk (sw) from reaching the current limit threshold
  set by RSC.  If the design goal is to use a minimum inductance value,
  let ΔIL = 2*IL(avg).  This will proportionally reduce output current
  capability.

Well, I'm not sure what to do here, but high current output sounds nice so I put it to 6% and the worksheet gives me the minimum inductance of \$ 920 \mbox{ } \mu H\$. It so happens that I have a 1 mH inductor in my junk-box (DPO-1.0-1000) so I decide to use it.
Finally, I have the schematic:

Now if I understand the operation of this device correctly, the timing capacitor is used to provide clock which is fed to the inductor as needed. If the sense resistor has too high voltage (meaning overcurrent condition) or the consumption is too low, clocks are skipped. As far as I can see, there should be no way for the chip itself to change the frequency set by the capacitor.
My problem seems to be the switching frequency and the way it changes with load. The regulator is in the documentation said to work up to 100 kHz and I'm seeing some strange results on the oscilloscope. I'm measuring the waveform on the diode and on the timing capacitor.
Here's how it looks like with no load:

As far as I know, this type of wave should appear because the regulator is skipping cycles and it should be normal.
Next, I have the load with some LEDs drawing around 200 mA.

Note that the frequency is a bit high. I expected 89 kHz and lower (since the circuit is on a breadboard and I expect there to be parasitic capacitance from neighboring rows), but it's 99.6 kHz, which is right on the limit of normal operation.

Here is what happens when I connect a microcontroller board flashing some LEDs. The frequency is more than twice the maximum operating frequency of the regulator.
Using a \$ 1 \mbox{ } \Omega\$ resistor and another power supply, I've determined that the highest instantaneous current from this board is 294 mA, so it's well within the limit of the 500 mA I designed this for. The output ripple is 680 mV peak to peak, so it seems to be more or less fine and the voltage is around 4.9 V, so it too seems to me more or less normal.
So any ideas what's going on with the frequency here? I've tried with various different timing capacitors and they all give similar behavior and none of them give me the calculated frequency.
UPDATE
Here's the oscillogram of the output using the springy type ground lead connector and bare probe tip synchronized with the peak of greatest magnitude :

UPDATE
About the frequency, I found some 10 Ω ceramic resistors and tried loading the supply with one of them (which should give me a 500 mA load), but I still get the high frequencies and it seems to be related somehow to current limiting, from what I can see. When I connect the resistor, the maximum current I can get is around 370 mA. I've experimented with different values of the sense resistors and with increased resistance of sense resistors, the frequency increases.
Here's an example of the \$C_t\$ waveform with 1 Ω resistor:

and here's with 0.5 Ω sense resistor:

A: The breadboard may be causing issues, check your layout (especially the feedback section)
Also, it's possible the inductor you are using is not suitable - it says it's only rated up to 100kHz, so it's SRF (self resonant frequency) is probably pretty low. It may be causing instability.
Try changing it to one with a higher SRF (e.g. >500kHz), but still with suitable current capability.
I did mention the output cap below but abdullah is right about the input cap being important. It does depend on the load, but the whole loop from in to out should be as small and low impedance as possible, ideally using a ground plane. On a breadboard that's "difficult" ;-)
If the frequency problem is not there with a steady load, I think as Kit says it's an output filtering issue, since the switcher won't be fast enough to adapt to high di/dt changes on the output and there's no "reserve". Increase the output filter capacitance and see if the ripple drops, if it does that's almost certainly the issue.
EDIT - Ah, I see you tried it with a resistor on the output.
In that case it would seem it's not the filtering. At this point I think I would use a different method of prototyping that's more suited to a switching regulator. Also use another chip just in case.
Either etch a board or use dead bug style, or stripboard with very careful attention to layout. If the frequency is still too high I would assume it's part of it's operation and not covered correctly in the datasheet - if this is the case then an e-mail to OnSemi is in order to see what they have to say.
EDIT 2 - Okay, after more reading I think the sense resistor (possibly combined with the inductor issue mentioned above) may be causing the current sense to trip too often and increase the timing capacitor charging slope. This will likely appear like the oscillator is switching faster.
A relevant quote from the App note:

When this voltage becomes greater than 330 mV, the current limit
  circuitry provides an additional current path to charge the timing
  capacitor CT. This causes it to rapidly reach the upper oscillator
  threshold, thereby shortening the time of output switch conduction and
  thus reducing the amount of energy stored in the inductor. This can be
  observed as an increase in the slope of the charging portion of the CT
  voltage waveform as shown in Figure 5.

Your oscillscope waveforms seem to agree with this description.
Also, if you haven't tried changing the inductor, do this and see how it goes, plus you could try not using the current sense (i.e. just connect to input voltage)

A: My best guess would be the amount of output filtering or possibly the sizing on the R_sc.
Note the comparator feeding back into the and gate which controls the switch in your schematic.  If the load current changes and it causes swings in the voltage feedback loop then you could create a virtual increase in the PWM frequency.  I don't quite have time to draw out a full graph for you, but basically if current increases in the load causes the switch to turn on (i.e. if you turn on a bunch of leds simultaneously), but then you quickly turn them back on, that will be superimposed on top of the 99.4kHz PWM and make the switching frequency look much higher.
The other thing you might try is making R_sc too big and see what the waveform looks like on a really consistent load.  Like you said, the pwm frequency shouldn't change, and the draw should cause the duty cycle to increase slowly because the difference between the output voltage and input voltage should approach 0 as you reach the maximum draw.  That way, all the energy is dissipated in the resistor, none in the switching converter at maximum draw.  I had a reason I thought this might be an issue, but I'll be honest I think it's the first thing.
Hope that helps! Good luck!

A: When dealing with switch-mode converters, you should pay attention to the high \$\dfrac{di}{dt}\$ paths of the circuit. To determine these problematic paths, one can use the diagram of the topology and draw the states of it. Let's take a look at the circuit diagram for the buck converter, in the different states the switch:

Red lines denote the high current flow. You can see that some parts remain RED in both positions of the switch and some parts change color. The ones that change color are the problematic paths, because the current flows through them change, when the switch changes position. That means they are high \$\dfrac{di}{dt}\$ parts of the circuit, and require care when designing the layout. Look at my this post on how inductance affects when there is high current change in time. So, what to do?

*

*Shorten and widen the trace, hence reduce the inductance. However, do not make it wider than it should be, otherwise you will create a bigger antenna for the EMI. Make it wide enough that it will carry the current needed.

*If these traces are connected to the GROUND net, then try to prevent them running on the ground plane or on the ground bus of a breadboard as much as possible. Only suiting path for this scenario, is the path from the anode of the diode to the ground lead of the input capacitor. Connect it directly and shortly.

Also, some of the things that you see in the scope are not really in the circuit itself. They are caused by the long ground lead of the scope probe. Shorten it, like so:

Resource: PCB Layout Guidelines from National Semiconductor

A: I am 7 years late, but I have to add my answer for others who come across this issue:
The very high ripple of 680mV (if you didn't mistype it) at the output seems to me like your Co (output capacitor) is either faulty or is not the low-ESR (equivalent series resistance) type.
 ESR is basically a "resistance" of capacitor seen at high frequencies. If your capacitor is rated for 85°C, it is very likely a high-ESR cap and not suitable for switching power supplies. Low-ESR caps are usually rated for at least 105°C, though the high-voltage ones (above 100V) usually remain at 85°C and seem to be fine considering the higher voltage:current ratios at higher voltages.
 I am surprised that nobody here has suggested or even mentioned that possibility.


text:
Q: Sliding tab with calendar in fragment I am having two sliding tabs working. Now I want Calendar in one of the tab but it is giving me error.
Error
12-16 09:58:54.437: E/AndroidRuntime(2495): FATAL EXCEPTION: main
12-16 09:58:54.437: E/AndroidRuntime(2495): Process: com.project.homepagedemo, PID: 2495
12-16 09:58:54.437: E/AndroidRuntime(2495): java.lang.NullPointerException
12-16 09:58:54.437: E/AndroidRuntime(2495):     at com.bharatwellness.mainactivities.DiaryTabOneCalorieConsumed.onCreateView(DiaryTabOneCalorieConsumed.java:66)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1504)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:942)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1121)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1484)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:482)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.view.View.measure(View.java:16497)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.view.View.measure(View.java:16497)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.view.View.measure(View.java:16497)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.view.View.measure(View.java:16497)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1912)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1109)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1291)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.view.Choreographer.doCallbacks(Choreographer.java:574)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.view.Choreographer.doFrame(Choreographer.java:544)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.os.Handler.handleCallback(Handler.java:733)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.os.Handler.dispatchMessage(Handler.java:95)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.os.Looper.loop(Looper.java:136)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at android.app.ActivityThread.main(ActivityThread.java:5001)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at java.lang.reflect.Method.invokeNative(Native Method)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at java.lang.reflect.Method.invoke(Method.java:515)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
12-16 09:58:54.437: E/AndroidRuntime(2495):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)

my oncreate method
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.tab_one_calorie_consumed, container, false);

        _calendar = Calendar.getInstance(Locale.getDefault());
        month = _calendar.get(Calendar.MONTH) + 1;
        year = _calendar.get(Calendar.YEAR);
        Log.d(tag, "Calendar Instance:= " + "Month: " + month + " " + "Year: "
                + year);

        selectedDayMonthYearButton = (Button) this.getView().findViewById(R.id.selectedDayMonthYear);
        selectedDayMonthYearButton.setText("Selected: ");

        prevMonth = (ImageView) this.getView().findViewById(R.id.prevMonth);
        prevMonth.setOnClickListener(this);

        currentMonth = (TextView) this.getView().findViewById(R.id.currentMonth);
        currentMonth.setText(DateFormat.format(dateTemplate,
                _calendar.getTime()));

        nextMonth = (ImageView) this.getView().findViewById(R.id.nextMonth);
        nextMonth.setOnClickListener(this);

        calendarView = (GridView) this.getView().findViewById(R.id.calendar);

        // Initialised
        adapter = new GridCellAdapter(getActivity().getApplicationContext(),
                R.id.calendar_day_gridcell, month, year);
        adapter.notifyDataSetChanged();
        calendarView.setAdapter(adapter);
        return rootView;
    }

I have check twice but nothing should be null. As it is working if i am using it directly as in main activity.

A: Change
  selectedDayMonthYearButton = (Button) this.getView().findViewById(R.id.selectedDayMonthYear);

to
  selectedDayMonthYearButton = (Button) rootView.findViewById(R.id.selectedDayMonthYear);

and do the same for all other Views.


text:
Q: Voip app using background task Now I am developing a voip app.
Is it okay to use background task to keep my app alive? so app can received incoming state to pop up a notification from the background.
I try CFStreamCreatePairWithSocket, but still can't get info from nsstream event callback.
If I use background task, App can get incoming state as it does in the front.
Thanks a lot.

A: Please always make sure to provide all required information to get quick help. e.g. Provide some code snippet if possible, provide information regarding which version of OS you are using etc.
Check following answer: It may help you. How to Maintain VOIP socket connection in background?


text:
Q: Is it possible to get Proxy setitings's Useranme and password from Mac system settings? I want my application to read the proxy settings information from the mac os settings,
i want to read the proxy server url and proxy username and password too...
Im able to read the proxy server url using scdyanmiccopyproxy() function, but
Is it possible to read the proxy username and password?

A: Yes. It's kept in the keychain. You can see that using Keychain Access.app, under the entry labeled by the proxy server URL. To obtain  it programmatically, you need to use the Keychain Service. There's a helpful Cocoa wrapper too, see EMKeychain.


text:
Q: Stuck in a loop using file management in C The program is:
Two files DATA1 and DATA2 contain sorted lists of integers/ Write a program to produce a third file DATA which holds a single sorted, merged list of these two lists. Use command line arguments to specify the file names.
#include<stdio.h>

//Two files DATA1 and DATA2 contain sorted lists of integers/ Write a program to produce a third file DATA which holds a single sorted, merged list of these two lists. Use command line arguments to specify the file names.

void sort(FILE*, FILE*, FILE*);

main()
{
    FILE *f1, *f2, *f;
    int i;

    f1=fopen("DATA1", "w");    //To set the sorted integers in file f1
    for(i=0;i<=10; i=i+2)
    putw(i, f1);
    fclose(f1);

    f2=fopen("DATA2", "w");    //To set the sorted integers in file f2
    for(i=1;i<=11; i=i+2)
        putw(i, f2);
    fclose(f2);

    printf("For first DATA:\n");    //To print the content of f1
    f1=fopen("DATA1", "r");
    while((i=getw(f1)) != EOF)
        printf("%d, ", i);
    fclose(f1);

    printf("\nFor second DATA:\n");    //To print the content of file f2
    f2=fopen("DATA2", "r");
    while((i=getw(f2)) != EOF)
        printf("%d, ", i);
    fclose(f2);

    sort(f1, f2, f);    //To sort the integers from f1 and f2 and merge the sorted into file f

    f=fopen("DATA", "r");    //To print the integers in file f
    while((i=getw(f)) != EOF)
        printf("%d, ", i);
    fclose(f);
}

void sort(FILE *d1, FILE *d2, FILE *d)
{
    int a, b;
    d1=fopen("DATA1", "r");
    d2=fopen("DATA2", "r");
    d=fopen("DATA", "w");
    a=getw(d1);
    b=getw(d2);
    for(;some condition;)
    {
        if(a>b)
        {
            int temp=a;
            a=b;
            b=temp;
            b=getw(d2);
            putw(a, d);
            b=getw(d2);
        }
        else
        {
            putw(a, d);
            a=getw(d1);
        }
    }
    fclose(d1);
    fclose(d2);
    fclose(d);
}

Now the program is compiled in gcc compiler by using the command "gcc file.c". After compiling when I run the program, it shows the content of file f1 but not the content of file f2. I seems as if it is stuck in a loop because Ctrl + D do not work. So I have to terminate the program.
The output is:

For first DATA:
  0, 2, 4, 6, 8, 10,
  For second DATA:
  ^Z
  [6]+  Stopped                 ./a.out

Now what is the problem here. I printed the integers of f2 in the same way I printed the integers of f1 but why is the problem only in file f2?

A: Your code should output:
For first DATA:
0, 2, 4, 6, 8, 10,
For second DATA:
1, 3, 5, 7, 9, 11,

which is what you need. I suspect the error happens shortly after, and the output buffer is just not flushed in time, thus the data are kept there, and not being displayed in standard output (your screen most likely).
Change your code to:
printf("\nFor second DATA:\n");    //To print the content of file f2
f2=fopen("DATA2", "r");
while((i=getw(f2)) != EOF)
    printf("%d, ", i);
fclose(f2);

printf ("\n");
fflush(stdout);

sort(f1, f2, f);

to see what I mean. The newline flushes the output buffer itself, so you can use either approaches.


text:
Q: Visualizing Ricci scalar curvature I am trying to learn more about Ricci scalar curvature. I am trying to get an image in my head of what scalar curvature actually represents about the curvature of a manifold. The most familiar image I have of a scalar giving me information about a space is a scalar field, like temperature. Is that the right way to think about scalar curvature? If not, how should one envision scalar curvature?
According to Wikipedia here, scalar curvature can be characterized as a multiple of the average sectional curvatures at a point.

A: For 2D manifolds the scalar curvature is the Gauss curvature. Positive means the manifold closes in on itself, negative means it spreads out like a saddle.
Some of this parallel remains in higher dimensions, since the sign of curvature determines the asymptotic volume comparison for geodesic balls (positive curvature $\implies$ less-than -Euclidean volume, negative $\implies$ greater than Euclidean). However this is on small scale only, and therein lies a problem: the scalar curvature does not deliver much global geometric information.
Indeed, the asymptotic volume definition implies that scalar curvature is additive under products. Thus, by taking product with a sufficiently scaled-down compact surface of constant negative  curvature (think of a tiny double torus), we can make scalar curvature negative, as long as it was bounded to begin with.  And by taking product with a tiny sphere, the scalar curvature can be made positive.
These examples explain why there isn't a picture of what a manifold of positive/negative scalar curvature looks like: it can look like pretty much anything. (There are some obstructions to manifolds admitting positive scalar curvature, but they are not  easy to visualize.)


text:
Q: What is better for sharing props between sibling functional components in React, Context or Redux? I have a situation where one component change is supposed to update other sibling components under same parent. Should I use context or Redux for this?
Or is it okay pass props around via callback function to parent and then to children?

A: Redux is likely overkill if you only have a small hierarchy of a few components.  Use React context to avoid prop drilling where you pass the same props through multiple layers. If you only have one layer, it's fine to use callbacks to pass to children.
If you need global access to this state use Redux (or similar). If you need more localized access to the state use React context.
To answer your question, since they have the same parent it's better to pass callbacks to the children.

A: So here's my take on this situation. Both Redux and Context help with state management and propagation across components. So here's the deal

*

*Use Redux, if you want the data to be used outside the parent component. For instance, you want the state to be available across your whole application (Global Data or data that is required in 2 or more unrelated components).

*Use Context, if only the children of the current component require the data. Not the siblings, not other components in the application - ONLY CHILDREN.

*Use props to pass it down to children, only if your component tree is 1 or 2 levels deep. If it is more, use Context


text:
Q: Inserting AngularJS values into HTML table is not working I am sending JSON to AngularJS through Node. I receive the correct data successfully in the controller which I print to the console. But when I try to fill the HTML table with the controller it doesn't work. I noticed that if I use the same fields but with "tasks" instead of "task" it will fill the "status" field into the table since the "tasks" object has a "status" field so the scope is technically working but I have no luck using "task" fields.
Controller
projectApp_TaskList.controller('getTaskListController', function ($scope, $http) {

    $http.get('/getTaskList')
        .then(function (data) {
            $scope.tasks = data;
            console.log($scope.tasks);
        });
});

Table

                    Priotity
                    Status
                    Title
                    Limit Date

                    {{task.priority}}
                    {{task.status}}
                    {{task.title}}
                    {{task.limitDate}}

Here's the link to the data I get on the console.

A: The object returned to $http.get().then is a response object that has multiple properties
The data you want is in a property data of that object
Try
$http.get('/getTaskList')
    .then(function (response) {
        $scope.tasks = response.data;
        console.log($scope.tasks);
    })


text:
Q: Não consigo fazer o scanf funcionar Eu tô tentando aprender C e hoje fiz um programa bem simples que solicita dados pessoais básicos e depois ele precisa imprimir esses dados na tela.
Coloquei 5 itens a serem solicitados e ele só solicita a metade deles e a outra metade aparece diretamente na tela, sem solicitar nada. Como se a metade fosse só um printf, sabe? Não roda a parte scanf.
Eu já olhei o código todo e não estou conseguindo achar o erro.
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

void main () {

    setlocale(LC_ALL, "portuguese");

    char nome;
    float media;
    int tel, id, mes;

    printf("Digite a primeira letra do seu nome: ");
    scanf("%c", &nome);

    printf("Digite seu telefone: ");
    scanf("%i", &tel);

    printf("Digite sua média: ");
    scanf("%2.2f", &media);

    printf("Digite o mês do seu nascimento: ");
    scanf("%i", &mes);

    printf("Digite sua idade: ");
    scanf("%i", &id);
}

A: Não é possivel usar %2.2f no scanf, só nos prints para exibir.
#include <stdio.h>
#include <stdlib.h>
int main(){

    char nome;
    float media;
    int tel, id, mes;

    printf("Digite a primeira letra do seu nome: ");
    scanf("%c", &nome);

    printf("Digite seu telefone: ");
    scanf("%i", &tel);

    printf("Digite sua média: ");
    scanf("%f", &media);

    printf("Digite o mês do seu nascimento: ");
    scanf("%i", &mes);

    printf("Digite sua idade: ");
    scanf("%i", &id);
}