text:
Q: Rename Android Studio project causing a bunch of errors and java files missing Following some links here I tried to rename a project. I went to c:\path\to\AndroidStudioProject and renamed the folder there, then found the .idea file and changed that. Now the project loads but java files are missing! However, on clicking java (in the bar at the top), then com I can see them each with a small red j.
I then looked in module Gradle build where there were 3 files, one with the new name and 2 older ones which stated that they did not belong so I deleted them, copying the compile info into the new one. Naturally on doing a Sync Now I get a bunch of errors.
Why does this have to be such a complex operation? Can anyone assist?

A: After you rename the folder, open the project in Android Studio.  From there, right click something that needs to be renamed (e.g., module, package names, etc.) and use Refactor->Rename from the context menu. Keep doing this until everything that can be refactored is.
You will need to manually change the value of applicationId in the app-level build.gradle. Obviously, things like @string/app_name will also have to be changed manually. I recommend making these manual adjustments from inside Android Studio rather than directly editing the files. That way you'll know immediately if you break something.


text:
Q: Playing next video by calling a function that needs the event passed to it The question of how can JavaScript call the next video has been asked as I have thoroughly researched this topic before posting. However, in the situation that I will describe, a video is running after an onclick event calls the function: function(e) and I need to be able to call the next video by calling the function(e) again once the code detects an ended event by using the addEventListener method.
I have posted all my code below. In addition I have added comments to illustrate what I "think" is happening. I am brand new to JavaScript and have recently retired, so I have had time to research the Internet to try and piece together what is taking place. Please feel free to clarify my commented code as I would appreciate being set straight on what I have wriiten.
I have also made an attempt to put the code on jsfiddle
https://jsfiddle.net/dan2004/tuouh36d/
but it only seems to function in Chrome.
My main question to everyone is in regard to the statement:
document.getElementById('videoPlayer').addEventListener('ended',handler,false);
If I call a function outside of the function, I can issue a message via an alert, but if I call the function that I am in (handler(e)) I cannot get the next video to run. Somehow I need to be able to call the handler(e) function and send it the next onclick event.
Thanks for any help.

  var video_playlist, links, i, videotarget, filename, video, source;

    // Gets the video object from
 in the HTML
   video_playlist = document.getElementById("player");

    // "links" is an array which contains all the  tags in the
.
    // This div is located within
 and contains a clickable playlist.
   links = video_playlist.getElementsByTagName('a');

    // This "for loop" scrolls through the links array of  attributes and
    // assigns an "onclick = handler" event to each one.
   for (i=0; i<links.length; i++) {
    links[i].onclick = handler;
   };

    // e is an [object MouseEvent]
   function handler(e) {

     // The handler function receives the full path to the mp4 file when it is clicked on in the playlist.
     // The "preventDefault" method stops the function from following that path.
     // This is so the data in the path may be parsed and manipulated below
    e.preventDefault();

     // videotarget grabs the href attribute of the item clicked on
     // in the "playlist". This is the full path to the video file.
    videotarget = this.getAttribute("href");

     // Through the use of substr, filename grabs that part of the href which
     // does not include the extension.
    filename = videotarget.substr(0, videotarget.lastIndexOf('.')) || videotarget;

     // The variable "video" contains the video object. This is obtained by using document.querySelector().
     // This document method uses the css id class, #player, and grabs the [object HTML VideoElement].
     // The [object HTML VideoElement] resides in

    video = document.querySelector("#player video");

     //Removes the poster attribute in the video tag
    video.removeAttribute("poster");

     // The source variable is used to hold an array of all the source tags in the
     // [object HTML VideoElement] from
.
    source = document.querySelectorAll("#player video source");

     // Using the substring extracted from the user's click choice in

     // the three file types for browsers to choose from are concatenated to the string.
     // These thre source files are then stored under the video object located in
.
    source[0].src = filename + ".mp4";
    source[1].src = filename + ".webm";
    source[2].src = filename + ".ogv";

     // The video object will load the appropriate source[].src file then play it
    video.load();
    video.play();

     // When the  video ends the following statement will call the function  test()
     // which will then broadcast the alert message "Video Ended"
    document.getElementById('videoPlayer').addEventListener('ended',test,false);

     // This statement will not call the handler function in order to play the next video selection.
//    document.getElementById('videoPlayer').addEventListener('ended',handler,false);

   }; // function handler(e)

   function test(){
    alert("Video Ended");
   };
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Video Playlist Tutorial</title>

   <video id="videoPlayer" controls="controls" width="640" height="360" preload="auto" autoplay >
    <source src="1.mp4" type="video/mp4" />
    <source src="1.webm" type="video/webm" />
    <source src="1.ogv" type="video/ogg" />
   </video>

Videos

    Bear

    Buck Bunny

A: Seeing as your handler() function relies on this being the clicked element, you can't just call that function, you'd have to also set the this-value to the next anchor etc. and trigger the event in a way that makes it look like it was triggered by the actual element.
An easier way to do this, would be to just decouple the playing logic, get the next element, and play the video

var video_playlist = document.getElementById("player");
var links = video_playlist.getElementsByTagName('a');

for (var i = 0; i < links.length; i++) {
    (function(j) {
        links[j].addEventListener('click', function(e) {
            handler.apply(this, [e, j])
        });
    })(i);
};

function handler(e, index) {
    e.preventDefault();
    var videotarget = this.getAttribute("href");

    play(videotarget, index).addEventListener('ended', function() {
        index = (++index) >= links.length ? 0 : index;
        play(links[index].getAttribute("href"), index);
    });
};

function play(videotarget) {
    var filename = videotarget.substr(0, videotarget.lastIndexOf('.')) || videotarget;
    var video = document.querySelector("#player video");
    var source = document.querySelectorAll("#player video source");

    video.removeAttribute("poster");
    source[0].src = filename + ".mp4";
    source[1].src = filename + ".webm";
    source[2].src = filename + ".ogv";
    video.load();
    video.play();
    return video;
};

    <video id="videoPlayer" controls="controls" width="640" height="360" preload="auto" autoplay>
        <source src="1.mp4" type="video/mp4" />
        <source src="1.webm" type="video/webm" />
        <source src="1.ogv" type="video/ogg" />
    </video>

Videos

        Bear
        Buck Bunny

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to show some user posts to ajax api vue js i just display 5 users post in modal
html

          ID
          Name

           {{user.id}}

{{posts.title}}

          {{user.name}}

js
new Vue({
  el: "#app",
  data: {
    users: [],
    posts: [],
  },
  methods: {
    Showpost(id,i) {
      console.log("id",id);
      console.log("i",i)
      fetch("https://jsonplaceholder.typicode.com/posts?userId=" + id)
        .then(response => response.json())
        .then((data) => {
          this.posts = data[i];
        })
    },
  },
  computed: {
    object: function(){
      return this.posts.filter(function(post){
        return post.userId >= 5
      })
    },
  },
  mounted() {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(response => response.json())
      .then((data) => {
        this.users = data;
      })
  },
});

A: i will do so simple code to clear how this should be done
at first

       {{user.id}}

      {{user.name}}

then
instead of
      this.posts = data[i];

do it
      this.posts = data;

and in your html
under the table tag
do

</>

if you want just show one post not many
make
data:function {
return{
users: [],
posts: {},
}
 },

and

</>

I hope this help you.
Good luck!


text:
Q: How to disable jquery when opened on an iphone I would like to disable Ascensor.js when the website is opened on an iphone?
I have tried this so far, but it doesnt seem to work
$(document).ready(function() {
      if($(screen).height() > 330) {
      $('#main', this).attr('disabled', 'disabled');
}
});

or does anyone know how to get ascensor to work properly on an iphone?

A: Well, couldn't you add that part to the backend side? Check for the user-agent, and if it belongs to an iPhone, do not add the <script type="text/javascript" src="Ascensor.js"/>
Another option would be this:
    if($(screen).height() > 330) {
          $('#main', this).attr('disabled', 'disabled');

    }

    else {
        var script = $("<script />");
        script.attr("type", "text/javascript");
        script.attr("src", "js/Ascensor.js");
        $("head").append(script);

   }

Basically this should add the script element if the condition is not met.

A: Use the below method to check for iPhone or iPod.
function isiPhone(){
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1)
    );
}

if(!isiPhone()){
    //Not an iPhone device do your stuff here
}


text:
Q: Align center and right with flex? I'm trying to horizontally center align group1 and right align group2 with flex.

        ...

        ...

CSS:
.holder{
    display: flex;
    justify-content:center;
}
.group2{
    align-self: flex-end;
}

But everything is just centered, what's the fix?

A: As flexbox is built on manipulation of margins there is no method of moving one item out of the flow other than using position:absolute.
Any other method leaves the center item affected by other elements.

.holder {
  display: flex;
  justify-content: center;
  border: 1px solid grey;
  position: relative;
}
.group1 {
  background: plum;
}
.group2 {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  border: 1px solid red;
}

    Group 1

    Group 2

A: Immagine you have a button with a text and a icon and you want the text on the center and the icon on the right. Don't forget to give a width to the button.
With flexbox is really simple to do it.

button {
 display: flex;
 justify-content: center;
 align-items: center;
 flex: 1;
 width: 400px;
 order: 1;
}

span {
 flex: 1;
}
<button>

  Click me

 >
</button>

A: We can achieve it using flex, grid and position.
Check out the solution for flex, grid as position has already been submitted above
Flex Solution:

.holder {
  display: flex;
}
.group1 {
  flex: 1;
  text-align: center;
}

...

.....

Grid Solution:

.holder {
  display: grid;
  grid-template-columns: 1fr 0fr;
}
.group1 {
  flex: 1;
  text-align: center;
  border: 1px solid green;
}
.group2 {
  border: 1px solid pink;
}

...

.....

A: You can set a height in the .holderand the play with align-self and text-align:
CSS
.holder{
    display: flex;
    justify-content:center;
    align-content: center;
    height: 200px;
    background: #ccc;
}
.group2{
    align-self: center;
    text-align: right;
    width: 50%;
}

.group1{
    align-self: center;
    width: 50%;
    text-align: center;
}

DEMO HERE

A: This is the best what you can do with just Flexbox

.holder{
  display: flex;
  justify-content: center;
}

.group1 {
  flex: 1;
  text-align: center;
}

.group2{
  margin-left: auto;
}

       Center

        Right

Better option is to use relative/absolute position with Flexbox

.holder{
  display: flex;
  justify-content: center;
  color: white;
  position: relative;
}

.group1 {
  flex: 1;
  text-align: center;
  background: black;
}

.group2{
  position: absolute;
  top: 0;
  right: 0;
}

       Center

        Right


text:
Q: java_home environment variable in linux not found I'm trying to add java_home in linux machine (centos 5.8)
I'm adding this part to setting JAVA_HOME and PATH for all users in my machine

vi /etc/profile
export JAVA_HOME=/opt/jdkx.x.x_xx
export PATH=$PATH:$JAVA_HOME/bin

after seting it up, i try to verify it by using echo command

echo $JAVA_HOME

but it does not give me any path.Is there something wrong with my configuration?

A: This method will persist OS updates
echo "export JAVA_HOME=/usr/java/default/" > /etc/profile.d/java_home.sh
If you have more then on version of java install there may be trouble.

A: The JAVA_HOME path is different because we often install different version JDK and maybe different places.  Once a I try to find the general way.  There is the result.
Firstly, to query the installed jdk package name: rpm -qa|grep java
my result is:java-1.6.0-openjdk
Secondly, to query the installed place of this package
rpm -ql java-1.6.0-openjdk

Most files is under: /usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0.x86_64/
go there to confirm it is a real JDK directory
Thirdly, execute export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0.x86_64/ in terminal.  Or add it /etc/bashrc for all user.

A: Question has been edited, answer doesn't make sense anymore.
Left as a placeholder for comments.
echo $SHELL will tell you which shell you are using. Most likely /bin/bash.
Assuming bash, /etc/profile is only read for a login shell (bash --login), not just a new interactive shell.
i.e. if you
sh1% vi /etc/profile
sh1% bash # /etc/profile not read
sh2% echo $JAVA_HOME
sh2%

sh1% vi /etc/profile
sh2% bash --login # /etc/profile should be read.
sh2% echo $JAVA_HOME
/opt/blah/blah/blah
sh2%


text:
Q: What's the async for? Often we see pipe | and async in the value of an attribute/directive. For example
<ngx-datatable [rows]="rows | async"
May I ask what are they supposed for?

A: Angular docs says:

Unwraps a value from an asynchronous primitive.

async pipe allows to avoid create variables or properties in TypeScipt. So we can use promises and observables in template.


text:
Q: Getting TypeError int() argument must be a string, a bytes-like object or a number, not 'NoneType' I am creating a shopping cart using Django.  I can add items from a product detail view but once I get to the shopping cart I can't update items.  I can remove them but when I update I get the above error
I think that the form is not getting what I am putting into the function but I don't know why.  Any help or guidance would be really appreciated.

Form
Add to Cart View
Adjust Cart View
Error Message
traceback


text:
Q: Как можно сделать код чище? Создаю с помощью JS таблицу. Присваиваю циклом повторяющиеся стили и атрибуты. Прошу, подскажите можно ли упростить мой код?
let elements = document.querySelectorAll("th");

if(elements) {
  for (let i = 0; i < elements.length; i++) {
    elements[i].classList.add("align-top");
    elements[i].setAttribute("scope", "col");
    elements[i].setAttribute("role", "button");

  }
}

A: Эта проверка лишняя, т.к. querySelectorAll всегда возвращает NodeList
if(elements) {
   // ...
}

for-i можно заменить на for-of
for (let i = 0; i < elements.length; i++) {
   // ...
}

так попроще
for (const element of elements) {
   // ...
}

а лучше пойти еще дальше и вызвать на объекте NodeList метод forEach и туда передать обработчик элементов.
document.querySelectorAll('th').forEach(function(element) {
    // ...
})

Заодно получится избавиться от лишних присваиваний и проверок
let elements = // ...

С атрибутами двоякая ситуация...
Если бы их было больше то, однозначно стоило бы ввести вспомогательную функцию, которая вставляет атрибуты по json'у:
function setAttributes(el, attrs) {
  for(var key in attrs) {
    el.setAttribute(key, attrs[key]);
  }
}

и потом вызвать...
тогда получилось бы
document.querySelectorAll('th').forEach(function(element) {
    setAttributes(element, {
        class: "align-top",
        scope: "col",
        role: "button"});
})

но c объявлением функции то, то на то и выходит... было бы больше атрибутов или нужно было бы это чаще делать - стоило бы попробовать

Замечание:
Как и следует из названия, функция setAttributes устанавливает атрибуты, а не модифицирует их. Соответственно, нужно быть аккуратнее с использованием данной функции вместе с атрибутом class. Если требуется не установить значение атрибута class, а модифицировать его, добавив новое значение  список, классов или наоборот удяляя что-то из этого списка, при этом сохранив часть прошлого списка классов, то лучше это делать не с помощью  setAttributes, а стандартными средствами classList.add().

ну а так, пока что самый короткий и прочтой вариант выглядит так (без setAttributes)
document.querySelectorAll('th').forEach(function(element) {
    element.classList.add("align-top");
    element.setAttribute("scope", "col");
    element.setAttribute("role", "button");
})

A: querySelectorAll в отличии от querySelector возврашает пустой NodeList потому можно убрать проверку if (elements) цикл и так не запустится:
let elements = document.querySelectorAll("th");

for (let i = 0; i < elements.length; i++) {
  elements[i].classList.add("align-top");
  elements[i].setAttribute("scope", "col");
  elements[i].setAttribute("role", "button");
}

Но я бы переписал ещё:

*

*let на const, чтобы не было соблазна его переопределять

*для простого перебора, обычный цикл на for of
const elements = document.querySelectorAll('th');

for (const element of elements) {
  element.classList.add('align-top');
  element.setAttribute('scope', 'col');
  element.setAttribute('role', 'button');
}


text:
Q: JQuery UI AutoComplete functionaility doesnt have matching or autofill I am using the latest autocomplete widget that is part of the latest Jquery UI. Two things that I need are autoFill to fill the textbox as I type and a way to match the values typed in with values in the DB. Does anyone know how to do this with the existing autocomplete? Thanks

A: Disclaimer: This will only work in modern browsers with support for input.setSelectionRange. If you want a solution for older browsers, you're going to need to find a cross-browser solution.
Anyway, here's how I would approach this:
$(document).ready(function() {
    $("#auto").autocomplete({
        source: function(request, response) {
            /* autofill: */

            /* If using AJAX, place your AJAX request here */
            var results = $.ui.autocomplete.filter(src, request.term)
                , el = this.element[0];

            if (results.length) {
                el.value = results[0];

                /* This will not work < IE9 */
                el.setSelectionRange(request.term.length, el.value.length);
            }

            response(results);
        },
        change: function (event, ui) {
            /* mustmatch: */
            if (!ui.item) {
                this.value = '';
            }
        }
    });
});

Example: http://jsfiddle.net/SgxyT/
As you can see, mustmatch is much easier to implement. All you have to do is revert the value entered if it was not selected in the dropdown.
On the other hand, autofill will require you to use a function as the source for the autocomplete, determine the results, and set the selection in the input.

A: You must write a server-side script, that builds proper SQL query and return matched rows in JSON format, compatible with autocomplete specification.

A: Did you see this link http://jqueryui.com/demos/autocomplete/#remote-jsonp ?
You can mention a server page as your data source. It is internally using the jquery ajax.
  $("#txtSearchKey").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "getcityname.aspx?term=" + $("#txtSearchKey").val(),
                        dataType: "json",
                        success: function (data) {
                            response($.map(data, function (item) {
                                return { label: item.CityName, value: item.CityId }
                            }));
                        }
                    });
                }
    });

You should have a server page (in this example, getcityname.aspx) which reads the querystring value and make a call to your database to get the city names starts with what you entered in the text box with id "txtSearchKey". You can return the response by a response.write.


text:
Q: Moving multiple Web.config sections to the same separate file In ASP.NET MVC 4, I know you can move sections of the Web.config file to other files by pointing the configSource attribute of those sections at the relevant files. I also know that you can more the appSettings section by using the file attribute to point at the correct file. However, as far as I can see these methods limit you to one section per file.
What I'm trying to do is move all settings that the end user can edit to one file, so that we can tell the user that this file can be tweaked, but any other .config file should be left well alone. Unfortunately, if I move (for example) the appSettings and connectionStrings sections to the same file, I get errors.

*

*If I drop them straight into the file, I get an error about having multiple root XML elements. Fair enough.

*If I wrap the sections in <configuration> tags like in the main Web.config file, I get an error that says "The format of a configSource file must be an element containing the name of the section", which suggests that the limit of one section per file is pretty strict.

Is there a way around this? Can I put multiple sections in one file?


text:
Q: Turn off recommended roads for biking in Google Maps but keep the streets with dedicated bike lanes Google maps api v3 lets you include bike path info
https://developers.google.com/maps/documentation/javascript/trafficlayer#bicycling_layer
It says "Dashed routes indicate streets or paths otherwise recommended for bicycle usage."
Do you know a way to turn off the dashed routes but maintain the dark and light green routes that represent dedicated bike routes and bike lanes?

A: I think the closest thing you can get is defining the Basic Map Type to MapTypeId.TERRAIN, which displays a physical map based on terrain information, which should look something like this.
Or.. you can take advantage of the Image Map Type, use your own image as map and load the bike routes on the map.
Well.. I was thinking about styling too. But it seems like once you turn off the road, you turn off the bike lanes also. Just like this.
You can play around with the stylier and see if you can find a way to figure it out. Be sure to share with us if you do find a way.


text:
Q: Consistent way to access route value parameters passed through querystring I have the following route defined in global.asax
routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Portal", action = "Index", id = UrlParameter.Optional }
);

I can't control whether users access the page with "/useraccount/edit/1" or "/useraccount/edit?id=1". When using the UrlHelper Action method to generate a url, the id value is not contained in RouteData if id is passed as a querystring parameter.
new UrlHelper(helper.ViewContext.RequestContext).Action(
                            action, helper.ViewContext.RouteData.Values)

I'm looking for a consistent way to access the id value, regardless of which url was used to access the page, or a way to customize the initialization of the RouteData object so that it checks the QueryString for missing route parameters and adds them if they are found.

A: You can use
@Url.RouteUrl("Default", new { id = ViewContext.RouteData.Values["id"] != null ? ViewContext.RouteData.Values["id"] : Request.QueryString["id"] })

A: try this solution
  var qs = helper.ViewContext
                .HttpContext.Request.QueryString
                .ToPairs()
                .Union(helper.ViewContext.RouteData.Values)
                .ToDictionary(x => x.Key, x => x.Value);

            var rvd = new RouteValueDictionary(qs);

            return new UrlHelper( helper.ViewContext.RequestContext).Action(action, rvd);

to convert NameValueCollection try this
public static IEnumerable<KeyValuePair<string, object>> ToPairs(this NameValueCollection collection)
        {
            if (collection == null)
            {
                throw new ArgumentNullException("collection");
            }

            return collection.Cast<string>().Select(key => new KeyValuePair<string, object>(key, collection[key]));
        }

A: Extending Route ended up being the easiest solution for my needs; Thank you for the suggestions! Let me know if there are any glaring issues (other than the class name) with my solution.
FrameworkRoute.cs
public class FrameworkRoute: Route
{
    public FrameworkRoute(string url, object defaults) :
        base(url, new RouteValueDictionary(defaults), new MvcRouteHandler())
    {
    }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var routeData = base.GetRouteData(httpContext);
        if (routeData != null)
        {
            foreach (var item in routeData.Values.Where(rv => rv.Value == UrlParameter.Optional).ToList())
            {
                var val = httpContext.Request.QueryString[item.Key];
                if (!string.IsNullOrWhiteSpace(val))
                {
                    routeData.Values[item.Key] = val;
                }
            }
        }

        return routeData;
    }
}

Global.asax.cs
protected override void Application_Start()
{
       // register route
       routes.Add(new FrameworkRoute("{controller}/{action}/{id}", new { controller = "Portal", action = "Index", id = UrlParameter.Optional }));


text:
Q: DBContext throwing errors attaching unique objects, with nullable foreign keys Most posts around the ObjectStateManager are true-duplicate issues based on unique primary keys.  My problem is that my table does Not have a primary key, but it does have multiple foreign keys, one of which is Nullable.
class MyObject
{
    int   Key1;
    int?  Key2;
}

context.MyTable.Attach(new MyObject() { Key1 = 100; Key2 = null; });
context.MyTable.Attach(new MyObject() { Key1 = 100; Key2 = 2000; }); ****

It blows up on the second call, even though this is a unique row in the database.
Any thoughts on how to get around this?  or enforce checking of BOTH keys?

A: As @BenAaronson mentioned, you should have a surrogate, primary key in your table in this instance. Entity Framework quite simply cannot deal with entities that have no primary key defined—in fact, I'm surprised your code even compiled/ran. Perhaps your real code with real class and property names caused EF to infer a primary key using its default conventions. For example:
public class MyClass
{
    public int MyClassId { get; set; }
    public int MyOtherClassId { get; set; }
}

In the code above, even without explicitly declaring it, EF would assume that the MyClassId property is the primary key for the class MyClass, even if that may not have been your intention.
If EF can't infer a primary key and one is not explicitly provided, then your code wouldn't compile (or at most, it wouldn't run).
So looking at your code, what appears to be happening is that EF inferred a primary key somehow (in your example above, Key1). You then tried to attach a new object to your context:
context.MyTable.Attach(new MyObject() { Key1 = 100; Key2 = null; });

This results in the context adding a new MyObject instance whose primary key value is 100 and whose Key2 property is null.
Next, you attempt to attach another item to the context:
context.MyTable.Attach(new MyObject() { Key1 = 100; Key2 = 2000; });

What this does is attempt to add a new item to the context whose primary key is 100, and this fails. This is because you already have an object being tracked by the context whose primary key value is 100 (executed by the first statement above).
Since you need to allow possibly null values for the Key2 property, you can't use a composite primary key, as you already stated. So you will need to follow @BenAaronson's advice and add a surrogate primary key:
public class Object
{
    // Alternatively, you can use a mapping class to define the primary key
    // I just wanted to make the example clear that this is the
    // surrogate primary key property.
    [Key]
    private int ObjectID { get; set; } // IIRC, you can make this private...
    public int Key1 { get; set; }
    public int Key2 { get; set; }
}

Now, you can do the following:
context.MyTable.Add(new MyObject() { Key1 = 100, Key2 = null; });
context.MyTable.Add(new MyObject() { Key1 = 100, Key2 = 2000; });

Notice I used the Add method and not Attach. That's because when using Attach, the context is assuming that you're adding an object to the context which already exists in the database, but which was not brought into the context via a query; instead, you had a representation of it in memory, and at this point, you want the context to start tracking changes made to it and update the object in the database when you call context.SaveChanges(). When using the Attach property, the context adds the object in the Unmodified state. That's not what we want. We have brand new objects being added to the context. So we use Add. This tells the context to add the item in the Added state. You can make any changes you want to it. Since it's a new item, it will be in the Added state until you call context.SaveChanges() and the item is persisted to your data store, at which time, it's state will be updated to Unmodified.
One more thing to note at this point. If this is a "many-to-many" table, you should never need to manually add rows to this type of join table in EF (there are some caveats to this statement, see below). Instead, you should setup a mapping between the two objects whose relationship is many-to-many. It's possible to specify an optional many-to-many relationship, too. If the first object has no relationship to the second, there should be no row in the join table for the first object, and vice versa.
Regarding join table caveats as alluded to above: if your join-tables (i.e. many-to-many mapping tables) are simple (meaning the only columns in the table are those columns mapping one ID to the related ID), then you won't even see the join-table as part of your object model. This table is managed by EF in the background through navigation properties on the related objects. However, if the join-table contains properties other than just the ID properties of the related objects (and, this implies you have an existing database or explicitly structured your object model this way), then you will have an intermediate entity reference. For example:
public class A
{
    public int ID { get; set; }
}

public class B
{
    public int ID { get; set; }
}

public class AToB
{
    // Composite primary key
    [Key]
    public int IdA { get; set; }
    [Key]
    public int IdB { get; set; }

    public A SideA { get; set; }
    public B SideB { get; set; }

    // An additional property in the many-to-many join table
    public DateTime Created {  get; set; }
}

You would also have some mappings to tell EF how to wire up the foreign key relationships. What you'd wind up with in your object model then, is the following:
myA.AToB.SideB  // Accesses the related B item to this A item.
myA.AToB.Created // Accesses the created property of AToB, telling you
                 // when the relationship between A and B was created.

In fact, if you have non-trivial join tables such as this example, EF will always include them in your object model when generating its model from an existing database.
I would strongly suggest that you check out Julie Lerman's and Rowan Miller's books on programming Entity Framework.


text:
Q: swagger formData validation not working It seems like the swagger validator for "type":"file" is not working.
{
    "name": "receipt",
    "in": "formData",
    "required": true,
    "type": "file"
}

If I use "required": false I get TypeError: Cannot read property 'value' of undefined.
If I use "requried": true I get ValidationError: "receipt" is required
I get the error with curl -X POST --header "Content-Type: multipart/form-data" --form "receipt=@myimage.jpg"  "http://localhost:8000/insights"
And when using swagger-ui.
The error must be in the validation since uploading files without specifying it is swagger works just fine. Also the validation for "in":"query" works just fine.
Workaround I would be happy with: Disabling the validation, so I can use the documentation function of swagger.


text:
Q: What is the difference between "in town" and "in a town"? What is the difference between "in town" and "in a town"? Or do they both mean the same thing?

A:
What is the difference between "in town" and "in a town"? Or do they both mean the same thing?

They don't mean (exactly) the same thing.
There are parallels with the following pairs of phrases:

*

*in school/in the school

*in prison/in the prison

*at sea/at the sea

*in water/in the water

*in print/in the print

In all cases, "the" may be substituted for "a"/"an".
but the first phrase, with no article, is fossilized into a phrase with a more specific meaning than the second.
For example, if I say "my cousin's still in school", I mean she still goes to school; she has not graduated yet. But "She's still in the school" means she is physically inside that location or building.
Same deal with "in prison". That would mean incarcerated there. But "in the prison" just means "in that location", perhaps for work or visiting hours or whatever.
As to your example with "in town" versus "in a/the town". "In town" means "in [the known] town for some kind of business or leisure, and probably only temporarily". But "in the town" seems more like someone just happens to be in that location, with or without a reason to be there, so here are some examples when you might use "in the town":

*

*There is a library in the town

*The missing person has been sighted in the town

*There has been an accident in the town

A: The preposition phrase "in a town" has no special meaning, it just means what it says.
The phrase, "in town", however, functions as an adverb, roughly means "here, in the local area".
Merriam-Webster describes it simply as "in this town", but it can be any place, not necessarily a town.

Drew's in town this weekend

This means Drew, who presumably doesn't live locally, is here, in this city/town/village/etc., this weekend.


text:
Q: Creating a folder and writing txt files to it to create a registration method (Java) The folder being created in the root is the way I want it to be so that's fine. The method also creates the file and folder just fine but I don't know how to get it to be created in the folder.
Here's what I have so far:
public void registration(TextField user, PasswordField pass){

    File admin = new File("adminstrator");

    if(!admin.exists()){
    admin.mkdir();
    }

   //add some way to save file to admin folder

    try (BufferedWriter bw = new BufferedWriter(new FileWriter("USER_PASS.txt", true))){

        bw.write(user.getText());
        bw.newLine();
        bw.write(pass.getText());
        bw.newLine();

        bw.close();
    }
    catch(IOException e){
        e.printStackTrace();
    }
}

A: You have put admin as path before file name like that
try (BufferedWriter bw = new BufferedWriter(new FileWriter(admin + "\\USER_PASS.txt", true))){

    bw.write(user.getText());
    bw.newLine();
    bw.write(pass.getText());
    bw.newLine();
    bw.close();
}
catch(IOException e){
    e.printStackTrace();
}

A: *

*I think it is better to avoid using AWT components like TextField in your program. Use light weight Swing components instead, like JTextField and JPasswordField.

*By using File.separator instead of a backslash you assure that your program will also behave correctly if you ever port it to another operating environment.

*JPasswordField has a .getPassword() method which returns a character array. You can use it directly in your BufferedWriter write method. You can even convert it to a String ps = new String(pass.getPassword());.

*It is always better to close your file in a finally block, because if an IOException occurs, it will skip the bw.close() method call, and your file will be left open.

*e.printStackTrace() is a quick and dirty solution. Avoid using it because it writes to stderr and the output might get lost. Read God's Perfect Exception in order to find out how God did it during Genesis. Use a logging framework. slf4j is a good option.
public void registration(JTextField user, JPasswordField pass) {  // 1
   File admin = new File("adminstrator");
   BufferedWriter bw = null;
   if (!admin.exists()) {
      admin.mkdir();
   }

   try {
       bw = new BufferedWriter(new FileWriter(admin + File.separator + "USER_PASS.txt", true)); // 2
       bw.write(user.getText());
       bw.newLine();
       bw.write(pass.getPassword()); // 3
       bw.newLine();
   } catch (IOException e) {
       e.printStackTrace();  // 5
   } finally { // 4
       try {
          if (bw != null) {
              bw.close();
          }
       } catch (IOException e) {
           e.printStackTrace(); // 5
       }
   }
}


text:
Q: Default Parameter PageSize A4 C# using itextsharp Is it possible to set values for default parameters for PageSize in C#? For example:
public virtual void Render(string reportTitle, Rectangle pageSize = PageSize.A4)
{
    foreach (Page p in pages)
    {
        p.Render(document);
        document.NewPage();
        document.AddCreationDate();
        document.AddTitle(reportTitle);
        document.SetPageSize(pageSize);
    }
}

I have the following error in Visual Studio 2010:

Default parameter value for 'pageSize' must be a compile-time
  constant.

A: When you write;
Rectangle pageSize = PageSize.A4

Your pageSize value can be change as a parameter.
From Named and Optional Arguments

A default value must be one of the following types of expressions:

*

*a constant expression;

*an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;

*an expression of the form default(ValType), where ValType is a value type.

The expression PageSize.A4 is not classified as a compile-time constant.


text:
Q: RODBC with MAC not working. Using unixODBC and Rstudio I followed this guide http://eriqande.github.io/2014/12/19/setting-up-rodbc.html to get RODBC working with MAC and I am able to connect to the DB.
Marcos-MacBook-Pro:~ MarcoB$ isql -v ODBC_SQLSS_R **** ******
+---------------------------------------+
| Connected!                            |
|                                       |
| sql-statement                         |
| help [tablename]                      |
| quit                                  |
|                                       |
+---------------------------------------+
SQL>

The configuration files are set according to the guide.
Marcos-MacBook-Pro:~ MarcoB$ cat /usr/local/etc/freetds.conf
[ODBC_SQLSS_R]
host = xxx.xxx.xxx.xxx
port = 1433
client charset = UTF-8

Marcos-MacBook-Pro:~ MarcoB$ cat /usr/local/etc/odbc.ini
[ODBC_SQLSS_R]
Driver = /usr/local/lib/libtdsodbc.so
Server = xxx.xxx.xxx.xxx
POrt = 1433

I install the RODBC package
> install.packages("RODBC", type = "source")
...
** R
** inst
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** installing vignettes
** testing if installed package can be loaded
* DONE (RODBC)

And when I try it out it seems that it does not use my UnixODBC libraries.
 library("RODBC")
 odbcDataSources()
 named character(0)

When I try to connect via ODBC
    odbcConnect("ODBC_SQLSS_R", uid="*****", pwd="******");
    Warning messages:
    1: In odbcDriverConnect("DSN=ODBC_SQLSS_R;UID=*****;PWD=*****") :
      [RODBC] ERROR: state IM002, code 1962223636, message [iODBC][Driver
  Manager]Data   source name not found and no default driver specified.
 Driver could   not be loaded

The error message indicates to me that RODBC is still using iODBC. I browsed the internet for days now but I can't find a solution for the problem.
Would be really amazing if anybody here could point me in the right direction.
Marco

A: A clean reinstall of my Mac seem to have solved the library issues.
I just followed the guide exactly again and it worked.


text:
Q: Client registration data of AdapterSecurityContext is null while testing the API using POSTMAN I have written a server side REST API which requires client registartion data to perform some operation. I have used AdapterSecurityContext and I am fetching the client registration data using getClientRegistrationData method of AdapterSecurityContext. I need to test the API before giving the endpoint to mobile APP developers  so I am trying to check the API suing POSTMAN.
The problem is when I try to hit the same API from POSTMAN for testing the response I get nullpointer exception because getClientRegistrationData is null. I am begginer in MFP so I just needed to know is it possible to pass client registration data through POSTMAN or it can only be obtained when adapter is connected to mobile client.

A: You can retrieve client registration data only when you invoke adapter endpoints using mobile/web clients.
This doesn't work with confidential clients.


text:
Q: Hibernate map repeated column (within an entity) Table looks like this: I am skipping few columns for simplicity
ColumnnID   ColumnA    ColumnB
     1         1           A
     2         1           B
     3         2           C
     4         3           C

Table mapped to an entity MyClass
class MyClass {

  @Id
  private long columnId;

  @column(name = "columnA")
  private long columnA;

  @column(name = "columnB")
  private long columnB;
}

After executing simple query (criteria) I wont my hibernate entity look like this
Criteria criteria = this.getSessionFactory().getCurrentSession()
                .createCriteria(MyClass.class);

and result:
data: {
    myClass : {
        columnId: 1
        columnA: 1
        mapColumnB : [
           A,
           B
        ],
     },
      myClass : {
        columnId: 3
        columnA: 2
        mapColumnB : [
           C
        ],
     },
     myClass : {
        columnId: 4
        columnA: 3
        mapColumnB : [
           C
        ],
     }

    }

Any ideas? need to map within an entity.
If I can do it and can get only row by row, what would be efficient way in Java to rebuild list to presentation I need ?

A: EDIT: the answer is for original question (before editing the question by post owner(asker)!!) and it's not for current version of question!!!.

The expected result you mentioned, isn't an Entity, it just could be a result of a criteria or hql query.
You can write the Entity according to your data / table / query but you need to provide an Id for the Entity(mapped from unique field(s)), and as your sample data does not have a unique column(s) so you can't, you have to add an extra column(PK / Unique) to the table or you have to use a Composite key for the Id, I mean use a combination of (ColumnA and ColumnB) for Id, just do a little search you'll see how to do it; as soon as you did it you'll be able to get the expected result without any complicated criteria or hql query.


text:
Q: I want to get all urls of website by php script, is this possible or not? I want to get all urls of website by php script, is this possible or not ?
Make sure it is not for one page only.
If i enter one domain name then i want all urls on that website even its inner pages also.

A: You could try a sitemap generator like: https://www.xml-sitemaps.com/


text:
Q: CUDA Check out nvcc "-arch"-flag during run time Is there somehow a possibility to call different kernels depending on whether for example nvcc -arch=sm_11 or nvcc -arch=sm_20 has been used to compile the code? To be a bit more explicit:
if (FANCY_FLAG == CU_TARGET_COMPUTE_11)
    // Do some conversions here..
    krnl1<<<GRID_DIM1, BLOCK_DIM1>>>(converted_value1);
else if (FANCY_FLAG == CU_TARGET_COMPUTE_20)
    krnl2<<<GRID_DIM2, BLOCK_DIM2>>>(value1);

As you can see I found the CUjit_target_enum in cuda.h but I wasn't able to find out whether the nvcc defines any flags which would be equal to one of the enums values.
My intention for this is that I don't know whether my device support double precision floats or not. That would mean I have to convert my data from double to float and hence, run a different kernel (Yes, I'd prefer to run the kernel with double precision over single precision wherever possible).
I'd also appreciate a completely different approach as long as it does the trick.

A: *

*In the device code check CUDA_ARCH macro value

*In the host code - check major and minor fields of the device properties.


text:
Q: How to draw data file column with very small data difference using gnuplot I have a data file with 7 columns in which I need to draw the first column versus 4th, 5th, 6th and 7th column.
The data file looks like the following:
1.005146    1   2   0   0   0   0
1.006025    1   2   0   0   0   0
1.008025    1   2   0   0   0   0
1.010025    1   2   0   0   0   0
1.012025    1   2   0   0   0   0
1.014025    1   2   0   0   0   0
1.015146    1   2   0   0   0   0
1.016025    1   2   0   0   0   0
1.018025    1   2   0   0   0   0
1.020025    1   2   0   0   0   0
......

when I try to plot the graph using the following command, I got only one point:
plot "queuelength.txt" using 4 with linespoints 1

and a warning to adjust both x and y range. So to fix it I use the actual x and y range
plot [0:40][0:50] "queuelength.txt" using 4 with linespoints 1

But I got nothing!! so I've tried to change the first column data for 10 rows from 1 to 10 and it works!! so does that mean gnuplot can't deal with a data that has very small difference equals to 0.002 between each row?
Is there anyway to deal with it or to draw it using gnuplot?

A: Your data file contains only carriage returns (ASCII 13, \r) as line endings. Gnuplot cannot handle those properly. You must have line feeds (ASCII 10, \n), or both \r\n as line endings.
What works for me is
plot '< sed ''s/\r/\n/g'' qlength_map1.txt' using 1:4


text:
Q: CRM 2011: How to publish the duplicate detection rules in dynamic crm 2011? I Published duplicate detection rules in one week back, but still it is publishing in dynamic crm 2011,can anyone tell me what is the reason behind this.

A: Could you perhaps provide some more details here. Are you saying that you published and the publishing process itself is still running a week later? If so I would suggest the process has crashed an you may need to perform an iisreset and try again.
Or am I misunderstanding what you mean here? Some more details would help to better understand the problem.

A: Solution: restart the 'Microsoft Dynamics CRM Asynchronous Processing Service'
Ofter happens when you go into system jobs or want to run bulk deletion and statuts indicates 'waiting for ressources'


text:
Q: fetch data from a table having foreign key in yii1 I have a table name business and second table address. Business table has attributes, id,buisness name,image and address table has attributesaddress_id,business_id,street,city,house.
In my business model i have the relationship like this 'addresses' => array(self::HAS_MANY, 'Address', 'business_id'),.
The thing which i want is to fetch the data like street,city,house from the address table and show that in the Cdetail view of Business. I just know that it can be done with the relationship, but do not know exactly the answer.
Below is my Cdetail view of Business.
<?php
/* @var $this BusinessController */
/* @var $model Business */
?>

<?php
$this->breadcrumbs=array(
    'Businesses'=>array('index'),
    $model->id,
);

$this->menu=array(
    array('icon' => 'glyphicon glyphicon-list','label'=>'List Business', 'url'=>array('index')),
    array('icon' => 'glyphicon glyphicon-plus-sign','label'=>'Create Business', 'url'=>array('create')),
    array('icon' => 'glyphicon glyphicon-edit','label'=>'Update Business', 'url'=>array('update', 'id'=>$model->id)),
    array('icon' => 'glyphicon glyphicon-minus-sign','label'=>'Delete Business', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->id),'confirm'=>'Are you sure you want to delete this item?')),
    array('icon' => 'glyphicon glyphicon-tasks','label'=>'Manage Business', 'url'=>array('admin')),
);
?>

<?php echo BsHtml::pageHeader('View','Business '.$model->id) ?>

<?php $this->widget('zii.widgets.CDetailView',array(
    'htmlOptions' => array(
        'class' => 'table table-striped table-condensed table-hover',
    ),
    'data'=>$model,
    'attributes'=>array(
        'id',
        'business_name',
          'image',
    ),
)); ?>

after a lot of googling
i finally did this
<?php
/* @var $this BusinessController */
/* @var $model Business */
?>

<?php
$this->breadcrumbs=array(
    'Businesses'=>array('index'),
    $model->id,
);

$this->menu=array(
    array('icon' => 'glyphicon glyphicon-list','label'=>'List Business', 'url'=>array('index')),
    array('icon' => 'glyphicon glyphicon-plus-sign','label'=>'Create Business', 'url'=>array('create')),
    array('icon' => 'glyphicon glyphicon-edit','label'=>'Update Business', 'url'=>array('update', 'id'=>$model->id)),
    array('icon' => 'glyphicon glyphicon-minus-sign','label'=>'Delete Business', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->id),'confirm'=>'Are you sure you want to delete this item?')),
    array('icon' => 'glyphicon glyphicon-tasks','label'=>'Manage Business', 'url'=>array('admin')),
);
?>

<?php echo BsHtml::pageHeader('View','Business '.$model->id) ?>

<?php $this->widget('zii.widgets.CDetailView',array(
    'htmlOptions' => array(
        'class' => 'table table-striped table-condensed table-hover',
    ),
    'data'=>$model,
    'attributes'=>array(
        'id',
        'business_name',
            'image',
            array(
            'name' => 'addresses', //name of relation in business model
            'value' => function ($data) {
                // Get all related address using the relation defined in the business model and use CHtml::listData to store data inside the $addresses variable as an array using `id` as key and `child_name` as value
                $addresses = CHtml::listData($data->addresses, 'id','sector');
                // Return names as a comma separated list
                return implode(', ', $addresses);
            },
            'type'=>'raw'
        )

    ),
)); ?>

now i am getting city name in cdetailview but how can i get sector,street_number too ?

A: From your database schema i can see that a business can have many addresses.
If you want to display all of them you can use the following:
<?php
/* @var $this BusinessController */
/* @var $model Business */
?>

<?php
$this->breadcrumbs=array(
    'Businesses'=>array('index'),
    $model->id,
);

$this->menu=array(
    array('icon' => 'glyphicon glyphicon-list','label'=>'List Business', 'url'=>array('index')),
    array('icon' => 'glyphicon glyphicon-plus-sign','label'=>'Create Business', 'url'=>array('create')),
    array('icon' => 'glyphicon glyphicon-edit','label'=>'Update Business', 'url'=>array('update', 'id'=>$model->id)),
    array('icon' => 'glyphicon glyphicon-minus-sign','label'=>'Delete Business', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->id),'confirm'=>'Are you sure you want to delete this item?')),
    array('icon' => 'glyphicon glyphicon-tasks','label'=>'Manage Business', 'url'=>array('admin')),
);
?>

<?php echo BsHtml::pageHeader('View','Business '.$model->id) ?>

<?php

//Create the attributes array to use it in CDetailView
$attributes = array(
    'id',
    'business_name',
    'image',
);

//Get all the addresses for the specific business_id
$addresses = Address::model()->findAll(
    array(
    'select'=>'city', 'condition'=>'business_id=:business_id',
    'params'=>array(':business_id'=>$model->id)));

//Insert all the addresses in your attributes array
$i = 1;
foreach($addresses as $key => $value) {
    $attributes[] = array(
        'name'=>'City '.$i++,
        'value'=>$value->city
    );
}
?>

<?php $this->widget('zii.widgets.CDetailView',array(
    'htmlOptions' => array(
        'class' => 'table table-striped table-condensed table-hover',
    ),
    'data'=>$model,
    'attributes'=>$attributes,
)); ?>

A: Ok, here is the deal, i have two tables, business and address, address table has business_id key as foreign key, and i want to show, a business address in one of the business's view i made i call it views/(userbusiness.php).
I copied paste this code from my views/view.php to views/userbusiness.php.
<?php
/* @var $this BusinessController */
/* @var $model Business */
?>

<?php
$this->breadcrumbs=array(
    'Businesses'=>array('index'),
    $model->id,
);

$this->menu=array(
    array('icon' => 'glyphicon glyphicon-list','label'=>'List Business', 'url'=>array('index')),
    array('icon' => 'glyphicon glyphicon-plus-sign','label'=>'Create Business', 'url'=>array('create')),
    array('icon' => 'glyphicon glyphicon-edit','label'=>'Update Business', 'url'=>array('update', 'id'=>$model->id)),
    array('icon' => 'glyphicon glyphicon-minus-sign','label'=>'Delete Business', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->id),'confirm'=>'Are you sure you want to delete this item?')),
    array('icon' => 'glyphicon glyphicon-tasks','label'=>'Manage Business', 'url'=>array('admin')),
);
?>

after that i am getting the data of a business address just like that in the userbusiness.php.
<?php $address= $model->addresses;
foreach ($address as $ad)
 {

     echo $ad->street_number;
     echo $ad->sector;
      echo $ad->city;
 }
 ?>

now in my userbusiness.php view, i can echo street_number etc where ever i want. just like below.

<?php echo $model->business_name; ?>

 <?php $address= $model->addresses;
foreach ($address as $ad)
 {

     echo $ad->street_number;
     echo $ad->sector;
      echo $ad->city;
 }
 ?>

 Restaurant Website

+92-51-2898044s

Photos

<img src="<?php echo Yii::app()->request->baseUrl;?>/img/<?php echo $model->image; ?>" alt="Image Alternative text" title="hotel PORTO BAY SERRA GOLF living room" />
<img src="<?php echo Yii::app()->request->baseUrl;?>/img/<?php echo $model->image; ?>" alt="Image Alternative text" title="hotel PORTO BAY SERRA GOLF living room" />
<img src="<?php echo Yii::app()->request->baseUrl;?>/img/<?php echo $model->image; ?>" alt="Image Alternative text" title="hotel PORTO BAY SERRA GOLF living room" />
<img src="<?php echo Yii::app()->request->baseUrl;?>/img/<?php echo $model->image; ?>" alt="Image Alternative text" title="hotel PORTO BAY SERRA GOLF living room" />
<img src="<?php echo Yii::app()->request->baseUrl;?>/img/<?php echo $model->image; ?>" alt="Image Alternative text" title="hotel PORTO BAY SERRA GOLF living room" />
<img src="<?php echo Yii::app()->request->baseUrl;?>/img/<?php echo $model->image; ?>" alt="Image Alternative text" title="hotel PORTO BAY SERRA GOLF living room" />
<img src="<?php echo Yii::app()->request->baseUrl;?>/img/<?php echo $model->image; ?>" alt="Image Alternative text" title="hotel PORTO BAY SERRA GOLF living room" />
<img src="<?php echo Yii::app()->request->baseUrl;?>/img/<?php echo $model->image; ?>" alt="Image Alternative text" title="hotel PORTO BAY SERRA GOLF living room" />
<img src="<?php echo Yii::app()->request->baseUrl;?>/img/<?php echo $model->image; ?>" alt="Image Alternative text" title="hotel PORTO BAY SERRA GOLF living room" />
<img src="<?php echo Yii::app()->request->baseUrl;?>/img/<?php echo $model->image; ?>" alt="Image Alternative text" title="hotel PORTO BAY SERRA GOLF living room" />
<img src="<?php echo Yii::app()->request->baseUrl;?>/img/<?php echo $model->image; ?>" alt="Image Alternative text" title="hotel PORTO BAY SERRA GOLF living room" />
<img src="<?php echo Yii::app()->request->baseUrl;?>/img/<?php echo $model->image; ?>" alt="Image Alternative text" title="hotel PORTO BAY SERRA GOLF living room" />
<img src="<?php echo Yii::app()->request->baseUrl;?>/img/<?php echo $model->image; ?>" alt="Image Alternative text" title="hotel PORTO BAY SERRA GOLF living room" />
<img src="<?php echo Yii::app()->request->baseUrl;?>/img/<?php echo $model->image; ?>" alt="Image Alternative text" title="hotel PORTO BAY SERRA GOLF living room" />
<img src="<?php echo Yii::app()->request->baseUrl;?>/img/<?php echo $model->image; ?>" alt="Image Alternative text" title="hotel PORTO BAY SERRA GOLF living room" />

Outstanding!

97% of guests recommend

4.7 of 5  rating

based on 1535 reviews

Business Rating Details

Exellent

1223

Very Good

61

Average

40

Poor

15

Terrible

9

Write a Review
Add Photos
 View Products
  Claim This business

Reviews

Salik Asad

Islamabad

Really liked this place.

Was this review helpful?
 7

Muhammad Waqas

Islamabad

Five out of five !!!!!!

Was this review helpful?
 7

Nouman Ali Sethi

Islamabad

Good Experience :)

Was this review helpful?
 7

1108 reviews on this hotel.   Showing 1 to 7

1

2

3

4

5

6

7

...

43

Next Page

Write a Review

<form>

Review Text
<textarea class="form-control" rows="6"></textarea>

<input class="btn btn-primary" type="submit" value="Leave a Review" />

</form>

About the Business

 <?php echo $model->business_description; ?>

Hours
From
To

Mon
9:00am
11:00pm

Tue
9:00am
11:00pm

Wed
9:00am
11:00pm

Thu
9:00am
11:00pm

Mon
9:00am
11:00pm

Fri
9:00am
11:00pm

Sat
9:00am
11:00pm

Facilities Available

Wi-Fi Internet

Parking

You may like

Nandos

The Emperor's Table

A: I post this answer too because my previous one works if you want to have a different row for each address.
This one shows the whole address (city, street, house) in a single row for all addresses using relations as you asked. I have checked it and it works properly.
First, declare a virtual attribute at your Addresses model.
public $address;

Then, in BusinessController replace the actionView with the following:
public function actionView($id) {
    $model = Business::model()->with(array(
        'addresses'=>array(
                'select'=>(['alias'=>'CONCAT(city, " ", street, " ", house) AS address'])
            )
        ))->find(array('condition'=>'id=:id', 'params'=>array(':id'=>$id)));

    $this->render('view', array(
        'model'=>$model,
    ));
}

Finally, in your business/view.php write:
<?php $this->widget('zii.widgets.CDetailView',array(
    'htmlOptions' => array(
        'class' => 'table table-striped table-condensed table-hover',
    ),
    'data'=>$model,
    'attributes'=>array(
        'id',
        'business_name',
        'image',
        array(
            'name' => 'addresses',
            'value' => function ($data) {
                //Variable $addresses contains all addresses as a comma separated list
                $addresses = CHtml::listData($data->addresses, 'address_id', 'address');
                return implode(', ', $addresses);
            },
            'type'=>'raw'
        ),
    ),
)); ?>


text:
Q: unique entry inherits entities symfony I am working with two classes:
employee and physician.
doctor class inherits employed.
How could put a restriction to not use any email could ever recorded in employee? Each email must be unique in the two classes.
for class employee I have:
/**
 * @ORM\Entity
 * @ORM\Table(name="empleado")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="tipo1", type="string")
 * @ORM\DiscriminatorMap({"empleado" = "Empleado","medico" = "Medico"})
* @UniqueEntity(fields={"dni"}, message="Este valor ya se ha utilizado.")
* @UniqueEntity(fields={"email"}, message="Este valor ya se ha utilizado.")
* @UniqueEntity(fields={"username"}, message="Este valor ya se ha utilizado.")
 */

but do not extend to the class as a doctor also.
thanks.


text:
Q: Is it ever necessary to instantiate new HttpRequest objects in Django? I have a view that authenticates a user. If the user is authenticated, the program should call another view with the request and user as parameters.
    def home(request):
        if request.method == "POST":
            username = request.POST.get('username')
            password = request.POST.get('password')
            user = authenticate(username=username, password=password)

            if user is not None:
                return index(request, user)
            else:
                 context = {'error_message': "That username and password don't exist in our system."}
                 return render(request, 'list/home.html', context)

So, when index gets called, the request is the same instance as the request send to the home view, right? My concern is that the request is still a POST request when it should be a GET request.
Is this a misconception? Should I create a new request object and send it to index?
Thanks.

A: You should use redirect method
if user is not None:
    return redirect(reverse('index'))

A: From the excellent "What technical details should a programmer of a web application consider before making the site public?",

Redirect after a POST if that POST was successful, to prevent a refresh from submitting again.

So you're right, you'll want to redirect to make sure that the previous form isn't submitted. but further from that, you shouldn't think about views as being directly linkable and instead get into the mindset that a view is what you get to from making a request. So as afilardo suggests, you should redirect.
return redirect('index')


text:
Q: Reverse engineered Arguments in Dapper Dynamic parameters list I'm curently create some test on the controller of a MVC web site.
I use Dapper to get data from BDD through a single access point standardized.
For the test, I mock the data access, of course, but I need to get the _value of one of the parameters passed into the DynamicParameters, to know if I get all data from the queried table or only one based on a code.
Problem is I don't know hot to get _value porperty from a dynamic parameter.

A: OK, I have the solution.
As I had to create a personalized data type (JsonBParameter) I simply add a GetParameter that return the value in the class.... So easy :(


text:
Q: Estimating an exponential sum $\sum_{n = 1}^x e^n/n$
I'm interested in estimating the exponential sum
  $$
\sum_{n = 1}^x \frac{e^n}{n}
$$
  for reasonably large $x$.

One way to try to understand this sum is to approximate it with an integral
$$
\sum_{n = 1}^x \frac{e^n}{n} \leq \frac{e^x}{x} + \int_1^x \frac{e^t}{t} dt,
$$
which would lead us to estimate the integral version. The integral is closely related to the classical exponential integral $\text{Ei}(x)$, except that we only pay attention to the worst-converging part.
For either the integral or the sum, the summand/integrand $e^t/t$ grows so quickly that the entire sum/integral should be dominated by the last unit interval. In particular, the sum looks almost geometric with ratio $e$. I haven't made this rigorous, but this sort of reasoning suggests that
$$
\sum_{n = 1}^x \frac{e^n}{n} \leq 2 \frac{e^x}{x}.
$$
How can we estimate that sum, either by improving one of these arguments or otherwise?

A: Asymptotic series for sums like this where the largest contributions come from only a few terms of the sum (in this case the terms near $n=x$) can be found by expanding the subdominant factors in power series in this region.
We'll assume that $x$ is an integer, which allows us to set $m=x-n$ and rewrite the sum like
$$
\sum_{n=1}^{x} \frac{e^n}{n} = e^x \sum_{m=0}^{x-1} \frac{e^{-m}}{x-m}.
$$
Now the largest contribution to the sum comes from a neighborhood of $m=0$, and we expand
$$
\frac{1}{x-m} = \frac{1}{x} \sum_{j=0}^{\infty} \left(\frac{m}{x}\right)^j.
$$
We can substitute this back into the sum to get the asymptotic series
$$
\sum_{n=1}^{x} \frac{e^n}{n} \sim x^{-1}e^x \sum_{j=0}^{\infty} x^{-j} \sum_{m=0}^{x-1} m^j e^{-m}.
$$
By attaching the tails to the inner sums we introduce errors which are exponentially smaller than the terms of the series, and thus obtain
$$
\sum_{n=1}^{x} \frac{e^n}{n} \sim x^{-1} e^x \sum_{j=0}^{\infty} x^{-j} \sum_{m=0}^{\infty} m^j e^{-m}. \tag{$*$}
$$
We calculate
$$
\sum_{m=0}^{\infty} m^j e^{-m} = \begin{cases}
\frac{e}{e-1} & j=0, \\
\frac{e}{(e-1)^2} & j=1, \\
\frac{e(e+1)}{(e-1)^3} & j=2,
\end{cases}
$$
so the first few terms of the asymptotic series for your sum are
$$
\sum_{n=1}^{x} \frac{e^n}{n} = \frac{e}{e-1} x^{-1} e^x + \frac{e}{(e-1)^2} x^{-2} e^x + \frac{e(e+1)}{(e-1)^3} x^{-3} e^x + O\!\left(x^{-4} e^x\right).
$$
These calculations can be justified rigorously in a routine manner, e.g. as in §3.2 of de Bruijn's Asymptotic Methods in Analysis.

A: I will here derive the asymptotic
$$S(N) = \sum_{n=1}^N \frac{e^n}{n} \sim \frac{e}{e-1}\frac{e^N}{N}$$

Massaging the series we see that
$$S(N) = \frac{e^N}{N}\left[1 + \frac{1}{e(1-1/N)} + \frac{1}{e^2(1-2/N)} + \ldots \right]\\= \frac{e^N}{N}\left[\frac{e}{e-1} + \frac{1}{e(N-1)} + \frac{2}{e^2(N-2)} + \ldots + \frac{N-1}{e^{N-1}}\right]$$
where I have added $0 = \frac{e}{e-1} - 1 - \frac{1}{e} - \frac{1}{e^2}-\ldots$ to reach the last line. The ratio of two successive terms in the series above is
$$\frac{1+\frac{1}{k}}{e\left(1 - \frac{1}{n-k}\right)} \leq \frac{2}{e\left(1 - \frac{1}{n-1}\right)} \leq \frac{2+\epsilon}{e} < 1$$
for any $0 < \epsilon < e-2$ as long as $n$ is large enough. We can therefore bound the series above by a geometrical series giving us the upper bound
$$S(N) \leq \frac{e^N}{N}\left[\frac{e}{e-1} + \frac{1}{(N-1)} \frac{1}{e-2-\epsilon}\right] \implies \lim_{N\to\infty} \frac{NS(N)}{e^N} \leq \frac{e}{e-1}$$
To establish a lower bound take $g(z) = \sum_{n=1}^N \frac{x^n}{n}$ to get $g'(z) = \frac{x^N-1}{x-1}$ and by integrating up we get the integral identity
$$S(N) = H_N + \int_1^e \frac{z^N-1}{z-1}{\rm d}z$$
where $H_N = \sum_{n=1}^N\frac{1}{n} \sim \log(N)$. We can now use $\frac{z^N-1}{z-1} \geq \frac{z^N-1}{e-1}$ for $z\in[1,e]$ which in the integral identity above leads to
$$\lim_{N\to\infty} \frac{S(N) N}{e^N} \geq \frac{e}{e-1}$$
and the desired result follows.

A: I found that $\sum_{n=1}^N \frac{e^n}{n} < \frac{e^{N+1}}{N+1}$. Their values are of the same order. For example, for $N = 10^6$, the sum gives $4.8\times10^{434288}$ while the approximation gives $8.25\times10^{434288}$. In fact, I would go further to suggest that $\sum_{n=1}^N \frac{e^n}{n} \sim \frac{e^{N+1}}{N+1}$. Still not sure how to go about showing this, maybe induction will work.

A: One might note that
$$\begin{align}\sum_{n=1}^x\frac{e^n}n&=e\sum_{n=1}^x\int_0^et^{n-1}~\mathrm dt\\&=e\int_0^e\sum_{n=1}^xt^{n-1}~\mathrm dt\\&=e\int_0^e\frac{1-t^x}{1-t}~\mathrm dt
\\&=eH_x+e\int_1^e\frac{1-t^x}{1-t}~\mathrm dt\end{align}$$
Where $H_x$ is the $x$th Harmonic number. Use your favorite approximation ;). Thus, the remaining task is estimating the rest of the integral:
For $x>2$,
$$\int_1^e\frac{1-t^x}{1-t}~\mathrm dt<ex+\frac12\left(\frac{e^x-1}{e-1}-x\right)^2$$
Which follows from trapezoidal rule and the fact that $\frac{1-t^x}{1-t}$ is convex with respect to $t$ for $x>2$.
A lower bound may be constructed using a tangent line:
$$\int_1^e\frac{1-t^x}{1-t}~\mathrm dt>ex+\frac{(e-1)^2}4x^2(x-1)^2$$


text:
Q: dpkg: unrecoverable fatal error I am running Ubuntu 20.04.3
I am getting this error when running sudo apt full-upgrade
The following packages will be upgraded:
  brave-browser command-not-found ghostscript ghostscript-x google-chrome-stable libgs9 libgs9-common liblightdm-gobject-1-0 libnss-systemd libpam-systemd libsystemd0
  libsystemd0:i386 libudev1 libudev1:i386 lightdm linux-firmware linux-libc-dev openssh-client python3-commandnotfound systemd systemd-sysv systemd-timesyncd
  ubuntu-drivers-common udev
24 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/308 MB of archives.
After this operation, 2,211 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Preconfiguring packages ...
dpkg: warning: files list file for package 'fonts-tlwg-kinnari' missing; assuming package has no files currently installed
dpkg: unrecoverable fatal error, aborting:
 files list file for package 'linux-headers-5.11.0-43-generic' contains empty filename
E: Sub-process /usr/bin/dpkg returned an error code (2)


text:
Q: Is EF Core resistant to change the order of configurations in OnModelCreating? Let's assume, we have following model configuration and migrations already applied
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Customer>()...
    modelBuilder.Entity<Property>()...
    ...
    modelBuilder.Entity<Address>();
}

Does it any difference whether new entity configuration will be added at the beginning in the middle or at the end of current configurations? What's more, does it affect migrations when the order of configuration will be totally changed through refactoring?
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    ...
    modelBuilder.Entity<Contact>();
    ...
    modelBuilder.Entity<Address>();
    ...
    modelBuilder.Entity<Customer>()...
    modelBuilder.Entity<Property>()...

}

A: For explicit fluent configurations the order doesn't matter, and the entity configurations will override any conventions.
But if you are adding custom conventions, the order can matter, as documented in the section Convention Order here: http://entityframework.codeplex.com/wikipage?title=Custom%20Conventions
David


text:
Q: A couple Hilbert space questions I read in a different post that for a separable Hilbert space, it follows that $B(H)\oplus B(H) \cong B(H)$. However, I am not sure how to begin proving this.
If someone can provide a source or an idea for a proof, I'd really appreciate it.
Also on a separate note, I was wondering what a good source would be to learn about Hilbert-Schmidt and trace class operators between Hilbert spaces. Texts I have read usually cover operators in $B(H)$ but not in $B(H, K)$ in these contexts. Thanks!

A: The argument for separable infinite dimensional case is quite simple.Using orthonormal bases it follows that all separable infinite dimensional are isomorphic.This result immediately gives what you want.

A: It is never true that $B(H)\oplus B(H)\simeq B(H)$. At least, not as algebras.
This is a simple consequence of counting ideals:

*

*If $H$ is finite dimensional, $B(H)\oplus B(H)$ has two proper ideals, while $B(H)$ has none.

*If $H$ is infinite-dimensional and separable, $B(H)\oplus B(H)$ has 8 proper ideals, while $B(H)$ has only one.

*For non-separable $H$, it is at least obvious that they cannot be isomorphic as von Neumann algebras, because all ideals in $B(H)$ as sot-dense, while $B(H)\oplus B(H)$ has non-dense ideals.


text:
Q: Validation ErrorTemplate not applied when the control is made visible I have a control with validation and an error template set up which is not initially visible. The control becomes visible when the property a ContentControl is bound to switches to it. When the control is made visible, however, the error template is only applied after the bound property is updated. Any thoughts why this might be happening and what I can do about it?
XAML control snippet:
<TextBox Name="UserNameTextBox" Grid.Row="0" Grid.Column="1" Style="{StaticResource WinformsErrorTemplate}" Text="{Binding Path=UserName, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" IsEnabled="{Binding Path=CanEditCredentials}"/>

XAML error template:

        <!-- This error template style emulates a Winforms validation error icon -->
        <Style x:Key="WinformsErrorTemplate" TargetType="Control">
            <Setter Property="Margin" Value="3"/>
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <DockPanel LastChildFill="True">
                            <Ellipse DockPanel.Dock="Right"
                                     ToolTip="{Binding ElementName=myTextbox,
                                              Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"
                                     Width="15" Height="15"
                                     Margin="-25,0,0,10"
                                     StrokeThickness="1" Fill="Red" >
                                <Ellipse.Stroke>
                                    <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
                                        <GradientStop Color="#FFFA0404" Offset="0"/>
                                        <GradientStop Color="#FFC9C7C7" Offset="1"/>
                                    </LinearGradientBrush>
                                </Ellipse.Stroke>
                                <Ellipse.Triggers>
                                    <EventTrigger RoutedEvent="FrameworkElement.Loaded">
                                        <BeginStoryboard Storyboard="{StaticResource FlashErrorIcon}"/>
                                    </EventTrigger>
                                </Ellipse.Triggers>
                            </Ellipse>
                            <TextBlock DockPanel.Dock="Right"
                                       ToolTip="{Binding ElementName=myControl,
                                                Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"
                                       Foreground="White"
                                       FontSize="11pt"
                                       Margin="-15,0,0,5" FontWeight="Bold">!
                                <TextBlock.Triggers>
                                    <EventTrigger RoutedEvent="FrameworkElement.Loaded">
                                        <BeginStoryboard Storyboard="{StaticResource FlashErrorIcon}"/>
                                    </EventTrigger>
                                </TextBlock.Triggers>
                            </TextBlock>
                            <Border BorderBrush="Red" BorderThickness="1" Margin="0,0,0,10">
                                <AdornedElementPlaceholder Name="myControl"/>
                            </Border>
                        </DockPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip"
                            Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                                   Path=(Validation.Errors)[0].ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>

A: Found the solution. The issue was that there was an AdornerDecorator at the Window level, but not in any of the UserControls. Consequently, the ErrorTemplate was not able to render. The fix was to encapsulate everything below the UserControl in an AdornerDecorator:
<UserControl>
    <AdornerDecorator>
        <StackPanel>
            ...
        </StackPanel>
    <AdornerDecorator>
</UserControl>

See Validation ErrorTemplate not showing on data errors for more information.

A: I had the same issue with a program that had multiple views inside a tab control.
The validation error would be displayed, but would disappear when I switched to a different tab and back again.
Adding the AdornerDecorator to each view fixed the problem.
Thanks


text:
Q: Combinar dos TreeMap desde una funcion en Java Estoy tratando de hacer una función que reciba como parámetros dos TreeMap y los combine entre ellos. Mi problema está en que no encuentro como pasar como parámetro un TreeMap genérico para que reciba cualquier tipo de TreeMap, es decir, se debe específicar el tipo de dato de la Key y el Valor, pero la idea de la función es que me reciba cualquier dato dentro del TreeMap sin importar cuál sea.
public void compararTree(TreeMap<String, Integer>map1, TreeMap<String, Integer>map2) {
    TreeMap<String, Integer> combinado = new TreeMap<>();
    for (Map.Entry<String, Integer> ent : map2.entrySet()) {
        combinado.put(ent.getKey(), ent.getValue());
    }

    for (Map.Entry<String, Integer> ent : map1.entrySet()) {
        combinado.put(ent.getKey(), ent.getValue());
    }

    System.out.println(combinado.keySet() + " - " + combinado.values());
}

He intentado con haciendo lo siguiente:
public void compararTree(TreeMap map1, TreeMap map2)

pero entonces el metodo map.Entry me genera error porque sigue esperando el TreeMap con los dos parámetros para la Key y el Value.

A: Para lograr lo que buscas, simplemente haz tu método genérico. Quedaría:
public <K, V> void combinarTree(TreeMap<K, V> map1, TreeMap<K, V> map2) {
        TreeMap<K, V> combinado = new TreeMap<>();
        combinado.putAll(map1);
        combinado.putAll(map2);

        System.out.println(combinado.keySet() + " - " + combinado.values());
    }


text:
Q: Is it possible to run "mysqld" without installation in Linux? I have run mysqld.exe in Windows to run the server without installation. I am able to connect to it via a client and everything works fine.
Is it possible to do the same in Linux? Can we run mysqld without complete installation of the whole MySQL package. I tried several ways but failed.

A: Q: Is it possible to run "mysqld" without installation in Linux?
A: Short answer: no.
The mysqld executable depends on shared libraries, and on runtime configuration of several different files in several different locations.
Q: Is it possible to create an embedded mySQL configuration, in lieu of the standard install?
A: Depending on your requirements, this might be something you wish to investigate:

*

*https://www.mysql.com/oem/

A: The Bitnami stack provides what you need.
https://bitnami.com/tag/mysql
Basically, they provide self-contained packages for the different services that are normally available through apt, yum or any other packages manager. I use it for example to install Redmnine (BUG tracking system) and the installation was straightforward.
The good thing is that the installation process doesn't affect your current system (packages, shared libraries etc) since all the dependencies: packages, shared libraries, etc are installed in a single directory. Thus, it's very easy to install, test and delete the whole thing easily if you would like to.

A: Depending on what you mean by "without complete installation of the whole MySQL package"... the answer is yes.
As a DBA, I don't trust package management to manipulate my MySQL installations, so I never install MySQL Server from package management.
I manage everything myself, and essentially everything is stored under /usr/local/mysql from the Linux Generic binary tarball.  There is nothing really "installed" in the sense of mystery files added who-knows-where on the system.  Upgrades involve extracting a new tarball and creating a new symlink for the datadir.
The only external dependency is easily resolved with $ sudo apt-get install libaio1.


text:
Q: Evernote Android-job not getting triggered periodically I have a task which should be triggered periodically every 15 mins once it is scheduled. Below given is the code I use,
int jobId = new JobRequest.Builder(WallpaperJob.TAG)
        .setPeriodic(TimeUnit.MINUTES.toMillis(15), TimeUnit.MINUTES.toMillis(5))
        .setPersisted(true)
        .setUpdateCurrent(true)
        .build()
        .schedule();

I tried changing the phone date and time but it does not get triggered,I hope it is supposed to be triggered with respect to changes in system time. I cannot completely deny the job being triggered because at certain times I have noticed the job to have been taken place;but I am not sure of the interval.


text:
Q: Native Javascript querySelectorAll() with multiple/many pseudo selectors/matches How can I place many pseudo selectors inside the native Javascript querySelectorAll()?
Example: I want to search for an element with an id that starts with [id^=starting]  and ends with [id$=ending].
(Couldn't find existing question so making my own and answering it)

A: With Native Javascript this would be the code:
document.querySelectorAll('[id^=starting][id$=ending]');
or
document.querySelectorAll('[id^='+startingString+'][id$='+endingString+']');
This will get an element which starts with the specified string AND ends with the specified string.
Edit: And to do an "OR", put a space between them:
document.querySelectorAll('[id^=starting] [id$=ending]');

A: If you need to query for the elements starting with a string or with another string, you have to use the following structure:
document.querySelectorAll('[id ^= "startingString-"], [id ^= "anotherStartingString-"]')


text:
Q: How do I make Postgres extension available to non superuser I installed a Postgres extension (unaccent) with
sudo su posgres
psql create extension unaccent

and now I can use unacccent in sql, but only if I am the Postgres user.
How do I make Postgres extension available to all/another user
(Im on Ubuntu using Postgres 9.3.5 installed using apt-install)
jthinksearch=# \dx;
                         List of installed extensions
   Name   | Version |   Schema   |                 Description
----------+---------+------------+---------------------------------------------
 plpgsql  | 1.0     | pg_catalog | PL/pgSQL procedural language
 unaccent | 1.0     | public     | text search dictionary that removes accents
(2 rows)

jthinksearch=#

jthinksearch=> \du;
                             List of roles
 Role name |                   Attributes                   | Member of
-----------+------------------------------------------------+-----------
 postgres  | Superuser, Create role, Create DB, Replication | {}
 ubuntu    |                                                | {}

postgres@ip-172-31-39-147:/home/ubuntu/code/jthinksearch/reports/src/main/sql$ exit
ubuntu@ip-172-31-39-147:~/code/jthinksearch/reports/src/main/sql$ psql jthinksearch
psql (9.3.5)
Type "help" for help.
I gave user superuser role but that didnt help, then as suggested put the schema name in , that had an effect on the error message but still didnt work
jthinksearch=# \du;
                             List of roles
 Role name |                   Attributes                   | Member of
-----------+------------------------------------------------+-----------
 postgres  | Superuser, Create role, Create DB, Replication | {}
 ubuntu    | Superuser                                      | {}

jthinksearch=# select unaccent(name) from musicbrainz.artist where id=195660;
ERROR:  function unaccent(character varying) does not exist
LINE 1: select unaccent(name) from musicbrainz.artist where id=19566...
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
jthinksearch=# ^C
jthinksearch=# select public.unaccent(name) from musicbrainz.artist where id=195660;
ERROR:  text search dictionary "unaccent" does not exist
jthinksearch=#

A: Here is my solution. I have a superuser (postgres) and a non-superuser (pg4e_user_8087f) and a database (pg4e) and I want to install hstore and uuid-ossp extensions and use them without becoming the superuser.  I am using PostgreSQL 11.
Superuser window:
\c pg4e
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
ALTER EXTENSION "uuid-ossp" SET SCHEMA public;
CREATE EXTENSION IF NOT EXISTS "hstore";
ALTER EXTENSION "hstore" SET SCHEMA public;
GRANT ALL ON ALL FUNCTIONS IN SCHEMA public TO pg4e_user_8087f;

Non-superuser window after the above commands are finished:
pg4e=> \dx
                            List of installed extensions
   Name    | Version |   Schema   |                   Description
-----------+---------+------------+--------------------------------------------------
 hstore    | 1.5     | public     | data type for storing sets of (key, value) pairs
 plpgsql   | 1.0     | pg_catalog | PL/pgSQL procedural language
 uuid-ossp | 1.1     | public     | generate universally unique identifiers (UUIDs)

pg4e=> select uuid_generate_v1();
           uuid_generate_v1
--------------------------------------
 2114df5a-16bb-11ea-8000-468ce7a721ef
(1 row)

pg4e=> SELECT 'a=>1,b=>2'::hstore;
       hstore
--------------------
 "a"=>"1", "b"=>"2"
(1 row)

At one point, I had figured almost all of it out but did not realize that the superuser had to be connected to the database in question to create and then permit the extension.  Once I figured out that this was done for a particular database, it fell into place quickly.

A: Based on this error message:

ERROR:  text search dictionary "unaccent" does not exist

and the previous one where unaccent without the schema prefix is not found,  it means that the public schema, where the unaccent function resides, is not in your search_path.
It happens that unaccent fails in this case because it's a dictionary function and basically it needs to find its stuff through the search_path.
This is explained in more details in Does PostgreSQL support "accent insensitive" collations?
Once the public schema is added to the search_path of the users who need to call it (this is normally the default), this should work and they don't need to be superuser.
Or if this solution is not acceptable, you may also use an intermediate stub function that embeds the schema and adds immutability, as suggested in the answer linked above.


text:
Q: Function to Split a String into Letters and Digits in C I'm pretty new to C, and I'm trying to write a function that takes a user input RAM size in B, kB, mB, or gB, and determines the address length. My test program is as follows:
int bitLength(char input[6]) {

  char nums[4];
  char letters[2];

  for(int i = 0; i < (strlen(input)-1); i++){
    if(isdigit(input[i])){
      memmove(&nums[i], &input[i], 1);
    } else {
      //memmove(&letters[i], &input[i], 1);
    }
  }
  int numsInt = atoi(nums);
  int numExponent = log10(numsInt)/log10(2);
  printf("%s\n", nums);
  printf("%s\n", letters);
  printf("%d", numExponent);
  return numExponent;
}

This works correctly as it is, but only because I have that one line commented out. When I try to alter the 'letters' character array with that line, it changes the 'nums' character array to '5m2'
My string input is '512mB'
I need the letters to be able to tell if the user input is in B, kB, mB, or gB.
I am confused as to why the commented out line alters the 'nums' array.
Thank you.

A: In your input 512mB, "mB" is not digit and is supposed to handled in commented code. When handling those characters, i is 3 and 4. But because length of letters is only 2, when you execute memmove(&letters[i], &input[i], 1);, letters[i] access out of bounds of array so it does undefined behaviour - in this case, writing to memory of nums array.
To fix it, you have to keep unique index for letters. Or better, for both nums and letters since i is index of input.

A: There are several problems in your code. @MarkSolus have already pointed out that you access letters out-of-bounds because you are using i as index and i can be more than 1 when you do the memmove.
In this answer I'll address some of the other poroblems.
string size and termination
Strings in C needs a zero-termination. Therefore arrays must be 1 larger than the string you expect to store in the array. So
char nums[4];     // Can only hold a 3 char string
char letters[2];  // Can only hold a 1 char string

Most likely you want to increase both arrays by 1.
Further, your code never adds the zero-termination. So your strings are invalid.
You need code like:
nums[some_index] = '\0';  // Add zero-termination

Alternatively you can start by initializing the whole array to zero. Like:
char nums[5] = {0};
char letters[3] = {0};

Missing bounds checks
Your loop is a for-loop using strlen as stop-condition. Now what would happen if I gave the input "123456789BBBBBBBB" ? Well, the loop would go on and i would increment to values ..., 5, 6, 7, ... Then you would index the arrays with a value bigger than the array size, i.e. out-of-bounds access (which is real bad).
You need to make sure you never access the array out-of-bounds.
No format check
Now what if I gave an input without any digits, e.g. "HelloWorld" ? In this case nothin would be written to nums so it will be uninitialized when used in atoi(nums). Again - real bad.
Further, there should be a check to make sure that the non-digit input is one of B, kB, mB, or gB.
Performance
This is not that important but... using memmove for copy of a single character is slow. Just assign directly.
memmove(&nums[i], &input[i], 1); ---> nums[i] = input[i];

How to fix
There are many, many different ways to fix the code. Below is a simple solution. It's not the best way but it's done like this to keep the code simple:
#define DIGIT_LEN 4
#define FORMAT_LEN 2

int bitLength(char *input)
{
    char nums[DIGIT_LEN + 1] = {0};    // Max allowed number is 9999
    char letters[FORMAT_LEN  + 1] = {0}; // Allow at max two non-digit chars

    if (input == NULL) exit(1);  // error - illegal input

    if (!isdigit(input[0])) exit(1); // error - input must start with a digit

    // parse digits (at max 4 digits)
    int i = 0;
    while(i < DIGITS && isdigit(input[i]))
    {
        nums[i] = input[i];
        ++i;
    }

    // parse memory format, i.e. rest of strin must be of of B, kB, mB, gB
    if ((strcmp(&input[i], "B") != 0) &&
        (strcmp(&input[i], "kB") != 0) &&
        (strcmp(&input[i], "mB") != 0) &&
        (strcmp(&input[i], "gB") != 0))
    {
          // error - illegal input
          exit(1);
    }
    strcpy(letters, &input[i]);

    // Now nums and letter are ready for further processing
    ...
    ...
  }

}


text:
Q: Jquery Calling Rails Controller I have a giant check list that is going to have rows of check boxes.  Each row is one event.  When the check box is 'checked' it is replaced with the user's initials and the current date.  I want the user to be able to click on the TD that has the user's info and then have jquery pop up a dialog box which will ask if you want to uncheck this field.
My problem is I have no idea how to call a method from the controller after the dialog box is accepted.  I will need to send the ID and the Category that is passed to the dialog box, to the method also.
Rails View Code:
<td style='text-align:center;' class='completed_box' id='<%= check_list.id %>' category='videos_edited'>
                            <div id='videos_edited_<%= check_list.id %>' style='display:none;'>
                                Are you sure you would like to uncheck videos edited recieved?

                                <%= check_list.videos_edited_user_id.initials %>

                                <%= check_list.videos_edited_date.strftime("%-m/%d")  %>

JQuery Code:
$(document).ready(function(){

    $(".completed_box").click(function(e){
        id = this.id
        category = $(this).attr('category');
        $("#" + category + "_" + id).dialog({
          resizable: false,
          height:140,
          modal: true,
          buttons: {
            Yes: function(){
                uncheck(id,category); // This is the function I'm not sure how is going to work
                $(this).dialog('close');
            },
            Cancel: function(){
                $(this).dialog('close');
                }
            }
        });
    });
});

A: Use the gon gem to pass the 'uncheck' url to your javascript, so your javascript knows where to post the message.
If you post to an 'uncheck' action with JSON data, with the id of the record to deselect, then your controller can make the change (or better, call model or lib object to make the change), and if successful just end with something like:
head :ok

If unsuccessful, you may want to render a simple JSON hash with the error message to display, with possibly a different status code like 422 - Unprocessable entity. In your jQuery Ajax, include an error event handler to display the error message if it failed, or recheck the box, or whatever you want to have happen.


text:
Q: linked reports in ssrs not returning data I am adding a new parameter to a report that is suppose to parse to a linked report
In the new report the same parameter will be created to retreive data on that report.
The general data set is a code but tyhe parametr datasource is a cube.so there is no drop down list to choose parameter.How do I parse the value.Will just selecting the parameter on tyhe fx  tab do tyhe job?
I tried =Fields(Parameters!EA.Value).Value
it is giving me an error.
i TRIED =Parameters!EA.Value
It is returning 0 values on lnked report

A: I bet you have to allow a default value on the parameter of null, so the report will run.


text:
Q: Why is the EEPROM of my ESP8266 not working? I need to get some values saved into eeprom on my esp 8266, but it's not working. I get the Error "ERROR! EEPROM commit failed" when i try to EEPROM.commit() some writes. I tested it with my own code, but it also doesn't even work with the examples from the EEPROM library. I have multiple ESP8266MOD and tested with some of them, but no one worked. Anybody got an idea?
If you need additional Infos ill tell you

A: As we discussed in the comments, it is not working because ESP8266 do not have EEPROM and your option is to use Flash to emulate the EEPROM.
I have not done a thorough research as I am not using ESP8266 on regular basis but did try the ESP_EEPROM library and it seem to be working well, here's the code I just tested:
#include <ESP_EEPROM.h>

void setup() {
  Serial.begin(115200);
  while(!Serial);
  EEPROM.begin(16); // looks like 16 bytes is the minimum
  EEPROM.put(0, 1234); // first parameter sets the position in the buffer, second the value
  boolean res = EEPROM.commit();
  Serial.println(res); // should print 1 (true) if commit worked as expected
  int myVar;
  EEPROM.get(0, myVar);
  Serial.println(myVar);
}

void loop() {
}

A: in some cases the problem is in the Arduino Ide Tools. For example, the Flash Size might be set to 512KB, and your device Flash Size might be 4MB. Then, you need to select in the Arduino Ide Tools, the correct size of your ESP. This problem happened to me, I thought there was a problem in muy code, but when I changed the Flash Size, the EEPROM start to work.


text:
Q: How can I install BlueGriffon 2.0 from a deb package or PPA? Is it possible to install BlueGriffon 2.0 from a deb package or PPA?

A: Not that I know of, but the install is very easy, you download the tar, unpack it to a location, like your home, and then you run the bluegriffon app from there, after you start it, you can lock it to your start bar, and then just click on the icon from there, it really is that easy to install.
http://nixmash.com/linux/how-to-install-blue-griffon-in-ubuntu-and-linux-mint/

A: It is even simpler now, with the version of January 2017 and Ubuntu 16:
The file is a .deb, you click on it, and it opens a window for installation. Just click "Install", it will ask you for permission, and that's all. It only did not notify about having finished the installation.


text:
Q: Finding difference in 2 shapefiles and deleting the difference I have 2 shapefiles: shapefile A (yellow) and shapefile B (purple). I already did some basic data cleanup on shapefile A, but now want to use shapefile B because it has less overlaps between polygons.
How can I detect the difference between the 2 shapefiles? Basically I want to remove the differences. So in the following image, the purple polygons on the right (shapefile B) should not be there as they were already removed in shapefile A.

I tried in the Difference tool in QGIS but it didn't help.

A: Would it work to Select by location for features that touch and then inverse the selection?

A: You could to use "Spatial Query" plugin:

*

*Layer A

*Where the feature = Equals

*Layer B

And then you'll need to invert the selection to obtain the polygons that are not equal.