text:
Q: ArrayList iteration gives exception java.util.ConcurrentModificationException java.util.ConcurrentModificationException: "This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible."
Any idea why my set method gives this exception?
private ArrayList<Double> voltagesList = new ArrayList<Double>();
private ArrayList<String> devicesList = new ArrayList<String>();

public void setVoltage(String device, double voltage) {
    for(String d: devicesList){
            if(d.equals(device)){
                voltagesList.set(devicesList.indexOf(device), voltage);
        }
            else{
                voltagesList.add(voltage);
                devicesList.add(device);
            }
    }
}

A: Instead of using a pair of Lists you should be using a Map.
private final Map<String, Double> deviceVoltageMap = new HashMap<>();

public void setVoltage(String device, double voltage) {
    deviceVoltageMap.put(device, voltage);
}

A: Yes the reason you're getting this is devicesList.add(device);  You are adding to this list as you're iterating it.  You can't do that in a foreach loop on an ArrayList .
What I usually do is collect the things I want to add in a separate, temporary list and then outside of the loop I call addAll.  Here's an example:
package com.sandbox;

import java.io.FileNotFoundException;
import java.util.ArrayList;

public class Sandbox {

    public static void main(String[] args) throws FileNotFoundException {
        Sandbox sandbox = new Sandbox();
        sandbox.devicesList.add("foo");
        sandbox.setVoltage("bar", 1.0);
    }

    private ArrayList<Double> voltagesList = new ArrayList<Double>();
    private ArrayList<String> devicesList = new ArrayList<String>();

    public void setVoltage(String device, double voltage) {
        ArrayList<String> newDevicesList = new ArrayList<String>();
        for (String d : devicesList) {
            if (d.equals(device)) {
                voltagesList.set(devicesList.indexOf(device), voltage);
            } else {
                voltagesList.add(voltage);
                newDevicesList.add(device);
            }
        }
        devicesList.addAll(newDevicesList);
    }

}

A: ListIterator<String> iter = devicesList.listIterator();
while(iter.hasNext()) {
   String d = iter.next();
   if(d.equals(device)){
       voltagesList.set(devicesList.indexOf(device), voltage);
   }
      else{
         voltagesList.add(voltage);
         iter.add(device);
   }
}

A: You can't modify a collection you're iterating over, unless you're iterating with iterator and calling iterator.remove() to modify it.
You can create a new empty collection and add elements to it.


text:
Q: How do I change the class-path of one of my applications in JBoss EAP 6.4 I have a JBoss EAP 6.4 implementation which runs a bunch of separate applications within it. All living in the same WAR file.
For one of those applications I want to modify the class-path. Specifically I want it to exchange two jars for two others.
Is that possible?

redpajama_set_name: RedPajamaStackExchange


text:
Q: PostgreSQL - SUM true-false column & group by month giving me a percentage i have a table with id and some other data that I already filtered.
first I wanted to know how I convert into a new table that output
select A, B from Table
where B between '2020-03-01' and '2020-04-30'
order by B ASC
;

i have this output like this:
A       B
1    12-03-2000
0    12-04-2000
1    03-02-2000
1    04-02-2000
0    02-05-2001

my interest is focused only on 2 months
i want to know the percentage represents the sum of both true & false (separately) in each month

A: I think you want the months in columns with the percent true and false for each month.  That uses conditional aggregation:
select A,
       count(*) filter (where month(b) = 3) * 1.0 / sum(count(*)) filter (where extract(month from b) = 3) as march,
       count(*) filter (where extract(month from b) = 4) * 1.0 / sum(count(*)) filter (where month(b) = 4) as april
from Table
where B between '2020-03-01' and '2020-04-30'
group by A;


text:
Q: Difference between vectors,vertex and faces? I always find this difficult to understand as it seems all very theoretical.
glVertex(0.0f,0.0f,0.0f);
glVertex(0.0f,0.0f,-1.0f);
glVertex(-1.0f,0.0f,-1.0f);
glVertex(-1.0f,0.0f,0.0f);

that's one face of a cube in openGL.
I open up a obj file and the faces are stored like this:
f 61 67 52
f 50 66 49

etc etc

A: I'm guessing here but you seem to be confused about the format of the obj file.
f 61 67 52 is actually really simple: It specifies that the vertices #61, #67, and #52 form a triangle (a face) in 3D space.
I will also point out that your referencing a sequence of four OpenGL Immediate Mode glVertex calls as "one face of a cube" is not a particularly good description of what that code actually does or represents. The code itself specifies four 3D vertices and that is the only information being specified. The concept of a face, or for that matter a triangle (the building block of 3D graphics), is not the same thing as the specification of vertices.
There are a few reasons that you don't see a lot of people using the geometric term "face" in 3D Graphics, its usage in .obj files being an exception. It is because the graphics hardware is designed to operate on triangles: If you wanted to make a pentagonal face you'd really be constructing it out of 3 or more triangles. I couldn't tell you why it is f 61 67 52 rather than t 61 67 52 as that'd make more sense. Note that if you take four non-coplanar vertices you cannot make a flat geometric face out of it! This is why it is okay to refer to a triangle as a face: Any 3 points are coplanar.

A: *

*Vector is or can be thought of as a direction (target position
coordinates - your current position coordinates would tell you the
direction you need to go)  and/or simply a list of coordinates in
particular n-dimensional space e.g. (1, 0, 0) in 3-D (x, y, z).

*Vertex is a point in a space, which could be described by a Vector (a
list of coordinates (x, y, z)).

*Face is a convex space which is made by connecting at least 3
vertices one by one usually anti-clockwise (that would make a
triangle). Direction is important to understand which side the face
would be facing. Other side would not be rendered.

Each face in a mesh usually has a number, which acts as an index and a normal vector, which shows the direction where is the rendered side of this particular face (simply from where to look to see the texture which might be mapped onto this face). This all depends on a particular format how mesh is stored (obj is only one of several formats, proprietary programs usually have their own closed format).


text:
Q: Karate not supporting JSON Path I have a JSON path, say $[advertiserId]  and this evaluates to
[
  "001E000000yBFskIAG"
]

using tool https://jsonpath.com/? .
However, the equivalent Karate syntax does not work:
And match response[*].advertiserId == '001E000000yBFskIAG'
It does not recogize this path.
If I have JSON:
{
"advertiserId":"someID"
}

Then
And match response[*].advertiserId == 'someID'
should work. Karate ought to be able to support basic JSON matching.

A: Karate is stricter - if there is JsonPath "wildcard" e.g. * or .. the result will always be an array. Maybe jsonpath.com converts a single element array to the value for convenience - but we will never do that.
The below works:
* def response = [{ advertiserId: '001E000000yBFskIAG' }]
* match response[*].advertiserId == ['001E000000yBFskIAG']


text:
Q: PHP query error I am using LIKE to do my searching, i try it in phpMyAdmin and return the result but when i use it in php it return empty result.
$search = "ip";
$start = 0;
$query = "SELECT * FROM product WHERE product_name LIKE '%$search%' LIMIT $start,30";
$result = mysql_query($query);
if(empty($result))
    $nrows = 0;
else
    $nrows = mysql_num_rows($result);

It will return result when i using phpMyAdmin to run this query but when i use it in php, it return empty.
Update:
Sorry guys,
I just found out the problem is i didn't connect database as well. anyway, thanks for helping.

A: Try This
 $query = "SELECT * FROM `product` WHERE `product_name` LIKE '%".$search."%' LIMIT 0, 30";

A: And if the sole purpose of your code is to get the number of products with the searched-for name, use SELECT COUNT(*) instead of doing a mysql_num_rows() on all your data. It will decrease your querytime and the amount of data that is (unnecessarily) fetched.

A: I am not sure why this is not working, as the query seems to be correct to me. I would like to suggest you writing query this way

$query = <<<SQL
 SELECT * FROM product WHERE product_name LIKE "%$search%" LIMIT $start,30

SQL;

please note that there should not be any space or any character after SQL;

A: $query = "SELECT * FROM product WHERE product_name LIKE '%" . $search . "%' LIMIT " . (int) $start. ",30";

A: you can use directly mysql_num_rows()
but here is right code
$query = "SELECT * FROM product WHERE product_name LIKE '%".$search."%' LIMIT $start,30";

A: $search = "ip";
$start = '0';
$query = "SELECT * FROM product WHERE product_name LIKE '%".$search."%' LIMIT $start,30";
$result = mysql_query($query)or die(mysql_error());
if(mysql_num_rows($result) == 0){
    $nrows = 0;
} else{
    $nrows = mysql_num_rows($result);
}

//use mysql_num_rows($result) instead of empty($result) because in this situation $result is every time not empty so use inbuilt PHP function mysql_num_rows($result);


text:
Q: Bodiless function in Golang Reading the source code of math/floor.go, starting from line 13, I read some code like this:
func Floor(x float64) float64

func floor(x float64) float64 {
    if x == 0 || IsNaN(x) || IsInf(x, 0) {
        return x
    }
    if x < 0 {
        d, fract := Modf(-x)
        if fract != 0.0 {
            d = d + 1
        }
        return -d
    }
    d, _ := Modf(x)
    return d
}

It seems the func Floor has no body. I tried to copy and paste these code in my go file. it doesn't compile. The error message is missing function body. So my question is: is a bodiless function legal in Go's syntax? Thanks.

A: In my case I had "../../../pkg/mod/golang.org/x/tools@v0.0.0-20190814235402-ea4142463bf3/go/ssa/interp/testdata/src/fmt/fmt.go:3:6: missing function body" error!
and it was because I used fmt without importing it so my IDE imported the wrong package.
I fixed it by removing the import (golang.org/x/tools/go/ssa/interp/testdata/src/fmt)
and just importing fmt

A: It's the way how functions are implemented in assembly. You find the assembly implementation in the floor_ARCH.s (e.g.: AMD64) files.
To quote the spec:

A function declaration may omit the body. Such a declaration provides the signature for a function implemented outside Go, such as an assembly routine.


text:
Q: (ANDROID) ImageView won't position correctly I have an Android related issue:
I am trying to centre a logo on the screen of my device, but it won't position correctly.
I am using the following function:
public void ImageCentered(int ID){
    ImageView iv = (ImageView) findViewById(ID);
    int x = 0;
    int y = 0;

    RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    x = (screenWidth/2)-(iv.getWidth()/2);
    y = (screenHeight/2)-(iv.getHeight()/2);
    position.setMargins(x, y, 0, 0);

    iv.setLayoutParams(position);
}

This could should work,but it won't. The image is set off slightly to the right and bottom like in this image:
https://www.dropbox.com/s/tf7r1u1xqcmb9t9/2014-08-16%2018.36.04.png
Now, the strange thing is, when I use the following code:
public void ImageCentered(int ID){
    ImageView iv = (ImageView) findViewById(ID);
    int x = 0;
    int y = 0;

    RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    x = (screenWidth/2)-(iv.getWidth()/2);
    y = (screenHeight/2)-(iv.getHeight()/2);
    position.setMargins(x, y, 0, 0);
    Message(IntToStr(x)+", "+IntToStr(y));

    iv.setLayoutParams(position);
}

this is the result:
https://www.dropbox.com/s/mjw80zlzkav6dzs/2014-08-16%2018.41.16.png
Side note: The text in the Message() function does not matter, nor does its position within the ImageCentered() function.
I am not calling the function in my OnCreate(), as the width and height of the image would always return 0, so I looked something up and found this:
@Override
public void onWindowFocusChanged(boolean hasFocus){
    ImageCentered(R.id.image);
}

This piece of code is in my MainActivity.java file, whereas the ImageCentered() function is in my UtilLib.java file.
So, I was wondering: What's going on here? Why does the code work when I pop in a Message() but not when I leave it out?
Sure, I can try hardcoding the data, but what about smaller/bigger screens?
I hope an Android guru can help me out here, as I've been struggling with this for quite some time now.
EDIT
Just noticed something interesting when pressing "OK" on my Message:
https://www.dropbox.com/s/a7lu6588hy1opw7/2014-08-16%2018.51.55.png
My guess is that my problem lies there, but after clicking the "OK" button once more, the data is "492, 207" again. scratches head

A: Assuming rom your code that the ImageView is inside a RelativeLayout, You could also do:
// get imageview layout params or create new ones
RelativeLayout.LayoutParams params = imageView.getLayoutParams();

params.addRule(RelativeLayout.CENTER_HORIZONTAL);

this way the image will be automatically centered without all those manual calculations!.
You can also specify it in the XML with
 <ImageView .....
  android:layout_centerHorizontal="true"/>

A: I've ultimately decided to just hardcode the x and y coordinates, and later on use some sort of scaling-conversion to position them properly, unless someone can provide me with a better method of fixing this.
UPDATE
So, after googling after a while (again), I have finally found the answer and created two functions:
public int GetImageHeight(int ID){
    ImageView iv = (ImageView)findViewById(ID);
    iv.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
               MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    iv.layout(0, 0, iv.getMeasuredWidth(), iv.getMeasuredHeight());

    return iv.getMeasuredHeight();
}
public int GetImageWidth(int ID){
    ImageView iv = (ImageView)findViewById(ID);
    iv.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
               MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    iv.layout(0, 0, iv.getMeasuredWidth(), iv.getMeasuredHeight());

    return iv.getMeasuredWidth();
}

All you have to do is pass the ID of the image you made in your xml file, like so:
GetImageHeight(R.id.logo)


text:
Q: Cassandra driver error in installing I am getting following error in installing Cassandra driver for python.
Command "c:\python33\python.exe -u -c "import setuptools, tokenize;__file__='c:\
\users\\vmasama\\appdata\\local\\temp\\pip-build-we10p7\\cassandra-driver\\setup
.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n
', '\n'), __file__, 'exec'))" install --record c:\users\vmasama\appdata\local\te
mp\pip-olh8j5-record\install-record.txt --single-version-externally-managed --co
mpile" failed with error code 1 in c:\users\vmasama\appdata\local\temp\pip-build
-we10p7\cassandra-driver\

Any one have any idea about this ? What am i missing ?
Following errors were also there when i run pip install cassandra-driver

Failed building wheel for cassandra-driver
  Failed cleaning build dir
  for cassandra-driver

python version : 3.3

A: I tried it in an environment missing compiler paths and observed something similar. I think it's a problem in setuptools error handling when it doesn't find what it's expecting. The easiest way I've found is to use the VS Command Prompt shortcut installed with Visual Studio:

Perhaps the easiest way to do this is to run the build/install from a Visual Studio Command Prompt (a shortcut installed with Visual Studio that sources the appropriate environment and presents a shell).

http://datastax.github.io/python-driver/installation.html#windows-installation-notes


text:
Q: Why is the Java compiler giving the incoherent ".class expected" compile error? If I have a piece of code like this:
public class ABC {
    public static void main(String[] args) {
        if (true)
            int a = 0;
    }
}

When I compile it, Java compiler produces an error

.class expected.

*

*I know that when we don't use braces, we can use only one statement after if.

*And I also know that I will not be able to use the int variable a, because as soon as the ; is encountered, the program comes out of if, and the variable a loses it's scope.

I am not surprised that this code emits an error, but why is the error message '.class' expected?
What is Java compiler trying to say?

A: I suspect the problem is that the only token sequence that can legitimately follow the keyword token of int in this case is . followed by class. The declaration statement you've got at the moment isn't valid because a local variable declaration on its own isn't a Statement as per JLS 14. (It's a BlockStatement.)
Note that in the tutorialspoint environment referenced in the comment, if you use a class instead of int, a different error is produced - potentially because the set of valid tokens is different in that scenario. (String.getClass(); would be valid for example, whereas int.getClass(); wouldn't.)
There is a valid question asked in a comment:

Why this .class thing? If you know any situation in which int followed by .class can compile, then please tell me.

And that's easy - you can call a method on the Class reference returned by int.class:
public class ABC
{
    public static void main(String args[])
    {
        if(true)
            int.class.getName();
    }
}

That's not useful code, but it is valid code. It compiles for me without warnings or errors.
As mentioned in comments, more recent compiler versions give more useful errors - I would recommend upgrading.

A: As opposed to what some commenters say, this code can actually produce that error.
int a = 0;
    ^

According to the Java Language Specification, a variable declaration needs to be in a code block:

Every local variable declaration statement is immediately contained by a block. Local variable declaration statements may be intermixed freely with other kinds of statements in the block.

I assume you already knew that.
But why the .class expected error?
The reason why the exception says .class expected, is compiler specific. Other compilers will emit not a statement or illegal start of expression.
My guess is that it is related to the way the compiler evaluates the code. The only way int can be valid at that location, is when followed by .class. So as soon as the token int is detected, the compiler expects it to be followed by .class.
For example,
if (true)
    int.class.getFields();

would be a valid statement.
So the compiler gives an error that is in some way logical, that is, .class expected.
Other compilers probably evaluate the whole statement as a variable declaration, rather than separate tokens like int, a, = and 0.
Specific compiler
I do not know which specific compiler tutorialspoint.com is using, but their javac version (using javac -version) is javac 1.7.0_75 on Fedora release 21 (Twenty One) (using the command cat /etc/issue.net).
PS: I don't know if you have a specific reason for using the compiler of which you posted an image, but I suggest you start using Eclipse or Netbeans.


text:
Q: Remove float css I have a css code that has a float property. When i resize the window of my browser, the menus of my webpage are moving down. I already comment-out the float properties, but nothing's changed. What should I do to make it fixed that it will not move down even though I resize my browser?

A: float got nothing to do with the floating of the div's when the window is resized.
It just ask the div to be aligned to the left,right only if there is space,
what i think you should do is to make wrapper div ID called "content" like this below and add all your inside div elements there,
#content{
width:960px;
margin:0px auto;
}

now inside this div content, if you have 2 div's width 400px and 400px if you set their property to float left they align left, if you set it float right they align right..
if there is no space, like if one div is 400px and other one is 600px even if the property is set to float left they will come as vertical dives as combined width is more than container div
learn more about fix width css design


text:
Q: how do i check the difference between the current price and a certain price? i created a strategy but i'm struggling to implement something.
i went through the documentation but i can't seem to find a solution or anything regarding obtaining the current price.
so let us say the strategy bought nas100 at 13000.00 and the current price of nas100 is 13075.00 which is a 75 pips gain/profit. so i want to calculate the difference between the price the strategy bought at and the current price. if the difference between the price the strategy bought at and the current price is >= 50 pips i want the strategy to create a stop loss order and put it 5 pips above the price at which the strategy bought and then trail the price every +5 pips it moves. how can i implement this?

A: close will refer to the current price.
You can use strategy.opentrades.entry_price(strategy.opentrades-1) to get the last entry price.
Then do your calculations.


text:
Q: VMWARE: How to trunk 4 x 1Gbit Ports for a Virtual Machine Port Group Yesterday i asked this Question:
VMware NIC Teaming - How to gain more than 1Gbit/s copy speed between two VMs?
I had a missunderstanding about the "NIC Teaming" --> "Load Balancing" options in VMWare network configuration.
So now my Question is how can i trunk 4 x 1 Gbit Ports for a virutal machine port group. My current configuration can be seen here:

Problem is, that i have a Windows Server 2012 R2 VM which should be faster than 1 Gbit/s. But with my current configuration this isn't possible - a VM will never be faster than 1Gbit/s with that config.
At the moment i can not use 10 Gbit Ports... :-/

A: LACP might help you.
However, you won't get more than 1 Gbit/s for a single connection. That's because LACP chooses the uplink to use through a combination of different parameters. If source and destination MAC, IP and port stay the same LACP will always use the same uplink. But LACP can give you more overall bandwith.
Btw: your virtual switch is effectively the access switch for the VMs. So if you connect it directly to your 10 Gbit backbone you'll get a lot more than with LACP and Gbit uplinks;-)


text:
Q: Finding static Methods in Laravel Docs I'm having trouble navigating the Laravel documentation. I use the static method \Illuminate\Support\Facades\Validator::make, and I would like to find out more information about it. However, I cannot find it in the documentation page for \Illuminate\Support\Facades\Validator (https://laravel.com/api/5.1/Illuminate/Validation/Validator.html). I have had similar experiences with other static methods that I find in Laravel code snippets.
Where can such things be found (specifically where can documentation on \Illuminate\Support\Facades\Validator::make be found)?

A: If you see the actual class itself (\Illuminate\Support\Facades\Validator) in your IDE you will see this:
/**
* @see \Illuminate\Validation\Factory       <-- TELLS YOU WHERE TO LOOK
*/

class Validator extends Facade
{
    ...
}

The make method is in \Illuminate\Validation\Factory and the docs for it is found here https://laravel.com/api/5.1/Illuminate/Validation/Factory.html#method_make

A: The class you mentioned is a so-called facade. This means that it has an underlying class. You can find more information about facades in the official documentation.
You can find the underlying class in the comment above the facade class.
/**
 * @see \Illuminate\Validation\Factory <- HERE
 */
class Validator extends Facade
...


text:
Q: Remove part of associative array I want to search an associative array and when I find a value, delete that part of the array.
Here is a sample of my array:
    Array
(
    [0] => Array
        (
            [id] => 2918
            [schoolname] => Albany Medical College
            [AppService] => 16295C0C51D8318C2
        )

    [1] => Array
        (
            [id] => 2919
            [schoolname] => Albert Einstein College of Medicine
            [AppService] => 16295C0C51D8318C2
        )

    [2] => Array
        (
            [id] => 2920
            [schoolname] => Baylor College of Medicine
            [AppService] => 16295C0C51D8318C2
        )
}

What I want to do is find the value 16295C0C51D8318C2 in the AppService and then delete that part of the array. So, for example, if that code was to run on the above array, it was empty out the entire array since the logic matches everything in that array.
Here is my code so far:
            foreach($this->schs_raw as $object) {
                if($object['AppService'] == "16295C0C51D8318C2") {
                    unset($object);
                }
        }

A: array_filter will help (http://php.net/manual/en/function.array-filter.php)
$yourFilteredArray = array_filter(
    $this->schs_raw,
    function($var) {
        return $object['AppService'] != "16295C0C51D8318C2"
    }
);

A: Try like this:
foreach ($this->schs_raw as &$object) {
    if($object['AppService'] == "16295C0C51D8318C2") {
        unset($object);
    }
}

Eventually:
foreach ($this->schs_raw as $k => $object) {
    if($object['AppService'] == "16295C0C51D8318C2") {
        unset($this->schs_raw[$k]);
    }
}

A: Try this:
foreach($this->schs_raw as $key=>$object) {
  if($object['AppService'] == "16295C0C51D8318C2") {
    unset($this->schs_raw[$key]); // unset the array using appropriate index
    break; // to exit loop after removing first item
  }
}

A: Why not create a new array? If match not found, add index to new array... If it is found, don't add it. Your new array will only contain the data you want.


text:
Q: UIView animation warning I am using following code
[UIView animateWithDuration:1.0
                      delay:0.05
                    options:UIViewAnimationCurveEaseIn
                 animations:^{

                                  //Code

                 } completion:^(BOOL finished) {}];

I am getting the following warning
Implicit conversion from enumeration type 'enum UIViewAnimationCurve' to different enumeration type 'UIViewAnimationOptions' (aka 'enum UIViewAnimationOptions')

How to solve this?

A: You should be using UIViewAnimationOptionCurveEaseIn instead.
UIViewAnimationCurveEaseIn is part of a different enum used in other methods.


text:
Q: Django: Change URL's keyword argument on current language I have these two keyword arguments
sitemap_en = {
    "blog_en":BlogSiteMap('en'),
     ...
}

sitemap_ja = {
    "blog_ja":BlogSiteMap('ja'),
     ...
}

I want to have this condition in urls.py,
if current_language == "en":
    sitemaps = sitemap_en
else:
    sitemaps = sitemap_ja

url(r'^sitemap.xml/$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}, name='sitemap')

I know if else will not be executed but i want to have this in my url. SO anyone help me how to achieve my goal?

A: Urls are parsed before any request is processed.
A simple solution is to decorate django.contrib.sitemaps.views.sitemaps:
from django.contrib.sitemaps.views import sitemap

def locale_sitemaps(request):
    # assuming you make a "sitemaps" dict here of {language_code: sitemap}
    return sitemap(request, sitemaps=sitemaps[request.LANGUAGE_CODE])

Then, make your URL to use this view:
url(r'^sitemap.xml/$', 'views.locale_sitemaps', name='sitemap')


text:
Q: SCITE4Autohotkey debugger not working I installed SCITE4Autohotkey under autohotkey last version
everything work ok,
but I cannot activate the debugger.
when I set the bullet stop near line no (and press debug mode). the code is not stopped
on [F5] or RUN
any suggestion ?

A: End the process InternalAHK.exe*32

A: Save your file first.
Set your stop bullets (red dots) by clicking just next to the line numbers.
Go to first line of code, press debug (little insect) first (Icon changes and new single line icons appear), then press Run (blue triangle) or single line (blue arrows).
"Run" will now run the code until the first red dot, you can then continue with single line execution (Blue arrows) or continue with run (blue triangle) until the next red stop bullet.
Works flawlessly with my system (Win-7, AHK_L).

A: Fix this issue by simply selecting a platform, just click this
 and select Default from the dropdown menu.
(I was not able to run and debug scripts inside SciTE4AutoHotkey)

A: Sometimes, I need to close the file and reopen it and then I'm able to create breakpoints.


text:
Q: how to send a 1D pointer to a function which requires a 2D pointer in c++? I have a function which requires **double, while the pointer I defined is *double, how to send it to the function? Sample code is the following,
void eig(int n, double **A);
int main(){
  int DIM=5;
  double *HMAT = new double [DIM*DIM];
  eig(DIM,HMAT);
  delete [] HMAT;
}

void eig(int n, double **A) {}

Compilation complains
main.cc:8:15: error: cannot convert 'double*' to 'double**' for argument '2' to 'void eig(int, double**)'

A: I think the misunderstanding is that void eig(int n, double **A) does not denote a "pointer to a 2D-array" but a pointer to a pointer to a double value.
Depending on what you do with A in function eig, this can be meaningful or not: If eig is about allocating or reallocating a new array, then you'd use a double **A in order to pass back the newly allocated memory to the caller. However, if you just want to access the values of the array, it's sufficient to pass just a pointer to the array (not a pointer to a pointer). See the following code explaining the difference. Hope it helps.
void eig1(int n, double **A) {
    *A = new double [n*n];  // OK; pass back the array by writing its starting address into the pointer to which A points.
}

void eig2(int n, double *A) {
    A = new double [n*n];  // does not make sense; changes local variable `A` only; will result in a memory leak
}

void eig_populate(int n, double *A) {
    for (int i=0;i<n;i++) {
        A[i]=i;  // OK; does not allocate a new array but accesses an existing one
    }
}

int main(){
    double *HMAT = nullptr;
    eig2(5,HMAT); // will not change HMAT
    eig1(5,&HMAT); // will change HMAT
    eig_populate(5, HMAT);
}

A: You've misread the error message. Pay attention to line numbers: the problem isn't the call to eig, it's the assignment of a double** created by new *[DIM*DIM] to HMAT, whose type is double*. To fix that error, change the type of HMAT to double**.


text:
Q: Limit upload speed in sharepoint I am uploading a document in sharepoint2010 document library by using server object model concept.
I want to limit the upload speed through code.
Can anyone please tell me, How do i limit the upload speed in sharepoint2010?
Is there any option available on document library to limit the speed?
or else provide me any c# code to limit the uploading speed.
Thanks in Advance


text:
Q: Entity Framework Type for Storing Only Year and Month I want to save production year and month on an entity. I don't want to save the time and date of the month.
I can come up with multiple solutions, and the best two so far is:
public class Product
{
    private DateTime _productionMonth;

    public DateTime ProductionMonth
    {
        get => _productionMonth;
        set => _productionMonth = new DateTime(value.Year, value.Month, 1);
    }
}

or
public class Product
{
    public int Year { get; set; }
    public int Month { get; set; }
}

But I don't feel any of the solutions is the perfect solution...
Does there exists any better solutions? Maybe an attribute on DateTime?

A: You could store it as a single integer, using YYYYMM format. The entity can expose unmapped ([NotMapped]) helper methods to covering to/from DateTime, and/or a ValueTuple (year int, month int) though from EF queries you would need to use the single mapped value. YYYYMM are sortable so you can query a range efficiently.


text:
Q: How do I set the hostname of an AWS Lightsail VM? Reviewing cloudinit configs on my new Lightsail VM, it seems to be talking to a metadata API for settings like hostname. I don't see any lightsail UI component to set the hostname, but if I poke at the ec2 metadata from the VM, I see some user-data. Is there any way to write to it so that cloudinit won't override a hostname I set?
EDIT:
Looks like Lightsail has its own purpse for user-data:
$ cat /var/lib/cloud/instances/user-data.txt

#!/bin/sh
echo Lightsail: Starting Instance Initialization.

cat > /etc/ssh/lightsail_instance_ca.pub << EOF
ssh-rsa nope EOF
echo Lightsail: SSH CA Public Key created.

echo >> /etc/ssh/sshd_config
echo 'TrustedUserCAKeys /etc/ssh/lightsail_instance_ca.pub' >> /etc/ssh/sshd_config
echo Lightsail: SSH CA Public Key registered.

service sshd restart
echo Lightsail: sshd restarted.

#cloud-config
hostname: pwnguin

So in cloud-init output log, it complains about hostname: command not found. I can probably put a shell command to set a hostname, but I might be out of luck on the cloudconfig route.

A: When launching your instance, you can pass the user-data containing your initial configuration (eg. hostname) as follows:
aws lightsail create-instances --instance-names <value> --availability-zone <value> --blueprint-id <value> --bundle-id <value> --user-data file:///full/path/to/myconfig

The content of myconfig file should be:
#cloud-config
hostname: test-vm


text:
Q: What word or phrase means the opposite of "white space"? I'm currently writing some C# extension methods dealing with string parsing, and I like to be terse yet descriptive and accurate in my method names.
Question: Is there a good word or phrase that describes the opposite of white space?
To be clear, this set of characters are visible and would consume ink if printed on paper.  But I don't care to use terms related to ink, paper, or printing, nor do I want to assume any particular colors.
VisibleCharacters seems the most technically accurate but a bit long.
NonWhiteSpace seems like a double negative to me. I'd rather deal in what something IS, rather than what it IS NOT.
Thanks.

A: I went with the word "glyph", and called my function HasGlyph.
It seems to correctly cover characters which are readable, visible and printable; but does not refer to white-space or control characters. It doesn't assume that the character is being displayed graphically or is being printed. It doesn't assume any color. It also covers letters, numbers, and shapes.
Plus, its also a very short name.
http://en.wikipedia.org/wiki/Glyph
In case you're curious, my extension method:
public static bool HasGlyph(this string value)
{
    if (string.IsNullOrWhitespace(value)) return false;
    // TODO: Not 100% sure if the opposite of the IsNullOrWhitespace method covers what I want, but its good enough until I find out otherwise.
    return true;
}

A: If you really mean everything but whitespace, I would suggest using the term non-whitespace character. This is also what the Perl documentation does for the \S character class, see the perlre and perlrecharclass manual pages (search for \S).
This term

*

*is more accurate than non-blank (with blank usually referring to the character with ASCII code 32)

*does not imply whitespace being not printable

Note that this definition includes characters like NUL or ESC that are neither whitespace (because they do not actually insert any kind of space) nor graphic / printable. So maybe you really want to limit yourself to graphic characters.

A: According to what you can find in the Unix manuals (man isspace), you may call them "printable characters" or "graphic characters":
   isspace()
          checks for white-space characters.  In the "C" and "POSIX" locales,
          these are: space, form-feed ('\f'), newline ('\n'), carriage return ('\r'),
          horizontal tab ('\t'), and vertical tab ('\v').

   isgraph()
          checks for any printable character except space.


text:
Q: Perl s/../../ not working as expected The code is a bit convoluted, but I simplified it a bit. I know I could easily do this:
$svn_module s#.*/##;

And pull off just the end of the module. But something strange is going on here:
#! /usr/bin/env perl
use strict;
use warnings;

my $svn_module = "http://svn.vegicorp.net/svn/trunk/SessionController";
print qq(DEBUG: svn_module = "$svn_module"\n);
$svn_module =~ s#^.*(branches/.+?/)|(trunk)/##;
print qq(DEBUG: svn_module = "$svn_module"\n);

This prints:
DEBUG: svn_module = "http://svn.vegicorp.net/svn/trunk/SessionController"
DEBUG: svn_module = "http://svn.vegicorp.net/svn/SessionController"

However, I was expecting:
DEBUG: svn_module = "http://svn.vegicorp.net/svn/trunk/SessionController"
DEBUG: svn_module = "SessionController"

Why does my substitution expression remove trunk/, but not the rest of the string up to trunk/?
By the way, adding an extra set of parentheses helps:
$svn_module =~ s#^.*((branches/.+?/)|(trunk))/##;

will work.
By the way, this is Perl 5.8.8. This is a server, and pretty much the version I'm stuck on.

A: Probably it should be this
s#^.*(?:branches/.+?/|trunk)/##;
Because, the other way it was a single alternation where the ^.* are not part
of the second alternation (the one that matched).
   ^ .*
   ( branches/ .+? / )
|
   ( trunk )

Edit: Expanded new regex explained
 ^                       # Beginning of string anchor
 .*                      # Optional match as many as possible non-newline character until ..
 (?:                     # Start non-capture grouping
      branches/ .+? /        # 'branches' plus '/' plus 1 or more chars plus '/'
   |  trunk                  # Or, 'trunk'
 )                       # End grouping

The equivalent in terms of your original regex is this
   ^ .*
   ( branches/ .+? / )
|
   ^ .*
   ( trunk )

A: I think you answered the question by yourself. The | operator has lowest precedence, so putting the additional parentheses is the solution.

A: Perhaps I'm missing something here, David, but instead of substituting everything up to the last part that you want to get what you want, why not capture just that last part?
use strict;
use warnings;

my $svn_module = "http://svn.vegicorp.net/svn/trunk/SessionController";
my ($end_module) = $svn_module =~ /([^\/]+)$/;
print $end_module;

Output:
SessionController


text:
Q: cant sort active records I am a noobie and I am trying to simply get all the records in the database and display them in alphabetical order. Whenever I display the index page the records are always sorted in descending by their id. I used the console to try calling EvalTest.order("name") and again I kept getting the records sorted by their id in descending order instead of by name. Do I need to add an index on the name column to sort by it? This seems like the answer should be so easy but I can't seem to figure it out...
Here is my code:
User Model:

    class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation
  has_secure_password
  has_many :eval_tests

  before_save { |user| user.email = email.downcase }
  before_save :create_remember_token

  validates :name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence:   true,
                     format:     { with: VALID_EMAIL_REGEX },
                     uniqueness: { case_sensitive: false }
  validates :password, presence: true, length: { minimum: 6 }
  validates :password_confirmation, presence: true
  after_validation { self.errors.messages.delete(:password_digest) }

  private

    def create_remember_token
      self.remember_token = SecureRandom.urlsafe_base64
    end
end

Eval_Test Model:
class EvalTest < ActiveRecord::Base
  attr_accessible :description, :name
  belongs_to :user

  validates :user_id, presence: true
  validates :name, presence: true
  validates :description, presence: true, length: { maximum: 350 }
  default_scope order: 'eval_tests.created_at DESC'
end

EvalTest Controller:
class EvalTestsController < ApplicationController
  def show
    @eval_test = EvalTest.find(params[:id])
  end

  def new
    @eval_test = EvalTest.new
  end

  def index
    @eval_tests = EvalTest.order("name")
  end

  def create
    @eval_test = current_user.eval_tests.build(params[:eval_test])
    if @eval_test.save
      flash[:success] = "Nouveau test cree!"
      redirect_to @eval_test
    else
      render 'new'
    end
  end
end

Evaluation Test index.html.erb:
<% provide(:title, 'Index des tests') %>

Index des tests

  <% @eval_tests.each do |eval_test| %>

      <%= link_to eval_test.name, eval_test %>

  <% end %>

A: This is happening because you have used default scope in your model. Try
@eval_tests = EvalTest.reorder("name")
This should solve your issue.


text:
Q: Initial Image bytes If I debug an asm file with Windbg the image is loaded at a location in memory, in my case its 00400000. If I dump the data from 00400000 I can see my assembly code is loaded in the image file at and offset of 10000 from this address and not at 00400000.
Here's the dump for the start of the image.
00400000 ->  00905a4d 00000003 00000004 0000ffff
00400010 ->  000000b8 00000000 00000040 00000000
00400020 ->  00000000 00000000 00000000 00000000
00400030 ->  00000000 00000000 00000000 000000c0

So, my question is what is this header at the start of the image and what is it used for? It looks like all images have this header.
Thanks in advance.

A: What you have posted looks like a PE header in 32 bit format:
0:000> dd 00400000
00400000  00905a4d 00000003 00000004 0000ffff
00400010  000000b8 00000000 00000040 00000000
00400020  00000000 00000000 00000000 00000000
00400030  00000000 00000000 00000000 00000080

If you dump it as bytes, it will show the ASCII characters along with it and you can easily recognize the "MZ" header.
0:000> db 00400000
00400000  4d 5a 90 00 03 00 00 00-04 00 00 00 ff ff 00 00  MZ..............
00400010  b8 00 00 00 00 00 00 00-40 00 00 00 00 00 00 00  ........@.......
00400020  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................
00400030  00 00 00 00 00 00 00 00-00 00 00 00 80 00 00 00  ................

You can use the !dh command to decode it:
0:000> !dh 00400000

File Type: EXECUTABLE IMAGE
FILE HEADER VALUES
     14C machine (i386)
       3 number of sections
5911398E time date stamp Mon May  8 20:37:50 2017

       0 file pointer to symbol table
       0 number of symbols
      E0 size of optional header
      22 characteristics
            Executable
            App can handle >2gb addresses
[...]

If you don't want to use WinDbg, there's Stud_PE where you can load an executable and it will analyze it for you.


text:
Q: Fragment exitTransition overlaps enterTransition For animating Fragments, I want to declare the animation at runtime based on provided inputs. Because FragmentTransaction.setCustomAnimations only uses static xml files, I am using Fragment.setEnterTransition, Fragment.setExitTransition (setCustomAnimations is not an option).
The problem I am having is that when performing a "forward" push animation, the incoming fragment is expected to slide over the outgoing fragment, and the outgoing fragment slides to the left (not fully, so the incoming one will overlap it). However, the exiting fragment is drawn on top of the incoming fragment:

For backwards navigation, this side effect provides the intended behaviour.
I believe this is an issue with setCustomAnimations as well, and have seen a solution there to swap the top two views of the fragment container.
However, this method for some reason does not work with the Fragment transitions API.
Has anyone hit this issue and found a solution?

A: I have the same problem. I couldn't find a solution so I have created the following issue:

*

*https://issuetracker.google.com/issues/194808726
Hopefully they will do something about it.
Google recommends single-activity, fragments etc. Thats all fine and well, but it is unacceptable that simple use-cases like the one you have explained are just broken after all these years. No words for it.


text:
Q: highlighting next  tag after clicking an anchor I'm using some code I found to highlight an id after clicking an anchor link.
I'd like to modify this to instead highlight the next
 tag in a definition list:

Q1

A1

Q2

A2

Q3

A3

Here is the jquery from Lincoln Loop
    function highlight(elemId){
    var elem = $(elemId);
    elem.css("backgroundColor", "#ffffff"); // hack for Safari
    elem.animate({ backgroundColor: '#ffffaa' }, 1500);
    setTimeout(function(){$(elemId).animate({ backgroundColor: "#ffffff" }, 3000)},1000);
}

if (document.location.hash) {
    highlight(document.location.hash);
}
$('a[href*=#]').click(function(){
    var elemId = '#' + $(this).attr('href').split('#')[1];
    highlight(elemId);
});

I can't seem to get the usual .next or .sibling modifications to work.

A: I'd use the next adjacent sibling selector:
highlight(elemId + ' + dd');

A: I'm not entirely sure what you're trying to achieve, but assuming that you're clicking a link on the same page, and then trying to highlight the targeted element you could use a pure css solution:
:target + dd > p { /* css */ }

It should target the p that is a direct descendant of the dd which is the immediate sibling of a target-ed dt element.
There are some caveats to this approach, though; I cant' imagine that IE < 8 (and possibly including 8) will implement it properly. And it would almost certainly require a valid doctype.
Demo at jsbin: http://jsbin.com/oqamu4


text:
Q: Changing Sharepoint to modern experience and back The entire sharepoint is set in classic experience, recently I have been creating document libraries that are in modern experience.
How to change the entire SharePoint form classic to modern experience ?
The other thing that concerns me is that in case I want to change back to classic experience because of different reasons.
Can I  switch back to classic experience on my entire sharepoint ?
I'm not sure but I think that I heard that once you switch to modern experience this process is irreversible.

A: You can control classic and modern experience of SharePoint of list and libraries in its respective settings.
Go to List/Library Settings -> Advanced settings, you will find below options. By default if you choose default experience, list and library experience will be inherited from site(be it classic or modern) and if you want to control as list/library level, you can choose any of other 2 options.

For pages which are created using classic experience, needs to be converted to modern(refer this link), but if page is created in modern experience, you cannot convert, you have to recreate page.

A: There is a site collection feature "SharePoint Lists and Libraries experience". You could activate this feature to turn off the new SharePoint list and library experience for this site collection.


text:
Q: Is there a Galactic Civil War map? Is there a map showing what areas of the galaxy the Empire and the Rebellion controlled during the time of the Galactic Civil War?

A: Technically, throughout the Civil War, the Alliance for the Restoration of the Republic really controlled one world: Mon Calamari, the homeworld of the Mon Calamaris and the Quarrens.
Everything else, including the GHQ on Yavin and Hoth, was always treated as being temporary accommodations, given that the Empire was relentlessly pursuing them.


text:
Q: Determine if Type is a pure "Data Type" Microsoft lists what I would consider "programming primitives" (I understand this is a misnomer) as "Data Types" in their documentation. The list of "Data Type" objects by their metric is thus:

Boolean
  Byte
  Char
  Date
  Decimal
  Double
  Integer
  Long
  Object
  SByte
  Short
  Single
  String
  UInteger
  ULong
  User-Defined
  UShort

Source
Currently, I am trying to create a function that generates a flat graph from a given object, because I am trying to serialize objects into JSON. The objects that I am working with have many, many circular references that always break the JSON serialize-r because it exceeds the recursion limit.
My Question:
How can I tell using introspection, reflection, what-have-you, intelligently, if an object is a "Pure" data type? As in: the object is a Boolean, Byte Char, etc, etc, not an object that simply inherits from Boolean Byte, or Char, etc.
My Reasoning:
What I hope to accomplish, is that as I recursively traverse through a given object, and am generating a flat structure from that, that I can hold onto object references in a list, and "skip" over objects that I have already hit, and just assign those Guids. The Guid will live in the JSON with the reference to the object, but for all intents and purposes (from the JSON serialize-r side of things), the circular references will be broken, allowing it to serialize.
However, things like strings, bools, nulls, those are easily describable in JSON. Is there a way as I'm checking if I have cataloged the object already, to also check if the object is a "pure Data Type"? To clarify, I still want to write strings, ints, bools, nulls, into the JSON even if I have already encountered a reference to those items.
I am also open to alternative solutions, or better ideas. I am trying to wrap my head around the problem better. Thanks in advance!

A: Not counting Object and User-Defined as "pure types", the .NET Framework Type class actually includes a property that will return True only for (most of) the built-in types: Type.IsPrimitive.
Primitive (meaning basic or simple) refers to standalone, basic types that represent a single value: They're either a single number (Integer, Long, Short, etc.), a single character (Char) or a single bit (Boolean). Thus you can check the Type.IsPrimitive property to quickly determine if the current object is any of the numerical types defined in the CLR (plus the Char).
If myObj.GetType().IsPrimitive Then

The good thing is that .NET Framework does not allow inheritance of structures, so you'll never bump into a type that inherits from, say, a Boolean.
Now you'll just need to check for the remaining non-primitive types (which too cannot be inherited) and you should have everything you need:

*

*Date

*Decimal

*String
All you need to do is:
Dim objType As Type = myObj.GetType()
If objType.IsPrimitive OrElse
    objType Is GetType(String) OrElse
     objType Is GetType(Date) OrElse
      objType Is GetType(Decimal) Then

And there you have it!
I would suggest turning this into an Extension Method for simple usage:
Imports System.Runtime.CompilerServices

Public Module Extensions

    <Extension()>
    Public Function IsPureType(ByVal Obj As Object) As Boolean
        If Obj Is Nothing Then Return False

        Dim objType As Type = Obj.GetType()
        Return objType.IsPrimitive OrElse
                objType Is GetType(String) OrElse
                 objType Is GetType(Date) OrElse
                  objType Is GetType(Decimal)
    End Function
End Module

Then you can use it like:
If myObj.IsPureType() Then

EDIT
Jimi pointed out that you can inherit TypeDelegator and override the IsPrimitiveImpl function which lets you (as a programmer) specify if your custom type is primitive or not.
However, in not a single one of my tests was I able to get Obj.GetType().IsPrimitive to return True for my custom classes. Presumably this is because Obj.GetType() returns the automatically generated RuntimeType for your custom class, and not a TypeDelegator, so there shouldn't be a need to worry.


text:
Q: Cannot use Unity Ads 2017.3.1.p1 Whenever I try to Play my game in the editor after enabling Unity Ads, I get these errors. Never had a problem before this project. I've tried upgrading to the latest patch (the one I'm on now), serializing assets as text and enabling them manually (they were already enabled), toggling ads, restarting, ect.

EDIT:
I'm not calling any ad things before it's ready. I had this code, but I commented it out just to check if the problem persists:
using UnityEngine;
using UnityEngine.Advertisements;

public class Ads : MonoBehaviour
{
    private int ShowEachTry = 3;

    private int TrysCount;

    /// <summary>
    ///
    /// </summary>
    void Start()
    {
        Debug.LogError("Ads aren't working");
        //Advertisement.Show();
    }

    public void SetTry()
    {
        TrysCount++;
        if (TrysCount >= ShowEachTry)
        {
            if (!GameManager.adsDisabled)
            {
                if (Advertisement.IsReady())
                {
                    //Advertisement.Show();
                }
            }
            TrysCount = 0;
        }
    }
}

I added the Advertisement.Show() in the start function after the problem started happening just to check.

A: When you call Advertisement.Show(); on the Start() method, Unity hasn't been able to "Get Ads" or in other words it hasn't initialized. What you should do instead is wait about 1 or 2 seconds and then call Advertisement.Show().
Example:
Using System.Collections;
IEnumerator Start()
{
    yield return new WaitForSeconds(1.5f);
    Advertisement.Show();
}


text:
Q: C++ STL Map gives TLE when looping with auto? I was working on this problem on CodeForces. My solution was giving TLE and I could not figure out why. Eventually I narrowed it to the faulty line and it was essentially the following
// map<int, set<long long>> res;
for(auto z : res) if(res[z.first].count(x)) res[z.first].erase(x);

This gives TLE on Test case 6. Now my res map has three keys at max (1,2,3). If I change the loop to-
for(int j = 1; j<=3; j++) if(res[j].count(x)) res[j].erase(x);

then the solution works and runs for all test cases. I want to understand why does the first loop not work and how to know when can I use that loop and when not?
Link to TLE submission. Link to correct submission. Only difference is in line 81-82.

A: for(auto z : res)

It copies the inner maps to z pairs each loop iteration. Try
for(auto& z : res)


text:
Q: What is the best strategy to recover from an error - neglecting the record where error occurs I am getting a No implementation found for native Ldalvik/system/VMRuntime;.pauseGc Error, below is the logCat.
05-13 22:39:22.538: W/dalvikvm(8350): No implementation found for native Ldalvik/system/VMRuntime;.pauseGc:(Ljava/lang/String;)I
05-13 22:39:22.543: E/MyThread(8350): Pause GC
05-13 22:39:22.543: E/MyThread(8350): java.lang.reflect.InvocationTargetException
05-13 22:39:22.543: E/MyThread(8350): at java.lang.reflect.Method.invokeNative(Native Method)
05-13 22:39:22.543: E/MyThread(8350): at java.lang.reflect.Method.invoke(Method.java:515)
05-13 22:39:22.543: E/MyThread(8350): at android.app.MyThread.pauseGC(MyThread.java:5525)
05-13 22:39:22.543: E/MyThread(8350): at android.app.MyThread.performLaunchActivity(MyThread.java:2324)
05-13 22:39:22.543: E/MyThread(8350): at android.app.MyThread.handleLaunchActivity(MyThread.java:2471)
05-13 22:39:22.543: E/MyThread(8350): at android.app.MyThread.access$900(MyThread.java:175)
05-13 22:39:22.543: E/MyThread(8350): at android.app.MyThread$H.handleMessage(MyThread.java:1308)
05-13 22:39:22.543: E/MyThread(8350): at android.os.Handler.dispatchMessage(Handler.java:102)
05-13 22:39:22.543: E/MyThread(8350): at android.os.Looper.loop(Looper.java:146)
05-13 22:39:22.543: E/MyThread(8350): at android.app.MyThread.main(MyThread.java:5602)
05-13 22:39:22.543: E/MyThread(8350): at java.lang.reflect.Method.invokeNative(Native Method)
05-13 22:39:22.543: E/MyThread(8350): at java.lang.reflect.Method.invoke(Method.java:515)
05-13 22:39:22.543: E/MyThread(8350): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
05-13 22:39:22.543: E/MyThread(8350): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
05-13 22:39:22.543: E/MyThread(8350): at dalvik.system.NativeStart.main(Native Method)
05-13 22:39:22.543: E/MyThread(8350): Caused by: java.lang.UnsatisfiedLinkError: Native method not found: dalvik.system.VMRuntime.pauseGc:(Ljava/lang/String;)I
05-13 22:39:22.543: E/MyThread(8350): at dalvik.system.VMRuntime.pauseGc(Native Method)
05-13 22:39:22.543: E/MyThread(8350): ... 15 more

I searched across various forums, but this bug is related to Samsung 4.4.2 and above updates for a Subset of note devices ( I have two Note devices with same specs and this bug only occurs on one of them)
The idea here is to know what is exactly causing this bug, so that I can change the course of my program to avoid a condition wherein this bug can occur. A credible or an official answer is most sought after and I am putting a bounty of 200 on this question once I get eligible.
In my case this occurs when I am doing a memory intense operation, my knowledge (Naive as it might be) tells me it has got something to do with pausing the GC, would a (manual) call to System.gc resolve things for me?
How to recover from this error? In my loop I am reading from One DB table, Address book and a file one after the other. These read values undergo calculation process and results are stored in a larger DB. These statements are in a while loop, I have put checks in try catch so that if any and not limited to this error occurs. I start from the next iteration of the loop using a continue statement in the catch clause- neglecting the record where crash occurs. However the execution is not guaranteed using this method, as the crash can keep happening forcing the subsequent records to be omitted.
Edit: here is the culprit block of code:
if(FLAG ==1){
    toRead=new File(getApplicationContext().getFilesDir()+"/Reminders/fileone.txt");
}else{
    toRead=new File(getApplicationContext().getFilesDir()+"/Reminders/output.txt");
}

//  copyDirectoryOneLocationToAnotherLocation(new File(getApplicationContext().getFilesDir()+"/Reminders/output.txt"), new File("mnt/sdcard/filecheck.txt"));

FileInputStream fis=new FileInputStream(toRead);
Scanner sc=new Scanner(fis);

String currentLine;
while(sc.hasNextLine()){
    try{
        System.out.println("count in file"+i);

        currentLine=sc.nextLine();
        // TODO = gets concatnated
        StringTokenizer st=new StringTokenizer(currentLine,"=",false);
        CONTACT_NAME = toTitleCase(st.nextToken());

        if(CONTACT_NAME.contains("'")){
            CONTACT_NAME = CONTACT_NAME.replace("'", "");
        }
        // *********
        String listStr = st.nextToken();
        String cut = listStr.substring(1, listStr.length() - 1);
        String[] array = cut.split(",");

        //      System.out.println("Array is: "+Arrays.toString(array));

        CONTACT_ID = (array[0].trim());
        String dateStr = (array[1].trim());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = format.parse(dateStr);
        java.sql.Date dx = new java.sql.Date(date.getTime());
        Date key = dx;
        dateToInsert = String.valueOf(dx);

        CONTACT_IMAGE_URI = (array[2].trim());
        if(CONTACT_IMAGE_URI.contains("?typ")){
            CONTACT_IMAGE_URI = CONTACT_IMAGE_URI+"e=normal";
        }
        if (isCancelled()) {
            break;
        }
        progress = ("" + Character.toUpperCase(CONTACT_NAME.charAt(0)) + CONTACT_NAME.substring(1) + "\n"+i + " of " + lines + " Contacts"); // Progress displayed here.
        years = getDiffYear(key);               // For years elapsed
        secon = seconds(key);                   // for seconds elapsed
        min = seconds(key) / 60;                // For minutes elapsed
        hours = getDiffHour(key);// For hours elapsed
        mon = months(String.valueOf(key));      // for months elapsed
        days = daysElapsed(key);                // Days elapsed
        weeks = daysElapsed(key) / 7;           // For weeks

        //===============================================================================================================
        if (dateToInsert.contains("0001-") == true){ //Special Case, we added 0001 to Birthdays Which Have NO Year field.
            //===========================================================================================================

            dbHelper.insert(dateToInsert, CONTACT_NAME, "","", CONTACT_IMAGE_URI, "", "", "", CONTACT_ID, "", "","1"); // All other fields will be empty, because we don't have a Year.
            int PRIMARY_ID = dbHelper.getPrimaryId();
            String FOREIGN_KEY = dbHelper.getHighestID(PRIMARY_ID);

            //=====================================================================================================
            //In this case we are only interested in fetching the year alert for next birthday of this contact -->
            //=====================================================================================================

            intCal.yearsToNotify(years, dateToInsert);
            int yearsSpecial = intCal.getYearsRegular();
            Date dateYearsReg = intCal.getYearsRegDate();

            dbHelper.insertNotifications(5, convertDate(dateYearsReg), 0, yearsSpecial,FOREIGN_KEY,PRIMARY_ID,CONTACT_IMAGE_URI,dateToInsert );

        }
        //=========================================================================
        //Case when all the Date fields exist and we set up notifications  --->
        //=========================================================================
        else if(dateToInsert != "null" && dateToInsert.contains("0001-") != true){
            dbHelper.insert(dateToInsert, CONTACT_NAME, String.valueOf(days), String.valueOf(hours), CONTACT_IMAGE_URI, String.valueOf(min),String.valueOf(mon), String.valueOf(secon), CONTACT_ID, String.valueOf(weeks), String.valueOf(years),"1");
            int PRIMARY_ID = dbHelper.getPrimaryId(); // Fetch the PrimaryId (_id) of the above inserted row, its the Foreign key for Notification and SpecialNotifications Table.
            String FOREIGN_KEY = dbHelper.getHighestID(PRIMARY_ID); // Same as above, but fetches the Name field of the last inserted row.

            //=========================================================================
            //**Database Insertions Notifications Table/ SpecialNotifications Table**
            //=========================================================================

            //=======================================================================================//
            //Regular intervals DB Insertions:
            //======================================================================================//
            //Notification Types:
            //1 for months
            //2 for weeks
            //3 for days
            //4 for minutes
            //5 for years
            //6 for seconds
            //7 for hours
            //======================================================================================//

            //==============================
            //For Months
            //==============================
            intCal.monthsNotify(mon, dateToInsert);
            int monSpecial =  intCal.getMonthRegular();
            Date dateMonReg = intCal.getMonRegDate();

            dbHelper.insertNotifications(1, convertDate(dateMonReg), 0, monSpecial,FOREIGN_KEY,PRIMARY_ID,CONTACT_IMAGE_URI,dateToInsert );

            //===============================
            //For Weeks
            //===============================
            intCal.weeksToNotify(weeks,dateToInsert);
            int weekSpecial = intCal.getWeekRegular();
            Date dateWeekReg =intCal.getWeekRegDate();

            dbHelper.insertNotifications(2, convertDate(dateWeekReg), 0, weekSpecial,FOREIGN_KEY,PRIMARY_ID,CONTACT_IMAGE_URI,dateToInsert );

            //===============================
            //For Days
            //===============================
            intCal.daysToNotify(days, dateToInsert);
            int daysSpecial= intCal.getDaysRegular();
            Date dateDaysReg = intCal.getDaysRegDate();
            dbHelper.insertNotifications(3, convertDate(dateDaysReg), 0, daysSpecial,FOREIGN_KEY,PRIMARY_ID,CONTACT_IMAGE_URI,dateToInsert );

            //===============================
            //For minutes
            //===============================
            intCal.minutesToNotify(min,dateToInsert);
            long minutesSpecial= intCal.getMinutesRegular();
            Date dateMinsReg = intCal.getMinutesRegDate();
            dbHelper.insertNotifications(4, convertDate(dateMinsReg), 0,(int) minutesSpecial,FOREIGN_KEY,PRIMARY_ID,CONTACT_IMAGE_URI,dateToInsert );
            //==============================
            //For Years
            //==============================
            intCal.yearsToNotify(years, dateToInsert);
            int yearsSpecial = intCal.getYearsRegular();
            Date dateYearsReg = intCal.getYearsRegDate();
            dbHelper.insertNotifications(5, convertDate(dateYearsReg), 0, yearsSpecial,FOREIGN_KEY,PRIMARY_ID,CONTACT_IMAGE_URI,dateToInsert );
            //=============================
            //For Seconds
            //=============================
            intCal.secondsToNotify(secon, dateToInsert);
            long secondsSpecial= intCal.getSecondsRegular();
            Date dateSecondsReg = intCal.getSecondsRegDate();
            dbHelper.insertNotifications(6, convertDate(dateSecondsReg), 0, secondsSpecial,FOREIGN_KEY,PRIMARY_ID,CONTACT_IMAGE_URI,dateToInsert );

            //=============================
            //For Hours
            //=============================
            intCal.hoursToNotify(hours, dateToInsert);
            int hoursSpecial= intCal.getHoursRegular();
            Date dateHoursReg= intCal.getHoursRegDate();
            dbHelper.insertNotifications(7, convertDate(dateHoursReg), 0, hoursSpecial,FOREIGN_KEY,PRIMARY_ID,CONTACT_IMAGE_URI,dateToInsert );

            //============================================================================================//
            //Special Intervals
            //============================================================================================//
            //Notification Types:
            //1 for months
            //2 for weeks
            //3 for days
            //4 for minutes
            //5 for years
            //6 for seconds
            //7 for hours
            //For Years

            intCal.specialIntervalYears(years, dateToInsert);
            int yearsOnceSpecial =intCal.getYearsSpecial();
            Date dateYearsSpecial = intCal.getYearsSpDate();
            dbHelper.insertSpecialNotifications(5, convertDate(dateYearsSpecial), yearsOnceSpecial,FOREIGN_KEY,PRIMARY_ID);

            //For Months
            intCal.specialIntervalMonths(mon,dateToInsert);
            int monthsOnceSpecial= intCal.getMonthsSpecial();
            Date dateMonthsSpecial = intCal.getMonthsSpDate();
            dbHelper.insertSpecialNotifications(1, convertDate(dateMonthsSpecial), monthsOnceSpecial,FOREIGN_KEY,PRIMARY_ID);

            //For Weeks
            intCal.specialIntervalsWeeks(weeks,dateToInsert);
            int weeksOnceSpecial= intCal.getWeeksSpecial();
            Date dateWeeksSpecial = intCal.getWeeksSpDate();
            dbHelper.insertSpecialNotifications(2, convertDate(dateWeeksSpecial), weeksOnceSpecial,FOREIGN_KEY,PRIMARY_ID);

            //For Days
            intCal.specialIntervalsDays(days, dateToInsert);
            int daysOnceSpecial= intCal.getDaysSpecial();
            Date dateDaysSpecial = intCal.getDaysSpDate();
            dbHelper.insertSpecialNotifications(3, convertDate(dateDaysSpecial), daysOnceSpecial,FOREIGN_KEY,PRIMARY_ID);

            //For Hours
            intCal.specialIntervalsHours(hours,dateToInsert);
            int hoursOnceSpecial= intCal.getHoursSpecial();
            Date dateHoursSpecial = intCal.getHoursSpDate();
            dbHelper.insertSpecialNotifications(7, convertDate(dateHoursSpecial), hoursOnceSpecial,FOREIGN_KEY,PRIMARY_ID);

            //For Minutes
            intCal.specialIntervalMinutes(min,dateToInsert);
            long minutesOnceSpecial= intCal.getMinutesSpecial();
            Date dateMinutesSpecial= intCal.getMinutesSpDate();
            dbHelper.insertSpecialNotifications(4, convertDate(dateMinutesSpecial), (int)minutesOnceSpecial,FOREIGN_KEY,PRIMARY_ID);

            //For Seconds
            intCal.specialIntervalsSeconds(secon,dateToInsert);
            long secondsOnceSpecial= intCal.getSecondsSpecial();
            Date dateSecondsSpecial= intCal.getSecondsSpDate();
            dbHelper.insertSpecialNotifications(6, convertDate(dateSecondsSpecial), secondsOnceSpecial,FOREIGN_KEY,PRIMARY_ID);
        }

        publishProgress(progress);
        Asycdialog.setMax(lines);
        Asycdialog.incrementProgressBy(1);
        i++;
    }catch (Exception e){
        System.out.println("From catch 4"+e);
        continue;
    }
}

Edit 2:
I am doing the above process inside a try catch wherein I am using transactions to speed up things. I have implemented these transaction snippets at the opening of the try block, where I start the transaction and I end them at the finally block and set them successful at the same place.

A: It seems to be a Samsung specific bug. It has been reported to

*

*AOSP issue tracker

*at Samsung developer forum here and here
So far there does not seem to be a solution except updating your Android version (if I got that right).

A: I would suggest to change the dbHelper.insert to be done inside a transaction this may walk-around the issue.
Although your code works is really slow and memory intensive so it may lead straight to an existing bug or occur only in "stressed" devices.
When you insert data to SQLite this way
 private void execQuery(String tableName,ContentValues val)
 {
    sqliteDb = instance.getWritableDatabase();
    sqliteDb.insert(tableName, null, val);
    return true;
 }

the android method .insert performs a lot of safe checks and then insert them. This procedure I guess allocates a lot of memory and as I measured before takes a lot more execution time than the creation of transaction and inserting data on that.
String sql = "INSERT INTO table (col1, col2) VALUES (?, ?)";
db.beginTransaction();

SQLiteStatement stmt = db.compileStatement(sql);
for (int i = 0; i < values.size(); i++) {
    stmt.bindString(1, values.get(i).col1);
    stmt.bindString(2, values.get(i).col2);
    stmt.execute();
    stmt.clearBindings();
}

db.setTransactionSuccessful();
db.endTransaction();

Note that transaction should start before first insert and end after last insert not a transaction for each insert.
More about transactions at SO here.
I know that my answer may look too irrelevant to the question but I am quite positive that the error would be avoided that way and also the performance will be much improved. Sometimes is better to change the whole logic instead of handling the error.


text:
Q: Sage accounting software tag as opposed to sagemath I am reviewing suggested Edits this morning and came across one where the editor has removed the sage tag from this question: Sage Accpac Ireport method failed
They left this note:

sage tag only is for sage math software (sagemath.org). To whoever moderates this - what would a good tag for the accounting software be? Clearly one is needed, this happens about once a week.

I personally don't know anything about either piece of software so I figured I would pass along their question here to bring more attention to the matter.
EDIT:
P.S. props go to kcrisman for bringing this issue up.
EDIT2:
More information about the 2 different software that sage may refer to:

*

*Sage ERP AccPac or Sage 300 ERP: http://na.sage.com/sage-300-erp/

*SageMath: http://www.sagemath.org/

A: I like @nhahtdh's answer, and suggest upgrading it to have

*

*sagemath for Sage math

*sage-accounting for the whole suite of Sage accounting software

*sagepay already exists for the UK online payment version of the Sage accounting software, apparently

*sage would then be a disallowed tag somehow, if that's possible.

As long as all current sage tags are migrated to the proper new tag, I think this would be acceptable to those of us who answer Sage (math) questions.  I don't think that there is a Sage accounting answering community in the same way ;-)


text:
Q: Shiny - Switching Between Models I've built a shiny app to model smooth surfaces. Thin plate splines and tensor product smooths. Unfortunately, when I try call input$Mod using functions such as get() it breaks.
How can I call model fits? I don't want to remodel the same data on repeat each time the user makes an input selection.
The app reads a locally stored CSV
Shiny App
# Clear all
rm(list = ls(all.names = T))
gc()

iris <- get(data("iris"))
write.csv(iris, file = 'iris.csv', row.names = FALSE)

library(tidyverse)
library(mgcv)

# UI
ui <- navbarPage(title = "Analytics",
                 tabPanel("Models",
                          sidebarLayout(
                            sidebarPanel(width = 3,

                                         fileInput(inputId = "file1",
                                                   label = "Upload CSV",
                                                   accept = c(".csv")),

                                         uiOutput("RespSelector"),

                                         uiOutput("PredSelector"),

                                         selectInput(inputId = "Mod",
                                                     label = "Model Type:",
                                                     choices = c("Thin Plate Spline" = 'Model1',
                                                                 "Tensor Product Smooth" = 'Model2'))
                                         ),

                            mainPanel(
                              verbatimTextOutput("Summary1"),
                              br(),
                              verbatimTextOutput("Summary2"))

                            )))

# Server
server <- function(input, output, session) {

  # Upload CSV
  csv_data <- reactive({req(input$file1)

    # Read CSV and lightly trim tails
    read_csv(input$file1$datapath) %>%
      rowid_to_column("ID")
  })

  # Extract numeric colnames
  VARS_numeric <- reactive({req(input$file1, input$file1$datapath, csv_data())

    csv_data() %>%
      select(where(is.numeric), -ID) %>%
      colnames() %>%
      sort()
  })

  # Render response for UI selector
  output$RespSelector <- renderUI({req(input$file1, input$file1$datapath, csv_data(), VARS_numeric())
    selectizeInput(inputId = "response",
                   label =  "Select 1 response variable",
                   selected = NULL,
                   choices = VARS_numeric(),
                   multiple = FALSE)
  })

  # Render predictor UI selector
  output$PredSelector <- renderUI({req(input$file1, input$file1$datapath, csv_data(), VARS_numeric())
    selectizeInput(inputId = "predictors",
                   label =  "Select 2 predictors variables",
                   choices = VARS_numeric()[!(VARS_numeric() %in% input$response)],
                   multiple = TRUE,
                   options = list(maxItems = 2))
  })

  # Data
  Data <- reactive({req(input$file1, input$file1$datapath, csv_data(), VARS_numeric(), input$predictors, input$predictors[1], input$predictors[2], input$response)
    csv_data()
  })

  # s(x1,x2) Equation
  ModelEquation1 <- reactive({req(input$file1, input$file1$datapath, csv_data(), VARS_numeric(), input$predictors, input$predictors[1], input$predictors[2],
                                  input$response, Data())
    Equation1 <- as.formula(paste0(input$response," ~ ", 's(', input$predictors[1],',', input$predictors[2], ', bs = "tp")'))
  })

  # te(x1,x2) Equation
  ModelEquation2 <- reactive({req(input$file1, input$file1$datapath, csv_data(), VARS_numeric(), input$predictors, input$predictors[1], input$predictors[2],
                                  input$response, Data())
    Equation2 <- as.formula(paste0(input$response,' ~ ', 'te(',input$predictors[1],',',input$predictors[2],')'))
  })

  # Model 1
  Model1 <- reactive({req(input$file1, input$file1$datapath, csv_data(), VARS_numeric(), input$predictors, input$predictors[1], input$predictors[2],
                          input$response, Data(), ModelEquation1())
    gam(ModelEquation1(), method="REML", data = Data())
  })

  # Model 2
  Model2 <- reactive({req(input$file1, input$file1$datapath, csv_data(), VARS_numeric(), input$predictors, input$predictors[1], input$predictors[2],
                          input$response, Data(), ModelEquation2())
    gam(ModelEquation2(), method="REML", data = Data())
  })

  # Summary
  output$Summary1 <- renderPrint({req(Model1(), Model2())
    summary(get(Model1()))
  })

}

# Create Shiny app
shinyApp(ui = ui, server = server)

A: If that is the only issue, you change your selectInput() as
selectInput(inputId = "Mod", label = "Model Type:", choices = c("Thin Plate Spline" = 'Model1',
                                                                 "Tensor Product Smooth" = 'Model2'))

Then create a eventReactive model as
  myModel <- eventReactive(input$Mod, {
    switch(input$Mod,
           "Model1" = Model1b(),
           "Model2" = Model2b())
  })

and lastly use this in predict as
Z <- matrix(predict(myModel(), newdat), steps, steps)


text:
Q: Terraform fails with timeout creating aws resources I want to use a terraform script to create an ec2 instance. I want also to be able to connect to the machine using SSH and a key-pair created in the AWS console.
This is the relevant portion of the script:
resource "aws_instance" "web" {
  instance_type = "t2.micro"
  ami = "${lookup(var.aws_amis, var.aws_region)}"

  key_name = "${var.key_name}" # this is my keypair
  connection {
    type = "ssh"
    user = "${var.ssh_user}"
  }
  vpc_security_group_ids = ["${aws_security_group.default.id}"]
  subnet_id = "${aws_subnet.default.id}"
  provisioner "remote-exec" {
    inline = [
      "sudo apt-get -y update"
    ]
  }
}

Then, after 5 minutes a get a timeout indicating that terraform could not connect to the ec2 instance
aws_instance.web: Still creating... (5m20s elapsed)
aws_instance.web (remote-exec): Connecting to remote host via SSH...
aws_instance.web (remote-exec):   Host: 34.250.66.198
aws_instance.web (remote-exec):   User: ubuntu
aws_instance.web (remote-exec):   Password: false
aws_instance.web (remote-exec):   Private key: false
aws_instance.web (remote-exec):   SSH Agent: true
Error applying plan:

1 error(s) occurred:

* aws_instance.web: 1 error(s) occurred:

* timeout

However, even if terraform files with a timeout

*

*All the resources are actually created successfully

*I am able to list them on the AWS console

*I'm able to manually connect through SSH + pem file to the instance without any issue (even before the timeout error): ssh -i "aws.pem" ubuntu@instance_ip
This information might be relevant:
* terraform version: v0.10.7
* region: eu-west-1
* OS: El Capitan 10.11.6
Just in case this is how i'm mapping the amis
variable "aws_amis" {
  default = {
    eu-west-1 = "ami-674cbc1e"
    us-east-1 = "ami-1d4e7a66"
    us-west-1 = "ami-969ab1f6"
    us-west-2 = "ami-8803e0f0"
  }
}

Thanks a lot for your help

A: You need to specify the private key in the connection, something like this:
provisioner "remote-exec" {
    inline = [
        "sudo apt-get -y update"
    ]
    connection {
        private_key = "${file("/location/of/the/pem/file")}"
    }
}


text:
Q: Getting error for adding InfogainLoss layer? I followed the instructions here to create weight matrix for classes and add the Infogainloss function, which is able to tackle my imbalance data. The few last layers
    ....
layer {
      name: "score_fr"
      type: "Convolution"
      bottom: "fc7"
      top: "score_fr"
      param {
        lr_mult: 1
        decay_mult: 1
      }
      param {
        lr_mult: 2
        decay_mult: 0
      }
      convolution_param {
        num_output: 5 #21
        pad: 0
        kernel_size: 1
        weight_filler {
            type: "xavier"
        }
        bias_filler {
            type: "constant"
         }
      }
    }
    layer {
      name: "upscore"
      type: "Deconvolution"
      bottom: "score_fr"
      top: "upscore"
      param {
        lr_mult: 0
      }
      convolution_param {
        num_output: 5 #21
        bias_term: false
        kernel_size: 64
        stride: 32
        group: 5 #2
        weight_filler: {
             type: "bilinear"
         }
      }
    }
    layer {
      name: "score"
      type: "Crop"
      bottom: "upscore"
      bottom: "data"
      top: "score"
      crop_param {
        axis: 2
        offset: 19
      }
    }
    layer {
      name: "accuracy"
      type: "Accuracy"
      bottom: "score"
      bottom: "label"
      top: "accuracy"
      include {
        phase: TEST
      }
    }
    layer {
      name: "prob"
      type: "Softmax" # NOT SoftmaxWithLoss
      bottom: "score"
      top: "prob"
      softmax_param { axis: 1 } # compute prob along 2nd axis
    }
    layer {
      bottom: "score"
      bottom: "label"
      top: "infoGainLoss"
      name: "infoGainLoss"
      type: "InfogainLoss"
      infogain_loss_param {
        source: "/.../infogainH.binaryproto"
        axis: 1  # compute loss and probability along axis
      }
    }

And edited/added the files that have been included in this link. However, it is giving an error while creating the layer in the network:
I0221 05:25:20.213062  5265 solver.cpp:91] Creating training net from net file: train_val.prototxt
[libprotobuf ERROR google/protobuf/text_format.cc:274] Error parsing text-format caffe.NetParameter: 604:9: Message type "caffe.InfogainLossParameter" has no field named "axis".
F0221 05:25:20.213347  5265 upgrade_proto.cpp:88] Check failed: ReadProtoFromTextFile(param_file, param) Failed to parse NetParameter file: train_val.prototxt
*** Check failure stack trace: ***

*

*How can I solve this error? from which point this error stem from?

*And what is this parameter exactly doing?
softmax_param { axis: 1 } # compute prob along 2nd axis
I would really appreciate if someone could post any suggestion.
Thanks.


text:
Q: what is the issue with my shiny code that is not spitting out the ggplot plot? I am new to making shiny apps. Essentially I am trying to make a shiny app that does the following:

*

*ui allows you to load a df from your local computer

*the df is read and then the user can select two other inputs from drop down menu -column names from the dataframe to plot a ggplot

*gives the output ggplot

Here is what is happening

*

*the df is read in fine

*the dropdown select menu input in the ui work fine

*the ggplot is just not responsive

Here is my code:
library(shiny)
library(readxl)
library(ggplot2)
library(dplyr)

ui <- fluidPage(
  titlePanel("Upload Excel Sheet"),
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Choose Excel Sheet",
                accept = c(
                  "text/csv",
                  "text/comma-separated-values,text/plain",
                  ".csv")),
     selectInput("x", "X-axis", choices = ""),
     selectInput("y", "Y-axis", choices = "")
     ),
    mainPanel(
      plotOutput("plot1")
    )
  )
)

server <- function(input, output,session) {
  data <- reactive({
    inFile <- input$file1
        if (is.null(inFile))
      return(NULL)
        read_excel(inFile$datapath)
  })
  observe({
    updateSelectInput(session, "x", choices = names(data()))
    updateSelectInput(session, "y", choices = names(data()))
  })

  output$plot1<- renderPlot({
    data()%>%ggplot(aes(x=input$x, y=input$y))+geom_bar(stat="identity"))
  })
}

shinyApp(ui = ui, server = server)

What I have tried:

*

*I have replaced the plot output (renderPlot) with a table output (renderTable) and see that the code "reads" the df and spits out the table.

*I have pulled the df in a separate piece of code (read_excel) into R and then run the ggplot command on it and it seems to be working fine.

I feel like I am missing something obvious here, and perhaps something critically basic. If possible please try the code on any excel sheet in your local dir.

A: Several things need to be adjusted here.

*

*There is an extra close-paren with geom_bar(stat="identity")), removed.

*ggplot2 aesthetics need to be either non-standard evaluation symbols (not workable here), or we need to use a technique described here: https://ggplot2.tidyverse.org/articles/ggplot2-in-packages.html#using-aes-and-vars-in-a-package-function-1. Namely, .data[[varname]] (with strings) or {{ varname }} (with user-provided NSE symbols). We'll use the former here.

Some optional things for more resiliency (and good code practices):

*I suggest the use of req(.) liberally. See my examples. It not only handles some of the if (is.null(..)) you have to deal with, it also very well handles  downstream reactivity.

*You allow ".csv" but always use read_excel, I've fixed that by including a simple if.
Code.
server <- function(input, output,session) {
  data <- reactive({
    req(inFile <- input$file1$datapath)
    if (grepl("csv$", inFile)) {
      read.csv(inFile)
    } else {
      read_excel(inFile$datapath)
    }
  })
  observe({
    updateSelectInput(session, "x", choices = names(data()))
    updateSelectInput(session, "y", choices = names(data()))
  })

  output$plot1<- renderPlot({
    req(data(), input$x, input$y)
    data() %>%
      ggplot(aes(x=.data[[ input$x ]], y=.data[[ input$y ]])) +
      geom_bar(stat="identity")
  })
}

Extension: in addition to req, I also recommend becoming familiar with validate and need. For instance, if we update your data <- reactive(.) to be:
  data <- reactive({
    req(inFile <- input$file1$datapath)
    if (grepl("csv$", inFile)) {
      out <- readr::read_csv(inFile)
    } else {
      out <- readr::read_excel(inFile$datapath)
    }
    isnum <- sapply(out, is.numeric)
    validate(
      need(sum(isnum) >= 2, "We need at least two numeric columns")
    )
    out
  })

(and no other changes anywhere else), then all dependent reactive blocks "see" the problem. For instance, if I feed a CSV with insufficient numeric columns, we see

where we would normally see

(where the plot is peeking out on the bottom).


text:
Q: How to visualize a blockingcollection I think i have some problems with logic right now.
I have used a blocking collection to make thread safe calls to other PCs. In general it looks like this:
public class MyClass
{
  private BlockingCollection<workUnit> workUnits = new BlockingCollection<workUnit>();

  public void EnQueue(workUnit item)
  {
    workUnits.Add(item);
  }

  private void DeQueue()
  {
    while (!stopFlag)
    {
      workUnit item = workUnits.Take();
      DoLongRunningDBStuff(workUnit);
    }
  }
}

Now I want to visualize this to a user.
A user should see that

*

*items are in Queue

*item processing has started

*result of processing (mainly passed/failed/exception)

And now I got some headache.
I was thinking to do the following:
Have a Grid to display the items to users.

*

*If item is Enqueued add it to workunits and additionally to a list bound to the datagrid

*If item is Dequeued (consumed) update the item in the list for the grid.

What makes the headache, is how to make this thread safe, and which parts are needed to be thread safe.
If I put something which takes time behind workUnit.Add I think it could be possible, that data gets mixed.
Would something like this be feasible?

*

*If item is Enqueued add it to workunits and an additional BlockingCollection for UI

*If item is Dequeued, make a tryget on 2. BlockingCollection and remove it there, update the status and attach it to second list again.

Would I need an additional lock aound 1 and 2? If so, wouldn't it block completly the add if waiting for Take?
Is there an easy solution or approach to visualize, what is going on?

A: I will try do it this way:
public class MyClass
{
  private BlockingCollection<workUnit> workUnits = new BlockingCollection<workUnit>();

  public void EnQueue(workUnit item)
  {
    workUnits.Add(item);
  }

  private void DeQueue()
  {
    while (!stopFlag)
    {
      workUnit item = workUnits.Take();
      item.SetState("Processing Started");
      try
      {
          DoLongRunningDBStuff(workUnit);
          item.SetState("Processing Successful");
      }
      catch
      {
          item.SetState("Processing Failed");
      }
    }
  }
}

in this example I would then make workItem.SetState(...) fire an event that will update UI for the particular item. However, because the event is raised in a non-UI thread, it will be the handler of the event (the form displaying the grid I would assume) that would need to post the update into the context of the UI thread (e.g. If you are using WinForms you would call the Invoke method of the control displaying the data).
In another (preferred) suggestion I would do the following (if you can use the TPL in .NET 4.0 and later):
public class MyClass
{
  public Task EnQueue(workUnit item)
  {
    // Schedule the work on the thread pool.
    // If you need limited concurrency here, there are schedulers to enable this.
    return Task.Run(() => DoLongRunningDBStuff(item));
  }
}

And if you use .NET 4.5 you would be able to use the await feature that would automatically synchronise the continuation of the task in the context of the UI thread. E.g. in the on the caller's side (assuming it is initiated on the UI thread) you would simply do the following:
private async void btnAddItem_Click(object sender, EventArgs e)
{
    var item = new workUnit();

    // TODO: Add item on UI here

    try
    {
        await myClass.EnQueue(item);

        // TODO: Update UI with success result here (no context synchronisation is needed here it is already in the UI context)
    }
    catch
    {
        // TODO: Update UI with error result here (no context synchronisation is needed here it is already in the UI context)
    }
}

In both examples you do not even need any locking, you simply need to have the updates posted to the correct context (and in the last example that is not even explicitly needed, the compiler takes care of it for you)


text:
Q: Application of 'apply' functions in R I have got the following list which was generated by using split function with state as index.
 $AK
                   Hospital_Name         State     Mortality_Rate
  99  PROVIDENCE ALASKA MEDICAL CENTER    AK           13.4
 100   MAT-SU REGIONAL MEDICAL CENTER    AK           17.7
 102      FAIRBANKS MEMORIAL HOSPITAL    AK           15.5

 $AL
                                 Hospital_Name        State   Mortality_Rate
  1                 SOUTHEAST ALABAMA MEDICAL CENTER    AL           14.3
  2                    MARSHALL MEDICAL CENTER SOUTH    AL           18.5
  3                   ELIZA COFFEE MEMORIAL HOSPITAL    AL           18.1

$AR
                             Hospital_Name       State   Mortality_Rate
 193           SILOAM SPRINGS MEMORIAL HOSPITAL    AR           15.6
 194            JOHNSON REGIONAL MEDICAL CENTER    AR           16.9
 195 WASHINGTON REGIONAL MED CTR AT NORTH HILLS    AR           15.2

I want to select Hospital Name of 2nd row from each of these states. Can somebody help with an apply function here? I was trying to use sapply the following way(not working) -
       x <- sapply(test.case3,function(i) test.case3[[i]][2,1])

so that, by varying 'i', I can get result as follows -
   > test.case3[[1]][2,1]
    [1] "MAT-SU REGIONAL MEDICAL CENTER"
   > test.case3[[2]][2,1]
    [1] "MARSHALL MEDICAL CENTER SOUTH"
   > test.case3[[3]][2,1]
    [1] "JOHNSON REGIONAL MEDICAL CENTER"

Kindly advise.
I required to produce the final report in the following format.(ignore the data, in below example)
       Hospital_Name                    State
    D W MCMILLAN MEMORIAL HOSPITAL       AL
   ARKANSAS METHODIST MEDICAL CENTER     AR
   JOHN C LINCOLN DEER VALLEY HOSPITAL   AZ


text:
Q: How can I customize the accessory disclosure image in a UITableViewCell? I would like to use a custom version of the standard disclosure accessory image in my UITableView. How can I do this? I'm hoping that sub-classing UITableViewCell is not necessary for something this basic.

A: I ran into the same problem as Greg--the accessory view doesn't track (if you use an UIImageView)
I solved it like this:
UIImage * image = [ UIImage imageNamed:@"disclosure-button-grey.png" ] ;
UIControl * c = [ [ UIControl alloc ] initWithFrame:(CGRect){ CGPointZero, image.size } ] ;

c.layer.contents = (id)image.CGImage ;
[ c addTarget:self action:@selector( accessoryTapped: ) forControlEvents:UIControlEventTouchUpInside ] ;
cell.accessoryView = c ;
[ c release ] ;

A: You'll need to create a custom view and assign it to the accessoryView property of the UITableViewCell object. Something like:
myCell.accessoryView = [[ UIImageView alloc ]
                       initWithImage:[UIImage imageNamed:@"Something" ]];

A: - (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    UIImage *indicatorImage = [UIImage imageNamed:@"Arrow.png"];
    cell.accessoryView =[[[UIImageView alloc]  initWithImage:indicatorImage] autorelease];

    return cell;
}

well i do this with the help code given above

A: I'd do it as follows:
UIImageView *chevronImgVw = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"chevron_accessory_vw_img.png"]];
chevronImgVw.frame = CGRectMake(cell.accessoryView.frame.origin.x, cell.accessoryView.frame.origin.y, 10, 20);
cell.accessoryView = chevronImgVw;

A: There is a nice example from Apple showing how to use UIControl to fulfill this kind of accessoryView customisation.
Overriding - (void)drawRect:(CGRect)rect in UIControl is not the easiest way, but gives you lots of flexibility to style nice accessory views.

A: Swift 4 & 5:
This worked for me:
class MyCell: UITableViewCell {

// boilerplate...

    fileprivate func commonInit() {
        // This is the button we want, just need to change the image.
        accessoryType = .detailButton
    }

    open override func layoutSubviews() {
        super.layoutSubviews()
        // Grab the "detail" button to change its icon. Functionality is set in the delegate.
        if let submitButton = allSubviews.compactMap({ $0 as? UIButton }).first {
            submitButton.setImage(#imageLiteral(resourceName: "icons8-enter-1"), for: .normal)
        }
    }

   // everything else...
}

Best of all, this lets me use tableView(_:accessoryButtonTappedForRowWith:) to handle the button actions.
I used this for the button, but the same technique works for the disclosure image, [since/so long as] there is only one class in that branch of the hierarchy tree of the element you want to touch.

Oh, right, my code calls this:
extension UIView {
    var allSubviews: [UIView] {
        return subviews.flatMap { [$0] + $0.allSubviews }
    }
}

A: In swift 4 & 5
myCell.accessoryView = UIImageView(image: UIImage(named: "Something"))

A: NOTE: Do NOT set a custom cell to tag:0. That tag is reserved for the textLabel view. If you set tags in Xcode Storyboard, you must set tags for custom views/labels to 1 or higher.
Note Apple's example:
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath (NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    UILabel *label;

    label = (UILabel *)[cell viewWithTag:1];
    label.text = [NSString stringWithFormat:@"%d", indexPath.row];

    label = (UILabel *)[cell viewWithTag:2];
    label.text = [NSString stringWithFormat:@"%d", NUMBER_OF_ROWS - indexPath.row];

    return cell;
}

A: I tried the above code and it doesn't seem to work anymore, maybe due to the age of this post so I'll throw down my line that gave me the customized accessory view.
[cell setAccessoryView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrowBtn"]]];

Hope someone finds this useful.


text:
Q: C# XNA Random tile engine public void Draw(SpriteBatch theSpriteBatch)
    {
        Random rand = new Random();
        for(int y = 0; y < map.GetLength(0); y++) {
            for(int x = 0; x < map.GetLength(1); x++) {
                theSpriteBatch.Draw(tile[rand.Next(0,3)], new Rectangle(x*tileWidth,y*tileHeight,tileWidth,tileHeight),
                    Color.White);
            }
        }
    }

When I do this it just flickers the tiles and constantly redraws them. What do I do to get the random effect with it only drawing once? Is there a way I could click on these tiles with the mouse and have them change? Also, is there a way to make one tile more prevalent than the others?

A: I believe you are looking to only randomly generate the tiles one time and then draw THAT random sequence every time. Remember, Draw in XNA runs every "frame", which is generally way more than once per second!
Copy your current loops over to a new area: your map loading. Also add a 2D data structure (array or whatever) to store the results of your tile generation. I'm calling my sample 2D integer array tileNums. Now, keep the loops as they are now but change the innards to store the results instead of draw:
    Random rand = new Random();
    for(int y = 0; y < map.GetLength(0); y++) {
        for(int x = 0; x < map.GetLength(1); x++) {
            tileNums[x, y] = rand.Next(0,3);
        }
    }

Now just change the innards of your current Draw loop to no longer generate randomly and instead to take from this data:
    //Random object no longer needed
    for(int y = 0; y < map.GetLength(0); y++) {
        for(int x = 0; x < map.GetLength(1); x++) {
            theSpriteBatch.Draw(tile[tileNums[x, y]], new Rectangle(x*tileWidth,y*tileHeight,tileWidth,tileHeight),
                Color.White);
        }
    }