text:
Q: Error: The getter 'title' isn't defined for the type 'RSSParser' I wanted to implements a simple tutorial of how parsing an Rss Feed with Flutter, here is my code:
import 'package:flutter/material.dart';
import 'package:webfeed/webfeed.dart';
import 'package:http/http.dart' as http;
import 'package:url_launcher/url_launcher.dart';
import 'package:cached_network_image/cached_network_image.dart';

 class RSSParser extends StatefulWidget {
  @override
    _RSSParserState createState() => _RSSParserState();
 }

 class _RSSParserState extends State<RSSParser> {
  final String url = "https://www.90min.com/posts.rss";
  RssFeed _feed;
  String _title;
  static const String loadingFeedMsg = 'Loading Feed...';
  static const String feedLoadErrorMsg = 'Error Loading Feed.';
  static const String feedOpenErrorMsg = 'Error Opening Feed.';

   Future<RssFeed> loadFeed() async{
    try{
    final client = http.Client();
    final response = await client.get(url);
     return RssFeed.parse(response.body);

  }
    catch(e){

   }
   return null;

 }

updateTitle(title){
  setState(() {
  _title = title;
});
}

@override
void initState() {
// TODO: implement initState
super.initState();
updateTitle(widget.title);
}

updateFeed(feed){
 setState(() {
  _feed = feed;
 });
}

@override
 Widget build(BuildContext context) {
 return Scaffold(
  appBar: AppBar(
    title: Text(_title),
  ),
 );
 }
}

The problem is that i got a compilation error in that instruction
 updateTitle(widget.title);

with the following error message:

The getter 'title' isn't defined for the type 'RSSParser'

In the tutorial, it works fine!!
Do you have an idea how to solve this?
Thank you

A: You haven't declared title for you RSS widget. It should look something like ths:
 class RSSParser extends StatefulWidget {
final String title;
const RSSParser({required this.title});

This should solve your error.

A: This is not working because there is not title in RSS class.
I think you are not clear with use of widget.something. It means that in the class which extends StatefulWidget there is a something parameter which i need to get in stateObject.
See the code to understand.
class YellowBird extends StatefulWidget {
  const YellowBird({ Key? key }) : super(key: key);
  String someData = 'SomeData'; // Some data

  @override
  _YellowBirdState createState() => _YellowBirdState();
}

//This is the state object
class _YellowBirdState extends State<YellowBird> {

 // Now that if you need some data from the above class. You use use this widget.someData to get it here
  String getHere = widget.someData ;
  @override
  Widget build(BuildContext context) {
    return Container(color: const Color(0xFFFFE306));
  }
}


text:
Q: Windows 8 not booting at all I am using a Lenovo ThinkPad Twist with Windows 8, and it isn't booting at all. It doesn't even show the Lenovo logo or anything. It makes no sound, nothing. It used to work. It stopped working after Action Center said to reboot because of a drive error. I rebooted the computer, but then my friend decided to randomly start typing on the keyboard and managed to cancel the shutdown. After that, it wouldn't log in so I held down the power button to force a shutdown. Now, it doesn't boot

A: This sometimes works with PC's and some laptops (don't know about ultrabooks without the ability to remove the batter).
Hold the power button in for about 30 seconds. Release the button, take a deep breath, and try the power again.
Good Luck!

A: Ok, finally got it fixed (I had a warranty), and they didn't tell me what the problem was exactly, but here's what I figured out: Lenovo Thinkpad Twists (and some other lenovo computers) come with a "Settings" application, and one of the things it lets you change is that "battery life saver" where it only charges the battery to 50%, and then holds it there to extend the batteries longevity. Well, the software f-ed up, and it completely stopped charging, even though it should have been holding it at 50%, so it ran down to almost 0%, and it didn't have enough power to boot again after shutting it down (and because it was plugged in, windows gave me no warnings beforehand because it assumes everything is ok with the battery if it's plugged in). Somehow, it booted up again after a few days, and I got rid of the software.

redpajama_set_name: RedPajamaStackExchange


text:
Q: accepting only Request from specific server to my asp.net pages Hello guys i have server "A" where i would like to put a link to an application to server "B". Server "A" is a unix machine running java and redhat linux. when user come to server "A" they must first authenticate so that they can get to see the application in server "A". What i like to do now is leverage server "A"'s authentication and basically allow the user to see the page rendered page on server "B" if and only if he has be authenticated on server A.(server "A" sets a cookie i believe) I would want to make the page on server B check wheter the user is authenticated and its coming from server "A". If it is then render the page if its not then redirect the user back to server A to authenticate.
Server "B" its a windows machine running windows server 8 64bit.
Can someone point me in the right direction This seems possible however im not sure how to accomplish.
Thanks in advance.

A: The answer to this its not possible there are few script out there  that go like this
public string GetIPAddress()
  {
     string strHostName = System.Net.Dns.GetHostName();
     IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
     IPAddress ipAddress = ipHostInfo.AddressList[0];

     return ipAddress.ToString();
  }

This returns the ip address of the server your are on but not the server that it actually making a post or a get request to this server.
The closest thing that you could get is  the best source that i have been able to find is this,
Request.ServerVariables["HTTP_REFERER"];

This gives me the hostname of the server making a call.


text:
Q: Gorm freeze while connect to mysql on AWS (no errors) this code stacks on aws,  but locally works fine, no errors
func Connect() {

dsn := fmt.Sprintf(
    "%s:%s@tcp(%s:3306)/%s?charset=utf8&parseTime=True&loc=Local",
    os.Getenv("DB_USER"),
    os.Getenv("DB_PASSWORD"),
    os.Getenv("DB_HOST"),
    os.Getenv("DB_NAME"),
)
log.Println("db 1")
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
log.Println("db 2")
if err != nil {
    fmt.Println(err.Error())
    panic("CAN NOT CONNECT TO DB")
}

}
db -1 appears in logs
db -2 absent
and after some time  aws kills container


text:
Q: Not able to uninstall Managed Package because of community I have a managed package (Chargent Anywhere) which consist a lightning component named "Chargent_Payment_Central".
I have a community in my org and that community is not using "Chargent_Payment_Central" component in any page but yes it is being shown on the custom component list.
So while I am trying to uninstall "Chargent Anywhere" it gives any error because of community.
I am not able to figure out how to uninstall the package. (Tried to uninstall after deactivating the community but that didn't work and I can not delete the community).
Please help.
Thanks in advance.

A: I had the same issue in my previous project, so I removed the reference forceCommunity:availableForAllPageTypes from my component.  After that, it will not show on the custom lightning component. Finally, you can uninstall your package.


text:
Q: sitemap.xml URL is not getting redirected to new URL I have a sitemap.xml file generated in magento2 on localhost. Following is the link http://magento.local/sitemap.xml
Now i want to redirect above URL to http://magento.local/pub/sitemap.xml using URL rewrite. I have created URL Rewrite as
shown in this image
But http://magento.local/sitemap.xml URL is not getting redirected http://magento.local/pub/sitemap.xml. But if I delete original sitemap.xml file it gets redirected to new URL. Is there any way I can redirect it without deleting existing sitemap.xml?
Another option
I added the following rule to .htaccess file and it works fine on local, but on server it fails. URL is not getting redirected
<IfModule mod_alias.c>
Redirect 301 /sitemap.xml  http://magento.local/pub/sitemap.xml
</IfModule>

A: According to URL Rewrites

The URL Rewrite tool lets you change any URL that is associated with a
product, category, or CMS page.

I believe your sitemap.xml is a physical file which is locate on the disk, then it won't work with Url Rewrite. When you delete the original file, server will try to consider the URL as a page. You can do the redirection using nginx rewrite rule, refer here

A: In your htaccess file you need to paste this code. It works for me.
RewriteCond %{HTTP_HOST} ^http://magento.local$

RewriteRule ^sitemap.xml http://magento.local/pub/sitemap.xml


text:
Q: vue-chartjs and custom legend using generateLegend() The generateLegend() wrapper does call the legendCallback defined in my Vue code but I'm lost to how to render the custom HTML in vue-chartjs. What do I do with htmlLegend as described in the vue-chartjs api docs like here.
Here is the line chart component I'm trying to render with a custom HTML object.
import { Line, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins

export default {
  extends: Line,
  mixins: [reactiveProp],
  props: ['chartData','options'],
  data: () => ({
    htmlLegend: null
  }),
  mounted () {
    this.renderChart(this.chartData, this.options);
    this.htmlLegend = this.generateLegend();
  }
}

Here is my vue template
<template>

                <line-chart :chart-data="datacollection" :options="chartOptions"></line-chart>

</template>

A: Well, htmlLegend holds the markup of the generated legend... so you can just put it into your tag via v-html
<template>

    <line-chart :chart-data="datacollection" :options="chartOptions"></line-chart>

</template>

A: mounted() {
    this.renderChart( this.chartData , this.options );
    var legend = this.generateLegend();
    this.$emit('sendLegend', legend)
}

and then in the vue file add a new div to show the legend and also listen to the event to get the legend data

<line-chart @sendLegend="setLegend" :chart-data="datacollection" :options="chartOptions"></line-chart>

and also add this to the data
   chartLegend: null,

and you also need a method
    setLegend (html) {
        this.chartLegend = html
    },


text:
Q: Maintaining print CSS stylesheet files How do you usually handle changes to screen and print CSS files? I typically have one screen CSS and one print CSS file and for the most part the I would copy the contents of screen CSS to print CSS file and then modify some properties, classes or ids, maybe set some display:none to certain classes etc.
The problem is, while working on a site or web app I make numerous changes to screen CSS and usually forget about print CSS then I have to sync them from time to time and I just don't think that the most optimal way.

A: For print stylesheets I tend to also apply the media="screen" stylesheet to the media="print" as well as a second stylesheet that appears later, which essentially, just removes the elements I don't want to print.
It's a fairly simplistic approach, though, and only works to any potential if it's regularly reviewed, so I couple it with a policy of always revising (or, at least, checking) it when I revise the screen-stylesheet.


text:
Q: Error while starting Bro I am trying to install Bro on my machine running Ubuntu 16.04 and I am facing the following problem on bro start. It has multiple errors and kindly assist on how to resolve them.
[BroControl] > start
starting bro (was crashed) ...
bro terminated immediately after starting; check output with "diag"
[BroControl] > diag
[bro]

Bro 2.4.1
Linux 4.4.0-36-generic

==== No reporter.log

==== stderr.log
    fatal error: problem with interface eth0 (eth0: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed: No such device)

==== stdout.log
max memory size         (kbytes, -m) unlimited
data seg size           (kbytes, -d) unlimited
virtual memory          (kbytes, -v) unlimited
core file size          (blocks, -c) unlimited

==== .cmdline
-i eth0 -U .status -p broctl -p broctl-live -p standalone -p local -p bro local.bro broctl broctl/standalone broctl/auto

==== .env_vars
PATH=/usr/bin:/usr/share/broctl/scripts:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
BROPATH=/var/spool/bro/installed-scripts-do-not-touch/site::/var/spool/bro/installed-scripts-do-not-touch/auto:/usr/share/bro:/usr/share/bro/policy:/usr/share/bro/site
CLUSTER_NODE=

==== .status
TERMINATED [atexit]

==== No prof.log

==== No packet_filter.log

==== No loaded_scripts.log

My ifconfig shows up this :
root@anuvrattiku-Inspiron-13-7368:/etc# ifconfig -a
lo        Link encap:Local Loopback
      inet addr:127.0.0.1  Mask:255.0.0.0
      inet6 addr: ::1/128 Scope:Host
      UP LOOPBACK RUNNING  MTU:65536  Metric:1
      RX packets:6594 errors:0 dropped:0 overruns:0 frame:0
      TX packets:6594 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1
      RX bytes:950826 (950.8 KB)  TX bytes:950826 (950.8 KB)

wlp1s0    Link encap:Ethernet  HWaddr 68:07:15:23:f2:f8
      inet addr:10.250.39.91  Bcast:10.250.255.255  Mask:255.255.0.0
      inet6 addr: fe80::274a:2cde:a0c8:1131/64 Scope:Link
      UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
      RX packets:271804 errors:0 dropped:0 overruns:0 frame:0
      TX packets:49076 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:342567344 (342.5 MB)  TX bytes:6733501 (6.7 MB)

Any help would be appreciated.

A: you're gonna need to check the bro config files mainly "/usr/local/bro/etc/node.cfg" and modify the hostname and the interface variables
based on the diag results it's showing "==== .cmdline
-i eth0 -U .status -p broctl " which means it's using the default configs.
thus. all what you need to make it work is just to change the interface to wlp1s0
be aware that's you're gonna need to make more configurations to start using it.

A: run sudo nano /usr/local/bro/etc/networks.cfg
on your interface change it from eth0 to wlp1s0


text:
Q: How to create thread specific memory appender in NLog I am pasting my code snippet using log4Net,
-Just in brief:
I am creating a new rolling appender and a memory appender and attaching them to a logger in logger repository for every new thread.
Whatever I write in rolling appender, automatically got in memory appender of specific thread.
I want to achieve same using NLog
I tried NLog but I got two behaviour

*

*all file targets writing into same memory target, not thread specific target.

*After setting new appender everything is getting written in new appender.
class Program {
private static Random rnd = new Random();
private static object sync = new object();

static void Main(string[] args)
{
    List<Task> tasks = new List<Task>();
    // Execute the task 10 times.
    for (int ctr = 1; ctr <= 5; ctr++)
    {
        tasks.Add(Task.Factory.StartNew(FirstWorldTask));
        Thread.Sleep(10);
    }
    Task.WaitAll(tasks.ToArray());
}

private static void FirstWorldTask()
{
    string loggerName = "Logger";
    string randomName = rnd.Next().ToString();

    lock (sync)
    {
        loggerName += randomName;
        Console.WriteLine(loggerName);
    }

    log4net.Layout.PatternLayout patternLayout = new log4net.Layout.PatternLayout("%message%newline");
    patternLayout.ActivateOptions();

    RollingFileAppender rollingFileAppender = new RollingFileAppender();
    rollingFileAppender.AppendToFile = false;
    rollingFileAppender.RollingStyle = RollingFileAppender.RollingMode.Size;
    rollingFileAppender.MaxSizeRollBackups = 0;
    rollingFileAppender.MaximumFileSize = "20MB";
    rollingFileAppender.Layout = patternLayout;
    rollingFileAppender.File = "./" + randomName + "/logfile.txt";
    //appender.File = GlobalSettings.FOLDER_NAME + "logfile" + currentCount.ToString() + ".txt";
    rollingFileAppender.ActivateOptions();

    MemoryAppender memoryAppender = new MemoryAppender();
    memoryAppender.AddFilter(new log4net.Filter.LevelRangeFilter() { LevelMin = log4net.Core.Level.Info, LevelMax = log4net.Core.Level.Fatal });

    log4net.Repository.Hierarchy.Hierarchy hierarchy = (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository();
    log4net.Repository.Hierarchy.Logger logger = hierarchy.GetLogger(loggerName) as log4net.Repository.Hierarchy.Logger;

    logger.AddAppender(rollingFileAppender);
    logger.AddAppender(memoryAppender);
    hierarchy.Configured = true;

    var m_log = log4net.LogManager.GetLogger(loggerName);

    for (int i = 0; i < 5; i++)
    {
        m_log.Info(i + " " + randomName);
        Thread.Sleep(10);
    }

    StringBuilder stringBuilder = new StringBuilder();
    foreach (var loggingEvent in memoryAppender.GetEvents())
    {
        stringBuilder.AppendLine(loggingEvent.MessageObject.ToString());
    }

    memoryAppender.Clear();
    Console.WriteLine(stringBuilder.ToString());
}

}
NLog Config:
    <target name="LogFile"
            xsi:type="File"
            fileName="${mdc:item=LogsDirectory}/logfile.txt"
            layout="${message}"
            maxArchiveFiles="10"
            archiveAboveSize="20000000"
            archiveNumbering="Sequence"
            archiveFileName="${mdc:item=LogsDirectory}/logfile.{#}.txt"/>
    <target name="Memory" xsi:type="Memory" layout="${message}"/>

  <rules>
    <logger name="LogFile" minlevel="Debug" writeTo="LogFile" />
    <logger name="LogFile" minlevel="Info" writeTo="Memory" />
</rules>

NLog Code for FirstWorldTask
    private static void FirstWorldTask()
    {
        var folderName = rnd.Next();
        NLog.MappedDiagnosticsContext.Set("LogsDirectory", folderName);
        ILog logger = LogManager.GetLogger("LogFile");
        var memoryTarget = (MemoryTarget)NLog.LogManager.Configuration.FindTargetByName("Memory");
        memoryTarget.Logs.Clear();
        for (int i = 0; i < 5; i++)
        {
            logger.Info(i + " " + folderName);
            Thread.Sleep(10);
        }
        int j = 0;

        while (j < memoryTarget.Logs.Count)
        {
            Console.WriteLine(memoryTarget.Logs[j] + "\t" + folderName);
            memoryTarget.Logs.RemoveAt(j);

            j++;
        }
    }


text:
Q: Installing Exchange 2010 Error with Ipv6 disabled/enabled I've tried installing Exchange 2010 on Windows 2k8 R2. Following error occurred when installing Hub Transport Role.

Hub Transport Role Failed
  Error: The following error was generated when "$error.Clear(); install-ExsetdataAtom -AtomName SharedMachineSettings -DomainController $RoleDomainController" was run: "An error occurred with error code '2147950640' and message 'There is no such object on the server.'.".
  An error occurred with error code '2147950640' and message 'There is no such object on the server.'

I have tried installation with both IPV6 turned on and off. Both failed and both required me to do some magic to uninstall Exchange, and try installation again.
Feel free to shoot your ideas what can be done to resolve the error. In the end I will install HyperV and put Exchange 2010 on different server but that's not what the server owner wanted.

A: Did you update the Active Directory schema for Exchange 2010 as per this Microsoft Exchange 2010 forum link with a similar problem?
See Exchange Server 2010 Planning and Deployment - Prepare Active Directory and Domains for more info on the steps.

A: For future reference as Sim suggested:
It should be noted that GUI when you install Exchange 2010 teoretically executes setup /prepareAD for you but for me it never worked good and it crippled my installation so i had to use manual installation steps to remove Exchange 2010.
The best approach for installing Exchange to not have to deal with those errors is to prepare AD as per Sim suggestion and link. But to outline all steps I did that helped me here they are:

*

*setup /pl (even thou it's not necessary)

*setup /ps

*setup /prepareAD /OrganizationName:"First Organization"

*setup /prepareDomain (also not necessary)

and run installation again and ... all roles installed successfully.
So actually the GUI part of installation which is supposed to prepareAD is crippling installation and not always doing what it's supposed. Thanks Sim!
Hopes this little thread will help people solve problems with Exchange 2010 installation.


text:
Q: Range slider - avoid moving forward when reaching a value specified in another element lets say i have a range slider going from value 1 to 100
by default i would be able to slide it going from 1 to 100.
I would like the slider to block, when reaching a value specified in another element.
I've been trying it like this (where 20 would be the value in the element, just easier for the example), but that isn't perfect. the Thumb does indeed stop, but i think internally if you keep sliding, it will remember that value, even if you don't see it.
EDIT:
would a for loop be something good here?
for(i=slider.value;i<20;i++)
...

if (slider.value >=20)
slider.value=20

Anyone better at this who can help?

A: Wrap everything in a <form> if you haven't already then assuming your limit is set by another <input>, assign an event handler to the <form> so it will trigger whenever there's an "input" event. Have the event handler change the [max] attribute value of the range input to the [value] of the limit <input>.

const limit = e => {
  const io = e.currentTarget.elements;
  let max = io.limit.value;
  io.range.max = max;
  io.view.value = io.range.value;
};

const ui = document.forms.ui;
ui.oninput = limit;
input {
  display: inline-block;
  width: 5ch;
  text-align: right;
}

#range {
  width: 20ch
}
<form id='ui'>
  <input id='limit' type='number' max='100' value='100'>
  <output id='view'>0</output><br>
  <input id='range' type='range' min='0' max='100' value='0'>
</form>


text:
Q: Dehn surgery for non-compact manifolds Lickorish theorem states that every closes, orientable, compact 3-manifold can be obtained by surgery on $S^3$. What do we know about surgery for non-compact manifolds? I.e. can we obtain $\mathbb{R}^2 \times S^1$ from surgery on $S^3$, $\mathbb{R}^3$, or at least from surgery on some non-compact manifold?

A: I'll turn my comments into an answer, since your comment indicates that this is what you want to know.
Surgery preserves compactness, so no, there is no surgery on $S^3$ that produces $\mathbb R^2 \times S^1$.
To prove this, start with a compact manifold $M$ and an embedded solid torus $T \subset M$. Step 1 of surgery is to remove the interior of $T$, so $M - \text{int}(T)$ is a closed subset of $M$, hence compact. Step 2 of surgery is to glue in a different solid torus $T'$, using some homeomorphism
$$f : \partial T \to \partial(M - \text{int}(T) = \partial T
$$
The resulting surgered manifold is thus the quotient of the disjoint union of $M - \text{int}(T)$ and $T'$ by the relation $x \sim f(x)$, $x \in \partial T$. Since the two pieces of that disjoint union are compact, their union is also compact, and its quotient is compact.


text:
Q: Apply two greps and awk to same input I'm using two short UNIX commands in my python script to get some data about nearby wireless access points.

*

*n°1, gets the ESSID of the access point :

"iwlist NIC scan | grep ESSID | awk '{print $1}'"

*

*n°2, gets the signal strength of the access point :

"iwlist NIC scan | grep level | awk '{print $3}'"
My problem is that I use these two commands one after the other which means that it doesn't generate "symmetric" data. You might get 6 ESSIDs and 4 Signal strength data.
Because the first time, the script found 6 APs (A, B, C, D, E and F) and the next time only 4 APs (A, C, E and F).
Some my question is the following :

*

*Is there a way to "split" the result of the first iwlist NIC scan and then apply two different grep and awk sequences to the same input ?

Just so that you at least get a symmetric list of results.
Thank you in advance !

A: In general, you can accomplish this type of routing using tee and process substitution:
iwlist NIC scan | tee >( grep -i ESSID | awk '{print $1}' ) | grep -i level | awk '{print $3}'

but this is inferior in this situation for several reasons:

*

*grep is superfluous, since awk can do the filtering itself

*The two branches are similar enough to fold into a single awk command, as Jonathan Leffler points out.

*The two output streams are merged together in a nondeterministic manner, so it may be difficult or impossible to determine which level corresponds to which ESSID. Storing the output of each branch in a file and later matching them line by line helps, but then this is not much better than asgs's solution.

But the technique of passing one command's output to two different pipelines without an explicit temporary file may be useful elsewhere; consider this answer just a demonstration.

A: What about using awk as grep:
iwlist NIC scan | awk '/ESSID/ {print $1} /level/ {print $3}'

This gives you the ESSID and level lines all at once.  You'd probably want to be a little more sophisticated and at least tag the lines with what it represents; the options are legion.  It isn't clear from your code how you're going to use the output, so I'm not going to try and second-guess how best to present it (but I would expect that network ID and level on the same line would be a nice output — and it is doable).

A: #!/bin/bash
iwlist <NIC> scan > tmpfile
grep -i ESSID tmpfile | awk '{print $1}'
grep -i level tmpfile | awk '{print $3}'
rm tmpfile

A script something like this might just do what you're expecting.


text:
Q: Fread returns wrong value when reading unsigned int with large values When I read an unsigned int from a binary file, it only reads the correct value if the value in the file is fairly low - when I try to read a value over 150,000 it gives me something like 9000... It's weird. Smaller numbers work perfectly however, like 50,000...
unsigned int value;

file = fopen(filePath, "rb");
fseek(file, 0, 0);
fread(&value, sizeof(unsigned int), 1, file);

printf("Value from file: %i\n", value);

The binary file was created on the same computer & operating system that the program runs on... what am I missing? The binary files are created properly and most of them do return the correct value & work fine, only the ones with large numbers don't...

A: You got the right value but used the wrong format string to print it, yielding undefined behavior. %i is for signed integers. You need %u.
The above is definitely a bug, but if it's not the source of the problem at hand, it's also possible that you're using a legacy compiler on Windows and the writing code is failing to open the file in binary mode. In that case, the value may get corrupted if one of the bytes happens to be 0x0a, in which case the value read back would be wrong.


text:
Q: Equiv Relation of Orbits - Group Action Let $G$ be a group that acts on $X$. I want to show that the orbits of $G$ partition $X$. I am given the relation $x\sim y \iff x\in Orb(y)$. Now:
$x\sim y\iff x\in Orb(y) \iff x=gy$ for some $g\in G \iff g^{-1}x=y$ for some $g\in G$ $\iff y\in Orb(x) \iff Orb(x)=Orb(y)$.
So I use this to show the three conditions of an equivalence relation:
$x\sim x \iff Orb(x)=Orb(x)$
$x\sim y \iff Orb(x)=Orb(y) \iff Orb(y)=Orb(x) \iff y\sim x$
$x\sim y, y\sim z \Rightarrow Orb(x)=Orb(y)=Orb(z) \Rightarrow Orb(x)=Orb(z)\Rightarrow x\sim z$
Does this look okay?


text:
Q: Scala - meaning of "companion contains its own main method, which means no static forwarder can be generated" Given the following class and its companion object:
class B extends A

object B extends B

Where A is an abstract class in another file:
abstract class A {
    def main(args: Array[String]): Unit = println("hey")
}

The above code is packaged into an uber-jar using the sbt assembly plugin, where the entry point is object B main method inherited from class B.
The above works fine. It runs. No problem at all.
Hoewver, sbt keeps warning:
[warn] B has the main method with parameter type Array[String], but B will not be a runnable program.
[warn]   Reason: companion contains its own main method, which means no static forwarder can be generated.
[warn] object B extends B

*

*Do you know the meaning of this warning?

*And why sbt assurance that object B won't run, doesn't happen?

Thank you.

A: For a class to be runnable in java, main needs to be static. Yours isn't, so, the object isn't runnable. That's what compiler is telling you.
Just rename main in A to something else, and then add a main in the object, that calls it.

A: It does not run for me.
I have this file B.scala.
package foo.bar

abstract class A {
    def main(args: Array[String]): Unit = println("hey")
}

class B extends A

object B extends B

When I try to run foo.bar.B I get an error:
sbt> runMain foo.bar.B
[info] running foo.bar.B
[error] (run-main-0) java.lang.NoSuchMethodException: foo.bar.B.main is not static

And the reason is exactly as the warning says. Class B contains a non-static main method which it inherited from class A. You can't have 2 methods with exactly the same name and type signature in one class, even if one is static and another in non-static. This means that the compiler cannot generate a static main method in class B that forwards to the non-static main method in object B.
Why it does run correctly for you I don't know.
It's not so hard to avoid this problem. Just don't use the companion object as an entrypoint. I.e. rename either class B or object B.
package foo.bar

abstract class A {
    def main(args: Array[String]): Unit = println("hey")
}

class BClass extends A

object B extends BClass


text:
Q: Trouble pinch zooming core plot graph in iOS I have created a graph with Core Plot and am trying to use the pinch zoom feature.  I want the pinch to work in just the x axis or just the y axis.  I have accomplished this by using the following code in a pinch gesture recognizer that I put in.
- (void)handlePinch:(UIPinchGestureRecognizer*)recognizer
{
//NSLog(@"We are pinching");
//This allows you to figure out which direction the pinch is occuring HORIZ or VERT

if (recognizer.state != UIGestureRecognizerStateCancelled)  //If gesture is occuring
{
    _startScale = 1.0f;

    if (recognizer.numberOfTouches == 2)  //With two fingers
    {
        CGPoint firstPoint = [recognizer locationOfTouch:0 inView:recognizer.view];
        CGPoint secondPoint = [recognizer locationOfTouch:1 inView:recognizer.view];

        CGFloat tangent = fabs(secondPoint.y - firstPoint.y) / (secondPoint.x - firstPoint.x);

        CGFloat angle = fabs(tangent);
        //NSLog(@"angle is %f", angle);

        if (angle <= 0.2679491924f)
        {
            //NSLog(@"HORIZONTAL");
            _zoomX = _startScale * recognizer.scale;

        }
        else if (angle >= 3.7320508076f)
        {
            //NSLog(@"VERTICAL");
            _zoomY = startScale * recognizer.scale;
        }
        else
        {
            //NSLog(@"BOTH");
        }
    }
}

[self changePlotRange];

}
The method changePlotRange is as follows.
- (void)changePlotRange
{

CPTGraph *graph = _hostView.hostedGraph;
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;

plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromCGFloat(_Xmin * _zoomX) length:CPTDecimalFromCGFloat((_Xmax - _Xmin) * _zoomX)];

plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromCGFloat(_Ymin * _zoomY) length:CPTDecimalFromCGFloat((_Ymax - _Ymin) * _zoomY)];
}

This works great and I can zoom in and out on either axis independently.  However, when I start again to pinch, the scale jumps back to one and the graph bounces back to the original scale so you need to scale again.  I want this to work like a picture, pinch a little, zoom a little, pinch some more and the picture zooms from the last scale.
So within the pinch gesture, I tried to keep the current scale and return it later with...
if (recognizer.state == UIGestureRecognizerStateEnded)
{
    _startScale = _zoomX;
}

I put this inside the handlePinch method.  But it still goes back to a scale of one.  Any help would be appreciated as I have searched and tried numerous things over the past three days.

A: You need to save the ending zoom values for both x and y separately since they will probably be different. Also, don't reset the start scale at the beginning of the gesture recognizer handler—you want it to use the previous zoom value.


text:
Q: Dual Pricing for GCP Cloud Functions with Firebase I created a new GCP Project, and created a hello-world serverless cloud function from GCP Console.
I immediately get a mail that a Firebase project has been created as well, and my Cloud Function has been upgraded to 'Blaze' plan of firebase.
My question is, which pricing model should I refer?
https://cloud.google.com/functions/pricing - GCP
OR
https://firebase.google.com/pricing - Firebase
There is a difference in both pricing, where if you see in firebase pricing, 125K invocations/month are free, while in GCP Pricing, 2M invocations/month are free.
I am confused on which pricing is applicable if I simply want to use Cloud Functions, because even if I create a function from GCP Console, firebase console also shows the function in its console.

A: You're misunderstanding the Firebase pricing page.  The 125K/month refers to the Spark plan in the left most column, all of which is completely free for the month.  If your plan is Blaze, you would use the right most column to assess cost.  That column doesn't show the free allowance, just the actual costs beyond the free limit.  If you hover your mouse over the question mark next to "Cloud Functions" on that row, you will see a description that says the first 2,000,000 invocation are free.  This matches the Cloud pricing.  So I believe they are in sync.
If you have questions about billing, you should reach out to Firebase support directly rather than Stack Overflow, which is for programming questions.


text:
Q: Is there a simple way to find the owner of a Process in Unix using C? I want to be able to check the owner of a process of which I got the ID from using C on a Unix system. It also needs to work on cygwin. Additionally it would be nice to get the date the process was created, too.
I've seen there are ways through looking up the generated files in /proc/<process-id>/. But unfortunately on cygwin you would need the right permissions to read those files.
If possible I am searching for a way without using those files or system commands. I had also found this threat:
How to programatically get uid from pid in osx using c++?
But it won't work due to missing definitions of KERN_PROC, KERN_PROC_PID and some more.
(Have not found the librarys for those in C)
So in short:
Does anyone know how I could get the informations on a specific process using c without needing system calls or reading the files in /proc/?

A: here under a simple implementation using ps command.
It's certainly not the most elegant but it should work for Unix and Cygwin:
#include <stdio.h>
#include <string.h>

int get_proc_uid(int pid, char *uid, int uid_size)
{
 FILE *fp;
 int pid_l, ret = -1;
 char uid_l[16];
 char cmd[64], line[128];

 snprintf(cmd, sizeof(cmd), "ps | grep %d", pid);
 fp = popen(cmd, "r");
 if(fp == NULL)
    return ret;

 while(fgets(line, sizeof(line), fp) != NULL)
    {
    if(strstr(line, "grep") == NULL)//filter grep dummy result
        {
        sscanf(line, "%d %s", &pid_l, uid_l);
        if(pid_l == pid)
            {
            strncpy(uid, uid_l, uid_size);
            ret = 0;
            break;
            }
        }
    }
 pclose(fp);

 return ret;
}


text:
Q: Get a response as xlsx using solrj in spring boot In an spring boot application, I am using solrj to query on solr 7.4. I want the output as xlsx file(not csv).
As mentioned here, I have added the required jars into the solr server classpath. Now when i hit http://localhost:8983/solr/collection_name/select?q=*:*&wt=xlsx in browser, I get a proper response from solr to download the result as a xlsx file.

BUT

How can i achieve this using SOLRJ in a spring boot app?

For other formats, like wt=xml/json/csv, solr response is a string which i can return from controller and set the content info in header to send it as a file. But i didn't get much info on how can i achieve it in case of xlsx file.

Any help is appreciated.

A: Finally i figured out a way.
As per the solr documentation, first copy the required jars into solr server classpath, then use the below code to get the response as xlsx file...
SolrQuery solrQuery = new SolrQuery();
solrQuery.setQuery("add solr query");
solrQuery.addFilterQuery("add filter query");
solrQuery.setParam("wt", "xlsx");

QueryRequest request = new QueryRequest(solrQuery);
request.setMethod(METHOD.POST);
request.setResponseParser(new InputStreamResponseParser("xlsx"));

SolrClient client = // create solrClient
NamedList<Object> resp = client.request(request, collectionName);
InputStream xlsxStream = (InputStream) resp.get("stream");
OutputStream outStream = new FileOutputStream("/path/to/xlsx/file");
IOUtils.copy(xlsxStream, output);


text:
Q: Are hard-coded STRINGS ever acceptable? Similar to Is hard-coding literals ever acceptable?, but I'm specifically thinking of "magic strings" here.
On a large project, we have a table of configuration options like these:
Name         Value
----         -----
FOO_ENABLED  Y
BAR_ENABLED  N
...

(Hundreds of them).
The common practice is to call a generic function to test an option like this:
if (config_options.value('FOO_ENABLED') == 'Y') ...

(Of course, this same option may need to be checked in many places in the system code.)
When adding a new option, I was considering adding a function to hide the "magic string" like this:
if (config_options.foo_enabled()) ...

However, colleagues thought I'd gone overboard and objected to doing this, preferring the hard-coding because:

*

*That's what we normally do

*It makes it easier to see what's going on when debugging the code

The trouble is, I can see their point!  Realistically, we are never going to rename the options for any reason, so about the only advantage I can think of for my function is that the compiler would catch any typo like fo_enabled(), but not 'FO_ENABLED'.
What do you think?  Have I missed any other advantages/disadvantages?

A: if (config_options.isTrue('FOO_ENABLED')) {...
}

Restrict your hard coded Y check to one place, even if it means writing a wrapper class for your Map.
if (config_options.isFooEnabled()) {...
}

Might seem okay until you have 100 configuration options and 100 methods (so here you can make a judgement about future application growth and needs before deciding on your implementation). Otherwise it is better to have a class of static strings for parameter names.
if (config_options.isTrue(ConfigKeys.FOO_ENABLED)) {...
}

A: I realise the question is old, but it came up on my margin.
AFAIC, the issue here has not been identified accurately, either in the question, or the answers.  Forget about 'harcoding strings" or not, for a moment.

*

*The database has a Reference table, containing config_options.  The PK is a string.

*There are two types of PKs:

*

*Meaningful Identifiers, that the users (and developers) see and use.  These PKs are supposed to be stable, they can be relied upon.

*Meaningless Id columns which the users should never see, that the developers have to be aware of, and code around.  These cannot be relied upon.

*It is ordinary, normal, to write code using the absolute value of a meaningful PK IF CustomerCode = "IBM" ... or IF CountryCode = "AUS" etc.

*

*referencing the absolute value of a meaningless PK is not acceptable (due to auto-increment; gaps being changed; values being replaced wholesale).
.

*Your reference table uses meaningful PKs. Referencing those literal strings in code is unavoidable.  Hiding the value will make maintenance more difficult; the code is no longer literal; your colleagues are right.  Plus there is the additional redundant function that  chews cycles.  If there is a typo in the literal, you will soon find that out during Dev testing, long before UAT.

*

*hundreds of functions for hundreds of literals is absurd. If you do implement a function, then Normalise your code, and provide a single function that can be used for any of the hundreds of literals.  In which case, we are back to a naked literal, and the function can be dispensed with.

*the point is, the attempt to hide the literal has no value.
.

*It cannot be construed as "hardcoding", that is something quite different.  I think that is where your issue is, identifying these constructs as "hardcoded".  It is just referencing a Meaningfull PK literally.

*Now from the perspective of any code segment only, if you use the same value a few times, you can improve the code by capturing the literal string in a variable, and then using the variable in the rest of the code block.  Certainly not a function. But that is an efficiency and good practice issue.  Even that does not change the effect IF CountryCode = @cc_aus

A: I really should use constants and no hard coded literals.
You can say they won't be changed, but you may never know. And it is best to make it a habit. To use symbolic constants.

A: In my experience, this kind of issue is masking a deeper problem: failure to do actual OOP and to follow the DRY principle.
In a nutshell, capture the decision at startup time by an appropriate definition for each action inside the if statements, and then throw away both the config_options and the run-time tests.
Details below.
The sample usage was:
if (config_options.value('FOO_ENABLED') == 'Y') ...

which raises the obvious question, "What's going on in the ellipsis?", especially given the following statement:

(Of course, this same option may need to be checked in many places in the system code.)

Let's assume that each of these config_option values really does correspond to a single problem domain (or implementation strategy) concept.
Instead of doing this (repeatedly, in various places throughout the code):

*

*Take a string (tag),

*Find its corresponding other string (value),

*Test that value as a boolean-equivalent,

*Based on that test, decide whether to perform some action.

I suggest encapsulating the concept of a "configurable action".
Let's take as an example (obviously just as hypthetical as FOO_ENABLED ... ;-) that your code has to work in either English units or metric units. If METRIC_ENABLED is "true", convert user-entered data from metric to English for internal computation, and convert back prior to displaying results.
Define an interface:
public interface MetricConverter {
    double toInches(double length);
    double toCentimeters(double length);
    double toPounds(double weight);
    double toKilograms(double weight);
}

which identifies in one place all the behavior associated with the concept of METRIC_ENABLED.
Then write concrete implementations of all the ways those behaviors are to be carried out:
public class NullConv implements MetricConverter {
    double toInches(double length) {return length;}
    double toCentimeters(double length) {return length;}
    double toPounds(double weight)  {return weight;}
    double toKilograms(double weight)  {return weight;}
}

and
// lame implementation, just for illustration!!!!
public class MetricConv implements MetricConverter {
    public static final double LBS_PER_KG = 2.2D;
    public static final double CM_PER_IN = 2.54D
    double toInches(double length) {return length * CM_PER_IN;}
    double toCentimeters(double length) {return length / CM_PER_IN;}
    double toPounds(double weight)  {return weight * LBS_PER_KG;}
    double toKilograms(double weight)  {return weight / LBS_PER_KG;}
}

At startup time, instead of loading a bunch of config_options values, initialize a set of configurable actions, as in:
MetricConverter converter = (metricOption()) ? new MetricConv() : new NullConv();

(where the expression metricOption() above is a stand-in for whatever one-time-only check you need to make, including looking at the value of METRIC_ENABLED ;-)
Then, wherever the code would have said:
double length = getLengthFromGui();
if (config_options.value('METRIC_ENABLED') == 'Y') {
    length = length / 2.54D;
}
// do some computation to produce result
// ...
if (config_options.value('METRIC_ENABLED') == 'Y') {
    result = result * 2.54D;
}
displayResultingLengthOnGui(result);

rewrite it as:
double length = converter.toInches(getLengthFromGui());
// do some computation to produce result
// ...
displayResultingLengthOnGui(converter.toCentimeters(result));

Because all of the implementation details related to that one concept are now packaged cleanly, all future maintenance related to METRIC_ENABLED can be done in one place. In addition, the run-time trade-off is a win; the "overhead" of invoking a method is trivial compared with the overhead of fetching a String value from a Map and performing String#equals.

A: I believe that the two reasons you have mentioned, Possible misspelling in string, that cannot be detected until run time and the possibility (although slim) of a name change would justify your idea.
On top of that you can get typed functions, now it seems you only store booleans, what if you need to store an int, a string etc. I would rather use get_foo() with a type, than get_string("FOO") or get_int("FOO").

A: If I use a string once in the code, I don't generally worry about making it a constant somewhere.
If I use a string twice in the code, I'll consider making it a constant.
If I use a string three times in the code, I'll almost certainly make it a constant.

A: I think there are two different issues here:

*

*In the current project, the convention of using hard-coded strings is already well established, so all the developers working on the project are familiar with it. It might be a sub-optimal convention for all the reasons that have been listed, but everybody familiar with the code can look at it and instinctively knows what the code is supposed to do. Changing the code so that in certain parts, it uses the "new" functionality will make the code slightly harder to read (because people will have to think and remember what the new convention does) and thus a little harder to maintain. But I would guess that changing over the whole project to the new convention would potentially be prohibitively expensive unless you can quickly script the conversion.

*On a new project, symbolic constants are the way IMO, for all the reasons listed. Especially because anything that makes the compiler catch errors at compile time that would otherwise be caught by a human at run time is a very useful convention to establish.

A: Another thing to consider is intent. If you are on a project that requires localization hard coded strings can be ambiguous. Consider the following:
const string HELLO_WORLD = "Hello world!";
print(HELLO_WORLD);

The programmer's intent is clear. Using a constant implies that this string does not need to be localized. Now look at this example:
print("Hello world!");

Here we aren't so sure. Did the programmer really not want this string to be localized or did the programmer forget about localization while he was writing this code?

A: I too prefer a strongly-typed configuration class if it is used through-out the code.  With properly named methods you don't lose any readability.  If you need to do conversions from strings to another data type (decimal/float/int), you don't need to repeat the code that does the conversion in multiple places and can cache the result so the conversion only takes place once.  You've already got the basis of this in place already so I don't think it would take much to get used to the new way of doing things.


text:
Q: Avoiding BLANK ROW with 'Stretch with Overflow' in report In my jasper report, i have 9 columns. For the col2 and col9, set the properties as
isStretchWithOverflow="true"
positionType="Float"
stretchType="RelativeToTallestObject"
isRemoveLineWhenBlank="true"
isPrintInFirstWholeBand="true"
isPrintWhenDetailOverflows="true"

So the values in col2 and col9 are stretched when the data overflows in EXCEL export. But the issues is, when the col2 or col9 is stretched in columnwise when the data overflows, at the same time it was adding BLANK ROW for col1,col3....col8.
Also i have added the property to avoid the blank row
<property name="net.sf.jasperreports.export.xls.remove.empty.space.between.rows" value="true"/>

**

Link to sample excel export file

**

A: You have to add stretchType="RelativeToTallestObject" on all the other fields so that they change height when col2 and col9 stretch on overflow. This way all thew fields in a single row will have the same height.


text:
Q: Module Parse Failed For React Table Css I am having trouble importing this:import 'react-table/react-table.css';
I get this error:
ModuleParseError: Module parse failed: /Users/andy/Sites/purpose-www/node_modules/react-table/react-table.css Unexpected token (1:0)
You may need an appropriate loader to handle this file type.

But I have setup the webpack configuration for css-loader. Here is my webpack config:
module: {
    loaders: [
      {
        test: /\.css$/,
        exclude: /node_modules/,
        loader: 'style-loader!css-loader?localIdentName=[name]__[local]__[hash:base64:5]&modules&importLoaders=1&sourceMap!postcss-loader',
      }, {
        test: /\.css$/,
        include: /node_modules/,
        loaders: ['style-loader', 'css-loader'],
      }, {
        test: /\.jsx*$/,
        exclude: [/node_modules/, /.+\.config.js/],
        loader: 'babel',
      }, {
        test: /\.(jpe?g|gif|png|svg)$/i,
        loader: 'url-loader?limit=10000',
      }, {
        test: /\.json$/,
        loader: 'json-loader',
      },
    ],
  },

Bable.rc:
{
  "presets": ["react", "es2015", "stage-0"],
  "plugins": ["react-hot-loader/babel", "react-html-attrs", "transform-class-properties"],
  "env": {
    "production": {
      "presets": ["es2015", "react", "react-optimize", "es2015-native-modules", "stage-0"]
    }
  }
}

Any ideas?


text:
Q: Remove unnecessary rows from a relational table I have a relational database (mysql) with two tables: Cities and Events .
Cities table:
   - city_id
   - city_name
   - city_coord

Events table
   - event_id
   - event_name
   - event_descr
   - city_id

In the Cities table I have 1500+ rows, and nearly 1300 rows aren't linked to the events table. How can I delete these rows?

A: You can do:
DELETE FROM cities
WHERE city_id NOT IN (SELECT city_id FROM events)

As mentioned in the comments, if city_id can be null in events, this will not work.
See this answer on why that is

A: DELETE FROM Cities
WHERE city_id NOT IN (SELECT city_id
                       FROM Events)


text:
Q: android progress dialog doesn't show percent Dialog doesn't show me percent If I've used code
    final Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        int total = msg.arg1;
        mProgressDialog.setProgress(total);
        if (total >= 100){
            try {
                mProgressThread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
            mProgressThread.setState(ProgressThread.STATE_DONE);
        }
    }
};

and in thread code
while ((count = input.read(data)) != -1) {
                total += count;
                Message msg = mHandler.obtainMessage();
                msg.arg1 = total;
                mHandler.sendMessage(msg);
                output.write(data, 0, count);
            }

What's wrong? If I use total++; instead total +=count; the scale raise to 19 percent but doesn't raise to 100%. It is because the file is download faster than the while loop 100 iteration.
If I use total += count; It shows 0 but the the scale is on 100% the file is downloaded.

A: You seem not to pass any percentage information to the handler but the total absolute number of read characters. When you write total++; you pass the number of of times your read routine receives data and when you write total +=count; you pass the total number of all characters you read in during your complete read routine.
If you want to show percentages you need to pass in the progress from 0-100. To do this you need to know how many characters you will read in total and write total +=count; and pass total/CountOfAllCharactersToRead. This way you will properly ass the %-fraction to the proress dialog.
Just a another comment. If your reading routine is very fast it can happen that the UI does not update frequently and you will not see the progress bar actually running from 0 to 100.


text:
Q: Android Intents: Is this a wrong way to set up an intent? So apparently there are two ways to get an intent to work.
Intent intent = new Intent(this, DisplayMessageActivity.class);

or
Intent intent = new Intent("com.example.tutorialone.DISPLAYMESSAGEACTIVITY");

The second way refers to the activity declared in the AndroidManifest. I find the second way to be easier, and it works, but are there any major drawbacks to this? What is the correct way to set up an intent?

A: the first way only can start your own Activity in your project.
the second can start a activity of other App if its exproted != false in AndroidManifext.xml.
I guess.

A: The first one is explicit call to an activity where as the other one as Vann said used to call to activities related to other apps if found in manifest. You can also call implicitly like that:
Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.so.com"));

A:
What is the correct way to set up an intent?

Both of the methods that you use are perfectly correct. Check out the 'Constructors' section in the docs for more info. Personally, I would use the first method when I can, as hard-coding the path to the activity is susceptible to typos etc., and also reduces the readability of your code.
The first method is contextual, because it looks for the given activity in the context of your application.
The second method is not, because you specify exactly what activity you are looking for. The drawback here is that if you change the path to the activity, or you change the app's namespace, this will no longer work.
If you're using the second method, my advice would be to store the path in a final variable like so:
public static final String DISPLAY_MESSAGE_ACTIVITY = "com.example.tutorialone.DISPLAYMESSAGEACTIVITY";

Then call it like this:
Intent intent = new Intent(DISPLAY_MESSAGE_ACTIVITY);

This way, you avoid typos etc, and your code is more readable. Hope this helps!

A: Intent intent = new Intent(this, DisplayMessageActivity.class);

Is an explicit intent. Here you know the className DisplayMessageActivity.class. So, you will start DisplayMessageActivity directly. you specify the exact class name in explicit intents.
Intent intent = new Intent("com.example.tutorialone.DISPLAYMESSAGEACTIVITY");

Is an implicit intent. Because you just specify the action to be performed i.e, com.example.tutorialone.DISPLAYMESSAGEACTIVITY, all the components that are capable of handling this action are eligible for being opened.
Note : Always use explicit intents when starting services.


text:
Q: how to make date comparison more efficient in javascript/typescript I have a asynchronous data I am loading from Firebase Firestore with this function
  graphDataSubscription;
  //dataCounter;
  passTotalCalData;
  totalCalories;
  dates=[];
  caloriesData=[];
  getGraphDateCalories() {
    if(this.graphDataSubscription){
      this.graphDataSubscription.unsubscribe()
    }
    this.graphDataSubscription = this.mealService.grabMealGraphDataCalories(this.startDate, this.gatheredUid.uid).subscribe(items => {
      this.dates = []
      this.passTotalCalData = []
      //this.dataCounter = 0;
      this.totalCalories=0;
      this.caloriesData=[];
      items.forEach( item => {
        //this.dataCounter++
        var data: any =  item.data()
        this.passTotalCalData.push(data.calories)
        this.caloriesData.push(data);
        this.totalCalories += data.calories;
        this.dates.push(moment(data.date).locale(window.navigator.language).format("DD MMM"))
      })
      console.log("data acquired");
      this.calendarData = this.getCalendarData();
      this.calendarData = [...this.calendarData];
    })
  }

then I am trying to insert gathered values to an object to show in a chart which requires a specific object format. It is a HeatMap chart so it must include whole previous year days even there is not a data for each day. like in this link
this is the function I am doing the date comparison, It takes almost 12 seconds even if the asynchronous data is gathered within a second.
  calendarData: any[] = [];
  getCalendarData(): any[] {
    //console.log("begin")
    // today
    const now = new Date();
    const todaysDay = now.getDate();
    const thisDay = new Date(now.getFullYear(), now.getMonth(), todaysDay);

    // Monday
    const thisMonday = new Date(thisDay.getFullYear(), thisDay.getMonth(), todaysDay - thisDay.getDay() + 1);
    const thisMondayDay = thisMonday.getDate();
    const thisMondayYear = thisMonday.getFullYear();
    const thisMondayMonth = thisMonday.getMonth();

    // 52 weeks before monday
    const calendarData = [];
    const getDate = d => new Date(thisMondayYear, thisMondayMonth, d);
    for (let week = -52; week <= 0; week++) {
      const mondayDay = thisMondayDay + week * 7;
      const monday = getDate(mondayDay);

      // one week
      const series = [];
      for (let dayOfWeek = 7; dayOfWeek > 0; dayOfWeek--) {
        const date = getDate(mondayDay - 1 + dayOfWeek);

        // skip future dates
        if (date > now) {
          continue;
        }

        // value
        var value = 0;
        console.log("assigning to the object begins")
        this.caloriesData.forEach(data => {

          if (data["date"] === date.toLocaleDateString('en-CA')) {
            value = data["calories"];
            //console.log("condition granted");
            return;

          }
        });
        console.log("assigning to the object ends")

        series.push({
          date,
          name: weekdayName.format(date),
          value
        });
      }

      calendarData.push({
        name: monday.toString(),
        series
      });
    }

    return calendarData;
  }

I know this is too much code but I wasn't sure how to create a minimal example with this specific problem.
So is there a way to make this comparison faster?
this part is taking so long I mean it's a for each with in two nested for loops but I still don't understand why comparing these dates takes so much time
var value = 0;
console.log("assigning to the object begins")
this.caloriesData.forEach(data => {

  if (data["date"] === date.toLocaleDateString('en-CA')) {
    value = data["calories"];
    //console.log("condition granted");
    return;

  }
});
console.log("assigning to the object ends")


text:
Q: How to get the value of a CPointer in Visual Works The following C function populate a C struct in Visual Works (is working ok):
<C:int ssh_pki_import_pubkey_file (const char * filename,  VOID * pkey)>

Now a second function is defined as:
int ssh_userauth_try_publickey (ssh_session session, const char * username, const ssh_key pubkey)

In Smalltalk:
<C:int ssh_userauth_try_publickey (VOID session, const char * username, const VOID pubkey)>

If i call the second function (ssh_userauth_try_publickey) with the populated argument (with no transformation) of the first function (ssh_pki_import_pubkey_file) it fail.
So VOID * pkey has to match const VOID pubkey.
In GemStone/S this is done with #'&ptr' and #'ptr', so #'&ptr' will get the value of the pointer (the CPointer's value will be passed and updated on return).
Reading DLL & C Connect User's Guide does not yield result yet.

A: Short answer
use void** in your first function and void* in your second function
Long answer
In C, void means "nothing" and if you have a return type of void that means you don't return anything.
But void* means pointer to nothing (...that i know about)... basically you get a pointer to something where you don't know what it is. But it's still a pointer, which is not nothing.
If you have a function that produces a value not via return but via parameter, you need to pass a pointer so that the function can set its value. You can do that via void* but that's unintentional. Consider the following wrong C code:
void var;
myFunc(&var);

myFunc would take a void* as parameter in order to fill its value, but a variable of type void is wrong because what would be its value. In correct C you would do it like that:
void* var = NULL;
myFunc(&var);

Here the type of var is clearly a pointer and its value is even initialised. For myFunc there's no real difference here, except that it'll now have a void** as parameter.
So if you modify ssh_pki_import_pubkey_file's declaration to have a void** parameter and change ssh_userauth_try_publickey's declaration to accept a void* parameter, you should be fine.


text:
Q: java: NullPointerExc why a List contains the added object when a lambda expression is invoked directly on it. and Not when the lambda is a method I have JavaFX form, user can choose an image. the image is stored in an ArrayList, because I cannot assign it directly to an Image field inside the lambda expression
List<ImageByteInfo> imageBinary = new ArrayList<>();
imageBinary.add(null);//for create button test, null is a valid parameter
chooseImage.setOnAction((ActionEvent e) -> {
        File selectedFile = logoChooser.showOpenDialog(stage);
        if (selectedFile != null) {
            Image logo = new Image("file:" + selectedFile.getAbsolutePath());
            imageBinary.clear();
            imageBinary.add(ImageConverter.imageToByteArray(logo));
            System.out.println("list image first entry, INSIDE: " + imageBinary.get(0));//working
            previewLogo.setImage(logo);
        }
    });

so when the user finish entring all fields, I invoke a createButton, the problem is here, when I try to get the stored object in imageBinary List, directly in setOnAction() method. it works and get the object.
createButton.setOnAction((ActionEvent e) -> {
        System.out.println("list image first entry, Outside: " + imageBinary.get(0));
    });

But What I want to do is invoke a method that holds the content of this lambda expression, so I do this:
createSchoolButton.setOnAction(createBtnFire(
            nameInput.getText(), ..,
             imageBinary.get(0),
            .., zipInput.getText()));

this is createBtnFire()
private EventHandler<ActionEvent> createBtnFire(String name, ..
         ImageByteInfo logo, boolean addressEntered, String... addressFields) {
    EventHandler<ActionEvent> createBtn = (ActionEvent e) -> {
        //code..
        entity.setCreationDate(creationDate);//null
        System.out.println(logo);//this print null, so next line throws a NullPointerException
        entity.setImageByteInfoEntity(new ImageByteInfoEntity(logo.getByteImage(), logo.getWidth(), logo.getHeight()));
        //code..
        startUI.continueToMainContent();
    };
    return createBtn;
}

==> NullPointerException at entity.setImageByteInfoEntity(..);
I did make the list an instance variable, still null. So why when I don't use a method for the lambda expression it works and the list returns the object and when I use the method it returns null. Thanks.

A: This has to do with the scope of the lambda expression. Think of a lambda expression as an anonymous inner class. When the code fragment that defines the lambda is run, this lambda object is created. As it can hold references to variables outside the lambda expression they are initiated as well.
Therefore when using the lambda expression like the first variant, the reference to imageBinary is used and the first element of the list is accessed when the lambda expression is run.
In the second case you define an event handler and pass the first element of imageBinary into it, which at that point is still not initialized.
You can change the createBtnFire in the following way, so it behaves in the same manner:
private EventHandler<ActionEvent> createBtnFire(String name, ..
         List<ImageByteInfo> logos, boolean addressEntered, String... addressFields) {
    EventHandler<ActionEvent> createBtn = (ActionEvent e) -> {
        //code..
        entity.setCreationDate(creationDate);//null
        ImageByteInfo logo = logos.get(0);
        System.out.println(logo);
        entity.setImageByteInfoEntity(new ImageByteInfoEntity(logo.getByteImage(), logo.getWidth(), logo.getHeight()));
        //code..
        startUI.continueToMainContent();
    };
    return createBtn;
}


text:
Q: Problems with the library IFilter I want to use the IFilter interface to extract and then search the text from different documents. The IFilter interface fits this need perfectly, but there is an issue with 32/64 bit components.
The host OS is 64-bit. The application is 32-bit. I want to extract text from a .docx file, so I try to install the 32-bit Office 2010 Filter Pack. The installer fails with a message: 'The MSI Installer type does not match the platform  architecture.'
When I install the 64-bit version of the Filter Pack, the 32-bit dlls are not installed so the filters are still not available. How do I install the 32-bit filters on a 64-bit system? it's possible ?
Thanks a lot in advance

A: There is no support for installing the 32-bit filters on 64-bit Windows. The only solution you have is to install the 64-bit filters and create a 64-bit out-of-proc COM server application that exposes the functionality you require. This app could load the 64-bit filters and COM would handle the inter-process communication between your 32-bit app and the 64-bit out-of-proc COM server.

A: I found a way to install Filter Pack 32bits in a 64bits OS. To other file formats is similar.
Install Filter Pack 32 bits in a 32bits OS.
Copy ifilters files in directory "C:\Program Files\Common Files\Microsoft Shared\Filters" from 32 bits OS to the a directory "C:\Program Files (x86)\Common Files\Microsoft Shared\Filters" in 64bits OS.


text:
Q: How to reverse strings that contain surrogate pairs in Dart? I was playing with algorithms using Dart and as I actually followed TDD, I realized that my code has some limitations.
I was trying to reverse strings as part of an interview problem, but I couldn't get the surrogate pairs correctly reversed.
const simple = 'abc';
const emoji = '';
const surrogate = '♂';

String rev(String s) {
    return String.fromCharCodes(s.runes.toList().reversed);
}

void main() {
    print(simple);
    print(rev(simple));
    print(emoji);
    print(rev(emoji));
    print(surrogate);
    print(rev(surrogate));
}

The output:
abc
cba

♂
♂

You can see that the simple emojis are correctly reversed as I'm using the runes instead of just simply executing s.split('').toList().reversed.join(''); but the surrogate pairs are reversed incorrectly.
How can I reverse a string that might contain surrogate pairs using the Dart programming language?

A: When reversing strings, you must operate on graphemes, not characters nor code units. Use grapheme_splitter.

A: Dart 2.7 introduced a new package that supports grapheme cluster-aware operations. The package is called characters. characters is a package for characters represented as Unicode extended grapheme clusters.

Dart's standard String class uses the UTF-16 encoding. This is a common choice in programming languages, especially those that offer support for running both natively on devices, and on the web.
UTF-16 strings usually work well, and the encoding is transparent to the developer. However, when manipulating strings, and especially when manipulating strings entered by users, you may experience a difference between what the user perceives as a character, and what is encoded as a code unit in UTF-16.

Source: "Announcing Dart 2.7: A safer, more expressive Dart" by Michael Thomsen, section "Safe substring handling"

The package will also help to reverse your strings with emojis the way a native programmer would expect.
Using simple Strings, you find issues:
String hi = 'Hi ';
print('String.length: ${hi.length}');
// Prints 7; would expect 4

With characters
String hi = 'Hi ';
print(hi.characters.length);
// Prints 4
print(hi.characters.last);
// Prints

It's worth taking a look at the source code of the characters package, it's far from simple but looks easier to digest and better documented than grapheme_splitter. The characters package is also maintained by the Dart team.


text:
Q: server_address usage in python 3 Could someone help me understand the following python websocket code?
In particular I am interested in the server_address initialization. Does '' match to localhost by default? If not how can I get that to be localhost?
import socket
import sys

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('', 8080)
sock.bind(server_address)


text:
Q: Inserting integers from a text file to an integer array I have a text file filled with some integers and I want to insert these numbers to an integer array from this text file.
 #include <iostream>
 #include <fstream>

 using namespace std;

 int main(){

  ifstream file("numbers.txt");
  int nums[1000];

  if(file.is_open()){

     for(int i = 0; i < 1000; ++i)
     {
        file >> nums[i];
     }
  }

  return 0;
}

And, my text file contains integers line by line like:
102
220
22
123
68

When I try printing the array with a single loop, it prints lots of "0" in addition to the integers inside the text file.

A: Always check the result of text formatted extraction:
if(!(file >> insertion[i])) {
    std::cout "Error in file.\n";
}

Can it be the problem is your text file doesn't contain 1000 numbers?
I'd recommend to use a std::vector<int> instead of a fixed sized array:
 #include <iostream>
 #include <fstream>
 #include <vector>

 using namespace std;

 int main(){

  ifstream file("numbers.txt");
  std::vector<int> nums;

  if(file.is_open()){
     int num;
     while(file >> num) {
         nums.push_back(num);
     }
  }

  for(auto num : nums) {
      std::cout << num << " ";
  }

  return 0;
}


text:
Q: No data written to stdin or stderr from ffmpeg I have a dummy client that is suppose to simulate a video recorder, on this client i want to simulate a video stream; I have gotten so far that i can create a video from bitmap images that i create in code.
The dummy client is a nodejs application running on an Raspberry Pi 3 with the latest version of raspian lite.
In order to use the video I have created, I need to get ffmpeg to dump the video to pipe:1. The problem is that I need the -f rawvideo as a input parameter, else ffmpeg can't understand my video, but when i have that parameter set ffmpeg refuses to write anything to stdio
ffmpeg is running with these parameters
ffmpeg -r 15 -f rawvideo -s 3840x2160 -pixel_format rgba -i pipe:0 -r 15 -vcodec h264 pipe:1
Can anybody help with a solution to my problem?
--Edit
Maybe i sould explain a bit more.
The system i am creating is to be set up in a way, where instead of my stream server ask the video recorder for a video stream, it will be the recorder that tells the server that there is a stream.

A: I have have slowed my problem on my own. (-:
i now have 2 solutions.

*

*Is to change my -f rawvideo to -f data that works for me anyways.

*I can encode my bitmaps as jpeg in code and pipe my jpeg images to stdin. This also requires me to change the ffmpeg parameters to -r 4 -f mjpeg -i pipe:0 -r 4 -vcodec copy -f mjpeg pipe:1 and is by far the slowest thing i have ever done. and i can't use a 4k input

thanks @Mulvya for trying to help.
@eFox Thanks for editing my stupid spelling and grammar mistakes


text:
Q: GitHub option not available in PyCharm VCS | Checkout from Version Control I'm trying to clone a repository from GitHub to PyCharm, and so I looked up how to do that. I looked at this website, and it told me to go to

*

*Choose VCS | Checkout from Version Control | GitHub on the main menu. PyCharm establishes connection with GitHub using the login and password you registered. Upon establishing connection, the Select Git Hub Repository to Clone dialog box opens.

*From the Repository drop-down list, select the source repository to clone the data from.

But, when I go to VCS | Checkout from Version Control, there is no GitHub, only these options:

So I looked at this answer to this question, which was similar but on Intellij (I hope PyCharm and Intellij work similarly), and the answer was to

Go to File > Settings > Plugins and search for GitHub and Git Integration then install those. A restart might be required in order to apply the changes.

(answer was written by Enzokie). So I went there and those were both installed. What is wrong and why can't I clone a repository from GitHub?

A: GitHub is a web-based hosting service for version control using Git.
I copied that from their webpage.
The version control system you want to use is Git. And you will connect to GitHub, (which also uses Git), to clone the project you want.
So, select the Git option, enter the project URL and voila!
Another version control web-hosting service who also uses Git (but also Mercurial), is Bit-Bucket.
This Wikipedia page explains what Git is.


text:
Q: Making User Information Available on Every Page I'm an amateur, admittedly so, but I'm having fun trying to learn a little more about programming, and php in general, using CodeIgniter.
I have a test site up and running and feel like I have a decent grasp of MVC.  Without any formal background though, I know my architecture is screwy and sloppy so I poll from time to time for best practices from those in the know (that's you).
There's some data about users that I'd like to have access to on every page. Said data is stored in 3 different db tables.  The only way I can think to get the information into every controller is to create a model that pulls this data and then call the model in every controller, passing the data onto the view.
Another idea would be to create a library that loads the model, autoload it, and then grab the specific data from the functions in the library when I need them.
Am I thinking about this correclty?
Thanks.

A: You can use sessions.
When a user login, store his/her basic information in session by getting it from databases.
Now you can directly get them from session and show them on any webpage. Make shure this information does not contain user password :)


text:
Q: new Elastic search client code for filter aggregation followed by nested aggregation and term aggregation Please help me to get new ElasticsearchClient equivalent code for below search criteria.
Need new java ElasticsearchClient code for filters followed by nested query and term query.
{
  "aggs_all_filters": {
    "filters": {
      "filters": [
        {
          "bool": {
            "adjust_pure_negative": true,
            "boost": 1.0
          }
        }
      ],
      "other_bucket": false,
      "other_bucket_key": "_other_"
    },
    "aggregations": {
      "facetsData": {
        "nested": {
          "path": "data.attributes.facetEnable.searchable"
        }
      }
    }
  }
}


text:
Q: Import text file to new sheet, do some operations, then close the sheet I have a problem that I need help to solve. I want to import a text file to a new temporary sheet, find some data, put them in my current sheet and then close the new temporary sheet. Is this possible and how do I do this?

A: To create a new Worksheet, then remove it:

Option Explicit

Sub openWorkSheet()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets.Add(, ThisWorkbook.ActiveSheet)
End Sub

Sub closeWorkSheet(ByRef ws As Worksheet)
    If Not ws Is Nothing Then
        With Application
            .DisplayAlerts = False
            ws.Delete
            .DisplayAlerts = True
        End With
    End If
End Sub

To open a text file, read its contents and find specific strings:

Public Sub searchFile(ByVal filePathAndName As String)

    Const TYPICAL_START = "FIRST search string"
    Const TYPICAL_END = "LAST search string"

    Dim fso As Object
    Dim searchedFile As Object
    Dim fullFile As String
    Dim foundStart As Long
    Dim foundEnd As Long
    Dim resultArr() As String
    Dim i As Long

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set searchedFile = fso.OpenTextFile(filePathAndName)

    fullFile = searchedFile.ReadAll 'read entire file

    i = 1
    foundStart = 1
    foundStart = InStr(foundStart, fullFile, TYPICAL_START, vbTextCompare)

    If foundStart > 0 Then

        foundEnd = InStr(foundStart, fullFile, TYPICAL_END, vbTextCompare)

        While foundStart > 0 And foundEnd > 0
            ReDim Preserve resultArr(i)
            resultArr(i) = Mid(fullFile, foundStart, foundEnd - foundStart + 1)
            foundStart = InStr(foundStart + 1, fullFile, TYPICAL_START, vbTextCompare)
            If foundStart > 0 Then foundEnd = InStr(foundStart, fullFile, TYPICAL_END)
            i = i + 1
        Wend
    End If
End Sub

A: So now it shold work. This is the sub that does not want to work.
Sub Import()
   Dim DestBook As Workbook, SourceBook As Workbook
   Dim DestCell As Range
   Dim RetVal As Boolean

   ' Set object variables for the active book and active cell.
   Set DestBook = ActiveWorkbook
   Set DestCell = ActiveCell

   ' Show the Open dialog box.
   RetVal = Application.Dialogs(xlDialogOpen).Show("*.txt", , True)

   ' If Retval is false (Open dialog canceled), exit the procedure.
   If RetVal = False Then Exit Sub

   ' Set an object variable for the workbook containing the text file.
   Set SourceBook = ActiveWorkbook

   ' Copy the contents of the entire sheet containing the text file.
   Range(Range("A1"), Range("A1").SpecialCells(xlLastCell)).Copy

   ' Activate the destination workbook and paste special the values
   ' from the text file.
   DestBook.Activate
   DestCell.PasteSpecial Paste:=xlValues

   ' Close the book containing the text file.
   SourceBook.Close False

End Sub


text:
Q: what does double square brackets mean in swift? the below is the sample code in swift.
var loadedMessages = [[Message]]()

Message is a custom class. i'm not sure what [[Message]] () is doing.

A: It means it's an array of arrays of messages.  Think of it in terms of whatever appears between the square brackets being an array of that, and this can include another array.
Alternatively, if you were to write out without the "shorthand" array syntax, it would be Array<Array<Messages>>().

A: It is specifying that your variable loadedMessages is an array of arrays that contains Message objects. A JSON representation of loadedMessages might look like:
loadedMessages: [
  [ <Message>, <Message>, <Message> ],
  [ <Message>, <Message>, <Message> ]
]

A quick Playground implementation of something similar can give you a pretty good introspection of the situation:
var foo = [[String]]()
foo.append(["bar"])
foo[0][0] // reveals "bar"


text:
Q: Getting Awesomium to run on mono under linux I'm attempting to get a program developed in C# that uses awesomium (console only) running on linux(mono).
I've downloaded and installed the latest Awesomium SDK 1.7.5.

# ldconfig -p | grep libawe
libawesomium-1-7.so.5 (libc6,x86-64) => /usr/lib/libawesomium-1-7.so.5

Inside my solution I've included the reference to Awesomium.Mono.dll.
Inside the Awesomium.Mono.dll.config file I've done a dllmap to retarget for the linux OS.. maybe this isn't required?

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<!-- Fix the target below to target the Awesomium native library -->
<dllmap dll="awesomium" target="libawesomium-1-7.so.5" os="linux"/>
<dllmap dll="awesomium" target="@executable_path/../Frameworks/Awesomium.framework/Versions/A/Awesomium" os="osx"/>
</configuration>

I'm currently receiving an error stating the dll cannot be found

Unhandled Exception: System.TypeInitializationException: An exception was thrown by the type initializer for Awesomium.Core.WebCore ---> System.TypeInitializationException: An exception was thrown by the type initializer for Awesomium.Core.NativeMethods ---> System.TypeInitializationException: An exception was thrown by the type initializer for AweExceptionHelper ---> System.DllNotFoundException: libawesomium-1-7.so.5
  at (wrapper managed-to-native) Awesomium.Core.NativeMethods/AweExceptionHelper:RegisterExceptionCallbacks_awesomium (Awesomium.Core.NativeMethods/AweExceptionHelper/ExceptionDelegate,Awesomium.Core.NativeMethods/AweExceptionHelper/ExceptionDelegate,Awesomium.Core.NativeMethods/AweExceptionHelper/ExceptionDelegate,Awesomium.Core.NativeMethods/AweExceptionHelper/ExceptionDelegate,Awesomium.Core.NativeMethods/AweExceptionHelper/ExceptionDelegate,Awesomium.Core.NativeMethods/AweExceptionHelper/ExceptionDelegate,Awesomium.Core.NativeMethods/AweExceptionHelper/ExceptionDelegate,Awesomium.Core.NativeMethods/AweExceptionHelper/ExceptionDelegate,Awesomium.Core.NativeMethods/AweExceptionHelper/ExceptionDelegate,Awesomium.Core.NativeMethods/AweExceptionHelper/ExceptionDelegate,Awesomium.Core.NativeMethods/AweExceptionHelper/ExceptionDelegate)

Any advice?

A: This is how I got Awesomium to work in Mono on Linux:

*

*Download and install (on Windows) the Awesomium SDK for Windows (awesomium_1_7_5_1_sdk_win).

*Find Awesomium.Mono.dll (for me C:\Program Files\Awesomium Technologies LLC\Awesomium SDK\1.7.5.1\wrappers\Awesomium.NET\Assemblies), copy to Linux and reference in your Mono project, making sure Local Copy is checked.

*Download the Awesomium SDK for Linux (awesomium_1_7_5_sdk_linux64) and extract.

*Copy the contents of bin to the operating directory of your project (e.g. bin/Debug).

*Rename libawesomium-1-7.so.5.0 to libawesomium-1-7.so.0.0.
Example code (typos fixed from documentation):
using System;
using Awesomium.Core;

class MainClass
{
    public static void Main (string[] args)
    {
        using (var webView = WebCore.CreateWebView( 800, 600 ) )
        {
            webView.Source = new Uri( "http://www.google.com" );

            webView.LoadingFrameComplete += ( s, e ) =>
            {
                if (!e.IsMainFrame)
                    return;

                BitmapSurface surface = (BitmapSurface)webView.Surface;
                surface.SaveToPNG ("result.png", true);

                WebCore.Shutdown ();
            };
        }

        WebCore.Run();
    }
}


text:
Q: save HTML for of rendered PUG with dATA I want to save HTML source of my pugfile rendered with data.
My route is:
res.render('pugfile', { data: resp });

How can I do that?

A: There's a callback from .render().
res.render('pugfile', { data: resp }, function (err, pageBody) {
    if (err) throw err
    /* manipulate pageBody as you will,
     * but be sure to .send it to the browser if
     * you use this callback. */
    res.send(pageBody)
})

See here and here.

A: Try using this link and see whether it will be helpfull to you
link to possible answer
The createTemplateFile function simply creates a new file if it doesn't exist.
The exportTemplateFile function saves the HTML in the html variable rendered by pug and prettifies it with the pretty package and then overwrites the new template file
Thats according to that post


text:
Q: How to update a mysql row when multiple rows are displayed I have a php 5.5 website using mysql 5.5.
I have read a number of rows from a mysql table and displayed the data on a html page where the user can edit it.
How do i ensure that I update the correct row with the new data from the user?
For example, if the user updates the data in field 3 of row 6 then I need to update field 3 of row 6 on the database.
I tried having a submit button (with the same name) on every row but found that it doesn't matter which row the user changes, the last row on the table is updated.
That makes sense since the current value of the table key is the last row that was read but that doesn't help me at all...
Any ideas?
Thanks in advance

A:
I need to update field 3 of row 6 on the database

There is no field 3, and there is no row 6.  Your database doesn't guarantee sort order of anything unless it's explicitly specified in a query on that data.
So you don't need to update "field 3", you need to update an identified field:
UPDATE SomeTable SET SomeField = 'some value'

Notice that the field is explicitly named, it's not updated by some cardinal position in relation to other fields.  Similarly for rows, you need to identify the row(s) which should be updated:
UPDATE SomeTable SET SomeField = 'some value' WHERE SomeOtherField = 'some other value'

The row(s) is/are identified by some logical identifier, not by their cardinal position in relation to any other rows.
Without seeing any of your code or table structure it's hard to really be any more specific than that.  But what this essentially means to your HTML/PHP is that when the form is posted to the server with values to update, it needs to include some way of identifying what needs to be updated.  For example, one row in your HTML table might contain this:
<form action="somePage.php">
    <input type="hidden" name="id" value="1" />
    <input type="text" name="SomeField" value="some value" />
    <input type="submit" value="Submit" />
</form>

Then in your server-side code you would construct your query to use the value of $_POST['SomeField'] in the UPDATE statement, and use the value of $_POST['id'] in the WHERE clause for that UPDATE statement.

A: When you query the DB, use:
    "UPDATE SET your_field = 'new_value' WHERE changed_row= 'changed_row'"

According to W3Schools:
Notice the WHERE clause in the SQL UPDATE statement!
The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!
Hope that helpes?


text:
Q: Apply Custom Formatter after Sort Function with jqGrid I am using a custom control on an Xpage to build a table with jqGrid. The jqGrid receives the data via JSON and fills the table correctly.
My question is with the sort function of jqGrid. I apply a custom formatter to the cell value of my "docname" column when the table first builds. The issue that I am having is after sorting any of the columns this formatter becomes unusable. The format is still applied but this particular formatter builds a url that launches another Xpage and relies on the parameter "docid".
Here is my custom formatter:
function openDocument(cellvalue, options, rowObject) {
return ""
+ cellvalue + ""; }

Is there any way to get the rowObject "docid" back into the openDocument formatter after sorting the grid?
I researched some and found the onSortCol event and have it initialized like this:
 onSortCol: function(index,iCol,sortorder) {alert("Test")}

My alert that I have in the onSortCol initilization is working, I just need to find out how to set my "docid" parameter after the sort is run since it is currently set to undefined after the sort.
I have tried putting in:
{rowObject["docid"]}

But this just breaks the sorting all together.
I have also read these posts:
onSortCol Event
JQGrid Sorting - how to trigger onSortCol event
jqGrid - Is it possible to set onSortCol after init?
Thanks for your help.
Edit:
jqGrid Definition:
     $().ready(function(){
     jQuery("#listxGrid").jqGrid({
        url:'#{javascript:compositeData.url}',
        datatype: "json",
        colNames:#{javascript:compositeData.colNames},
        colModel:#{javascript:compositeData.colModel},
        shrinkToFit:  false,
        jsonReader: {
        repeatitems: false,
        id: '#{javascript:compositeData.colID}',
        root: function (obj) {
            if ($.isArray(obj)) return obj;
            if ($.isArray(obj.items)) return obj.items;
                                return [];
                            },
        page: function () { return 1; },
        total: function () { return 1; },
        records: function (obj) {
            if ($.isArray(obj)) return obj.length;
            if ($.isArray(obj.items))   return obj.items.length;
                                return 0;
                            }
                        },
        gridview: true,
        loadonce: true,
        ignoreCase: #{javascript:compositeData.ignoreCase},
        rowNum: #{javascript:compositeData.rowNum},
        rowList: #{javascript:compositeData.rowList},
        rownumbers: #{javascript:compositeData.showRowNumbers},
        height: #{javascript:compositeData.height},
        caption: '#{javascript:compositeData.caption}',
        pager: '#pagerxGrid',
        viewrecords: true,
        emptyrecords: '#{javascript:compositeData.emptyRecords}',
        sortable: true,
        onSortCol: function(index,iCol,sortorder) {alert(index)},
        grouping: #{javascript:compositeData.grouping},
        groupingView : {
            groupField : #{javascript:compositeData.groupField},
            groupDataSorted : true,
            groupColumnShow : #{javascript:compositeData.showGroupCol}

                            }

                });

A: I ended up solving the problem this way. On the jqGrid it was receiving the "docid" param from the remote data on the first load just fine but as soon as the sort function called it would be set to "undefined."
As @PerHenrikLausten pointed out with his link, after the onload function completes this remote data type is then switched to local data. By loading in the docid into a hidden column, this is then available as a parameter for my formatter after the data type is switched.
By adding:
'Docid' as a colName & {name:'docid', index:'docid', hidden: true} to the colModel

It allows me to sort the jqGrid from any of my columns that I have sortable set to true with the docid parameter as what it should be not "undefined."
Thanks everyone for your input.

A: Have a look at this answer which suggests the use of isArray to determine whether to use  rowObject["docid"] or rowObject[integer]:
jqGrid - rowObject inconsistencies?


text:
Q: Gaussian distributions - a question about convergence Let $\mu_n$ be Gaussian distributions with mean $0$ and standard deviation $1/n$ and $f$ a function.
It may be true that if $\underset{\mathbb{R}}{\int} f \mu_n dx \rightarrow  \underset{\mathbb{R}}{\int} f \delta_0dx$, then $\mu_n \rightarrow \delta_0$? Why yes or not?  If yes, in what conditions?
$\underset{\mathbb{R}}{\int} f \mu_n dx \rightarrow  \underset{\mathbb{R}}{\int} f \delta_0dx$ $\Leftrightarrow \underset{\mathbb{R}}{\int}f (\mu_n - \delta_0) dx \rightarrow 0 \Leftrightarrow \mu_n \rightarrow \delta_0$ ?
Thank you!

A: Let $\mu_n$ be the gaussian distribution with mean $0$ and standard deviation $1/n$.
Then $\displaystyle\int_\mathbb R f(x) \mu_n(\mathrm dx) \to f(0)$ for every bounded measurable function $f$ continuous at $0$.


text:
Q: The device is not connected exception I try to open a large number of files but after 5000 files or so I get
Exception in thread "Main" java.io.IOException: The device is not connected

Is this the expected behavior? Is there a way around it? I want to leave my code as straightforward as possible.

A: *

*Your operating system may limit the number of files one process can have open.

*Generally you want to be careful with resources like open files in java. Unless you have a specific reason for keeping all of those open, you'd be better off reading through each file, extracting the data you want, and then closing.

What exactly are you trying to achieve?

A: An open file has some cost in resources, so that opening another file fails when many files are already open is expected behavior. At least it is expecte by myself.
see for example this: http://www.msfn.org/board/lofiversion/index.php/t101414.html

A: It should not be a problem opening thousands of files if you remember to close() your files when you are done using them?
If not, you force the operating system to maintain state for your open files, which usually is a limited resource.
If you really need lots of simultaneous open files, the solution depends on the circumstances.  What is it you need to do?  Please show code.


text:
Q: Allowing logged in users to comment without moderation across a multisite installation I currently do web admin for an internet community based on BuddyPress and Multi Site, and use the Comment author must have a previously approved comment setting to make it easier for users to comment and not be moderated.  All users are vetted before their accounts are created so I know we don't have spambots.
However it does not quite behave as I wish it to and I wonder if there is a way to achieve what I want.  Ideally what I'd like is for:

*

*All logged in users to be able to comment anywhere on the multi-site without moderation that they have right to comment on, unless the owner of the subsite has ticked 'An administrator must always approve the comment'

*For non-logged in comments to always be approved if they've ever been approved anywhere on the multi-site. (Currently it only works if the new comment is on a post by the same author on the same site they were previously approved on)

Is this possible using existing settings or plugins?  If not can it be achieved another way and if so how?

A: You could hook into 'pre_comment_approved' and change its return value. Sample code, not tested:
add_filter( 'pre_comment_approved', 'wpse47172_approve_logged_in_users' );

function wpse47172_approve_logged_in_users( $approved )
{
    return is_user_logged_in() ? 1 : $approved;
}


text:
Q: SYSDATE in ORACLE I'm trying to get the system date using the SYSDATE function in oracle, but I keep getting results equal to the number of rows in the table I'm requesting the system date from
Here how my code looks like:
SELECT TRUNC(SYSDATE)As Currnt_Time FROM TABLE_NAME

And this is my output:
enter image description here
The result is displaying the current time N times, I just want it to display it one time

A: SELECT TRUNC(SYSDATE)As Currnt_Time FROM dual;

DUAL only has 1 column, one row. So you'll get one answer.
You're asking to run a select on a table, so it will apply across all rows, unless you provide a predicate.
So you COULD do this, but don't.
select trunc(SYSDATE)as CURRNT_TIME from TABLE
where rownum < 2;

This will always be more expensive than using the DUAL table. That's why we built it, in fact.

A: The easiest command should be:
SELECT TRUNC(SYSDATE)As Currnt_Time FROM TABLE_NAME WHERE ROWNUM = 1
And this is not the most elegant solution.


text:
Q: What statistic does R's sm use to test equality of densities? I'd like to ask what kind of test statistic is used in the R package 'sm' to test for equality of two density distributions. This is the package:
https://cran.r-project.org/web/packages/sm/index.html
There is a function called sm.density.compare, and the documentation refers to a book called "Bowman, A.W. and Azzalini, A. (1997). Applied Smoothing Techniques for Data Analysis: the
Kernel Approach with S-Plus Illustrations. Oxford University Press, Oxford.", but it doesn't list any details.
Which statistic is it using for this test? how is it calculating the p-values?

A: I don't have the book, but we can just look at the information for the function.
The help for the function states explicitly:
 Description:

 This function allows a set of univariate density estimates to be
 compared, both graphically and formally in a permutation test of
 equality.

So if the help is correct, it uses a permutation test (which is what I'd have done in this situation).
Examining the code of the function, it appears to be doing exactly what the help says -- a permutation test.
The test statistic is given by the line:
 ts <- sum((estimate[1, ] - estimate[2, ])^2)

Which is to say, it's a sum of squared differences in the density estimates, (by the look of it, summed over the evaluation points of the density estimates; in effect an integrated squared difference).
When there are more than two densities it looks like it uses a sum of squares of deviations from the average of the estimates.
The p-values in a true permutation test are found by generating all possible arrangements of the data into the two samples (of the same sample sizes as the original sample) and calculating the test statistic under each arrangement, counting the proportion of them at least as extreme$^\dagger$ at the particular one in the sample.
$\dagger$ (where more extreme = more consistent with the alternative)
However, in this case, all possible arrangements will generally be far too many to calculate, and instead the arrangements are sampled (they're usually sampled with replacement, which is convenient, and usually of little consequence if the number of possible arrangements is much larger than the number of sampled arrangements). This is properly a randomization test, but it's often the case that people call this a permutation test as well. The p-value is calculated in the same fashion (after adding the sample test statistic to the set of re-sampled statistics). (When this is done, it's possible to calculate a standard error for what is an estimate of the p-value.)