text:
Q: UIAlertController bug changing tintcolor of other UIImageViews I have what I assume is an odd iOS8 bug. Whenever I launch a UIAlertControllerI find that it is changing all of the tint colors of my UIImageViews that use the UIImageRenderingModeAlwaysTemplate image rendering mode to a dark grey. This happens whether or not I adjust the tint color of the UIAlertController. Below find a screenshot (Look at the bubble corners) which were the correct color before the UIAlertController was displayed and return to the correct color once it is dismissed.
Anybody know how to prevent this in iOS8?

UIAlertController *alertController = [UIAlertController
                                      alertControllerWithTitle:[NSString stringWithFormat:@"Question ended %@",[endDateFormat stringFromDate:[NSDate dateWithTimeIntervalSince1970:selectedActivity.utc]]]
                                      message:messageText
                                      preferredStyle:UIAlertControllerStyleActionSheet];
[alertController.view setTintColor:[UIColor colorWithHue:240.0/360 saturation:.03 brightness:.58 alpha:1]];

//...Add some actions and then
[self presentViewController:alertController animated:YES completion:nil];

A: Whenever a modal view is presented the tint color of the views behind it are changed to a gray "dimmed" color to indicate that they are not interactive. You should be able to fix this issue by setting the tintAdjustmentMode property of your UIImageViews.
See:
UIKit Framework > UIView Class Reference > Configuring a View's Visual Appearance > tintAdjustmentMode


text: Q: How to connect two web APIs I have a web api app. In client side of app, I created special control for reporting. This control is using Telerik Reporting api. User can send different kind of request. Also, users can use reporting with browser. In browser user should authorize before reporting anything. But in my client app user already authorized and it should be able to use this control without authorization. How can I join my web api and Telerik reporting api?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting log4j2 to work with eclipse I know there is allot of questions been asked on this but i have been trying to get this to work for few day's and i am not any more forward then when i started.
i have tried to use -Dlog4j.configuration=file:/path/to/log4j.properties and -Dlog4j.debug in eclipse vm arguments (under debug & run) and get no output
I have tried to use .properties and .xml but no joy
Tried to put the .xml and .properties files at the root, in the src and in an external folder which i added to my classpath ... still no joy
I think its using another .xml or .properties files in another lib/jar but because i cant get any debug to work i am finding very difficult to track what i am doing wrong here...
any help would be great! below is the code .. only the error message get's printed.
I have download (http://logging.apache.org/log4j/2.x/download.html) and imported into my app the
log4j-api-2.0-beta8.jar
log4j-core-2.0-beta8
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class CucmServMonitor
{
 private static final Logger logger  = LogManager.getLogger(CucmServMonitor.class.getName())
  public static void main(String[] args)
  {
    logger.error("testing ERROR level");
    logger.trace("exiting application");
    System.out.println(logger.getName());
  }
}

the xml file i am using just now log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
 <configuration status="WARN">
  <appenders>
   <Console name="Console" target="SYSTEM_OUT">
    <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
   </Console>
  </appenders>
 <loggers>
  <root level="debug">
   <appender-ref ref="Console"/>
  </root>
 </loggers>
</configuration>

A: Or... just create a resources directory like src/test/resources and add the log4j.xml file to that dir and then make that directory a source folder.  Then eclipse will automatically copy the file to the the classes dir and there you have it.

A: Manage to figure this one out. The hint was here.
http://pic.dhe.ibm.com/infocenter/wasinfo/v6r0/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftasks-112.htm
I needed to add a "class folder" of where the log4j2.xml was located and then make sure it was at TOP of the list:

Right click on your project and go to properties
Then follow the step shown below. After adding the folder make sure its at the top and then click ok

A: 1) Create the log4j.properties file inside the root folder
log4j.rootCategory=DEBUG, CONSOLE

# Appender writes to console
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=INFO
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n

2) Modify the code like this
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class CucmServMonitor {
    private static final Logger logger = Logger.getLogger(CucmServMonitor.class);
    public static void main(String[] args) {
        PropertyConfigurator.configure("log4j.properties");
        logger.error("testing ERROR level");
        logger.trace("exiting application");
        System.out.println(logger.getName());
    }
}

A: according to Alexis comment, I setup it, but eclipse still can not find log4j2.xml. finally, I solved it by removing the other jars imported, only keep log4j-api and log4j-core. before I imported all the jars downloaded from the Apache website. hope this can help someone.

A: According to Alexis comment, I setup it, but eclipse still can not find log4j2.xml. finally, I solved it by removing the other jars imported, only keep log4j-api and log4j-core. before I imported all the jars downloaded from the Apache website.
I solved my project for log4j->log4j2 version upgrading.


text:
Q: FindViewById on Android Subpage (using Xamarin.Forms) I'm developing a cross-platform app using Xamarin.Forms. As I want to set the background of my TabLayouts to a gradient, which isn't natively supported by XF, I've written a custom renderer for my TabbedPages:
using Android.App;
using Android.Graphics;
using Android.Support.Design.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Xamarin.Forms.Platform.Android.AppCompat;
using MyApp.Droid.Renderer;

[assembly: ExportRenderer(typeof(TabbedPage), typeof(CustomTabbedPageRenderer))]
namespace MyApp.Droid.Renderer
{
    public class CustomTabbedPageRenderer : TabbedPageRenderer
    {
        private Activity _activity;

        protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
        {
            base.OnElementChanged(e);

            _activity = this.Context as FormsAppCompatActivity;
        }

        protected override void DispatchDraw(Canvas canvas)
        {
            base.DispatchDraw(canvas);

            TabLayout tabs = _activity.FindViewById<TabLayout>(Resource.Id.sliding_tabs);

            var gradient = new MyGradient();

            tabs.SetBackground(gradient);
        }
    }
}

Now as intended the renderer gets triggered every time the app loads a TabbedPage.
However, _activity.FindViewById<TabLayout>(Resource.Id.sliding_tabs) always just returns the TabLayout of my MainPage (also properly setting MyGradient as background) and I can't figure out how to get the TabLayout on one of my subpages to modify it as well.
Not sure if this is a problem with Xamarin or Android...
Hope you guys can help me.
Thanks!
Jan
EDIT: here's the styles.xml (I hope that's what @Code-Apprentice was referring to):
<resources>
  <style name="MainTheme" parent="MainTheme.Base">
  </style>
  <!-- Base theme applied no matter what API -->
  <style name="MainTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
    <!--If you are using revision 22.1 please use just windowNoTitle. Without android:-->
    <item name="windowNoTitle">true</item>
    <!--We will be using the toolbar so no need to show ActionBar-->
    <item name="windowActionBar">false</item>
    <!-- Set theme colors from http://www.google.com/design/spec/style/color.html#color-color-palette -->
    <!-- colorPrimary is used for the default action bar background -->
    <item name="colorPrimary">#2196F3</item>
    <!-- colorPrimaryDark is used for the status bar -->
    <!--<item name="colorPrimaryDark">#1976D2</item>-->
    <item name="colorPrimaryDark">#FF8630</item>
    <!--<item name="android:windowTranslucentStatus">true</item>-->
    <!-- colorAccent is used as the default value for colorControlActivated
     which is used to tint widgets -->
    <item name="colorAccent">#FF4081</item>
    <!-- You can also set colorControlNormal, colorControlActivated
     colorControlHighlight and colorSwitchThumbNormal. -->
    <item name="windowActionModeOverlay">true</item>

    <item name="android:datePickerDialogTheme">@style/AppCompatDialogStyle</item>
  </style>

  <style name="AppCompatDialogStyle" parent="Theme.AppCompat.Light.Dialog">
    <item name="colorAccent">#FF4081</item>
  </style>
</resources>

Also a screenshot of the MainPage's top: http://i.imgur.com/VyX3YX7.png
And it's subpage ( MainPage.Navigation.PushAsync(new SubPage()); ): http://i.imgur.com/pRmecjE.png

A:
I do get both TabbedPages in my App just fine (via the renderer), but what I need is the TabLayout (the bar on top that contains the tabs on Android).

If I correctly understand your question this time, you want to customize the tab layout in TabbedPage for each subpage.
Then you will need to override the SetTabIcon method in TabbedPageRenderer. For example:
[assembly: ExportRenderer(typeof(MyTabbedPage), typeof(MyTabbedPageRenderer))]

namespace YourNameSpace.Droid
{
    public class MyTabbedPageRenderer : TabbedPageRenderer
    {
        protected override void SetTabIcon(TabLayout.Tab tab, FileImageSource icon)
        {
            base.SetTabIcon(tab, icon);

            //set your custom layout for tab. The layout resource "mytablayout" is placed in the layout folder of android project.
            tab.SetCustomView(Resource.Layout.mytablayout);
        }
    }
}

You can also check my answer in this question, there I placed a Button in the tab to remove the matching subpage.

A: For anyone else wondering, here's how I get the result I want now (even though I guess it's not the most elegant way of doing this):
using Android.Runtime;
using Android.Support.Design.Widget;
using Android.Views;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Xamarin.Forms.Platform.Android.AppCompat;
using MyApp.Droid.Renderer;

[assembly: ExportRenderer(typeof(TabbedPage), typeof(CustomTabbedPageRenderer))]
namespace MyApp.Droid.Renderer
{
    public class CustomTabbedPageRenderer : TabbedPageRenderer
    {
        protected override void OnVisibilityChanged(Android.Views.View changedView, [GeneratedEnum] ViewStates visibility)
        {
            base.OnVisibilityChanged(changedView, visibility);

            if (visibility == ViewStates.Visible)
            {
                var tabs = changedView.FindViewById<TabLayout>(Resource.Id.sliding_tabs);
                var gradient = new MyGradient();
                tabs.SetBackground(gradient);
            }
        }
    }
}


text:
Q: rails 3 validation of a string hiho
Is there any way to tell rails that my string may not be 'something'?
I am searching for something like
validates :string, :not => 'something'

thanks
klump

A: A couple of ways. If you have exact list of what it can't be:
validates_exclusion_of :string, :in => ["something", "something else"]

If you want to ensure that it doesn't exist as a substring at all:
validates_format_of :string, :with => /\A(?!something)\Z/

If it is more complicated and you want to hide the messy details:
validate :not_something

def not_something
  errors.add(:string, "Can't be something") if string =~ /something/
end

A: Either of these will do the job (click on the methods for documentation):

*

*Probably the best and fastest way, easy to extend for other words:
validates_exclusion_of :string, :in => %w[something]

*This has a benefit of using a regexp, so you can generalise easier:
validates_format_of :string, :without => /\A(something)\Z/

You can extend to other words with /\A(something|somethingelse|somemore)\Z/

*This is the general case with which you can achieve any validation:
validate :cant_be_something
def cant_be_something
  errors.add(:string, "can't be something") if self.string == "something"
end

*To get exactly the syntax you proposed (validates :string, :not => "something") you can use this code (a warning though, I discovered this while reading the master branch of the rails source and it should work, but it doesn't work on my ~ 3 months old install). Add this somewhere in your path:
class NotValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    record.errors[attribute] << "must not be #{options{:with}}" if value == options[:with]
  end
end


text:
Q: MariaDB of XAMPP hanging when trying to add fulltext search for a large table's column I have XAMPP 5.6.15 for Windows which is running 10.1.9-MariaDB. I have a table, InnoDB, with large amount of records and size, 49888 records and 245 MiB size. The main of its size in a column contains text named tafText.
Using PHPMyAdmin, I try to set fulltext search on that column. However, mysqld is hanged and the database server is topped:

The following is a copy of the error log generated after the occurrence of the error:
    2016-10-18 20:49:22 13360 [Note] InnoDB: Online DDL : Start
2016-10-18 20:49:22 13360 [Note] InnoDB: Online DDL : Start reading clustered index of the table and create temporary files
2016-10-18 20:49:22 1d78  InnoDB: Assertion failure in thread 7544 in file row0merge.cc line 892
InnoDB: Failing assertion: b < &block[srv_sort_buf_size]
InnoDB: We intentionally generate a memory trap.
InnoDB: Submit a detailed bug report to http://bugs.mysql.com.
InnoDB: If you get repeated assertion failures or crashes, even
InnoDB: immediately after the mysqld startup, there may be
InnoDB: corruption in the InnoDB tablespace. Please refer to
InnoDB: http://dev.mysql.com/doc/refman/5.6/en/forcing-innodb-recovery.html
InnoDB: about forcing recovery.
161018 20:49:22 [ERROR] mysqld got exception 0x80000003 ;
This could be because you hit a bug. It is also possible that this binary
or one of the libraries it was linked against is corrupt, improperly built,
or misconfigured. This error can also be caused by malfunctioning hardware.

To report this bug, see http://kb.askmonty.org/en/reporting-bugs

We will try our best to scrape up some info that will hopefully help
diagnose the problem, but since we have already crashed,
something is definitely wrong and this may fail.

Server version: 10.1.9-MariaDB
key_buffer_size=16777216
read_buffer_size=262144
max_used_connections=2
max_threads=1001
thread_count=2
It is possible that mysqld could use up to
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 787099 K  bytes of memory
Hope that's ok; if not, decrease some variables in the equation.

Thread pointer: 0x0x0
Attempting backtrace. You can use the following information to find out
where mysqld died. If you see no messages after this, something went
terribly wrong...
mysqld.exe!my_parameter_handler()
mysqld.exe!my_mb_ctype_mb()
mysqld.exe!?set_charset@String@@QAEXPBUcharset_info_st@@@Z()
KERNEL32.DLL!BaseThreadInitThunk()
ntdll.dll!RtlSubscribeWnfStateChangeNotification()
ntdll.dll!RtlSubscribeWnfStateChangeNotification()
The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.

What is the wrong in mysql settings that I have which makes this operation failed?
The following is copy of InnoDB related settings in my.ini:
# Comment the following if you are using InnoDB tables
#skip-innodb
innodb_data_home_dir = "C:/xampp-3/mysql/data"
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = "C:/xampp-3/mysql/data"
#innodb_log_arch_dir = "C:/xampp-3/mysql/data"
## You can set .._buffer_pool_size up to 50 - 80 %
## of RAM but beware of setting memory usage too high
innodb_buffer_pool_size = 256M
innodb_additional_mem_pool_size = 125M
## Set .._log_file_size to 25 % of buffer pool size
innodb_log_file_size = 5M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 50

A: Easy to find with google, if you type the "InnoDB: Failing assertion: b < &block[srv_sort_buf_size]" :)
This bug was reported in https://jira.mariadb.org/browse/MDEV-9129 , fixed in MariaDB 10.1.10. You have 10.1.9, so there it is not fixed.


text:
Q: Owfs.js doesn't see fake device I'm trying to run owfs on my local with fake devices (from owfs.conf) , but have troubles with it. This is my code, which prints empty array
var OwfsClient =  require('owfs').Client;
var owfs = new OwfsClient('127.0.0.1', '4304');

owfs.dir("/",function(err, directories){
    console.log(directories);
})

And it return nothing. In the same time when I do owdir from console I'm getting this
$ owdir
/3A.67C6697351FF
/3A.4AEC29CDBAAB
/3A.F2FBE3467CC2
/3A.54F81BE8E78D
/10.765A2E63339F
/05.C99A66320DB7
/bus.1
/bus.0
/uncached
/settings
/system
/statistics
/structure

Then I'm trying to read device like this
owfs.read("/10.765A2E63339F", function (err, data){
    console.log(err, data);
})

and it outputs
{ msg: 'Communication Error. Received -1',
  header:
   { version: 0,
     payload: 0,
     ret: -1,
     controlflags: 32,
     size: 0,
     offset: 0 },
  options:
   { path: '/10.67C6697351FF',
     command: 2,
     server: '127.0.0.1',
     port: '4304' } }

undefined

Any help appreciated.

A: Did you setup only owfs?
You MUST setup also OWserver
Default: owserver --w1 -p4304
More you can find here:

http://owfs.org/index.php?page=owserver

Sometimes you're also need this - ifconfig lo 127.0.0.1
Also update if not.  works only nodejs srv <= 0.12.8

https://github.com/benediktarnold/owfs


text:
Q: How to make this route parameter working? //jshint esversion:6

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const { redirect } = require("express/lib/response");
const { forEach } = require("lodash");

const homeStartingContent = "Lacus vel facilisis volutpat est velit egestas dui id ornare. Semper auctor neq";
const aboutContent = "Hac habitasse platea dictumst vestibulum rhoncus est pellentesque..";
const contactContent = "Scelerisque eleifend donec pretium vulputate sapien.";
let posts = [];

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

app.get("/", function(req, res){
  res.render("home",{startingContent:homeStartingContent,posts:posts});

})

app.get("/about", function(req, res){
  res.render("about",{aboutContent:aboutContent});
})

app.get("/contact", function(req, res){
  res.render("contact ",{contactContent:contactContent});
})

app.get("/compose", function(req, res){
  res.render("compose");
})

app.post("/compose", function(req,res){
  const post = {
    title:req.body.postTitle,
    content:req.body.postBody
  };
  posts.push(post);
  console.log(posts)
  res.redirect("/");
})

app.get("/posts/:postName",function(req, res){
  const requestedTitle = req.params.postName;
  posts.forEach(function(post){
    console.log(requestedTitle);
    const storedTitle =req.body.postTitle;
    console.log(storedTitle);
    if(storedTitle===requestedTitle){
      console.log("match found");
    }
    else{
      console.log("Not a match");
    }

  });
});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});

I am having issue with  app.get("/posts/:postName",function(req, res){ and  const storedTitle =req.body.postTitle;
The issue is whenever I run http://localhost:3000/posts/Test in browser I am suppose to get output as match found but when I console log storedTitle to debug  I get it as undefined istead of Test.
output screenshot:
output image
These are pictures of /compose ejs file.
compose.ejs

A: Instead of const storedTitle =req.body.postTitle; you should use const storedTitle = post.title;

A: You get undefined in log because, of the following lines:
const storedTitle =req.body.postTitle;
console.log(storedTitle);

Because, GET requests does not have body.
Change those lines as follows:
const storedTitle = post.title;
console.log(storedTitle);

I suppose it is a copy/paste error from /compose handler :-)
Good day!

A: You cannot use req.body in a GET request
It should either use POST
app.post("/posts/:postName",....
or
const storedTitle =req.query.postTitle;


text:
Q: Clear used RAM for Tkinter TEXT widget In my GUI I create a ttk.notebook and then put Text widgets into each tab and dump logs/info into these Text widgets. If the process is restarted with a new set of log files I .forget() the old tabs and then create the new ones. I've noticed that the ram used from the original Text widgets is not cleared when I do this. How can I free this ram?
Example:
from tkinter import *
from tkinter.ttk import Notebook
main = Tk()
def maker():
    nb = Notebook(main, name='nbook')
    nb.grid(row=0, column=0, columnspan=2)
    frame1 = Frame(name='frame1')
    txt = Text(frame1, wrap=NONE)
    txt.grid()
    nb.add(frame1, text='textwindow')
    txt.insert('end', 'hello\n' * 1000000)

def remover():
    print(main.winfo_children())
    for tab in main.children['nbook'].tabs():
        main.children['nbook'].forget(tab)
    print(main.winfo_children())

b1 = Button(main, text='Insert', command=maker)
b1.grid(row=1, column=0)
b2 = Button(main, text='Clear tabs', command=remover)
b2.grid(row=1, column=1)
main.mainloop()

In the example, when you click "Insert" it creates the widget and dumps a bunch of text into it. If you call remover with the "Clear tabs" button it forgets all tabs but the ram used by that text is never free. Even if you destroy the text widget the ram is not released. How can I free this up?

A: Text.delete('1.0', END)
Text.edit_reset()

Will clear the history of the Text widget, so call this after delete.
Hope this solves your problem

A: Destroying entire (set of) widget(s) when you only need to configure one of their attributes sounds like a very poor design, and such practice is notorious for resulting in pricey memory leaks, as you have already seen.
In any case, I reckon you would be much better off by simply configuring the widgets you already have, as opposed to destroying/recreating them when the changes are due.
From what I've been able to comprehend, you said you need to frequently display some text (namely, logs?) in the Text widget, so why not just clear the text you already have and insert the new one into the widget:
txt.delete('1.0', 'end') # clearing the text widget
txt.insert('end', my_log) # inserting the log into the text widget

A: I later found that just doing a .forget() on the tabs does not get rid of the memory used by the widgets. This may be because they are referenced somewhere else but I couldn't find the source. If I .destroy() the widgets from the tab before doing the .forget() on the tab itself then the memory is eventually freed by garbage collector. For my situation, running a new set of logs through the tool reuses the currently used memory and the extra(if any) is freed after it sits for a bit.


text:
Q: Symfony Webpack Encore advanced/custom configuration I'm thinking about using Webpack Encore in a new Symfony 5 project, I'd like to know if it possible to do the following:

*

*Use symfony config parameters (for isntance from config/services.yaml or other yaml file) into webpack.config.js

*Some users will define some CSS configuration (for instance text-size, some colors, etc...), internally these values will be stored in a database. Is it possible to read/use these values from database as values in LESS (or SASS) variables?
Thanks!


text:
Q: [golang]Is it possible to write TLS server without certificate? From client I already have tls config which sets InsecureSkipVerify to true. How to write server for this client which take any cert.
Can tls.config help in server too? like setting InsecureSkipVerify to true?

A: No, as @JimB told you, TLS can't work without certificates.
The reasoning is simple: TLS is all about security, and certificates
are cryptographic keys which provide that security (TLS uses a so-called
"asymmetric cryptography" where each party has a key pair consisting of
a private and public parts; the public part is what get sent to another party
when doing a TLS handshake).
But on the other hand the security TLS provides is two-fold:

*

*It provides mutual authentication of the parties participating in the
exchange.

*It provides encryption of the transmission channel¹.

Certificates are used for both aspects: the fact they contain cryptographic keys is used for (2), and the fact they have owner's identity encoded
in them (and verified by whoever was issued a particular cercificate)
is used for (1).
Let me not digress into discussing how (1) works in detail
(though I truly urge you to read some theory on it) but (1) is what
you actually want to sidestep.
The good (for you) thing is that it's cheaply doable:

*

*The TLS clients can be told to not verify the server's identity.

*The TLS servers can be told to do the same (and often it's the default
mode they operate in—which is typical for regular websites
for instance).

*You can create a so-called self-signed certificate for your TLS
server.

The latter requires nothing but something which is able to generate
X.509 certificates; OpenSSL is typically used for this;
just google for it.
If you're on Debian or Debian derivative (like Ubuntu, Mint etc)
consider installing the ssl-cert package and using
the make-ssl-cert program it provides.

¹ To be precise, they only protect the very initial phase of the exchange during which the parties generate and send to each other keys used for symmetric encryption, which are then used to encrypt the communication channel, and are regenerated (and re-exchanged) periodically. This is done because symmetric algoritms are way faster.


text:
Q: How to exclude bounding boxes of plots in lascatalog I have 96 1 ha (200m by 50 m) plots that I collected TLS data (each file separate). Most of the plots are close to each other and therefore they have overlapping bounding boxes (point clouds don't overlap themselves). I would like to calculate some grid metrics for all 96 plots using lidR package.
ctg <- readLAScatalog("infolder", filter = "-drop_z_above 1.3 -drop_class 2", chunk_size = 0,
                      chunk_buffer = 0)
opt_chunk_size(ctg) <- 0
opt_chunk_buffer(ctg) <- 0
opt_output_files(ctg) <- "outfolder/{ORIGINALFILENAME}"
summary(ctg)

hmean <- grid_metrics(ctg, mean(Z), 0.1)

Since I am giving chunk size of 0, catalog class considering bounding boxes as tiles and calculating metrics based on the bounding boxes. For this reason, I am getting raster image of a file which also includes part of neighboring image. Also, following warning message from R also referred to this problem.
Be careful, some tiles seem to overlap each other. lidR may return incorrect outputs with edge artifacts when processing this catalog.

If I want to make small chunks, size of 10m, lidR gives warning:
Be careful, a chunk size smaller than 250 is likely to be irrelevant.
Be careful, some tiles seem to overlap each other. lidR may return incorrect outputs with edge artifacts when processing this catalog.

How to calculate grid metrics for each file separately in my case?

A: The default behavior of lidR is to work by chunk or region of interest in such a way that the extent of the collection is covered by the chunks and that the output is a wall-to-wall output. You have perfectly understood the problem. Your files are too close to each other so it loads a portion of the neighbors that overlap the bounding box.
Your idea of using buffer = 0 + chunk = 0 is correct but does not actually works because you want to process strictly independent files. In short you want to loop through files. The problem is that the package is designed to processed non-independent files and to produce a continuous wall-to-wall output.
You can use
opt_independent_file(ctg) <- TRUE

This will set buffer = 0, chunk = 0  and disable wall-to-wall guarantees. This is equivalent to
opt_chunk_size(ctg) <- 0
opt_chunk_buffer(ctg) <- 0
opt_wall_to_wall(ctg) <- FALSE

But yet it won't work because grid_metrics does not respects the buffer (this is mentioned in the doc) and always adds a small buffer to guarantee a strict wall-to-wall output. Your case was not actually planned and must be fixed internally. This will be improved in next release (v3.0.2).
Thus your last option (waiting next release) is to loop manually. No buffer, by file, no wall-to-wall guarantees make the engine being a regular loop actually.
for (file in ctg$filename)
{
   las = readLAS(file, filter = "-drop_z_above 1.3 -drop_class 2")
   m = grid_metrics(...)
   writeRaster(m, ...)
}


text:
Q: Replicating Mac "drag and drop" behaviour in Windows On a Mac computer, when dragging a file or folder from a Finder window to an application's modal file selection window, the modal window navigates to the location of the dragged file or folder, and that file or folder is selected.
On a Windows computer, when dragging a file or folder from an Explorer window to an application's modal file selection window, the behaviour can be configured to copy, move or shortcut creation, but no similar functionality to the Mac behaviour exists. Is there any software to allow for this behaviour on Windows?
Thanks.


text:
Q: Throwing null in Java Working on Android I bumped into something like this:
    try {
         return someMethodThatThrowsExceptionA();
        } catch (ExceptionBthatExtendsExceptionA e) {
            // e is null but caught here.
        } catch (ExceptionA e) {
            // e is also null when caught.
        }
    }

While I still need to dig out the reasons why the exception is thrown inside many method calls, there are two very surprising things here for me:

*

*The Exception is caught, but somehow is null. As per A and B , I thought that throwing null was impossible.

*The Exception is catched by a catch block for a Subclass of the Exception that the method throws ( ExceptionBthatExtendsExceptionA ).

If I remove the catch block for ExceptionBthatExtendsExceptionA, the Exception is caught by the ExceptionA catch block, but is also null.
Could you explain me

*

*How a method is throwing null without creating a NullPointerException? ----> Not possible as per Java's specification.

*How is a null Exception correctly catched (casted?) to a specific catch block? How can can the catch block recognize that null is an instance of a Subclass and not of its parent Class? ----> Same as question before.

*Are these allowed Java behaviors or is this maybe a bug related to Android Studio or Dalvik / ART? ----> Possibly.

Edit:
It seems that this is a bug for the debugger in Android Studio 1.4.
After debugging and testing with different devices I've found this:

*

*The error doesn't happen when not debugging the app.

*It also doesn't present when debugging or not on Lollipop devices.

*It has only been present when debugging 4.3 or 4.4 devices so far, if I unplug the device, the app behaves as expected.

As more information for the implementation, the try/catch block described before is inside an AsyncTask's doInBackground(), and someMethodThatThrowsExceptionA() is a method constructs a query and calls internally a method that executes a Fusiontables.Query.Sql and throws ExceptionA , in this case IOException and it's subclass UserRecoverableAuthIOException (ExceptionBthatExtendsExceptionA) , so Http communications happen inside.
Also, when I try to catch the error inside someMethodThatThrowsExceptionA(), sometimes the Exception catched is not null, but it always ends up being null when I throw it again and catch it in the catch block of method that called someMethodThatThrowsExceptionA().
Since the Exception is correctly interpreted as an instance of UserRecoverableAuthIOException (ExceptionBthatExtendsExceptionA) and the code enters into its corresponding catch block, the bug has to be happening after this and before the debugger figures out the value of the exception inside the block.


text:
Q: Is it possible to make a binding in a menu control using list? I made a style for my menu control and now I want to use that style for all the menuItems, but with different text in the textbox. I was wondering if I can use a List to populate the binding element...I tried but it doesnt work...Have I missed something or I have to use something else?
  List<string> itemArray = new List<string>();
        itemArray.Add("label1");
        itemArray.Add("label2");
        itemArray.Add("label3");
        Binding binding = new Binding();
        binding.Path = new PropertyPath("itemArray");

       this.menu1.SetBinding(TextBox.TextProperty, binding);

and the one part of the style is, if it helps...:
 <Setter.Value>
    <ControlTemplate TargetType="{x:Type MenuItem}">
        <Grid>
            <Border Name="MainBorder" BorderThickness="2,2,2,0" >
                <Grid>
                    <TextBlock Text="{Binding Path=itemArray}" Margin="30,10,0,0" FontFamily="Arial" FontSize="14" FontWeight="Bold" />
                    <Image Width="15" Height="15" Source="image.PNG" Margin="-100,0,0,0" />
                </Grid>
            </Border>
        </Grid>
    </ControlTemplate>
</Setter.Value>

A: You're trying to bind a text element to a List<T>, which will result in the type name. If you want the menu to populate itself from a list of objects, consider binding the menu's ItemsSource property to that list:
     <Menu ItemsSource="{Binding ListOfItems}">
        <Menu.ItemTemplate>
           <DataTemplate>
              <MenuItem Header="{Binding Text}" Command="{Binding Command}" />
           </DataTemplate>
        </Menu.ItemTemplate>
     </Menu>

In this example, each list item is an object with a Text property which shows up as the display string, and a Command property, which is an object that implements ICommand. When the user chooses a menu item, that list item's Command.Execute method is invoked; you could use something like RelayCommand or ReactiveCommand to turn that into a method call.
This allows for a flat menu; for a hierarchical menu you'll have to do something a little different.


text:
Q: Model Data Reduction in OpenGLES2.0 for Android I had this idea, and I don't know enough about VBOs and FloatBuffers to know if it is valid. In an attempt to reduce data in my program, I had the idea to hold face data as a single string, and break it up with String.split("/") when rendering. This would remove all redundant vertices from my data, just as a WaveFront .OBJ file does. I figure that it will only slow down the GPU a little each time it draws a face, while greatly reducing my model sizes. However, VBOs and FloatBuffers, both packed and unpacked, take a consistent array of vertex data, represented in a single float[]. It seems that OGLES2.0 wants ALL the data in one buffer, in order. So, my idea doesn't seem to be holding up.
ex:
With redundancies:
Buffer = { x1, x2, x3... x30,000 }
(Draw all faces in order, all at once)
Without:
Buffer = { x1, x2, x3... x1,000 }
fData[x] = "x/x/x x/x/x x/x/x"
(Draw each face according to the references in fData[x], one at a time)
My questions are as follows:

*

*Is it ever appropriate to leave out redundant vertices in your buffers and use the .OBJs fData to assemble the faces when rendering? Why or why not?

*If not, what are my limits? I have a model with about 1,000 vertices before redundancies are added. Can a VBO or FloatBuffer handle that many vertices (with redundancies) in Android? Roughly how many of these models could I render at once before I run out of memory?

*If so, how do you suggest I let OGLES2.0 know where my data is in the buffer for each face? Buffer.setPosition(x)?

*What are the generally accepted methods of model storage in Android and other flavors of OpenGL? How would YOU store each model in order to reduce the amount of data to the smallest size possible?
Thanks for the help in advance.
Edit: 5. Would glDrawElements solve my problem? Right now I'm using glDrawArrays. I just read a post somewhere that led me to believe that glDrawElements is better when redundant vertices exist. Is this correct?

A: I found what I was looking for. The answer was, indeed, to use glDrawElements. With glDrawElements, you assign unique vertices to a FloatBuffer or VBO, then assign face data to a FloatBuffer or VBO. glDrawElements takes these two Buffers and does the work for you.
float vertsCoords[] = {0.5f, 0.5f, 0.5f,          //V0
                                  -0.5f, 0.5f, 0.5f,           //V1
                                  -0.5f, -0.5f, 0.5f,         //V2
                                   0.5f, -0.5f, 0.5f,         //V3
                                   0.5f, -0.5f, -0.5f,       //V4
                                   0.5f,  0.5f, -0.5f,       //V5
                                  -0.5f, 0.5f, -0.5f,       //V6
                                  -0.5f, -0.5f, -0.5f,     //V7
                    };
GLubyte indices[] = {0, 1, 2, 3,              //Front face
                            5, 0, 3, 4,             //Right face
                            5, 6, 7, 4,             //Back face
                            5, 6, 1, 0,             //Upper face
                            1, 6, 7, 2,              //Left face
                            7, 4, 3, 2,             //Bottom face
                  };

glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, vertsCoords);
glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, indices);

indices[] = fData[] and vertCoords[] = vData!
Taaadaaa!
Edit: I just found this very, very dissapointing news and figured I'd share it with y'all;
Quoted from gamedevs.net. "_Walrus" says,
If you are reducing shared verticies from your draw array method(i.e, removing redundant verticies) then you will run into problems cause you wont beable to specify multiple texCoords to that one vertex. I guess this is easier to explain with a cube. with a cube, a vertex is repeated 3 times (i.e., the corner). So each face of the cube will have the exact same vertex (geometrically speaking), but each face may have a different tex Coord. When u reduce the reducency when moving to index list then you run into the problem of multiple tex coord for one vertex. Opengl Doesnt support multiple texCoord for one vertex (with respect to index list), nor does it with any other array (ie., normals, colors...). So i guess the rule is: when decimating ur geometry, only remove redunant verticies that share, normals, position, texCoord..etc.
=(


text:
Q: Can't getElementById (HTMLDOM object is supposedly null). Where am I messing up? So I've been stuck on this for a bit...
I have an HTML page with a div element and an inline frame (iframe):
<!DOCTYPE html>
<meta charset="UTF-8"><link rel="stylesheet" type="text/css" href="/GLS_DBSearchProject/resources/css/GLS_DBSearchMainStyle.css">

DEBUG-OUTPUT

<?php

The div is simply there as a box that I made for testing as I get comfortable with JavaScript. The iframe houses a separate .php page "index.php". The HTML for "index.php" is entirely generated by the functions in this php code:
class UserInterface {
var $ParentAppInstance;

function __construct($AppInstance){
    $this->ParentAppInstance = $AppInstance;
    $this->DrawPageHTML();
    $this->DrawDBSetDropdown();
    $this->DrawAdvancedSearchBar();
}

//Override this function to change the HTML and PHP of the UI page.
protected function DrawPageHTML(){

    echo '

    ';

    echo '$AppInstanceData: ' . '
';
    echo '--CurrentDBSet_Str: ' . $this->ParentAppInstance->CurrentDBSet_Str;
}

protected function DrawDBSetDropdown(){
    echo '
';
        echo '<select onchange="SwitchDatabaseSet(this.ownerDocument)" name="DBSetList" form="DBSetSelector">';
        $i = 0;
        foreach ($this->ParentAppInstance->DBSets_Arr as $DBSet){
            if($DBSet->DBSetName == 'DBSet0'){/* DO NOTHING. IE. IGNORE IT*/}
            else{
                $i++;
                echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
            }
        }
        echo '</select>';
    echo '
';

}

In the DrawDBSetDropdown() function of the UserInterface class, I am drawing a selection box with variable options. Whenever the user changes the state of this selector, I'm calling the SwitchDatabaseSet() javascript function with the HTML DOM object of "index.php".
Up to this point, everything seems to work fine. Here's where things get weird:
function JSTEST(){
window.alert("JS Called Successfully!!");
}

function SwitchDatabaseSet(MainPageDoc){
    window.alert(null === MainPageDoc);//1.
    window.alert(MainPageDoc.domain);//2.
    MainPageDoc.getElementById("DebugOutput").innerHTML = "Test";//3.
 }

*

*Result: false. MainPageDoc is not null.

*Result: localhost. As expected the page is running on localhost. Notably, MainPageDoc != null.

*Suddenly MainPageDoc supposedly equals null; as I get the following Error:

Uncaught TypeError: Cannot set property 'innerHTML' of null

*document.getElementById() produces an identical result.
I'm trying to change the text of the DebugOutput
, but it's not working because of the issue above.
In 1. and 2. both indicate that MainPageDoc isn't null, so why am I getting the error at 3. ? What am I doing wrong here?

A: I don't think this is actually possible to do, and I may be wrong, but here is why:
It is possible, see second edit.
index.php generates an html webpage (let's call that "index_html")
The  tag to implement UserInterface.js is implemented within "index_html".
Therefore: document.getElementById("DebugOutput") and MainPageDoc.getElementByID("DebugOutput") are effectively identical, and they return null because they are both looking for an element with id="DebugOutput".
This
 is implemented in the first bit of HTML code that I provided <call that "true_index.html">, and not index_html. Therefore, both statements return null as described here.
Edit: I don't think it is possible to edit an HTML element in a parent HTML document from JavaScript that is contained within an iframe. I'll report back after I dig into this some.
Edit: This pretty much sums up the issue, was easy to find once I knew what I was looking for.


text:
Q: Row Labels for SlickGrid Is there a way to add row labels to slick grid?
I guess worst case, I could make a static first column but I was thinking there might be something built-in?

A: Basically what you need is just a column which you can style and format as you wish with your label content, but the functionality that is currently missing from SlickGrid is support for fixed/frozen columns.  There are some forks that have attempted to implement it, but the implementation is incomplete.


text:
Q: Google App Engine JDO persistence with HashMap child field I have a parent class and I want to store a HashMap within it. However, every time I try to modify that HashMap I get the following error:
PM org.datanucleus.store.appengine.MetaDataValidator checkForIllegalChildField
WARNING: Unable to validate one-to-many relation com.monsters.server.MonUser.monsters
Any idea what that's about? Here is the code:
This is the code to the Parent class
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable="true")
public class MonUser {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;

    @Persistent(serialized="true", mappedBy = "owner")
    @Element(dependent = "true")
    private HashMap<String,Monster> monsters;

...
@PersistenceCapable(identityType = IdentityType.APPLICATION, detachable="true")
public class Monster {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;

    @Persistent
    private MonUser owner;

...
I've tried everything on the appengine page on relationships and nothing seems to help. Any info would be extremely helpful!
P.S. I've gotten it to work with ArrayLists and the like but not hashmaps, hashtables, maps, etc. If that helps at all.

A: Only the following Collections are supported by JDO:

*

*java.util.ArrayList<...>

*java.util.HashSet<...>

*java.util.LinkedHashSet<...>

*java.util.LinkedList<...>

*java.util.List<...>

*java.util.Set<...>

*java.util.SortedSet<...>

*java.util.Stack<...>

*java.util.TreeSet<...>

*java.util.Vector<...>

A: You can persist a HashMap with:
@Persistent(serialized = "true", defaultFetchGroup="true")
see JDO - HashMap within an embedded Class
To ensure persistence of changes you need to always create a new instance of HashMap see the end of:
http://gae-java-persistence.blogspot.de/2009/10/serialized-fields.html


text:
Q: Awk script to loop and perform mathematical operations I have bash and awk script that I use to extract data from the text file.
However it is too slow with large datasets and doesn't work perfectly. I believe that it is possible to write all my bash loop in one awk command and I ask somebody to help me with this.
cat dummy_list
    AAA
    AAAA
    AAAAA

cat dummy_table
    13   19   AAA   69   96   "ID-999"   34
    23   42   AAA   12   19   "ID-999"   64
    53   79   AAA   43   58   "ID-482"   36
    13   43   AAA   12   15   "ID-492"   75
    23   90   AAA   45   87   "ID-492"   34
    12   41   AAAA   76   79   "ID-923"   23
    19   58   AAAA   15   87   "ID-923"   75
    10   40   AAAA   18   82   "ID-482"   23
    11   18   AAAA   18   82   "ID-482"   52
    15   19   AAAA   18   82   "ID-482"   62
    59   69   AAAA   10   18   "ID-482"   83
    78   89   AAAA   32   41   "ID-983"   24
    23   53   AAAAA  78   99   "ID-916"   82

What I want from this table:

*

*For every dummy_list item (AAA or AAAA or AAAAA) extract how many different times ID range was mentioned ( by this I mean unique columns 4+5+6 (like 69   96   "ID-999")). There are duplicate ID's (like 18   82   "ID-482") and I have to discard them.
My script looks like this:
while read a; do
    awk -v VAR="$a" '($3==VAR) {print $4"\t"$5"\t"$6}' dummy_table |
    sort -u |
    cut -f 3 |
    sort |
    uniq -c |
    awk '{print $1}' |
    tr '\n' ' ' |
   awk -v VAR="$a" '{print VAR"\t"$0}'
done < dummy_list

AAA     1 2 2
AAAA    2 2 1
AAAAA   1

It's the same as AAA "ID-482" mentioned once; "ID-492" mentioned twice; "ID-999" mentioned twice.
This is the output I want.

*For every dummy_list item get average number of how many times it gets mentioned with the same ID. For example AAA occurs twice with "ID-999", one time with "ID-482" and two times with "ID-492" - so it's (2+1+2)/3=1.66
My script looks like this:
while read a ; do
    ID_TIMES=$(awk -v VAR="$a" '($3==VAR) {print $6}' dummy_table |
       sort -u |
        wc -l) &&
    awk -v  VAR="$a" '($3==VAR) {print $6}' dummy_table |
    sort |
    uniq -c |
    awk -v VAR="$ID_TIMES" '{sum+=$1} END {print sum/VAR}'
done < dummy_list

AAA   1.666
AAAA  2.333
AAAAA 1

*For every dummy_list item extract ID range and calculate proportion between columns.
For example:
for AAA's ID-999:
    RANGE1=sum $5-$4(96-69) + $5-$4(19-12)
    RANGE2=sum $7(34+64)
    then RANGE2*100/RANGE1=288
For the output like this:
AAA 288 240 242
....
AAAAA 390

I wasn't able to write such script by myself as I got stuck with two variables $RANGE1 and $RANGE2.
If it it possible it would be great to discard duplicate ranges like 18   82   "ID-482" in this step as well.
I believe that all these there operations can be calculated with only one awk command and I feel desperate about my scripts.  I really hope that someone will help me in this operation.

A: You can try this.
file a.awk:
BEGIN {

    # read list of items

    while ( ( getline < "dummy_list" ) > 0 )
    {
        items[$1] = 0
    }
}

{
    # calculate ammountof uniqur ids

    key = $3 SUBSEP $6

    if ( ! ( key in ids ) && ( $3 in items ) )
    {
        unique_ids[$3] += 1
    }

    # calculate ammount of duplication

    ids [$3,$6] += 1

    # calculate range parameters

    range1 [$3,$6] += $5 - $4
    range2 [$3,$6] += $7
}

END {

    for ( item in items )
    {
        print "--- item = " item " ---\n"

        for ( key in ids )
        {
            split ( key, s, SUBSEP );

            if ( s[1] != item ) continue;

            range = range2[key] * 100 / range1[key]

            average[item] += float ( ids[key] ) / unique_ids[item];

            print "id = " s[2] "\tammount of dup = " ids[key] "  range = " int ( range )
        }

        print "\naverage = " average[item] "\n"
    }
}

run:
awk -f a.awk dummy_table
output:
--- item = AAAA ---

id = "ID-983"   ammount of dup = 1  range = 266
id = "ID-923"   ammount of dup = 2  range = 130
id = "ID-482"   ammount of dup = 4  range = 110

average = 2.33333

--- item = AAAAA ---

id = "ID-916"   ammount of dup = 1  range = 390

average = 1

--- item = AAA ---

id = "ID-999"   ammount of dup = 2  range = 288
id = "ID-482"   ammount of dup = 1  range = 240
id = "ID-492"   ammount of dup = 2  range = 242

average = 1.66667

There is one moment - I can't understand how you got 225
for "ID-482" and item AAA in question #3.
RANGE2 * 100 / RANGE1 = 36 * 100 / ( 58 - 43 ) = 240.

Are you sure, that your example on question #3 is correct?

A: Only a partial answer but here is a one-liner solution for your first problem:
  awk -F'   ' '{group[$3]++;ind[$6]++};{count[$3][$6]+=1}; END{for (i in group){for (j in ind) if(count[i][j] > 0) print i, j, count[i][j]}}' dummy_variable.txt

Output:
AAA "ID-482" 1
AAA "ID-999" 2
AAA "ID-492" 2
AAAA "ID-923" 2
AAAA "ID-482" 4
AAAA "ID-983" 1
AAAAA "ID-916" 1

It is then fairly trivil to use this output to calculate the answer to your second question.


text:
Q: Django: No module named apps The module django.apps cannot be found. It is a module normally included in Django, therefore I don't understand where this error comes from.
This happens after installing djangorestframework and adding this line:
from rest_framework import routers, serializers, viewsets

The CLI output shows that Django version 1.6 is detected:
In [1]: from django.apps import apps
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-380cc652af3e> in <module>()
----> 1 from django.apps import apps

ImportError: No module named apps

In [2]: import django

In [3]: django.VERSION
Out[3]: (1, 6, 11, 'final', 0)

Full exception:
Request Method: GET
Request URL:    http://www.somedomain.com/
Django Version: 1.6.11
Exception Type: ImportError
Exception Value:
No module named apps
Exception Location: /usr/local/lib/python2.7/dist-packages/rest_framework/utils/model_meta.py in <module>, line 11
Python Executable:  /usr/bin/python
Python Version: 2.7.6
Python Path:
['/home/ubuntu/workspace/djangoserver',
 '/home/ubuntu/workspace/djangoserver',
 '/home/ubuntu/lib/python/site-packages',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PILcompat',
 '/usr/lib/python2.7/dist-packages/gtk-2.0',
 '/usr/lib/pymodules/python2.7']
Server time:    Thu, 26 Nov 2015 13:25:42 +0000

A: It's right there in the Django docs, in bold, at the top:

New in Django 1.7.

From your question:
Django Version: 1.6.11


text:
Q: Regex match literal containing substring anywhere in input I'm a little bit confused with regular expressions, while I'm trying to match literal(string) in input, but the input can have substring in wanted literal.
For better understanding:
regex foobar
input this is fooXbar
wanted match fooXbar
Basically the question is, if it is possible to specify 'X' can be anywhere in input string or if I have to do this:
ugly regex: fX?oX?oX?bX?aX?r

A: Yes, you have to list X? explicitly.
Also note that you did not include X? after r, which means that X? does not apply to all positions.

A: you can add the X? using other tools, for example
 grep -oE "$(echo foobar | sed 's/./&X?/g')" file

will match fooXbar and other versions


text:
Q: Nginx 2 locations to serve files differently configuration I hope this finds you well. My tech stack is Nginx, React, PHP and MySQL. I want to have all requests on the browser point to index.html so react-router doesn't give me a blank page, so I don't need to use hashing in the URLS (e.g. /#/test, /#/greeting). Adding to this, I also want to be able to call simple php files located in /controllers through ajax calls. Is this possible given my setup?
example.com.conf
Location / {
    try_files $uri $uri/ /index.html
    root /var/www/html/example/dist;
    index index.php index.html index.htm index.nginx-debian.html
}

Location /controllers {
    root /example;
    try_files $uri =404;
}

Folder Structure
-var
----html
-------example
----------dist
----------controllers

A: At first I am not sure about you Folder structure, because you have in your config /var/www/html... and in the Folder structure block /var/html..., so I assumed you have /var/www/html....
The below nginx config file should work, but I don't have tested it. Maybe you need to adjust some values a little bit (e.g. root of the php location block).
server {
    listen 80;
    server_name example.com;
    server_tokens off;

    root /var/www/html/example/dist;

    index index.html index.php;

    location / {
        try_files $uri $uri/ /index.html?$query_string;
    }

    location /controllers {
        root /var/www/html/example;
    }

    location ~* \.(php|phtml)$ {
        root /var/www/html/example;
        fastcgi_index           index.php;
        fastcgi_pass            unix:/run/php/php7.4-fpm.sock;
        include                 /etc/nginx/fastcgi_params;
        fastcgi_param           SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param           SCRIPT_NAME $fastcgi_script_name;
        fastcgi_read_timeout    30000;
    }
}

Additional:
It should be one primary root folder and then for specific use cases root definitions within a location block: Nginx Wiki


text:
Q: StringBuffer find 'start' and 'end' and write anything between them StringBuffer find 'start' and 'end' and write anything between them
example:
text1
text2
start
text3
text4
end
text5

can i just print out of StringBuffer text3 and text4' Text that is between 'start' and 'end'

A: Assumming you have a StringBuffer sb that already contains the text:
int start = sb.indexOf("start");
int end = sb.indexOf("end");
if (start != -1 && end != -1) {
    String fragment = sb.substring(start + "start".length(), end);
    System.out.println(fragment);
}

Note that this finds text between "start" and "end" as you asked for in your question. However if the text in the StringBuffer has line breaks, you might actually want to search for text between "start\n" and "end\n".

A: use indexOf(String str) method to find out the index of start & end
Doc


text:
Q: Return with await when wrapping old async pattern into TaskCompletionSource? I am studying C# Asnc-await pattern and currently reading Concurrency in C# Cookbook from S. Cleary
He discusses wrapping old non TAP async patterns with TaskCompletionSource (TCS) into TAP constructs.
What I dont get is, why he just returns the Task property of the TCS object instead of awaiting it TCS.Task ?
Here is the example code:
Old method to wrap is DownloadString(...):
public interface IMyAsyncHttpService
{
    void DownloadString(Uri address, Action<string, Exception> callback);
}

Wrapping it into TAP construct:
public static Task<string> DownloadStringAsync(
    this IMyAsyncHttpService httpService, Uri address)
{
    var tcs = new TaskCompletionSource<string>();
    httpService.DownloadString(address, (result, exception) =>
    {
        if (exception != null)
            tcs.TrySetException(exception);
        else
            tcs.TrySetResult(result);
    });
    return tcs.Task;
}

Now why not just do it that way:
public static async Task<string> DownloadStringAsync(
    this IMyAsyncHttpService httpService, Uri address)
{
    var tcs = new TaskCompletionSource<string>();
    httpService.DownloadString(address, (result, exception) =>
    {
        if (exception != null)
            tcs.TrySetException(exception);
        else
            tcs.TrySetResult(result);
    });
    return await tcs.Task;
}

Is there a functional difference between the two? Is the second one not more natural?

A:
By marking it async, the compiler will generate warnings, that it should be considered to await this method

You don't have to mark your own method as async in order to get the "Task not awaited" warning. The following code generates the same warning for the calls to both T and U:
static async Task Main(string[] args)
{
    Console.WriteLine("Done");
    T();
    U();
    Console.WriteLine("Hello");
}

public static Task T()
{
    return Task.CompletedTask;
}

public static async Task U()
{
    await Task.Yield();
    return;
}

Whenever you find yourself with a method only containing a single await and that being the last thing it does (except possibly returning the awaited value), you should ask yourself what value it's adding. Aside from some differences in exception handing, it's just adding an extra Task into the mix.
await is generally a way of indicating "I've got no useful work to do right now, but will have when this other Task is finished" which of course isn't true (you've got no other work to do later). So skip the await and just return what you would have awaited instead.

A: Your version is strictly more complex -- instead of just returning the task, you make the method async, and await the task you could just be returning.

A: There is one subtle practical difference (other than the version with await being slower to run).
In the first example, if DownloadString throws an exception (rather than calling the delegate you pass it with exception set), then that exception will bubble through your call to DownloadStringAsync.
In the second, the exception is packaged into the Task returned from DownloadStringAsync.
So, assuming that DownloadString throws this exception (and no other exceptions occur):
Task<string> task;
try
{
    task = httpService.DownloadStringAsync(...);
}
catch (Exception e)
{
    // Catches the exception ONLY in your first non-async example
}

try
{
    await task;
}
catch (Exception e)
{
    // Catches the exception ONLY in your second async example
}

You probably don't care about the distinction - if you just write:
await httpService.DownloadStringAsync(...);

you won't notice the difference.
Again, this only happens if the DownloadString method itself throws. If it instead calls the delegate you give it with exception set to a value, then there is no observable difference between your two cases.

A: Folks, thanks for the helpful comments.
In the meantime I have read the sources referenced here and also investigated the matter further: Influenced by https://blog.stephencleary.com/2016/12/eliding-async-await.html I have come to the conclusion, that its best practice to include async-await by default even in synchronous methods of the async function chain and only omit async await when the circumstances clearly indicate that the method will not potentially behave differently as expected from an async method en edge scenarios.
Such as: the synchronous method is short, simple and has no operations inside which could throw an exception. If the synchronous method throws an exception the caller will get an exception in the calling line instead of the line where the Task is awaited. This is clearly a change from expected behavior.
For example handing over call parameters to the next layer unchanged is a situation which imo permits omitting async-await.

A: Read my answer why returning the task is not a good idea: What is the purpose of "return await" in C#?
Basically you break your call stack if you don't use await.


text:
Q: remove item from formBuilder When executing formBuild.group I am creating two values that I use only for validations, these two values do not want to save in the database, I would remove them before saving in the database.
profile.component.ts:
profileForm: FormGroup;
constructor(){
    this.profileForm = this.createPerfilForm();
 }

createProfileForm() {
    return this.formBuilder.group({
        id: [this.perfil.id],
        name: [this.perfil.name, [Validators.required, Validators.minLength(5), Validators.maxLength(45)]],
        email: [this.perfil.email, [Validators.required, Validators.email]],
        password: [''],
        passwordConfirm: ['', [confirmPassword]],
    });
}

saveProfile(){
     // I need to remove here password and passwordConfirm
     //before saving to the database
     this.authService.updateProfile(this.profileForm.value);
}

I need to remove this.profileForm.value from the password and passwordConfirm values, since I do not want to save these values in the database.

A: saveProfile(){
     // I need to remove here password and passwordConfirm
     //before saving to the database
     let copy = { ... this.profileForm.value };
     delete copy.password;
     delete copy.confirmPassword;
     this.authService.updateProfile(copy);
}

try this?

A: Make a new object with only what you need:
 this.authService.updateProfile({id: this.profileForm.value.id,
           name: this.profileForm.value.name, email:this.profileForm.value.email })


text:
Q: Invoke a method in Singleton class using reflection in java I have a following class:
Public class ABCinfo {
    private static ABCinfo instance = null;
    Public static ABCinfo getInstance(Param param); // get instance
    Private ABCinfo(Param); // making a Singleton class
    Public void methodA(Param1 param1); // need to invoke this method
}

using reflection in java, how can i invoke the methodA().
Basically I am writing an Android Application, i want to use method in already existing(assume it will be present all the time) application which is in the phone.
Below are the things I have tried:
String apkName = activity.getPackageManager().getApplicationInfo(packageName, 0).sourceDir;

PathClassLoader myPathClassLoader =
    new dalvik.system.PathClassLoader(
    apkName,
    ClassLoader.getSystemClassLoader());

Class<?> handler = Class.forName(className, true, myPathClassLoader);
Method m0 = handler.getDeclaredMethod("getInstance", new Class[] { Param.class  });
m0.setAccessible(true);
Object b = m0.invoke(null, new Object[]{ Param});
Method m = handler.getMethod("methodA", new Class[] { Param1.class});
Param1 methodParameter = "asdf";
Object b1 = m.invoke(b, new Object[] { methodParameter });

But its still not working.

A: I found the solution and its like below
Object b1 = m.invoke(handler.newInstance(), new Object[] { methodParameter });


text:
Q: How can i send parameters from one template to another template/view in django? Ok, so i have in my views.py these functions
def main(request):
    if request.method == 'POST':
        return newFunction(request)
    return render(request,'user/main.html')

def newFunction(request):
    num = request.POST["number"]
    let = request.POST["letter"]
    context = {'num':num,'let':let}
    return render(request,'user/test.html',{'c':context})

And that main.html looks like this
{%extends 'base/base.html'%}

{%block title%}Main{%endblock%}

{%block content%}

<form method="post">
    {%csrf_token%}
    <input type="text" name="number">
    <input type="text" name="letter">
    <button type="submit">Save</button>
</form>

{%endblock%}

The urls.py
path('index/',main,name='main'),
path('test/',newFunction,name='test'),

As you can see, i enter the main.html page and a form appears, asking me for a number and a letter. I enter these 2 inputs and when clicking the submit, it redirects me to another html and show me the letter and number. The problem is that the url still shows user/index.html, not user/test.html
How can i do this? i want to basically click the submit and send all the values to another template but changing the url in the process.

A: You can use ajax for do that. You can use form either, but ajax is more appropriate for just passing data to view.
Just sending ajax request with some data, and send it to your target view.
$.ajax({
    type: 'POST',
    url: "{% url 'test' %}",
    data: {
        "csrfmiddlewaretoken": "{{ csrf_token }}",
        "num": 'number',
        "let": 'letter'
    },
    dataType: 'json',
    success: function(e) {
        // success after receive response
    }
});

Of course you can send it with form. Just add your target url in action.
<!-- add your target url in action -->
<form method="post" action="{% url 'test' %}">
    {%csrf_token%}
    <input type="text" name="number">
    <input type="text" name="letter">
    <button type="submit">Save</button>
</form>

A: This can be handled on the frontend, using the action attribute within the opening <form> tag whose value should be the URL you want the form's data to be POST'd to on submit. Your opening <form> tag can be changed to the following:
<form method="post" action="/user/test.html">

Read: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data


text:
Q: I want User to be able to review courses I have a list of courses from my university that the students can review. How do i integrate in flutter so that user can search for a course and leave a review once with this info - term taken, professor, review under 20 words and rating 1-5.
Someone told me use firebase but I am not sure how to.
I have list of all the courses with no of credits and description in  a txt file.

A: Yes this is general practical you need a server to connect human from distance.
Firebase is best option for the beginner. it is easy to implement with any plate form like flutter. Thanks


text:
Q: Cant set min and max date of datetime picker for ionic In my ion-datetime I have dates to select. These dates are the dates provided from a function that finds the next available dates for delivery.
Here we have the function that gets the dates then set our result:
let result = getValidDates()
let temp = []
result.forEach(res => {
        temp.push(res.getDate())
    }
this.min = result[0].toLocaleDateString()
this.max = result.slice(-1)[0].toLocaleDateString()
this.pickupdates = result

Then we have our  component with the dayValues property which is the result from the above function:
<ion-datetime
  mode='md'
  presentation="date"
  [showDefaultButtons]="true"
  [dayValues] = "pickupdates"
  [min] = "min"
  [max] = "max"
>
</ion-datetime>

This then gives us the proper selectable dates. But those very same dates are the same dates that can be selected in the next month.
Ive tried tried to limit this by adding the min and max properties, but this then breaks and bring up the error:
"Cannot destructure property 'month' of 'parseDate(...)' as it is undefined."
and
"TypeError: Cannot read properties of undefined (reading 'month')"
In this case min and max would be:
min = "26/04/2022"
max = "02/05/2022"

but still brings up that error

A: the reason is min date max date should be yyyy/mm/dd or mm/dd/yyyy to be brief min="04/26/2022" and max="05/02/2022"


text:
Q: RxJS - stop requests with same parameters being made twice Let's say I have the following endpoint: /students/id.
I want to block a request with the same id being made multiple times (example: /students/1), but allow another request if the id is different.
I haven't been able to find a solution, operators like exhaustMap are not helping me/don't know how to use them for this case. I have also read about shareReplay but I don't know how to use it to take into account the parameters.
Edit
I'm actually using NGRX to accomplish my task. The issue is that I have several "student" components on one page that may make a requests to the same endpoint (/students/1) but display the same data in a different way. I can't check if the data is available with "withLatestFrom" because the requests are being dispatched one after another so there isn't enough time for the first requests to finish.
I also can't use exhaustMap because I don't want to block every requests to /students/id (2 components will need the data from /students/1 and another from /students/2)
getStudentEffect$ = createEffect(() => this.actions$.pipe(
    ofType(getStudent),
    exhaustMap((payload) => this.studentsService.get({id: payload.id})
      .pipe(
        map(student=> ({ type: '[Students API] Student Loaded Success', payload: student})),
        catchError(() => EMPTY)
      ))
    )
  );

A: The first thing that comes to my mind is you can create an object and serve the cache appropriately.
import { of } from 'rxjs';
import { tap } from 'rxjs/operators';
.....
@Injectable({ providedIn: root })
export class StudentService {
  studentCache = {};

  getSudentData(id: string) {
    if (this.studentCache[id]) {
      return studentCache[id];
    } else {
      return this.http.get(`/student/${id}`).pipe(
        // assuming your requests are always successful, you can extend to handle errors
        tap(studentData => {
           // store this response in the cache as an observable
           this.studentCache[id] = of(studentData);
        }),
      );
    }
  }
}

There might be a better way to do it or maybe a library like ngrx can help in this regard.


text:
Q: with tuple datastructure, how to sort two vectors keeping the pairs matched up? For a object, there are 2 attributes. For example, the object is a family. Then there are two vectors: member's height and member's weight.
what I want to do is to sort these members according to height. So I did something like the following code and there is an error:
     typedef std::tuple<double, char> lep_triplet;
     std::vector<lep_triplet> temporary_vec;
     std::sort( std::begin(temporary_vec), std::end(temporary_vec), [](const lep_triplet & left, const lep_triplet & right) { return  std::get<0>(left) > std::get<0>(right); });//

the error is:
/cvmfs/atlas.cern.ch/repo/ATLASLocalRootBase/x86_64/Gcc/gcc620_x86_64_slc6/6.2.0/x86_64-slc6/include/c++/6.2.0/ext/new_allocator.h:120:4: error: no matching function for call to 'std::tuple<double, char>::tuple(float&)'
  { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

Could you please take a look at it? I think I made something improper in the lambda function part. But I could not fix it... Thank you!


text:
Q: Optimize SQL request I want to optimize my SQL request because it looks so bad and it's a little bit slow.
I have two tables :
ORDERS
order_id | order_number | order_date | customer_id | commercial_id | product_id

CUSTOMERS
customer_id | customer_name

When a commercial make an order for a customer, I have entries like this in my ORDERS table :
1 | 6750 | 2021-08-09 | 854 | 64 | 12

1 | 6750 | 2021-08-09 | 854 | 64 | 32

1 | 6750 | 2021-08-09 | 854 | 64 | 41

I'm making an array to display list of commercial's orders :
order_number, order_date, customer_name

And to do this here is my code
//Getting all orders of the commercial

$req = $bdd->prepare("SELECT distinct order_number, order_date FROM orders WHERE commercial_id = :commercial_id ORDER BY order_date DESC");
$req->BindParam(':commercial_id',$commercial_id);
$req->execute();
$distinct_orders = $req->fetchAll(PDO::FETCH_ASSOC);

$orders = [];

//Looping all orders number and get the customer name

foreach($distinct_orders as $distinct_order){
    $req = $bdd->prepare("
        SELECT O.*, C.customer_name
        FROM orders O
        LEFT JOIN customers C
        ON O.customer_id = C.customer_id
        WHERE O.order_number = :order_number
    ");
    $req->BindParam(':order_number',$distinct_order['order_number']);
    $req->execute();
    $order = $req->fetch(PDO::FETCH_ASSOC);

    $orders[$order['order_number']] = [
        'order_number'      => $order['order_number'],
        'order_date'        => $order['order_date'],
        'customer_name'     => $order['customer_name']
    ];
}

I know it's so bad and I'm sure that there is a way to join to make it easier.

A: just use the commercial_id in the second query. Something like this :
$orders = [];

$req = $bdd->prepare("
        SELECT O.*, C.customer_name
        FROM orders O
        LEFT JOIN customers C
        ON O.customer_id = C.customer_id
        WHERE O.commercial_id = :commercial_id
");
$req->BindParam(':commercial_id',$commercial_id);
$req->execute();
$order = $req->fetch(PDO::FETCH_ASSOC);

//Looping all orders number and get the customer name
foreach($order as $order){
    $orders[$order['order_number']] = [
        'order_number'      => $order['order_number'],
        'order_date'        => $order['order_date'],
        'customer_name'     => $order['customer_name']
    ];
}

A: You can combine this into a single query as:
SELECT O.*, C.customer_name
FROM orders O LEFT JOIN
     customers C
     ON O.customer_id = C.customer_id
WHERE O.order_number IN (SELECT o2
                         FROM orders o2
                         WHERE o2.commercial_id = :commercial_id
                         ORDER BY order_date DESC
                        );

For this query, you want an index on orders(commercial_id, order_date desc).
Your question doesn't specify the structure of your data.  There might be simpler ways to express this.  For instance, is order_number unique?

A: This is working.
SELECT DISTINCT ORD.order_number, ORD.order_date, CUS.customer_id, CUS.customer_name
FROM orders ORD
LEFT JOIN customers CUS
ON ORD.customer_id = CUS.customer_id
WHERE ORD.commercial_id = :commercial_id
ORDER BY ORD.order_number DESC

Thanks everyone !


text:
Q: Disable Windows Firewall Without Admin Rights I need to disable the Windows 8.1 firewall but I don't have administrative rights. How can this be done?

A: This is not possible in the default configuration. Windows Firewall requires elevated permissions to reconfigure its settings. The MMC snap-in shows an "access denied" error, while the control panel version won't let you do anything interesting without elevating first. Starting, stopping, or reconfiguring the Windows Firewall service also requires administrator permissions. This makes sense: since the firewall settings affect everyone on the machine, unprivileged users should not be able to mess with them and thereby affect people other than themselves.
Please see your administrator and ask them to make the change you need. If you have physical access to the computer, you can see What can I do if I forgot my Windows password? to reset a given account's password, but please keep in mind that making unauthorized changes to computers is inadvisable personally even if possible technically. I recommend doing that only if you are rightfully the administrator but have lost your password.

A: To qualify the "it can't be done":
It could maybe be done by using some local privilege escalation vulnerability (either by exploiting the fact the system is behind on patches, or using something new that hasn't been fixed yet), and using the privileges thus attained.
This IS targeting the system with malware. This IS cracking. Doing that to any system of which you are not either the owner or the legit system administrator will very likely be viewed as a malicious and criminal act if discovered.
If this is a corporate computer, any other "unexpected" method is likely to land you in similar hot water - even if the responsible system manager did not explicitly set that policy, they are expecting the default policy they know to be valid and effective.


text:
Q: Debian laptop starts in grub command line First of all, I would like mention that I have very little experience with Linux, so please excuse me for bad terminology.
I have recently converted some school laptops from windows to Linux Debian in hope that they will run a bit better. (This is the first thing I have ever done with Linux)
They ran fine for a week or two, after which, most of them suddenly keep getting stuck in the grub command line menu.
I have googled a bit, and came across some things.
I had to point grub to the right place where grub.cfg is stored. I did this on all laptops, then told them to continue, and then updated the grub config file in the terminal
(steps I followed were listed on this site, among other places: https://www.howtoforge.com/tutorial/repair-linux-boot-with-grub-rescue/)
Now when I start up one of these laptops again, they once again open in the grub command line mode. I checked the settings using the set command, and both the prefix and root pointed to the right places.
I can simply type in normal, and the laptop will continue booting Linux, without me having to change anything.
This makes me believe that all the settings are correct, yet it does not open the screen where you can select to start up Linux, instead getting stuck at the grub command line menu.
If I re-clone Linux onto the hard drive using the original master clone I used for all the laptops, it will work fine again, but I have the feeling it will get the same problem in a week or two, and I don't really plan on having to re-clone all the laptops every two weeks.
upon booting a Linux Debian laptop, it opens the GRUB command line menu. Typing normal will continue booting the system as normal, making me think the settings are all correct.
Is there still a problem with these laptops? Is there a way to make sure the command line menu does not appear?

A: In you /etc/default/grub file, check to see if the entry GRUB_TIMEOUT_STYLE is set to menu, if not, set GRUB_TIMEOUT_STYLE=menu and also make sure GRUB_TIMEOUT is not 0 if you want to see the grub menu at boot. Don't forget to run sudo update-grub command after making changes.


text:
Q: How to create a site map using javascript I am looking for documentation on how to create a javascript which will follow all the links on a page, or site, and create a map or list of them. Or, if there is a better way to do this, that would be great too. I am just trying to get a comprehensive list of all the pages on a site with 3000+ pages. I also don't know what tags to put on this question, so tips in that area would be chill.

A: What you're looking for is referred to as:

*

*web crawling

*screen scraping

Use google and you'll be able to find a solution in the technology you prefer.
I personally like the python package scrapy
UPDATE: for instance, just searching for "javascript screen scraping tutorial" gives you: pjScrape a web scraping framework written in javascript


text:
Q: Usando stdlib en java, al usar el StdDraw me da un error Mi profe de programación nos ha dado escrito un programa para hacer un círculo y dibujarlo con StdDraw, pero no consigo que me compile.
He tenido problemas porque me daba error por la version del stdlib pero ese ya lo he solucionado y ha dejado de aparecerme, para dejarme en su lugar el siguiente error:
"Circulo.java:51: error: cannot find symbol
StdDraw.setPenColor(color);
^
symbol:   variable StdDraw
location: class Circulo
Circulo.java:52: error: cannot find symbol
StdDraw.circle(x, y, radio);
^
symbol:   variable StdDraw
location: class Circulo
Circulo.java:53: error: cannot find symbol
StdDraw.setPenColor(StdDraw.BLACK);
^
symbol:   variable StdDraw
location: class Circulo
Circulo.java:53: error: cannot find symbol
StdDraw.setPenColor(StdDraw.BLACK);
^
symbol:   variable StdDraw
location: class Circulo
Circulo.java:57: error: cannot find symbol
StdDraw.setPenColor(color);
^
symbol:   variable StdDraw
location: class Circulo
Circulo.java:58: error: cannot find symbol
StdDraw.filledCircle(x, y, radio);
^
symbol:   variable StdDraw
location: class Circulo
Circulo.java:59: error: cannot find symbol
StdDraw.setPenColor(StdDraw.BLACK);
^
symbol:   variable StdDraw
location: class Circulo
Circulo.java:59: error: cannot find symbol
StdDraw.setPenColor(StdDraw.BLACK);
^
symbol:   variable StdDraw
location: class Circulo
8 errors"
El código es:
"
public class Circulo
{
    private double x;
    private double y;
    private double radio;
    private Color color;

    public Circulo(double x, double y, double radio, Color color)
    {
        this.x = x;
        this.y = y;
        this.radio = radio;
        this.color = color;
    }

    public String toString()
    {
        return new String("(" + x + ", " + y + ", " + radio + ", " + color + ")");
    }

public void mover (double dx, double dy)
  {
    x += dx;
    y += dy;
  }
  public void pintar ()
  {
    StdDraw.setPenColor(color);
    StdDraw.circle(x, y, radio);
    StdDraw.setPenColor(StdDraw.BLACK);
  }
  public void pintarRelleno ()
  {
    StdDraw.setPenColor(color);
    StdDraw.filledCircle(x, y, radio);
    StdDraw.setPenColor(StdDraw.BLACK);
  }
  public double area ()
  {
    return Math.PI * radio * radio;
  }
  public double radio ()
  {
    return radio;
  }
  public Color color ()
  {
    return color;
  }
}"

Si alguien sabe por qué me aparece ese error y ayudarme, se lo agradecería :)

A: He copiado exactamente el código que has pasado y el único error que encuentro es que probablemente no tengas la clase StdDraw. Al copiar el código no tenia la clase y justo me sale el mismo error:

Luego busque la clase en cuestión la puse en el proyecto y ya me funciono (Me hice un circulo :) ). No se si es tu caso pero tiene toda la pinta de que no encuentra esa clase.

Te dejo el link para descargarla: StdDraw
Puedes copiar todo el texto y pegarlo en una clase StdDraw o bien clic derecho y guardar como...
Si estas usando el fichero stdlib.jar comprueba que has importado bien el fichero en el CLASSPATH y que tu IDE lo reconoce bien.


text:
Q: Importing surface geometry with field data into Paraview I have a 3D triangulated surface. The geometry  is stored in F which  is the array that contains the faces and V is the one holding vertices coordinates. In addition, at each vertex, a scalar quantity, S, and a vector with three components, A, are stored. I want to import this geometry and data into Paraview. I was thinking about saving the data as a VTK format. To do this, what would be the best format for the geometry, vtkPolyData or vtkUnstructured? Also, how can I add field data (the scalar quantity, S, and vector A, at each vertex) to the geometry? Do I need a separate file for this?
As a side question, is there any way to also store some data in the centroid of each triangle including scalar or vector data along the data that are stored at each vertex?

A: vtkPolyData are for surface "2D" cells. vtkUnstructuredGrid are for volumic "3D" cells.
So you need to use a vtkPolyData. To add the data you should use a vtkPointData, so each point (vertex) have data associated with it. Considering your side question, there is a vtkCellData, which store data for each cell, which are triangle in your case.
Have a look at the following examples:
http://www.vtk.org/Wiki/VTK/Examples/Cxx/IO/ReadPlainTextTriangles
http://www.vtk.org/Wiki/VTK/Examples/Cxx/PolyData/MiscPointData
In any case, if your format is not standard, in order to read it into paraview, you will need to write a python script or a C++ plugin.


text:
Q: Organizing images in the bootstrap grid layout Hi guys I need help in organizing a group of images using the bootstrap grid layout.
In the image there is the result I want reach: https://i.stack.imgur.com/RuJud.png
My code produces this result: https://i.stack.imgur.com/ZDa2Z.png
The position of the images is wrong, can you help me watching my code?

GIOCHI PREFERITI

CURRENTLY PLAYING

A: Not sure if this is what you were looking for

.row {
  background: blue;
  max-width: 410px;
}
.no-gutters {
  margin-right: 0;
  margin-left: 0;

  > .col, > [class*="col-"] {
    padding-right: 0;
    padding-left: 0;
  }
}

GIOCHI PREFERITI


text:
Q: exam components free? i need to implement a on-line exam using php and mysql, so need to get your opinion about good exam modules that are written using php? if it is free and easily configurable that is good! i need to easily modify the code and reconfigure it and include it with my own questions! i think you guys can give me better suggestions in this matter?? please suggest me what to do??
regards,
Rangana

A: I'd have a look into an online survey tool and extend that for your needs. Survey usually have radiobutton, checkbox and textfield answers, which is all you need in an exam as well.


text:
Q: How to chain include in C++? I don't know the proper term for this so pardon my post title. I wanted my workspace clean and organize so I thought maybe its that I should reorganize the file structure of the library I was writing for my game. I have a file structure which looks like this:
MyLibrary/include
MyLibrary/src

The problem with this is that on the client part, they are oblige to do something like this:
#include "MyLibrary/include/myfile.hpp"

I wanted it to look like this:
#include "MyLibrary/myfile.hpp"

How can I achieve this using C++?
Thank you!

A: If you want it to look like #include "MyLibrary/myfile.hpp", make your include directory look like this:
MyLibrary/include/MyLibrary/*.hpp

Then in whatever build system you are using, add MyLibrary/include into the include path.
For example, for GCC you could add -I local/path/to/include to your invocation. Have a look at the documentation for your specific build system for instructions.

A: Include files are looked up into the include directory path (a list of directories). For example with gcc you could use
#include "myfile.hpp"

and the compile by adding the option -I
gcc -I MyLibrary/include ...other options...

Note that you can provide option -I multiple times.
There is no way in compilers I know to however "skip" parts of the path... i.e. to make
MyLibrary/myfile.hpp

to resolve to
MyLibrary/include/myfile.hpp


text:
Q: Crashed: com.apple.main-thread EXC_BREAKPOINT 0x00000000e7ffdefe My Application is working fine if I open from home screen but when I open it from TestFlight application open button it crashes by giving the error that i obtained from Crashlytics.
    #0. Crashed: com.apple.main-thread
    0  ABC                        0x4f1778 specialized AppDelegate.handleRemoteNotificationFromKilledState([NSObject : AnyObject])      -> () (AppDelegate.swift:183)
    1  Abc                        0x10f3b8 specialised static _VariantDictionaryStorage.maybeGetFromCocoaStorage(_CocoaDictionaryStorage, forKey : A) -> B? (ViewController.swift)
    2  ABC                        0x4f212c specialized AppDelegate.application(UIApplication, didFinishLaunchingWithOptions : [NSObject : AnyObject]?) -> Bool (AppDelegate.swift)
    3  abc                        0x4ed0dc @objc AppDelegate.application(UIApplication, didFinishLaunchingWithOptions : [NSObject : AnyObject]?) -> Bool (AppDelegate.swift)
    4  UIKit                          0x24f82a6f -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 394
    5  UIKit                          0x251ac287 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 3086
    6  UIKit                          0x251b0241 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1588
    7  UIKit                          0x251c4811 __84-[UIApplication _handleApplicationActivationWithScene:transitionContext:completion:]_block_invoke3286 + 36
    8  UIKit                          0x251ad767 -[UIApplication workspaceDidEndTransaction:] + 134
    9  FrontBoardServices             0x21ffbbf7 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 18
    10 FrontBoardServices             0x21ffbaa7 -[FBSSerialQueue _performNext] + 226
    11 FrontBoardServices             0x21ffbda5 -[FBSSerialQueue _performNextFromRunLoopSource] + 44
    12 CoreFoundation                 0x208ef9e7 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 14
    13 CoreFoundation                 0x208ef5d7 __CFRunLoopDoSources0 + 454
    14 CoreFoundation                 0x208ed93f __CFRunLoopRun + 806
    15 CoreFoundation                 0x2083c1c9 CFRunLoopRunSpecific + 516
    16 CoreFoundation                 0x2083bfbd CFRunLoopRunInMode + 108
    17 UIKit                          0x24f7bf37 -[UIApplication _run] + 526
    18 UIKit                          0x24f76435 UIApplicationMain + 144
    19 abc                        0x4ef4ec main (AppDelegate.swift:16)
    20 libdispatch.dylib              0x204e8873 (Missing)

Any Thoughts on that why this happening.
Thanks in Advance!!
Update : - Code for AppDelegate.handleRemoteNotificationFromKilledState([NSObject : AnyObject])
func handleRemoteNotificationFromKilledState(userInfo:[NSObject : AnyObject]) {
  var pushDict = userInfo[UIApplicationLaunchOptionsRemoteNotificationKey] as! Dictionary<NSObject,AnyObject>
  let dict = pushDict["abc"] as? NSDictionary
  if (dict?.valueForKey("alert") as? NSString) != nil {
  let alert = dict?.valueForKey("alert") as! NSString
  if let type=pushDict["NT"] as? NSString {
     if type == "TO_ViewController_One" {
        let qcid = pushDict["abcID"] as? String
        self.notificationdictForkilled["qcid"] = qcid
        self.notificationdictForkilled["ToViewController"] = "TO_ViewController_One"
     } else if type == "TO_ViewController_Two" {
        let qcid = pushDict["abcID"] as? String
        self.notificationdictForkilled["qcid"] = qcid
        self.notificationdictForkilled["ToViewController"] = "TO_ViewController_Two"
     } else if type == "TO_ViewController_Three" {
        let qcid = pushDict["abcID"] as? String
        self.notificationdictForkilled["qcid"] = qcid
        self.notificationdictForkilled["ToViewController"] = "TO_ViewController_Three"
     } else if type == "TO_ViewController_Five" {
        let qcid = pushDict["abcID"] as? String
        self.notificationdictForkilled["qcid"] = qcid
        self.notificationdictForkilled["ToViewController"] = "TO_ViewController_Five"
     } else if type == "TO_ViewController_Four" {
        let qcid = pushDict["abcID"] as? String
        self.notificationdictForkilled["qcid"] = qcid
        self.notificationdictForkilled["ToViewController"] = "TO_ViewController_Four"
     } else if type == "TO_ViewController_Six" {
        let qcid = pushDict["abcID"] as? String
        self.notificationdictForkilled["qcid"] = qcid
        self.notificationdictForkilled["ToViewController"] = "TO_ViewController_Six"
     } else if type == "TO_ViewController_Seven" {
        let qcid = pushDict["abcID"] as? String
        self.notificationdictForkilled["qcid"] = qcid
        self.notificationdictForkilled["ToViewController"] = "TO_ViewController_Seven"
     } else if type == "TO_ViewController_Eight" {
        let qcid = pushDict["abcID"] as? String
        self.notificationdictForkilled["qcid"] = qcid
        self.notificationdictForkilled["ToViewController"] = "TO_ViewController_Eight"
     } else {
        let qcid = userInfo["abcID"] as? String
        self.notificationdictForkilled["qcid"] = qcid
        self.notificationdictForkilled["ToViewController"] = type as String
     }
     self.viewstate = "Killed"
  }
  }
}


text:
Q: Wordpress - Change page dynamically but within shortcode running php I am using a custom shortcode plugin. The plugin allows me to run some php. The php queries a non-wp database to build a page of vehicle specs and everything works great. The issue is that all of the information needed for the page title and description is contained within the data coming from the database. I've tried some of the standard wp php filters but the title does not change.
Is this not possibly because of the execution timing of the shortcode?
TinyMCE in WP admin. Shortcode
-----------------------------------------------
[myplugin data_id='42']

PHP window in shortcode editor
-----------------------------------------------
$GP=array_merge($_GET, $_POST);

echo "hello word" //works
echo $data_id;  //works
echo $GP[some_post_data]; //works
//connect to database (irrelevant)
echo "the title from data table for data_id 42 = ".$data[title];  //works

// the following has no effect on page title even though $data[title] contains valid data
add_filter('the_title','myCallback');
function myCallback($data){
  return $data[title];
  }

A: The problem is that $data[title] is out of scope, and that your filter callback is set up incorrectly. Also, you SHOULD encapsulate associative indexes with quotes.
When adding a callback to an existing filter, the arguments within the callback are passed by the filter definition. Case and point: Filtering The Title
The arguments within a standard filter for the_title are $title and $id. If you want to return the title from your $data array, you can do it the sloppy way using the global scope:
add_filter('the_title','myCallback');
function myCallback($title, $id){
    global $data;
    return $data['title'];
}

But personally, I would look into avoiding globals altogether and concentrate on utilizing custom filters. Look into Adding Your Own Hooks. After getting a handle on action hooks, Filter Hooks are pretty easy to grasp.