text:
Q: Lie algebras and the universal envelope algebra on direct sums On Page 13 of Bourbaki's Chapter I on Lie algebras, it is proven that if $\mathfrak g_1, \mathfrak g_2$ are Lie algebras and $\mathrm U$ denotes the functor from the category of Lie algebras over a field $F$ to the category of associative unital $F$-algebras taking the universal envelope algebra, then
$$
\mathrm U(\mathfrak g_1 \oplus \mathfrak g_2) \simeq \mathrm U(\mathfrak g_1) \otimes_F \mathrm U(\mathfrak g_2).
$$
Given an associative $F$-algebra $A$, denote by $[A]$ the corresponding Lie algebra over $F$ defined by the classical Lie bracket, namely $[x,y] = xy-yx$. This is functorial and $(\mathrm U,[-])$ form an adjoint pair. So I thought that the above was a consequence of the fact that $\mathrm U$ was left-adjoint and commuted with small colimits. However, neither of the above are coproducts, namely $\mathfrak g_1 \oplus \mathfrak g_2$ is not the coproduct in the category of Lie algebras and $\mathrm U(\mathfrak g_1) \otimes_F \mathrm U(\mathfrak g_2)$ is not the coproduct in the category of associative $F$-algebras.
So can anyone figure out categorically why this isomorphism is to be expected, or is it just a coincidence? I usually don't like coincidences. The most confusing part is that this isomorphism is constructed "naturally" in some way, namely we take the $F$-linear maps $\mathfrak g_i \to \mathrm U(\mathfrak g_i) \to \mathrm U(\mathfrak g_1) \otimes_F \mathrm U(\mathfrak g_2)$, use the fact that their images commute (which is precisely why $\mathfrak g_1 \oplus \mathfrak g_2$ is not the coproduct in the category of Lie algebras, i.e. the images do not always commute in general) and construct the map of Lie algebras $\mathfrak g_1 \oplus \mathfrak g_2 \to [\mathrm U(\mathfrak g_1) \otimes_F \mathrm U(\mathfrak g_2)]$ which then corresponds to a map $\mathrm U(\mathfrak g_1 \oplus \mathfrak g_2) \to \mathrm U(\mathfrak g_1) \otimes_F \mathrm U(\mathfrak g_2)$ by the $(\mathrm U,[-])$ adjunction.
The inverse map is also constructed naturally, namely by applying the functor $\mathrm U$ on the inclusions $\mathfrak g_i \to \mathfrak g_1 \oplus \mathfrak g_2$ and tensoring the resulting maps over $F$. It turns out that the two are inverse to each other, but I can't naturally figure out why, I have to dive into formulas with elements to see it.

A: It is not a coincidence. The tensor product of algebras and the direct sum of Lie algebras are both "commutative coproducts": they are the universal objects admitting a map from two objects whose images commute (this condition makes sense for both algebras and Lie algebras, compatibly with the forgetful functor from algebras to Lie algebras).


text:
Q: Resize images with Glide in a ImageView Android I have a lot of doubts about the treatment of the images in android, and I was hoping to see if you could solve them.
At this point I have an image that occupies 320 dp high, and match_parent width, which is around 60% of the screen.
This image of the load with Glide, of some images in 1080 that I have personally.
I tried to make centroCrop and fitXY, but always deform the images. The first type I know cuts the image, but the second one fits a size, but it does deform the image high or wide.
Is there any way, to insert it with Glide and see it as it is?
What properties have I to touch on ImageView and which of Glide?
<ImageView
        android:id="@+id/img"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:nestedScrollingEnabled="false"
        app:layout_collapseMode="parallax"
        android:scaleType="fitXY"
        app:layout_scrollFlags="scroll|enterAlways" />

A: If you want to load image without using glide then you can use scaleType "fitCenter" or "centerInside" as follows -
<ImageView
        android:id="@+id/img"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:nestedScrollingEnabled="false"
        app:layout_collapseMode="parallax"
        android:scaleType="centerInside"
        app:layout_scrollFlags="scroll|enterAlways" />

With Glide you can use override(w,h). When you use override(w,h), glide generates a new bitmap with width and height mentioned in override(w,h) and then load the image into ImageView. You can use fitCenter() to align the image. You can also use diskCacheStrategy(). If you don't use it, Glide will catch only newly generated bitmap. If you want to catch original image also then use diskCacheStrategy(DiskCacheStrategy.ALL).
Glide.with(context)
            .load(image_path)
            .override(800, 400)
            .fitCenter()
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .into(imageView)

I hope this helps.

A: you have to do the following with your imageview :
        <ImageView
            android:id="@+id/img"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:scaleType="fitCenter" />

and this with your glide :
    Glide.with(getBaseContext())
            .load(path)
            //.placeholder(R.drawable.drawable)
            .error(R.drawable.noimg)
            .animate(R.anim.animation_fade_in)
            .into(mImageView);

This works perfectly with me .

A: Glide 4.x - If you want get bitmap, try:
Glide.with(mContext).asBitmap().
                        load(pictureUri)
                        .apply(new RequestOptions().override(50, 50))
                        .listener(new RequestListener<Bitmap>() {
                            @Override
                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                                return false;
                            }
                        @Override
                        public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                            // resource is your loaded Bitmap
                            imgView.setImageBitmap(resource);
                            return true;
                        }
                    }).submit();

A: in glide 4.x 'override' is in 'apply' :
Glide.with(getBaseContext())
 .load(path)
 .apply(RequestOptions.placeholderOf(R.mipmap.no_wifi)
 .error(R.mipmap.no_wifi)
 .override(500,500))
 .into(mImageView);

A: Override must be accessed via RequestOptions in the most recent version of Glide 4.x. You can add RequestOptions through apply()
Glide.with(context)
    .load(path)
    .apply(new RequestOptions().override(600, 200))
    .into(imageViewResizeCenterCrop);

A: Glide
    .with(context)
    .load(path)
    .apply(new RequestOptions().override(600, 200))
    .centerCrop()
    .into(imageViewResizeCenterCrop);

@Raghunandan is right.you should try transformation your own way.

redpajama_set_name: RedPajamaStackExchange


text:
Q: referring script stuck in a loop What I am trying to do is redirect a user based on their referring url to a promo page. In the script below if someone comes from a referring url from "mydomainsite.com" they will be sent to "mydomainsite.com/promo.html" When I have the script below in the page "mydomainsite.com/promo.html" and it comes from a refer of "mydomainsite.com" it seems to loop or continue to load the page and it never loads the page "mydomainsite.com/promo.html" The script has to be in the "mydomainsite.com/promo.html," do to the page being a promo page and everyone can't have access to the page. I assume this is due to indexOf and it checks for "mydomainsite.com" then executes. Is there away to fix this?
<script language="JavaScript">
if (document.referrer.indexOf('mydomainsite.com') > -1)
location.href='http://mydomainsite.com/promo.html';
else
location.href='http://notfrommydomainsite.com';
</script>

A: As has been mentioned in the comments the referrer data is not reliable, however if you do want to pursue this...
The mqost likely cause of the issue you have is that when arriving at the redirected promo.html it finds the referrer is from mydomainsite.com so it simply goes to itself creating am infinite loop.
You will need to test for that and avoid the loop by checking that location.pathname is not promo.html :
if (document.referrer.indexOf ('mydomainsite.com') > -1 &&
        location.pathname !== 'promo.html')
    location.href = 'http://mydomainsite.com/promo.html';


text:
Q: How to catch invalid url error in got module get stream? I'm trying to using got module to get a file from a given url, but when the url is invalid, i can't catch the error with the error handler.
My code:
got.stream('https://google.com').on('error', error =>
        {
            console.log('error!!!')
        })


text:
Q: How to set the size of a QGraphicsView? I'd like to have a fixed size QGraphicsView, which I want to add to a layout together with some other widgets. However, the QGraphicsView simply ignores resize(), here is the relevant code:
QGraphicsScene* scene = new QGraphicsScene;
QGraphicsView* view = new QGraphicsView(scene);
view->setBackgroundBrush(QBrush(Qt::black, Qt::SolidPattern));
view->resize(1000, 600);

QVBoxLayout* layout = new QVBoxLayout;
layout->setMargin(0);
layout->addWidget(view);
setLayout(layout);

If I use setFixedSize() instead of resize(), the size is actually being set correctly. However, it seems that the window size is not updated, the window is not centered properly.
How am I supposed to set a fixed size for a QGraphicsView?

A: I know this is a very old question, but in case anyone else stumbles into it: you can set both minimumSize and maximumSize to the desired target size, and it should work regardless of what layout the QGraphicsView is in.

A: If I understood you right you want to have QGraphicsView centred inside the window and having fixed size. You need rather then VBoxLayout you should use QGridLayout with spacers, so your form should look like:
 <Empty>        <VSpacer>     <Empty>

 <HSpacer>   <GraphicsView>   <HSpacer>

 <Empty>        <VSpacer>     <Empty>


text:
Q: Spring JPA Specification with Sort I am using Spring JPA.
To be more precise I am using a Repository which extends JpaRepository and JpaSpecificationExecutor because I require pagination, filtering and sorting.
Now I have the pagination and filtering all working just fine, but I cannot get sorting to work as well.
I notice with some disappointment that JpaSpecificationExecutor has findAll() methods:
findAll(Specification, Pageable);
findAll(Specification, Sort);

But the one I need:
findAll(Specification, Pageable, Sort); //or something like this

does not exist!
So, Plan B, include Sorting in the Specification.
With the help of the Accepted Answer to this question: JpaSpecificationExecutor JOIN + ORDER BY in Specification I put together the following:
private Specification<MainEntity> matches() {
    return new Specification<MainEntity>() {

        public Predicate toPredicate(Root<MainEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

            List<Predicate> predicates = new ArrayList<Predicate>();

            //Attempt to sort by Surname, has no effect
            query.orderBy(cb.asc(root.get("surname")));

            //add string filters
            for (String field : stringFilterMap.keySet()) {
                String valuePattern = stringFilterMap.get(field);
                predicates.add(cb.like(root.get(field), "%"+valuePattern+"%"));
            }

            //...snip...

            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        }
    };
}

Where springFilterMap is an instance field, Map<String,String> whose keys are field names and values are filters values.
Above you will see my attempt to order by Surname, but this seems to have no effect.
What am I doing wrong; & how can I achieve Sorting along with Pagination and Filtering?

A: Use PageRequest, which is an implementation of Pageable, and implements paging and sorting at once, like you want it. For example through this constructor:
public PageRequest(int page, int size, Sort sort)

UPDATE:
Since Spring Data JPA 2.0 the above constructor is deprecated and you should use the static factory method of:
public static PageRequest of(int page, int size, Sort sort)


text:
Q: How can I optimize my javascript program? I am trying to solve this javascript problem and came up with this solution which gives the correct solution but the online judge is showing time limit exceeded. I want to optimize the algorithm. What can I change in my algorithm?
Problem Description: The special score(ssc) of an array of integers will be the sum of each integer multiplied by its corresponding index plus one in the array.
E.g.: with the
array [6, 12, -1]

arr =   [6,      12,       -1 ]
ssc =   1*6  +  2* 12 +  3.(*1) = 6 + 24 - 3 = 27

The array given in the example has six(6) permutations and are with the corresponding ssc:
Permutations      Special Score (ssc)
    [6, 12, -1]      1*6 + 2*12 + 3*(-1) = 27
    [6, -1, 12]       1*6 + 2*(-1) + 3*12 = 40
    [-1, 6, 12]       1*(-1) + 2*6 + 3*12 = 47
    [-1, 12, 6]       1*(-1) + 2*12 + 3*6 = 41
    [12, -1, 6]       1*12 + 2*(-1) + 3*6 = 28
    [12, 6, -1]       1*12 + 2*6 + 3*(-1) = 21
The total sum of the ssc's of all the possible permutations is: 27 + 40 + 47 + 41 + 28 + 21 = 204
The maximum value for the ssc is 47.
The minimum value for the ssc is 21.
We need a special function ssc_forperm() that receives an array of uncertain number of elements (the elements may occur more than once) and may output a list of dictionaries with the following data:
[{"total perm":__}, {"total ssc": ___}, {"max ssc": __}, {"min ssc":__}]

My Solution:
function permute(input) {
    var permArr = [],
        usedChars = [];
    return (function main() {
        for (var i = 0; i < input.length; i++) {
            var ch = input.splice(i, 1)[0];
            usedChars.push(ch);
            if (input.length === 0) {
                permArr.push(usedChars.slice());
            }
            main();
            input.splice(i, 0, ch);
            usedChars.pop();
        }
        return permArr;
    })();
}

function sscForperm(arr){
  var perm=permute(arr);
  var perm_arr=[];
  var temp_arr=[];
  var j=0;
  while(j<perm.length)
  {
      if(temp_arr.indexOf(perm[j].toString())===-1)
      {
          perm_arr.push(perm[j]);
          temp_arr.push(perm[j].toString());
      }
      j++;
  }
  var total_perm=perm_arr.length;

  var total=0;
  var max= 0;
  var k=0;
  while(k<perm_arr[0].length)
  {
      max+=perm_arr[0][k]*(k+1);
      k++;
  }
  var min=max;
  total+=max;

  var i=1;
  while(i<total_perm)
  {
      var l=0;
      var temp=0;
      while(l<perm_arr[0].length)
      {
          temp+=perm_arr[i][l]*(l+1);
          l++;
      }
      total+=temp;
      if(temp>max)
      {
          max=temp;
      }
      if(temp<min)
      {
          min=temp;
      }
      i++;
  }
  var dict1 = {"total perm":total_perm};
  var dict2 = {"total ssc":total};
  var dict3 = {"max ssc":max};
  var dict4 = {"min ssc":min};
  var ans=[];
  ans.push(dict1);
  ans.push(dict2);
  ans.push(dict3);
  ans.push(dict4);
  return ans;
}

A: A simple way to optimize your code is using Google Closure Compiler.
Google Closure Compiler
I pre-Compiled your code and the code I got is at
http://closure-compiler.appspot.com/code/jsc23712967d5b5fa4f457b1638ec432b22/default.js
this was fast and easy. It should now run somewhat faster

A: total perm = n!
total ssc can be derived from a formula since each array element appears in the total sum (n - 1)! times for each index:
total ssc = array sum * (n - 1)! * index sum
(6 + 12 - 1) * 2! * 3 * (3 + 1) / 2 = 204

max ssc and min ssc can be computed by simply sorting the array and applying the index multiples in either direction: ascending yields the max, descending the min.


text:
Q: How to add a class to a hyperlink when it contains a specific file extension? Can someone tell me how to take a string and run a function against it to check for a specific type of file (say a ".pdf"). If the string contains the file, then it needs to apply a "pdf" class to the anchor that contains the link.
Here's an example of a string:
My PDF

I would like it to be changed to this:
My PDF

A: Do this in CSS:
a[href$=".pdf"] {
   /* some rules */
}

But this may not be supported by some browser.
Alternatively, do this in Javascript, with jQuery or any library:
$('a[href$=".pdf"]').addClass('pdf'); // in jQuery

Or without library:
var elems = document.getElementByTagName('a');
for (var i = 0; i  < elems.length; ++i) {
    var a = elems[i];
    if (/\.pdf$/.test(a.href)) {
        a.className = 'pdf';
    }
}

A: (]*>)
replace by
\1 class="\2" \3
python code:
import re,sys
file = sys.argv[1]
f = open(file, 'r')
text = f.read()
f.close()
text = re.sub(r'(]*>)', r'\1 class="\2" \3', te$
f = open(file+'.re','w')
f.write(text)
f.close()

Can use it to modify html static


text:
Q: UIColor display not exactly correct? I input this in viewDidLoad
self.view.backgroundColor = [UIColor colorWithRed:231/255.0 green:77/255.0 blue:77/255.0 alpha:1.0];

and create label in xib , set color e74d4d(which convert to rgb is 231,77,77)
I want to show image on the website , but it tells me I need 10 reputation.
I debug the code,and find this,
(lldb) po self.view.backgroundColor
UIDeviceRGBColorSpace 0.905882 0.301961 0.301961 1

(lldb) po self.label.textColor
UIDeviceRGBColorSpace 0.87161 0.208926 0.237916 1

A: while you are passing value for UIColor always use float value.
self.view.backgroundColor = [UIColor colorWithRed:231.0/255.0 green:77.0/255.0 blue:77.0/255.0 alpha:1.0];

also use the same float value while you are converting to other format.
Edit: From the comments.
Dividing 231/255.0 and 231.0/255.0 are the same. Yes it is, but i have written that always pass float value means in for both values.
As user doesn't provided second conversation i thought function is using 255 for devision instead of 255.0 as a result it will be a integer value.
Try below code with RGBFromUIColor macro one by one, it will show different output.
self.titleLabel.backgroundColor = [UIColor colorWithRed:231/255 green:77/255 blue:77/255 alpha:1.0];
self.titleLabel2.backgroundColor = [UIColor colorWithRed:231.0/255.0 green:77.0/255.0 blue:77.0/255.0 alpha:1.0];
self.titleLabel3.backgroundColor = RGBFromUIColor(231, 77, 77);
self.titleLabel4.backgroundColor = RGBFromUIColor(231.0, 77.0, 77.0)

Now suppose macro for RGBFromUIColor is like below
#define RGBFromUIColor(r, g, b) \[UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]

or like this
#define RGBFromUIColor(r, g, b) \[UIColor colorWithRed:(r)/255 green:(g)/255 blue:(b)/255 alpha:1]

The last RGBFromUIColor will not have same value in case it doen't devided by float i.e 255.0

A: Your issue is that the text lable colour is not the same as your background colour?
I suspect your problem is that you are setting the text color to e74d4d which is a 24 bit value, no transparency value (the A in RGBA and ARGB). Try ffe74d4d or e74d4dff which set the transparency to opaque (alpha to 1). Even better, simply set it the same way as you set the background color, and iOS will automatically set the transparency to opaque.

A: This may not be what you are experiencing, but it I have previously seen some color problems with the OS X Color Picker due to the color calibration on my display. Sometimes it seems to select the color components by display value and then convert them to sRGB, when you actually want no conversion at all.
I would try the either of the following:

*

*Use the 'RGB Sliders' color picker panel.

*Paint the color in an image without a color profile, open the image in Preview.app and use the pipette tool to select that color.


text:
Q: Get VM GUI on a core server via VNC I have a linux server without GUI running several Windows 7 VMs. I would like to view the screen of the VMs. Is it possible to connect to the linux server with a desktop computer in order to display the VM's screen?
Thanks !
EDIT: I'm using VirtualBox 4 as a virtual software

A: As qasdfdsaq stated above, you can set up a RDP Server with VirtualBox.
But you need the VirtualBox Extension Pack installed first.


text:
Q: Fortify, how to run sourceanalyzer on a specific folder? I have a project folder with source code and a lot of other folders inside. The structure is something like the following:
My_project:
 node_modules
 src
 dist
 features
 helpers
 folder1
 folder2
 blablabla
 somefiles.js
 etc
I want to run the scan ONLY on folder 'dist'. The '-exclude' is not a good option because there are really a lot of folders and files there. The main idea is that I dont want to see issues with node_modules and other in fortify results. I only want to see what issues are in 'dist'.
Currently, I am running the following commands:
sourceanalyzer -clean
sourceanalyzer -b My_project ./dist//*
sourceanalyzer -Xmx8G -Xms4G -Xss24M -64 -logfile my.log -scan ./dist//* -f My_project.fpr
and then upload
For some reason I see issues in node_modules in the result.

A: Your translation command is in the right direction, but try this:
sourceanalyzer -b My_project dist/**/.
sourceanalyzer -b My_project -Xmx8G -Xms4G -Xss24M -64 -logfile my.log -scan My_project.fpr
You don't need the directory info in the scan command. Fortify "translates" your code in the first code and then the second command runs the scan against translated code.


text:
Q: How to serialize trait object with rocket::serde? I've got the following code:
use std::fmt::Debug;
use rocket::serde::{Serialize};
#[serde(crate = "rocket::serde")]

pub trait ComponentDto: Debug + Send + Sync + Serialize {}

use rocket::serde::{Deserialize, Serialize};

#[derive(Serialize)]
#[serde(crate = "rocket::serde")]

pub struct ParagraphDto {
    pub id: i32,
    pub uuid: String,
    pub user_id: i32,
    pub project_id: i32,
    pub position: i32,
    pub component: Box<dyn ComponentDto>,
    pub status: String,
    pub created_at: String,
    pub updated_at: String,
}

impl ParagraphDto {

How do I serialize trait object using rocket::serde?
Using rockett::serde as a normal struct to trait object results in the following error:
Compiling testa v0.1.0 (/mnt/repository/repository/projects/rust/testa)
error[E0038]: the trait `MyTrait` cannot be made into an object
    --> src/main.rs:21:20
     |
21 | fn getStruct() -> Box<dyn MyTrait> {
     | ^^^^^^^^^^^^^^^^^ `MyTrait` cannot be made into an object
     |
note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits. html#object-safety>


text:
Q: HtmlAgilityPack incorrect parsing of < in input I am trying to remove any scripts from my input using HtmlAgilityPack.
My input:

If the amount<500 show results. Else do not show results.<mytag1>This is an xml element</mytag1>

Expected result:

If the amount<500 show results. Else do not show results.<mytag1>This is an xml element</mytag1>

Final result:

If the amount<500 show="" results.="" else="" do="" not="" /><mytag1>This is an xml element</mytag1>

here is my code
    public HashSet<string> BlackList = new HashSet<string>()
    {
            { "script" },
            { "iframe" },
            { "form" },
            { "head" },
            { "meta" },
            { "comment" }
    };
    public static string GetSafeHtmlString(string sInputString)
    {
        HtmlDocument doc = new HtmlDocument();
        doc.OptionFixNestedTags = true;
        //doc.OptionAutoCloseOnEnd = true;
        doc.OptionDefaultStreamEncoding = System.Text.Encoding.UTF8;

        doc.LoadHtml(HttpUtility.HtmlDecode(sInputString));

        HtmlSanitizer sanitizer = new HtmlSanitizer();
        sanitizer.SanitizeHtmlNode(doc.DocumentNode);

        string output = null;

        using (StringWriter sw = new StringWriter())
        {
            XmlWriter writer = new XmlTextWriter(sw);
            doc.DocumentNode.WriteTo(writer);
            output = sw.ToString();

            if (!string.IsNullOrEmpty(output))
            {
                int at = output.IndexOf("?>");
                output = output.Substring(at + 2);
            }
            writer.Close();
        }

        doc = null;

        return output;
    }
    private void SanitizeHtmlNode(HtmlNode node)
    {
        if (node.NodeType == HtmlNodeType.Element)
        {
            // check for blacklist items and remove
            if (BlackList.Contains(node.Name))
            {
                node.Remove();
                return;
            }
        }

        if (node.HasChildNodes)
        {
            for (int i = node.ChildNodes.Count - 1; i >= 0; i--)
            {
                SanitizeHtmlNode(node.ChildNodes[i]);
            }
        }
    }

How can I get the expected results. The html parser is taking the < as start of new html tag. How can I add "<"(less than) character that is not start of html tag in input.

A: By escaping it to an HTML entity. The HTML escape sequence for < is <... similarly > is >.
Here's a handy chart.


text:
Q: put images in split by pages I have 100 images to put on my website in one div. I want to put 20 images and give page numbers in the down, so that if user clicks on '2' it takes to next 20 images. How is this possible. I have tried searching, but could not find any answer

A: Depends really how your page serves these images. If you have a static HTML page then your only option would be to use JavaScript/jQuery.
If info about your images is serves from a database behind your web application then you can use pagination and routing. For instance you could have an url http://mydomain.com/images and this would select the first 20 images from your database then bellow you gallery you can have a set of links Previous and Next and when you click on Next it takes you to the url http://mydomain.com/images/20 still the gallery page only /20 appended to it to use as an offset for your SQL Query.
Tho seems what you really need is just a simply jQuery image gallery something like this:

*

*http://www.tn3gallery.com/?refCode=fe8775

*http://galleria.io/

*http://spaceforaname.com/galleryview/#

*http://tympanus.net/codrops/2010/06/24/multimedia-gallery/


text:
Q: Pivoting a data frame How do I pivot the following data frame, so as to have one column per weekday?
import numpy as np
import pandas as pd

idx = pd.date_range('2018-01', '2018-12', name='date')
df = pd.DataFrame(np.random.random(len(idx)), index=idx, columns=['value'])
df['weekday'] = idx.weekday

I've tried the following, and whilst there is one column per weekday, there are a lot of NaN values. This is because the data frame's index is used by the pivoted data frame.
pivoted = df.pivot(columns='weekday', values='value')
pivoted.head()
# weekday            0         1         2       3         4   5   6
# date
# 2018-01-01  0.638018       NaN       NaN     NaN       NaN NaN NaN
# 2018-01-02       NaN  0.179721       NaN     NaN       NaN NaN NaN
# 2018-01-03       NaN       NaN  0.713559     NaN       NaN NaN NaN
# 2018-01-04       NaN       NaN       NaN  0.2092       NaN NaN NaN
# 2018-01-05       NaN       NaN       NaN     NaN  0.679759 NaN NaN

Ultimately, I'd like box plots of the values per weekday. The following works, because the NaN values are ignored.
pivoted.plot.box()

Surely, there's a way that doesn't involve a lot of NaN values?

A: If you just want a boxplot by weekday you don't need to pivot. Just call boxplot:
df.boxplot(column='value', by='weekday')


text:
Q: Unable to Remote Desktop Connect as Local Administrator In the screenshot below, you can see that I am currently logged into one of our Windows 2008 servers using my network account. It shows a picture of the settings in the Local Security Policy.
The Local Administrator Account for this machine is named Apache, and as you can see it has been given rights to log in via Remote Desktop.
Nevertheless, every time I try logging in via RDP, I get a message saying this user is not allowed to remote in.
Remote Desktop Connection

The connection was denied because the user account is not authorized for remote login.

What have I missed?

RESOLVED!
Here is my source: 2008 Terminal Server: Connection was denied, not authorized for remote login. | Technoogies Techno Blog
The solution for me was to add the user using the Remote settings feature, as shown in the four (4) steps below.
Somehow, none of the other techniques I came across showed this step.

A: Try adding the Remote Desktop Users group to his local computer's "allow remote desktop users" permissions.
For the default group policy allow Computer Configuration > Policies > Windows Settings > Security Settings > Local Policies > User Rights > Allow Log on through Remote Desktop Services > allowed the Remote Desktop users Group and his account exclusively as well.
Make sure the policy was updated using gpupdate /f and check


text:
Q: Break non-hyphenated compound words at word boundary I am using Bootstrap. Let us say I have text that looks like this:

"Stackoverflow"

Can I somehow automatically make sure that it breaks like this if the text does not fit the container:

"Stack
  -overflow"

instead of:

"Stackov
  -erflow"

with HTML/CSS?

A: No, for a document "Stackoverflow" is a single word. If you are using a CSS property to break the word then it will break according to the space available.
You have to define it if you want to break it from a particular point.

You can use Stack<wbr>overflow or Stack-overflow.

If use Stack<wbr>overflow, then it will be broken at <wbr>.

p.test1 {
    width: 60px;
    border: 1px solid #000000;
}

Stack<wbr>overflow

OR, if using Stack-overflow and using CSS property word-break: keep-all; then it will be broken at hyphens:

p.test1 {
    width: 60px;
    border: 1px solid #000000;
    word-break: keep-all;
}

Stack-overflow

But you have to define one of them.

A: You can insert  (soft hyphen)

#box {
  font-size:14px;
  font-family:courier;
  width:90px;
  background:yellow;
 }

Stackoverflow

A: If you want to break a specific word, then the answers given will work - insert an invisible break of some kind. It does, as pointed out, harm search results, but not so bad as you'd think.
If you want to break all compound terms that need wrapping, without manually going through and checking, then there is no way to do this, because you need context-sensitive English language parsing, which means you need a human brain doing it.
Consider how you would break the following strings:
lowrateslender.com
musictoyourears.com
heresearch.com
nakedsnow.com
picturespain.com
catspaying.net
attackshoes.com
williamsharp.net
andreward.net
goalsnow.net
hesstruck.net
artistrap.com
buildingskill.com
bearspray.com
atticsweep.com
matthewhale.com
singershaven.com
shoesworn.com
sinuscatscan.com
cometart.com
monkeyslap.com
scriptshack.com
nasalbum.com
moviesick.com
arizonasparesort.com
privateshot.com
nationsprinting.com
importcarshow.com

(copy-pasted from a google search for "ambiguous domain names")
...even given a dictionary to identify whole words within these terms, and inserting breaking spaces at those boundaries, it'd be a toss-up whether you would split these words as, say, "import-car-show" or "import-cars-how".
One of the main skills for programming is identifying algorithms which require natural language processing, and opting just for a "good enough" algorithm rather than wasting time on it. This is one such case.

A: You can use the <wbr> tag:

p {
  width: 60px;
  border: 1px solid black;
}

Stack<wbr>overflow

A: You can use zero-width space, . Just type Stackoverflow in HTML.


text:
Q: TypeError: Cannot read property 'length' of undefined in tsc.js I have created a nodejs api project using typescript. But I am not able to start it. This is the command I am running
npm start

This is the output of this command
> project1@1.0.0 prestart D:\Workspace
> tsc

D:\Workspace\node_modules\typescript\lib\tsc.js:9921
                for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) {
                                                                     ^

TypeError: Cannot read property 'length' of undefined
    at Object.forEachChild (D:\Workspace\node_modules\typescript\lib\tsc.js:9921:70)
    at setParentPointers (D:\Workspace\node_modules\typescript\lib\tsc.js:17392:12)
    at D:\Workspace\node_modules\typescript\lib\tsc.js:17392:64
    at visitNode (D:\Workspace\node_modules\typescript\lib\tsc.js:9533:24)
    at Object.forEachChild (D:\Workspace\node_modules\typescript\lib\tsc.js:9918:25)
    at setParentPointers (D:\Workspace\node_modules\typescript\lib\tsc.js:17392:12)
    at D:\Workspace\node_modules\typescript\lib\tsc.js:17392:64
    at visitNodes (D:\Workspace\node_modules\typescript\lib\tsc.js:9542:30)
    at Object.forEachChild (D:\Workspace\node_modules\typescript\lib\tsc.js:9891:24)
    at setParentPointers (D:\Workspace\node_modules\typescript\lib\tsc.js:17392:12)
    at bindChildrenWorker (D:\Workspace\node_modules\typescript\lib\tsc.js:15178:25)
    at bindChildren (D:\Workspace\node_modules\typescript\lib\tsc.js:15129:17)
    at bindContainer (D:\Workspace\node_modules\typescript\lib\tsc.js:15122:17)
    at bind (D:\Workspace\node_modules\typescript\lib\tsc.js:16214:21)
    at Object.forEach (D:\Workspace\node_modules\typescript\lib\tsc.js:275:30)
    at bindEach (D:\Workspace\node_modules\typescript\lib\tsc.js:15149:20)
    at visitNodes (D:\Workspace\node_modules\typescript\lib\tsc.js:9538:24)
    at Object.forEachChild (D:\Workspace\node_modules\typescript\lib\tsc.js:9707:24)
    at bindEachChild (D:\Workspace\node_modules\typescript\lib\tsc.js:15165:16)
    at bindChildrenWorker (D:\Workspace\node_modules\typescript\lib\tsc.js:15254:21)
    at bindChildren (D:\Workspace\node_modules\typescript\lib\tsc.js:15129:17)
    at bindContainer (D:\Workspace\node_modules\typescript\lib\tsc.js:15093:17)
    at bind (D:\Workspace\node_modules\typescript\lib\tsc.js:16214:21)
    at bindSourceFile (D:\Workspace\node_modules\typescript\lib\tsc.js:14851:17)
    at Object.bindSourceFile (D:\Workspace\node_modules\typescript\lib\tsc.js:14809:9)
    at initializeTypeChecker (D:\Workspace\node_modules\typescript\lib\tsc.js:36496:20)
    at Object.createTypeChecker (D:\Workspace\node_modules\typescript\lib\tsc.js:18543:9)
    at getDiagnosticsProducingTypeChecker (D:\Workspace\node_modules\typescript\lib\tsc.js:56042:93)
    at Object.getGlobalDiagnostics (D:\Workspace\node_modules\typescript\lib\tsc.js:56370:53)
    at compileProgram (D:\Workspace\node_modules\typescript\lib\tsc.js:59092:78)
    at compile (D:\Workspace\node_modules\typescript\lib\tsc.js:59051:26)
    at performCompilation (D:\Workspace\node_modules\typescript\lib\tsc.js:58940:33)
    at Object.executeCommandLine (D:\Workspace\node_modules\typescript\lib\tsc.js:58883:9)
    at Object.<anonymous> (D:\Workspace\node_modules\typescript\lib\tsc.js:59241:4)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (D:\Workspace\node_modules\typescript\bin\tsc:2:1)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v6.9.5
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! project1@1.0.0 prestart: `tsc`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the project1@1.0.0 prestart script 'tsc'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the project1 package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     tsc
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs project1
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls project1
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     D:\Workspace\npm-debug.log

and my package.json
{
  "name": "project1",
  "version": "1.0.0",
  "description": "Project 1",
  "main": "index.js",
  "scripts": {
    "prestart": "tsc",
    "start": "concurrently \"tsc --watch \" \"nodemon server.js startServer\"",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "license": "ISC",
  "dependencies": {
    "@types/es6-promise": "0.0.32",
    "body-parser": "^1.16.0",
    "es6-map": "^0.1.5",
    "giuseppe": "^1.2.0",
    "make-runnable": "^1.0.7",
    "request": "^2.79.0",
    "request-promise": "^4.1.1",
    "typescript": "^2.1.4"
  },
  "devDependencies": {
    "@types/chai": "^3.4.34",
    "concurrently": "^3.1.0",
    "nodemon": "^1.11.0"
  }
}

I have tried deleting node_modules folder and clearing cache using
npm cache clear

and then installing it again using
npm install

but fail to start? what could be the issue?

A: The issue was with typescript itself. Here is the issue raised on Github
https://github.com/Microsoft/TypeScript/issues/18301
but now the issue has been fixed.
Just update typescript module
npm update typescript --save


text:
Q: neo4j model a time-varying graph I am trying to find the best way to model time varying graph in neo4j. The current model use a time variable "year" in the relationship to capture the time. For example,
(A)-[year:2000]->(B)-[year:2000]->(C)
(A)-[year:2000]->(D)-[value:2000]->(E)
(A)-[year:1999]->(B)-[year:1999]->(C)
(A)-[year:1999]->(D)
CREATE (a:firm {name:'A'}), (b:firm {name:'B'}), (c:firm {name:'C'}),
(d:firm {name:'D'}), (e:firm {name:'E'}),
(a)-[:REL {year: 2000}]->(b)->[:REL {year: 2000}]->(c),
(a)-[:REL {year: 2000}]->(d)->[:REL {year: 2000}]->(e),
(a)-[:REL {year: 1999}]->(b)->[:REL {year: 1999}]->(c),
(a)-[:REL {year: 1999}]->(d);

We are modeling this way because the original database stores the bilateral relationship by year. This is definitely not a space-efficient way to store a time varying graph. If space is not our concern, is this a reasonable way to model a time varying graph?
In this case, is it possible to get the difference between two years, i.e., (D)-[value:2000]->(E)?
(I have read Neo4j time dependent graph model but it seems outdated.)


text:
Q: Guest PC and Host connected as if on lan I am trying to connect the guest win7 in the VM to the Host win7 so they act as if on lan, i would be able to access the localhost in the host and also connect to the internet.
In the settings of the virtual machine, i see these adapters, But I initially selected Shared Networking (NAT)

I opend command prompt in both guest and the host and types ipconfig/all, these are the results
Guest

Host

I pinged both host and guest IPv4Address, but it timed out
I pinged google.com on the guest OS, again it timed out.
what Am i missing?


text:
Q: How to modify and save html/css in server-side? I'm new in this subject so this might be a silly question for most of you. I have a simple server which several users will access. If any of them change a CSS property of an element, the others should be able to see the change in real time.
Should I use something like node.js to perform this? How do I save the changes the users do?
The page would look something like this: http://stom89.dyndns.org/
Thanks!

A: I think you would need to use a sql database and have a javascript to detect changes and update through AJAX. That's my best idea.

A: I guess what you want to change in your CSS / html , are states. Like if a lamp is on/off? Then you need to save each state in a mySQL DB and just grab the data for each user. If you want it to look like realtime for online users, then use js(ajax) to sync data regularly.
Alternative way without a DB would be with files.
If you don't wanna use mysql for this, you can use files. I suggest using ini files. For more on how to read/write ini files, you can visit this question. It's super simple and you'll be able to have each variable in a nifty array.
What you need: A bit of PHP, a little bit of jQuery (or js), understanding of GET variables
I suggest you create 3 files.

index.php :
Your main page which is the client. Pulls info using get
variables. You can use jQuery.get() for this.
getstate.php :
This is the file which will read the ini file and give you back the states for each device. Read them with jQuery.get() from index.php .
savestate.php:
This is the file which you'll send the new states to from index.php Example request: http://address.goes.here/savestate.php?bedroomlight=1&garagelight=0

Whats even more interesting is that ini files can be written/read easily by many programming languages so you can manipulate the data using your Raspberry Pi easily. (say someone turns of a light, a script polling state could change the ini file)

A: I have been messing with this subject for sometime if I completely understand your question. I would suggest looking at python, ruby or node.js though I could not say which is the easiest to learn for you though I would suggest python and a comet server which could be ape and simply have the server push the updates to the users that are already on the site.
Edit:
Suggestions for polling :: jQuery
http://api.jquery.com/jQuery.get/ for standard data retrieval which is about all you will need.


text:
Q: restricting different values to a single input type I used the script on one of my scripting it was great i thought i solved the problem but whenever i change my option every button on my page chages to the same value of the option.Can i restrict my values to a single input type?
this is the script in question
<select>
  <option text="ok">1</option>
  <option text="hello">2</option>
  <option text="test">3</option>
</select>
<input type="text" />

$(function(){
 $('select').on('change', function(){
    $('input').val($('option:selected', this).attr('text'));
  });
});

A: of course, just apply an id to the specific input and change
$('input').val(...)

into
$('#your-input-id').val(...)

A: This is why:
$('input')

Every change of your select, you are targetting all inputs in the page. You can restrict by making the selector specific, for example:
$('input[type=text]')   //all inputs of type "text"
$('input[type=submit]') //all inputs of type "submit"
$('input.customButton') //all inputs of class "customButton"

A: If every SELECT menu has an INPUT below it that you want to update, you can do:
$("select").change(function() {
    $(this).next("input[type='text']").val($('option:selected', this).attr('text'));
});


text:
Q: Is there any good references for i18n and L10n in ISO C++? There is a header (" < locale > ") in Standard ISO C++.
Is there any good references for Internationalization and localization in ISO C++?

A: The best sources I know are:

*

*Standard C++ IOStreams and Locales by Langer and Kraft (it has a tutorial part and a more reference part)

*the appendix in some version of the third edition of The C++ Programming Language by Stroustrup (which is also available online) is more a user guide than a reference

*the relevant section in the standard is only a reference and not suitable as a user guide.

A: No.
There are references on how to use C++ streams and the locale facets... but ISO C++ does not provide a way for true Internalization/Localization.
The subject is much more difficult than it appears, because some languages have arcane rules

*

*in Greek, the tolower method would require looking at the whole word, instead of just the current character because toupper is not injective.

*in Spanish, ll is a letter itself (although two distinct tokens), with its own place in the alphabet.

And I won't even start on the ordinals in Polish...
If you really want proper I18n/L10n in C++, you may turn toward the ICU library, which despite its C-ish interface, is the de-facto standard. For translation of content, you may want to look at GetText (a GNU project). The two can be combined to obtain both translation and manipulation of internationalized resources, like translating a list of items and rendering it sorted alphabetically.

A: Here is online reference manual.


text:
Q: How can I Parse text document in VB,Net for values? I'm looking to parse this text file into strings to insert them into a database.
Source Text File gets read as the following string:
Line of unwanted text
Another line of unwanted data

Timestamp: 1/1/10 12:00 PM
ID: 1
Details: All data processed. Length will vary.

I'd like to just read Timestamp, ID and Details and place them into separate strings to insert them into a data table. What is the best method of capturing everything after the : and to the end of the line?
Dim Details as String = TextFile.Substring(Message.IndexOf("Details:"), X)

A: Assuming your files are flawless... One way to do it :
Imports System.IO

    Dim AllLines() As String = File.ReadAllLines(FilePath)
    Dim DatasIndex As Int32 = -1

    For i As Int32 = 0 To AllLines.Length - 1
        If AllLines(i).StartsWith("T") OrElse AllLines(i).StartsWith("t") Then
            If AllLines(i).ToUpper().StartsWith("TIMESTAMP: ") Then
                DatasIndex = i
                Exit For
            End If
        End If
    Next

    If DatasIndex > -1 Then
        ' Dim ReadDate As Date = Date.Parse(AllLines(DatasIndex).Substring(11))
        ' Dim ReadID As Int32 = Integer.Parse(AllLines(DatasIndex + 1).Substring(4))
        Dim ReadDate As String = AllLines(DatasIndex).Substring(11)
        Dim ReadID As String = AllLines(DatasIndex + 1).Substring(4)
        Dim ReadDetails As String = AllLines(DatasIndex + 2).Substring(9)

        ' send to database
    End If

You didn't tell if Timestamp: , ID: and Details:  Strings are always in the same order and has a trailing space after each property name.

A: If you have to use a String as input, you can use String.Split to break it up into lines, and process each line.  String.Substring can be used to extract the rest of the line - I've just hardcoded the starting positions below.
Dim timestamp As String = Nothing
Dim id As String = Nothing
Dim details As String = Nothing
For Each line In input.Split({vbCrLf, vbCr, vbLf}, StringSplitOptions.None)
    If line.StartsWith("timestamp:", StringComparison.OrdinalIgnoreCase) Then
        timestamp = line.Substring(10).Trim()
    ElseIf line.StartsWith("id:", StringComparison.OrdinalIgnoreCase) Then
        id = line.Substring(3).Trim()
    ElseIf line.StartsWith("details:", StringComparison.OrdinalIgnoreCase) Then
        details = line.Substring(8).Trim()
    End If
Next

If you can change how you read the data, then the loop could just be:
For each line In File.ReadLines("your\file\name.txt")
    ...
Next


text:
Q: Handle when CloudTable.ExecuteAsync times out I have the following code:
var operation = TableOperation.InsertOrReplace(entity);
var options = new TableRequestOptions { MaximumExecutionTime = TimeSpan.FromSeconds(10) };
var context = new OperationContext();
var result = await table.ExecuteAsync(operation, options, context);

As you can see, I have set it to give up after 10 seconds.
When it hits the limit, the fourth line above apparently throws a NullReferenceException.
I would not like to catch that exception.
What would be the best way to handle this?
Maybe instead of await I can check the Task?
Or maybe there is something on the OperationContext?
Update with StackTrace - not a lot to go on.
System.NullReferenceException:
   at Save.Save+<SaveEntity>d__3.MoveNext (Save, Version=1.0.0.0, Culture=neutral, PublicKeyToken=nullSave, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null: E:\Code\Save\Save.csSave, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null: 164)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at Save.Save+<Run>d__2.MoveNext (Save, Version=1.0.0.0, Culture=neutral, PublicKeyToken=nullSave, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null: E:\Code\Save\Save.csSave, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null: 92)


text:
Q: iOS & GIT Broken Storyboard I've got a big problem with my iOS Project, after using the standard Source Control feature for BitBucket.
The last time I committed some changes to the repository my storyboards had all the views and constraint as i left them. The commit did not include changes to storyboard.
Now I opened my project, some UIViewControllers have all the views uninstalled, or some have the views at the correct position but all the constraint are broken.
What should i do ? I've reset all my changes, and no matter what commit I revert to, the Storyboard is in the same broken state.
EDIT
The problems seems to be with the storyboard it self, and does not involve GIT. In the storyboard, all the constraints have been uninstalled (but present), so the views have moved almost randomly on the screen. Also some views were uninstalled from the view controller.
SOLUTION
I reinstalled all of the views and constraints that were disabled. Thank you for your help.

A: When a conflict happens I close Xcode and open the storyboard in Vim (or any other editor).
At heart, a storyboard is a big XML file with tags that Xcode maintains for you. Therefore, when you have a conflict, you will have the standard
<<<<<<
first storyboard lines
======
second storyboard lines
>>>>>>

structure.
When you are done with selecting the lines of the storyboard you want to keep (they're actually relatively readable), just git add the Storyboard file to mark the conflict as resolved as you would any other file, commit and profit.
Maybe you could also use git blame on the source code view of the Storyboard file to help you track down when exactly it broke, and hence why reverting doesn't seem to work?

A: When you open the storyboard file as source code you will probably see the warnings due to the merge.


text:
Q: Issue with NavigationView causing font size to change on some items when clicked I am experiencing an issue with the NavigationView where the font size of some items changes when clicked. There have been no modifications made to the font in the application code. I have tested this in a new application and did not encounter the same problem, so it appears to be an issue specific to the current application. I have attempted to identify the root cause of the issue by disabling code related to the NavigationView temporarily, but the problem persists. I am seeking assistance to further investigate and resolve this issue.
this is my activity_main.xml layout

and it looks like that in the android design section

it works well when I select English lang but when I changed to Arabic lang I found it like this

note: I use the 2.3.1 version.
How I can fix this bug?


text:
Q: Mootools accordian remote trigger in Joomla I'm trying to customise the Joomla 2.5 Accordion contacts page to add a clickable map to trigger the accordion and I'm struggling. The accordion part works fine, and the map works fine with clickable areas, but I can't link the two.
The mootools accordion script that triggers the accordian is this (pretty standard Joomla contacts page version exept I added 'var OfficeAccordian =' on line 2:
window.addEvent('domready', function(){
    var OfficeAccordian = new Fx.Accordion(
        $$('div#contact-slider.pane-sliders > .panel > h3.pane-toggler'),
        $$('div#contact-slider.pane-sliders > .panel > div.pane-slider'), {
        onActive: function(toggler, i) {
            toggler.addClass('pane-toggler-down');
            toggler.removeClass('pane-toggler');i.addClass('pane-down');
            i.removeClass('pane-hide');
            Cookie.write('jpanesliders_contact-slider',$$('div#contact-slider.pane-sliders > .panel > h3').indexOf(toggler));
        },
        onBackground: function(toggler, i) {
            toggler.addClass('pane-toggler');
            toggler.removeClass('pane-toggler-down');
            i.addClass('pane-hide');i.removeClass('pane-down');
            if($$('div#contact-slider.pane-sliders > .panel > h3').length==$$('div#contact-slider.pane-sliders > .panel > h3.pane-toggler').length)
                Cookie.write('jpanesliders_contact-slider',-1);
        },
        duration: 300,
        opacity: false,
        alwaysHide: true
    });
});

but the script I need to simulate a click on the accordion trigger when I click a link on the map (standard anchor button in a list) is beyond me. I've had a go at adapting a few examples from various websites, but none have worked. My javascript skills are not good enough yet to know why they aren't working or how to fix them.
(I'm not sure it needs to be mootools as I have mootools & jquery both loaded & working on the site)

A: The Fx.Accordion has an interface (API of methods the instance exposes so you can control it).
All it takes is reading the manual:
http://mootools.net/docs/more/Fx/Fx.Accordion#Fx-Accordion:display
OfficeAccordian.display(2);

if that is not enough, you read the source code:
https://github.com/mootools/mootools-more/blob/master/Source/Fx/Fx.Accordion.js#L157
this reveals you can pass a second argument to .display as boolean to use fx or not.
p.s. this is not how you spell accordion (OfficeAccordian). :)


text:
Q: get valules for all fields from selected features The following code works for retrieving values within a particular field(Name1), but I want to retrieve mulitple fields.  Am I to create multiple variables for each field?
IMxDocument pMxDocument = ArcMap.Application.Document as IMxDocument;
        IMap pMap = pMxDocument.FocusMap;
        ILayer pLayer = pMap.get_Layer(0);
        IFeatureLayer pFeatureLayer = (IFeatureLayer)pLayer;
        IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;

        ITable pTable = (ITable)pFeatureClass;
        ICursor pCursor = pTable.Search(null, false);
        int fldIndex = pFeatureClass.Fields.FindField("Name1");
        IRow pRow = pCursor.NextRow();
        while (pRow != null)
        {
            MessageBox.Show(pRow.get_Value(fldIndex).ToString());
            pRow = pCursor.NextRow();

        }

Edit:  What I'm trying to do is get the selected features of a feature class, get the values for fields like Name, address, city, etc and then pass those values onto a document.  I thought I would give some background to what I am doing since I may be on the wrong track to start off with.

A: Here are two examples of getting values from the selected features.
This one lists all the values for the feature
IMxDocument pMxDocument = ArcMap.Application.Document as IMxDocument;
IMap pMap = pMxDocument.FocusMap;
ILayer pLayer = pMap.get_Layer(0);
IFeatureLayer pFeatureLayer = (IFeatureLayer)pLayer;
IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
IFields pFields = (IFields)pFeatureClass;
ITable pTable = (ITable)pFeatureClass;
ICursor pCursor = pTable.Search(null, false);
IRow pRow = pCursor.NextRow();
while (pRow != null)
{
    string.IsNullOrEmpty(output);
    for (int i = 0; i <= pFields.FieldCount - 1; i++) {
        output += pFields.Field(i).Name + ": " + pRow.Value(i).ToString + Constants.vbNewLine;
    }
    MessageBox.Show(pRow.get_Value(fldIndex).ToString());
    pRow = pCursor.NextRow();

}

This example lists just selected values of the feature
    IMxDocument pMxDocument = ArcMap.Application.Document as IMxDocument;
IMap pMap = pMxDocument.FocusMap;
ILayer pLayer = pMap.get_Layer(0);
IFeatureLayer pFeatureLayer = (IFeatureLayer)pLayer;
IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
IFields pFields = (IFields)pFeatureClass;
ITable pTable = (ITable)pFeatureClass;
ICursor pCursor = pTable.Search(null, false);
string[] FieldNames = {"Name", "Address", "City"};
string output = null;
IRow pRow = pCursor.NextRow();
while (pRow != null)
{
    string.IsNullOrEmpty(output);
    foreach (string fieldName in FieldNames) {
        output += fieldName + ": " + pRow.Value(pFields.FindField(fieldName)).ToString + Constants.vbNewLine;
    }
    MessageBox.Show(output);
    pRow = pCursor.NextRow();

}

A: I use following code snippet to get selected features from map for a specific feature layer:
public List<IFeature> GetSelectedFeatures(IFeatureLayer featureLayer)
{
    IFeatureSelection featureSelection = (IFeatureSelection)featureLayer;
    var selectionSet = featureSelection.SelectionSet;
    IFeatureClass featureClass = featureLayer.FeatureClass;
    string shapeField = featureClass.ShapeFieldName;
    ISpatialFilter spatialFilter = new SpatialFilterClass();
    spatialFilter.GeometryField = shapeField;
    spatialFilter.set_OutputSpatialReference(shapeField, _map.SpatialReference);

    ICursor cursor;
    selectionSet.Search(spatialFilter, false, out cursor);
    var featureCursor = cursor as IFeatureCursor;
    var features = new List<IFeature>();

    IFeature feature;
    while ((feature = featureCursor.NextFeature()) != null)
        features.Add((feature));

    return features;
}

To know more about selection you can go through IFeatureSelection Interface.
And as kenbuja says, you can copy fields by iterating through rows.


text:
Q: Do accounts-password email tokens ever expire? For Accounts.forgotPassword() and Accounts.sendVerificationEmail(), a token is generated.
Does that token ever expire?
If so, after what period of time?

A: At the moment there is no built-in code that relates to token expiration, neither setting an expiration time nor enforcing it.
The email reset data (token, email and token creation date) is saved in the user's record, as can be seen in the source:
var tokenRecord = {
  token: token,
  email: email,
  when: when
};
Meteor.users.update(userId, {$set: {
  "services.password.reset": tokenRecord
}});

Therefore, the date is in the following mongo selector:
'services.password.reset.when'

Unfortunately, all of the reset data is unset as soon as the resetPassword method is called with the correct token.
This makes it unavailable to the validateLoginAttempt callbacks:
Accounts.validateLoginAttempt(function(options) {
  if (options.methodName === 'resetPassword' && options.allowed === true) {
    console.log('resetPassword', options.user.services.password.reset); //undefined
  }
  return true;
});

Similarly, the email verification token is stored in user.services.email.verificationTokens, which (if set) is an array of token records.
The dates are, therefore, in
'services.email.verificationTokens.when'

You could, however, invalidate old tokens periodically quite easily with this info, or roll your own local fork or wrap of accounts-password.

A: With the current version of Meteor (1.9), tokens do expire, as you can see here in the code (and I guess it has been the case for quite a long time).
Reset password tokens expire after 3 days, when enroll tokens expire after 30 days
These two parameters are configurable using :
Accounts.config({
    passwordResetTokenExpirationInDays : 10,
    passwordEnrollTokenExpirationInDays : 60,
})


text:
Q: How far should I spread my fingers when swimming? One way to improve efficiency of swimming stroke is to increase area of the stroking surface - for example wear fins on hands.
But what if we increase drag of the palm? If we spread our fingers then the area will be the same, but palm will also capture some water by viscous drag.
If we spread fingers just a little bit, like grid fin, then, as per Bernoulli, water will speed up in the narrow place in between the fingers and lose even more kinetic energy due to drag.
So it looks like it is beneficial for the swimmer to spread his fingers a little during stroke. But I never met an advice like that in any swimming tutorial.
Is it really beneficial and what is the optimal gap / gained efficiency?

A: fitness.stackexchange link
Scholarly literature quotes:
The optimum finger spacing in human swimming (2009) by Minettia / Machtsiras / Masters, 10.1016/j.jbiomech.2009.06.012

optimal finger spacing (12°, roughly corresponding to the resting hand
posture) increases the drag coefficient (+8.8%), which is
'functionally equivalent' to a greater hand palm area ... human
swimming is severely limited by the localization of most of the engine
(71% of total muscle mass) in the non-propelling lower limbs  ...
'oars' (i.e. upper limbs, responsible of 88% of total thrust

NUMERICAL SIMULATION APPLIED FOR SWIMMING by BENHACINE

first study showed that the swimmer's hand experiences a significant
increase of drag when the fingers are slightly opened with a spread
rate no greater than 6%. ... the fully adducted (closed) thumb
configuration produced slightly higher values of drag ... suggesting
that the swimmer should keep the palm of his hand fully opened ...
2.11(%) finger spread

The effects of hand configuration on propulsive forces in swimming by Bazuin, Rens

Reaching a podium place in competitive swimming is dependent on
differences in finishing times smaller than 0.5%. ... The research
showed that a small finger spreading of 5° can increase the drag
coefficient of the hand with 1.7%, in comparison to closed fingers.
Larger spreadings were found to influence the drag coefficient
disadvantageously, where a 20° finger spreading reduced the drag with
1.5%. The found effects indicate that finishing times can be reduced with 0.3% by using 5° finger spreading instead of 20° spreading.

Optimising the freestyle swimming stroke: the effect of finger spread (2006) by Sidelnik & Young, 10.1007/BF02844114

It was determined with 95% confidence that a
finger spread of 10∘
creates more stroke force than a fingers-together configuration across
all pitch angles tested.

A: For swimming, your goal is to maximize the surface area of your hand to allow for more pulling. So you don't want to "shrink" the area by squeezing your hand into a smaller cup shape. But at the same time, you don't want to open your fingers fully as then you've got a laminar flow and would be akin to using a rake for a paddle.
If you open your fingers a little bit, as you suggest, you will increase the surface area a little compared to keeping them closed and the flow ought to be turbulent and allow for more pulling.
A quick web search shows a few online resources suggesting to do so, the latter even showing the image at the bottom for the ideal position.

*

*https://www.slowtwitch.com/Training/Swimming/What_do_I_do_with_my_hands_while_swimming__2297.html

*https://www.swimdojo.com/blog/2019/1/28/getting-handsy-what-to-do-with-your-hands-when-you-pull


text:
Q: Does Apache keep holding a key file open when mod_ssl is enabled? I was testing my httpd config on centOS-like OS, and found a "wired" error AH02574: Init: Can't open server private key file in one of the VirtualHost, while another one doesn't produce any error.
In my config file, same SSL cert is referred by both (two) virtual hosts, of course is the private key file also shared. The httpd fail to start with this config. When I dig into the log, I found one virtual host (example.com) config does not produce any error, while the other vhost (sub.example.com, at latter lines in the ssl.conf) can't read the key file. I suspect this is due to the file was opened by the programme already, and hence stays on hold preventing it to be opened again. If this is the case, how should I solve it? An simple solution comes to my mind was to duplicate the key file, but I doubt for any security risk.
To give a better idea, below is a sample config:
<VirtualHost *:443>
  ServerName example.com
  # ... some other config
  SSLCertificateFile    "/path/to/ssl.crt"
  SSLCertificateKeyFile "/path/to/ssl.key"
</VirtualHost>
<VirtualHost *:443>
  ServerName sub.example.com
  # ... some other config
  SSLCertificateFile    "/path/to/ssl.crt"
  SSLCertificateKeyFile "/path/to/ssl.key"
</VirtualHost>

A: Although with a different problem, but This answer also resolves my problem!
Here is the solution provided by that answer:
restorecon -RvF /path/to/key_file

A: As per answer given by Jimmy, You can include sudo at the beginning of the command as below. I have also spent some 2 hours battling the same error but this helped me
sudo restorecon -RvF /etc/ssl/keyfile

After running the command, it should show as per image attached. Then you can restart the apache service
[1]: https://i.stack.imgur.com/uipI4.png


text:
Q: In EF6 how do I define my class to store a list of references instead of a list of objects? VS2103, EF6, MVC, VB
Still learning how code first works.  With the following Classes:
Public Class Order
  Public Property OrderID as Integer
  Public Property Products as new List(Of Product)
  .
  .
End Class

Public Class Product
  Public Property ProductID as Integer
  Public Property name as String
  .
  .
End Class

Public Class ApplicationDbContext
  Public Property Orders As DbSet(Of Order)
  Public Property Products As DbSet(Of Product)
End Class

When I executed the following:
db.Orders.Add(anOrder)
db.SaveChanges()

I ended up also adding records to the Products datatable.  So I get it that wasn't the way to define the Class Order.  I was trying to have a property in Order that would navigate to the individual Products that make up the order.  I mistakenly thought I was creating a list of references into Products, but obviously I was creating the need for the system to store Product records in the Products datatable.
What should I have coded so that I can peruse through the Products on an order by getting a reference into Products instead of adding to Products?  I apologize if I'm not asking the question well.
Best Regards,
Alan

A: I am assuming that you are working with disconnected entities as you mentioned MVC.
The culprit is this line of code...
db.Orders.Add(anOrder)

This line of code not only sets the entity state of the root entity (the instance of the Order class in this case) to Added but also sets the entity state of every object in the graph to Added.  When EF sees objects with an entity state of Added, it will issue INSERT statements for these objects.  If your object graph contains references to existing entities (such as instances of the Product class that have previously been persisted), it is your responsibility to set the entity state of each object in the graph appropriately.


text:
Q: FTP Server strange response when trying to login I have the following code which should log me on a ftp server, the function send_get() simply sends the message from msg to the ftp server and fetches the response. print_resp() prints the response from the server. When I execute this code I get:
451 The parameter is incorrect.

451 The parameter is incorrect.

500 '

 ': command not understood.

451 The parameter is incorrect.

500 '

 ': command not understood.

Im using test.rebex.net (195.144.107.198) server and it seems to work fine on broswers and other online ftp testers.
bool ftp_mirror::login(const char* user, const char* pass){
    strcpy(msg, "CLNT ftp-mirror\n");
    if(!send_get())
        return false;
    print_resp();

    strcpy(msg, "USER ");
    strcat(msg, user);
    strcat(msg, "\n");

    if(!send_get())
        return false;
    print_resp();

    strcpy(msg, "PASS ");
    strcat(msg, pass);
    strcat(msg, "\n");

    if(!send_get())
        return false;
    print_resp();
    return true;
}

and these are some other functions i used in my code
bool ftp_mirror::send_msg(){
    if(0 > send(msg_sock, msg, strlen(msg), 0)){
        perror("send_msg")
        return false;
    }
    return true;
}

bool ftp_mirror::get_resp(){
    memset(resp, 0, RESP_LENGTH);
    if(0 > recv(msg_sock, resp, RESP_LENGTH, 0)){
        perror("get_resp")
        return false;
    }
    return true;
}

bool ftp_mirror::send_get(){
    if(!send_msg())
        return false;
    if(!get_resp())
        return false;
    return true;
}

A: The FTP protocol uses CRLF as its newline sequence. So change
strcat(msg, "\n");

to
strcat(msg, "\r\n");

I also recommend using sprintf() rather than sequences of strcpy() and strcat(), e.g.
sprintf(msg, "USER %s\r\n", user);

Or maybe you should avoid reinventing the wheel, and use an existing library like libcurl. If you need something lighter, see Good simple C/C++ FTP and SFTP client library recommendation for embedded Linux


text:
Q: Why member-of-pointer at operator() doesn't work? Why work the function call operator not together with a member-of-pointer operator?
struct F
{
    void operator()(){}
};

int main()
{
    F * f = new F;
    f->();   // Why this doesn't compile?
}

A: I guess the C++ gods simply thought the syntax was too obscure. The correct syntax is either:
f->operator()();

Or:
(*f)()

If the -> operator isn't overloaded then f-> is roughly equivalent to (*f)., (*f).() doesn't compile either, you would have to use:
(*f).operator()();

A: You should call it as  f->operator()() or (*f)().

A: I don't think there's any specific reason.
Both -> and . expect the name of a member to follow, and you haven't provided one.
There's just no need to create a special case in the grammar to permit that. It's complicated enough as it is!
(*f)() is the way to go.
Sorry if that's brief and unfulfilling, but if you're looking for some deep meaning here I think you're bound to be disappointed!


text:
Q: How to convert a manual sales calculator script into an automatic sales calculator script? I have this manual javascript

And the html

<input type="text" id="dollars" />
<input type="button" onclick="applyTax();" value="Calculate" />

So basically this script needs user to input data manually to calculate taxes. I'm trying to convert it into an automatic sales tax calculator for say an eCommerce site.
Cart page:

                <%-- Left Navigation --%>

<fmt:message key='summary'/>

<fmt:message key='CartCategoryLabel1'/>

                            <%-- Start of Left Nav Widgets--%>

                                <%-- clear cart widget --%>
                                <c:set var="value">
                                <c:choose>
                                <%-- if 'selectedCategory' session object exists, send user to previously viewed category --%>
                                        <c:when test="${!empty selectedCategory}">

                                        </c:when>

                                        <%-- otherwise send user to welcome page --%>
                                <c:otherwise>

                                    </c:otherwise>
                            </c:choose>
                         </c:set>
                <c:url var="url" value="${value}"/>

<fmt:message key='ClearCart'/>

                    <%-- checkout widget --%>
                    <c:if test="${!empty cart && cart.numberOfItems != 0}">

<fmt:message key='Checkout'/>

                </c:if>

                                <%-- continue shopping widget --%>
        <c:set var="value">
            <c:choose>
                <%-- if 'selectedCategory' session object exists, send user to previously viewed category --%>
                <c:when test="${!empty selectedCategory}">
                    category
                </c:when>
                <%-- otherwise send user to welcome page --%>
                <c:otherwise>
                    index.jsp
                </c:otherwise>
            </c:choose>
        </c:set>

<fmt:message key='ContinueShopping'/>

                    <%-- End of Left Navigation --%>

                <%-- Start of Cart Breadcrumbs --%>

My shopping cart

<big></big>

                        <%-- Subtotal of cart--%>
                        <c:if test="${!empty cart && cart.numberOfItems != 0}">

<big><fmt:message key='Subtotal'/> (${cart.subtotal})

                                </big>

                            <big></big>
                        </c:if>
                        <%-- End Subtotal of cart--%>

                        <%-- Number of items in cart--%>

                            <c:choose>
        <c:when test="${cart.numberOfItems > 1}">
            <big><fmt:message key='YouHave'/> (${cart.numberOfItems}) <fmt:message key='ItemsInYourCart'/>
</big>
        </c:when>
        <c:when test="${cart.numberOfItems == 1}">
            <big><fmt:message key='YouHave'/> (${cart.numberOfItems}) <fmt:message key='ItemsInYourCart'/>
</big>
        </c:when>
        <c:otherwise>
            <big><fmt:message key='EmptyShoppingCart'/>
</big>
        </c:otherwise>
    </c:choose>

<big></big>

                    <big>

                    </big>
                    <%-- End of cart Breadcrumbs --%>

                    <%-- Start of Products Table--%>

                                <c:forEach var="cartItem" items="${cart.items}" varStatus="iter">
                                    <c:set var="product" value="${cartItem.product}"/>

                                            <img class="img" src="${initParam.productImagePath}${product.name}.jpg"

                                            ${product.name}

                                            ${product.price}

                                            <form action="addToWishlist" method="post">

 <input
name="productId" value="${product.id}" type="hidden"> <input class="submit"
value="Add To Wishlist" type="submit"></form>

                                            <form action="updateCart" method="post">
                                                    <input type="hidden"
                                                           name="productId"
                                                           value="${product.id}">

                                                    <input type="text"
                                                           maxlength="2"
                                                           size="2"
                                                           value="${cartItem.quantity}"
                                                           name="quantity"
                                                           style="margin:0px">

                                                    <input class="updateButton"  type="submit"
                                                           name="submit"
                                                           value="update">

                                                </form>

                                </c:forEach>

                            <%-- End of Products Table--%>

So I'm thinking in order to convert the script to calculate cart subtotal automatically I would only have to change few things around by declaring different variables?
Example:

<input type="text" id="cartSubtotal" />
<input type="button" onload="applyTax();" value="Calculate" />

------ EDIT ----
For a better vision, this is a screenshot from Forever 21 checkout process. You see, at the end of the page, they display the total amount = cart subtotal + tax + shipping. This is exactly what i'm trying to do with a script.
Snapshot:

A: I think that this is what you were trying to do:

  <input type="text" id="cartSubtotal" />
  <input type="button" onClick="applyTax();" value="Calculate" />

However even after keeping on reading your subject things are not clear for you I think.
You have a server that generates pages, everything that is generated will process at the server side, therefore you can use your notations such as  or ${..}. But once this page is sent to the client (where the client is using javascript) you cannot change those informations anymore because you are not on a server anymore.
If you want to update data on your server you will have to contact the server again via an HTTP request or an Ajax call.

A: This is a solution to my best interpretation to what you want. To me it seems like you want to take the displayed subtotal and calculate the taxes via javascript. This probably isn't the best way to go about it as I assume you'll be using those values later during the checkout process and it'd behove you to calculate those values on the backend then display them rather than through javascript, but I digress.
Javascript:
function applyTax(){
  var cartSubTotal = parseFloat(document.getElementById( 'cartSubtotal' ).innerHTML);
  console.log(cartSubTotal);
  var salesTaxGst = (cartSubTotal / 100) * 5;
  var salesTaxPst =  (cartSubTotal / 100) * 9.975;
  var totalAmount = (cartSubTotal*1) + (salesTaxGst * 1) +(salesTaxPst * 1) ;

  document.getElementById( 'cartSubtotal' ).innerHTML = cartSubTotal.toFixed(2);
  document.getElementById( 'taxGst' ).innerHTML = salesTaxGst.toFixed(2);
  document.getElementById( 'taxPst' ).innerHTML = salesTaxPst.toFixed(2);
  document.getElementById( 'cartTotal' ).innerHTML = totalAmount.toFixed(2);
}

// Call the applyTax() when the window finishes loading...
window.onload = function() {
  applyTax();
}

Note: I added toFixed(2) to include the "cents" placeholders, even when their value is zero.
Using the following HTML:

Cart

Cart Subtotal: $100.00

Sales Tax GST: $

Sales Tax PST: $

Final Total: $

Would display something that looked like this:
Cart

Cart Subtotal: $100.00
Sales Tax GST: $5.00
Sales Tax PST: $9.97
Final Total: $114.97

Save that you're already inserting the price as a floating-point number into the item with the id cartSubtotal
Maybe a CodePen example to play with? http://codepen.io/scrapcode/pen/GgYXaQ


text:
Q: I'm getting this error and am struggling figuring out what is wrong. Process returned -1073741819 (0xC0000005) c++ code to calculate the distance between you and your desired service but im having trouble with the pointers i think, when i run the program it pauses after displaying
"skip first line"
"in while"
and then returns this error
"Process returned -1073741819 (0xC0000005)   execution time : 1.675 s"
the most I can really tell form my debugger is that it gets stuck in this loop,
while(fscanf(Filepointer, "%d %lf %lf %d %s", &N[counter].ID, &N[counter].X_Coordinate, &N[counter].Y_Coordinate, &N[counter].s, N[counter].CityName) != EOF)
{
    fgetc(Filepointer);
    counter++;
}

does anyone know why it's getting stuck in the loop or how to fix.
/////////File for program/////////
1 33.09 96.67 2 ALLEN 69
4 32.97 96.85 2 CARROLTON 58
8 32.86 96.7 2 DALLAS 98
9 33.83 96.7 2 DALLAS 21
10 32.97 96.74 2 DALLAS 104
11 32.91 96.71 2 DALLAS 102
12 32.94 96.78 2 DALLAS 100
19 33.11 96.8 2 FRISCO 92
20 33.1 96.84 2 FRISCO 70
21 33.14 96.85 2 FRISCO 64
22 33.14 96.89 2 FRISCO 109
25 32.88 96.6 2 GARLAND 103
26 32.91 96.64 2 GARLAND 68
33 33.05 96.62 2 PARKER 97
35 33.02 96.7 2 PLANO 30
36 33.04 96.77 2 PLANO 57
43 32.94 96.73 2 RICHARDSON 60
44 32.95 96.69 2 RICHARDSON 27
51 32.9 96.51 2 ROWLETT 20
52 32.89 96.56 2 ROWLETT 23
53 32.92 96.57 2 ROWLETT 89
2 33.11 96.67 1 ALLEN 47
5 33.04 96.86 1 CARROLTON 100
13 32.91 96.79 1 DALLAS 44
14 32.91 96.77 1 DALLAS 106
15 32.91 96.74 1 DALLAS 74
16 32.91 96.86 1 DALLAS 93
17 32.88 96.66 1 DALLAS 35
23 33.15 96.84 1 FRISCO 77
27 32.9 96.62 1 GARLAND 85
28 32.91 96.66 1 GARLAND 107
29 32.87 96.61 1 GARLAND 91
31 33.01 96.6 1 MURPHY 40
37 33.01 96.74 1 PLANO 81
38 33.01 96.79 1 PLANO 36
39 33.04 96.71 1 PLANO 29
40 33.03 96.7 1 PLANO 49
41 33.04 96.86 1 PLANO 32
45 32.94 96.73 1 RICHARDSON 88
46 32.92 96.74 1 RICHARDSON 20
47 32.93 96.72 1 RICHARDSON 109
48 32.99 96.75 1 RICHARDSON 84
49 32.97 96.7 1 RICHARDSON 63
54 32.91 96.52 1 ROWLETT 63
0 33.09 96.67 0 ALLEN 46
3 32.97 96.88 0 CARROLTON 30
6 32.98 96.78 0 DALLAS 85
7 32.92 96.81 0 DALLAS 31
18 33.13 96.82 0 FRISCO 99
24 32.9 96.66 0 GARLAND 87
30 33.01 96.6 0 MURPHY 33
32 33.05 96.62 0 PARKER 58
34 33.01 96.7 0 PLANO 25
42 32.94 96.73 0 RICHARDSON 23
50 32.89 96.57 0 ROWLETT 101
////////////////////////////////
//Program
#include <iostream>
#include<stdio.h>
#include <iomanip>
#pragma warning(disable:4996)//to stop fopen_s error.
#include <fstream>
#include<math.h>

using namespace std;

enum services_type { Police_Department, Hospital, Fire_Station};

struct Cities

{

    int ID;

    double X_Coordinate;

    double Y_Coordinate;

//        enum services_type s;

    int s;

    char CityName[25];

};

struct Cities N[60];

int main()

{

    cout << "This displays a list of services, and computes the distance between you and the chosen service\n\n";

    FILE *Filepointer;

// Filepointer = fopen("H:\serviceInfo.txt", "r");

    Filepointer = fopen("serviceInfo.txt", "r");

    if (Filepointer == NULL)

    {

        perror("Error\n"); // if the file doent open just the program

        return -1;

    }

    rewind(Filepointer);// just incase the pointer is not pointing at the start

    int counter = 0;

    char buffer[100];

    char ch;

    fgets(buffer, 100, Filepointer);// to ingore the first line.

    printf("skip first line\n");

    printf("in while\n");

    while(fscanf(Filepointer, "%d %lf %lf %d %s", &N[counter].ID, &N[counter].X_Coordinate, &N[counter].Y_Coordinate, &N[counter].s, N[counter].CityName) != EOF)

    {

        fgetc(Filepointer);

        counter++;

    }

    printf("%s    %s    \t%s    %s\n", "Id", "Coordinates", "Service Type", "City");

    int i;

    for (i = 0 ; i < counter; i++)

    {

        printf("%2d %8.2lf %8.2lf\t", N[i].ID, N[i].X_Coordinate, N[i].Y_Coordinate);

        switch (N[i].s)

        {

        case 0:
            printf("%5s","Police Station\t");
            break;

        case 1:
            printf("%5s","Hospital\t");
            break;

        case 2:
            printf("%5s","Fire Deparment\t");
            break;

        }

        printf("%-5s\n", N[i].CityName);

    }

    printf("Enter one of the following, please enter option A first\n");
    printf("a) Enter you location\nb) Find the nearest service\nc) Find the nearest POLICE DEPARTMENT\nd) Find the nearest HOSPITAL\ne) Find the nearest FIRE DEPARTMENT\nf) EXIT\n");

    char choice = 65;
    int end = 0;

    int menucounter = 0;
    double usercoordX;
    double usercoordY;

    double Alldistance[55];
    int indexcounter = 0;
    double XDIFF, YDIFF;
    double XplusY;
    double distanceR;
    double distanceRSorted[60];
    while (end != 1)

    {

        scanf(" %c",&choice);

#if 0

        choice = getchar();

        if ('\n' == choice)

        {

            /* Be silent on linefeeds */

            continue;

        }

#endif

        switch (choice)

        {

        case 'a':
        case 'A':

        {

            printf("You choose A\n");

            menucounter++;

            printf("Now enter your X and Y coordinates!\nPlease seperate the two with a space or enter.\n");

            scanf("%lf %lf", &usercoordX, &usercoordY);

            printf("Your X Coordinate is: %5.2lf and your Y Coordinate is: %5.2lf \n", usercoordX, usercoordY);

            printf("If not please press \"A\" to start over. \nIf it is, select the option you want to use.\n");

            break;

        }

        case 'b':
        case 'B':

        {
            if (menucounter == 0)
            {
                printf("Please enter option A first\n");
                break;
            }
            else
            {
                printf("You choose B\n");
                for (indexcounter = 0; indexcounter < 55; indexcounter++)
                {

                    XDIFF = pow(N[indexcounter].X_Coordinate - usercoordX, 2);
                    YDIFF = pow(N[indexcounter].Y_Coordinate - usercoordY, 2);

//Alldistance[distancecounter] =

                    XplusY = XDIFF + YDIFF;
                    distanceR = sqrt(XplusY);
                    Alldistance[indexcounter] = distanceR;
                    distanceRSorted[indexcounter] = distanceR;

                }

                int ii;

                float swap, temp; // i is my counter swap is for sitching and temp is to hold the new number
                do
                {
                    swap = 0;
                    for (ii = 0; ii < 55 - 1; ii++)
                    {
                        if (distanceRSorted[ii] > distanceRSorted[ii + 1])
                        {
                            swap = 1;
                            temp = distanceRSorted[ii];
                            distanceRSorted[ii] = distanceRSorted[ii + 1];
                            distanceRSorted[ii + 1] = temp;
                        }
                    }
                }
                while (swap);
                int compare, comparecounter, compareindex = 0, endcompare = 0;
                while (endcompare != 1)
                {
                    for (comparecounter = 0; comparecounter < 55; comparecounter++)
                    {
                        if (distanceRSorted[0] != Alldistance[comparecounter])
                        {
                            compareindex++;
                            endcompare = 0;
                        }
                        else
                        {
                            endcompare = 1;
                            break;
                        }
                    }
                }
                printf("%2d %8.2lf %8.2lf\t", N[compareindex].ID, N[compareindex].X_Coordinate, N[compareindex].Y_Coordinate);

                switch (N[compareindex].s)
                {

                case 0:
                    printf("%5s", "Police Station\t");
                    break;

                case 1:
                    printf("%5s", "Hospital\t");
                    break;

                case 2:
                    printf("%5s", "Fire Deparment\t");
                    break;

                }
                printf("%-5s\n", N[compareindex].CityName);
                printf("%5.4lf\n", Alldistance[compareindex]);
            }
        }
        break;

        case 'C':
        case 'c':

            if (menucounter == 0)

            {
                printf("Please enter option A first\n");
                break;
            }

            else
            {

                printf("You choose c\n");

                double Alldistance[55];
                int indexcounter = 0;
                double XDIFF, YDIFF;
                double XplusY;
                double distanceR;
                double distanceRSorted[60];
                for (indexcounter = 0; indexcounter < 55; indexcounter++)

                {

                    XDIFF = pow(N[indexcounter].X_Coordinate - usercoordX, 2);
                    YDIFF = pow(N[indexcounter].Y_Coordinate - usercoordY, 2);

//Alldistance[distancecounter] =

                    XplusY = XDIFF + YDIFF;
                    distanceR = sqrt(XplusY);
                    Alldistance[indexcounter] = distanceR;
                    distanceRSorted[indexcounter] = distanceR;
                }
                int ii;

                float swap, temp; // i is my counter swap is for sitching and temp is to hold the new number
                do
                {
                    swap = 0;
                    for (ii = 0; ii < 55 - 1; ii++)
                    {
                        if (distanceRSorted[ii] > distanceRSorted[ii + 1])
                        {
                            swap = 1;
                            temp = distanceRSorted[ii];
                            distanceRSorted[ii] = distanceRSorted[ii + 1];
                            distanceRSorted[ii + 1] = temp;
                        }
                    }
                }
                while (swap);
                int compare, comparecounter, compareindex = 0, endcompare = 0;
                while (endcompare != 1)
                {
                    for (comparecounter = 0; comparecounter < 55; comparecounter++)
                    {
                        if (distanceRSorted[0] != Alldistance[comparecounter])
                        {
                            compareindex++;
                            endcompare = 0;
                        }
                        else
                        {
                            endcompare = 1;
                            break;
                        }
                    }
                }

                printf("%2d %8.2lf %8.2lf\t", N[compareindex].ID, N[compareindex].X_Coordinate, N[compareindex].Y_Coordinate);

                switch (N[compareindex].s)

                {

                case 0:
                    printf("%5s", "Police Station\t");
                    break;

                case 1:
                    printf("%5s", "Hospital\t");
                    break;

                case 2:
                    printf("%5s", "Fire Deparment\t");
                    break;

                }
                printf("%-5s\n", N[compareindex].CityName);
                printf("%5.4lf\n", Alldistance[compareindex]);
            }

            break;

        case 'd':
        case 'D':

            if (menucounter == 0)
            {
                printf("Please enter option A first\n");
                break;
            }
            else
            {
                printf("You choose d\n");
                for (indexcounter = 0; indexcounter < 55; indexcounter++)
                {

                    XDIFF = pow(N[indexcounter].X_Coordinate - usercoordX, 2);
                    YDIFF = pow(N[indexcounter].Y_Coordinate - usercoordY, 2);

//Alldistance[distancecounter] =

                    XplusY = XDIFF + YDIFF;
                    distanceR = sqrt(XplusY);
                    Alldistance[indexcounter] = distanceR;
                    distanceRSorted[indexcounter] = distanceR;

                }
                int ii;

                float swap, temp; // i is my counter swap is for sitching and temp is to hold the new number
                do
                {
                    swap = 0;
                    for (ii = 0; ii < 55 - 1; ii++)
                    {
                        if (distanceRSorted[ii] > distanceRSorted[ii + 1])
                        {
                            swap = 1;
                            temp = distanceRSorted[ii];
                            distanceRSorted[ii] = distanceRSorted[ii + 1];
                            distanceRSorted[ii + 1] = temp;
                        }
                    }
                }
                while (swap);
                int compare, comparecounter, compareindex = 0, endcompare = 0;
                while (endcompare != 1)
                {
                    for (comparecounter = 0; comparecounter < 55; comparecounter++)
                    {
                        if (distanceRSorted[0] != Alldistance[comparecounter])
                        {
                            compareindex++;
                            endcompare = 0;
                        }
                        else
                        {
                            endcompare = 1;
                            break;
                        }
                    }
                }

                printf("%2d %8.2lf %8.2lf\t", N[compareindex].ID, N[compareindex].X_Coordinate, N[compareindex].Y_Coordinate);

                switch (N[compareindex].s)

                {

                case 0:
                    printf("%5s", "Police Station\t");
                    break;

                case 1:
                    printf("%5s", "Hospital\t");
                    break;

                case 2:
                    printf("%5s", "Fire Deparment\t");
                    break;

                }

                printf("%-5s\n", N[compareindex].CityName);
                printf("%5.4lf\n", Alldistance[compareindex]);

            }
            break;

        case 'E':
        case 'e':

            printf("\n E\n");
            if (menucounter == 0)
            {
                printf("Please enter option A first\n");
                break;
            }
            else
            {
                printf("You choose e\n");
                for (indexcounter = 0; indexcounter < 55; indexcounter++)
                {
                    printf("in while1\n");
                    XDIFF = pow(N[indexcounter].X_Coordinate - usercoordX, 2);
                    YDIFF = pow(N[indexcounter].Y_Coordinate - usercoordY, 2);

//Alldistance[distancecounter] =

                    XplusY = XDIFF + YDIFF;
                    distanceR = sqrt(XplusY);
                    Alldistance[indexcounter] = distanceR;
                    distanceRSorted[indexcounter] = distanceR;

                }
                int ii;
                float swap, temp; // i is my counter swap is for sitching and temp is to hold the new number
                do
                {
                    printf("in while2\n");
                    swap = 0;
                    for (ii = 0; ii < 55 - 1; ii++)
                    {
                        if (distanceRSorted[ii] > distanceRSorted[ii + 1])
                        {
                            swap = 1;
                            temp = distanceRSorted[ii];
                            distanceRSorted[ii] = distanceRSorted[ii + 1];
                            distanceRSorted[ii + 1] = temp;
                        }
                    }
                }
                while (swap);

                int compare, comparecounter, compareindex = 0, endcompare = 0;

// while (endcompare != 1)

                {
                    for (comparecounter = 0; comparecounter < 55; comparecounter++)
                    {
                        printf("in while3\n");
                        if (distanceRSorted[0] != Alldistance[comparecounter])
                        {
                            compareindex++;
                            endcompare = 0;
                        }
                        else
                        {

                            endcompare = 1;
// break;

                        }
                    }
                }

                printf("%2d %8.2lf %8.2lf\t", N[compareindex].ID, N[compareindex].X_Coordinate, N[compareindex].Y_Coordinate);

                switch (N[compareindex].s)

                {

                case 0:
                    printf("%5s", "Police Station\t");
                    break;

                case 1:
                    printf("%5s", "Hospital\t");
                    break;

                case 2:
                    printf("%5s", "Fire Deparment\t");
                    break;

                }
                printf("%-5s\n", N[compareindex].CityName);
                printf("%5.4lf\n", Alldistance[compareindex]);
            }
            break;

        case 'f':
        case 'F':

            printf("Goodbye\n");
            end++;
            break;

        default :

            printf("!ERROR, invalid choice, pick a valid menu option!\n");
            break;
        }
    }
// system("pause");
    return 0;
}

there seems to be a memory overflow issue or something similar just not sure what is causing the issue as the debuggers in my ide arent mutch help


text:
Q: About MpMoviePlayerViewController Hi Everyone Gud Evening
I have taken a view on which i had to play the video, the video is being played Perfectly, but  very rarely i the video is not being appeared on the view, at that time i got a warning in the console like
WARNING: under normal conditions, _fillInQueueWithExtraSpace:ignoreExistingItems: should not be re-entered.
Could some one help me to sort out this problem
Thank  You Everyone
I have 2  UIView's in being displayed on the same view, In one view when i start drawing the movieplayer gets started in the bottomProgressView , in the viewcontroller in viewdidload the code is like this
        - (void)viewDidLoad
{
    [super viewDidLoad];
NSString *url = [[NSBundle mainBundle] pathForResource:@"progres" ofType:@"mp4"];
    timeCompletedCnlr = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:url]] ;
    [timeCompletedCnlr.view setFrame:CGRectMake(0,468, 600, 50)];
    [timeCompletedCnlr setControlStyle:MPMovieControlStyleNone];
    [bottomProgressView addSubview:timeCompletedCnlr.view];
}

When i touch the  view that is being to drawn  then the below method is called.
     - (void)removeGivenWord
{
    [bottomToolBar removeFromSuperview];
    [self.view addSubview:bottomProgressView];

    [timeCompletedCnlr play];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(helpVideoFinished:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:timeCompletedCnlr];

    UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    doneBtn.frame = CGRectMake(601, 940, 167, 43);
    [doneBtn setBackgroundImage:[UIImage imageNamed:@"done.png"] forState:UIControlStateNormal];
    [doneBtn addTarget:self action:@selector(doneButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:doneBtn];

}
the view on which the video is placed also contains the done button too..
    - (void)doneButtonClicked {
[timeCompletedCnlr stop];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(helpVideoFinished:)
                                             name:MPMoviePlayerPlaybackDidFinishNotification
                                           object:timeCompletedCnlr];

}
     - (void) helpVideoFinished:(NSNotification*) aNotification {
MPMoviePlayerController *player1 = [aNotification object];
[[NSNotificationCenter defaultCenter]removeObserver:self
                                               name:MPMoviePlayerPlaybackDidFinishNotification
                                             object:player1];
[smoothLineView completed5Sec];
NSLog(@"5sec called");
NSError *error = [[aNotification userInfo] objectForKey:@"error"];
if (error) {
    NSLog(@"Did finish with error: %@", error);
}

}
My Problem is the video sometimes it appears and sometime it doesn't come,