text:
Q: Cannot fetch students from db and display it in the angular front end no error is visible

              Name
              Profile
              Cgpa Criteria
              Action

                {{company.name}}
                {{company.profile}}
                {{company.cgpaCriteria}}

                    Detail
                    Edit
                    Find Students
                    Delete

`enter code here`

This is company.html file which displays the list of all companies . This portion is working
when we click on find students button , the students who match the company criteria must be displayed .
There is no error but the students are not being displayed.
    import { Component, OnInit } from '@angular/core';

import {CompService} from '../../comp.service'
import {Company} from '../../company'

@Component({
  selector: 'app-companies',
  templateUrl: './companies.component.html',
  styleUrls: ['./companies.component.css']
})
export class CompaniesComponent implements OnInit {

  constructor(
  public compService:CompService
  ) { }

  ngOnInit() {
   this.getCompanies();
  }

  model = new Company();
  companies:Company;

  getCompanies()
  {
    this.compService.getCompanies().subscribe(companies=>{this.companies = companies;
  })
 }

 deleteCompany(id){
 this.compService.deleteCompany(id)
 .subscribe(()=>{
 this.getCompanies()
 })

 }

}

This is the companies.component.ts file which contains function

              Name
              Department
              Cgpa
              Action

                {{student.name}}
                {{student.department}}
                {{student.cgpa}}

                    Register Student
                    UnRegister Student
                    Register Students
                    Delete

this is the register.component.html file
    import { Component, OnInit } from '@angular/core';

    import {FormBuilder, FormGroup , Validators} from '@angular/forms';
    import { ActivatedRoute, Params, Router } from '@angular/router';

    import {StudService} from '../../stud.service'
    import {Student} from '../../student'

    @Component({
      selector: 'app-register-student',
      templateUrl: './register-student.component.html',
      styleUrls: ['./register-student.component.css']
    })
    export class RegisterStudentComponent implements OnInit {

      constructor(

      public studService:StudService,
        public route:ActivatedRoute,
         public router:Router
      ) { }

      model = new Student();
      students:Student;

      cgpa = this.route.snapshot.params['cgpa'];
      department = this.route.snapshot.params['department'];

      registerStudents()
      {
      this.studService.getStudentBasis(this.cgpa,this.department)
      .subscribe(student=>{
      this.model = student;
      })

      }
       ngOnInit() {
      this.registerStudents()
      }

    }

this is the registercomponent.ts file which is used when we click on find students

import { Injectable } from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class StudService {

  constructor(private http:Http) { }

    getStudents()
    {
    return this.http.get("http://localhost:3000/api/students").map(res =>res.json());
    }

    getStudent(id)
    {
    return this.http.get("http://localhost:3000/api/show/"+id).map(res =>res.json());
    }

    addStudent(info)
    {
    return this.http.post("http://localhost:3000/api/registerstudent",info).map(res =>res.json());
    }

    deleteStudent(id)
    {
    return this.http.delete("http://localhost:3000/api/removestudent/"+id).map(res =>res.json());
    }

    updateStudent(id , info)
    {
    return this.http.put("http://localhost:3000/api/updatestudent/"+id,info).map(res =>res.json());
    }

    getStudentBasis(cgpa,department)
    {

    return this.http.get("http://localhost:3000/api/findStudent/"+cgpa+"/"+department).map(res=>res.json());
     }

}

this is the studService.ts file which contains all the functions
This is the page which displays the list of companies
This is the page which opens when we click on find students as you can see no students are visible but when I run it on localhost:3000 the function written in backend works


text:
Q: Angular code in Codeship then Heroku I would like to post a basik Angular code to Codeship then heroku. But I have a problem what i can't solve. I got this error.
I searched, i found a that node version is too old, but my node version in my computer is the newest 6.11.0, npm 3.10.10.
    {
  "name": "anonymous",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "http-server dist -p $PORT",
    "build": "ng build",
    "test": "ng test --single-run",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "postinstall": "ng build --aot -prod"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/cli": "1.1.1",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/compiler-cli": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "core-js": "^2.4.1",
    "http-server": "^0.10.0",
    "node-wget": "^0.4.2",
    "rxjs": "^5.1.0",
    "wget": "0.0.1",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/language-service": "^4.2.1",
    "@types/jasmine": "2.5.45",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.0.4",
    "tslint": "~5.3.2",
    "typescript": "~2.3.3"
  }
}

I don't know where to set node version in an angular project.

A: You are seeing this error because the version of Node used by your Codeship build server is too old.
As per your error message it is currently using version v0.10.48.
You need to update the Node Version as part of the CodeShip deployment.
Assuming you are using a custom script, you need the following line to it.
#Update node to version 6.11.0
nvm install 6.11.0

Note that you need Node 4.1 or later for the Angular CLI.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Appium Inspector Specify either app or appTopLevelWindow to create a session {
  "platformName": "windows",
  "appium:automationName": "windows",
  "appium:appTopLevelWindow": "2f0c10"
}

This doesn't work with described error. But the same works on C#
I don't have app package or Id, only location of exe and this appTopLevelWindow.
I would like to attach the session with inspector. Can anybody help?
WinAppDriver log:
POST /session HTTP/1.1
Accept: application/json
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US
Connection: keep-alive
Content-Length: 406
Content-Type: application/json
Host: 127.0.0.1:4723
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) appium-inspector/2022.2.1 Chrome/91.0.4472.164 Electron/13.6.3 Safari/537.36

{"capabilities":{"alwaysMatch":{"platformName":"windows","appium:automationName":"windows","appium:appTopLevelWindow":"2f0c10","appium:newCommandTimeout":3600,"appium:connectHardwareKeyboard":true},"firstMatch":[{}]},"desiredCapabilities":{"platformName":"windows","appium:automationName":"windows","appium:appTopLevelWindow":"2f0c10","appium:newCommandTimeout":3600,"appium:connectHardwareKeyboard":true}}
HTTP/1.1 400 Bad Request
Content-Length: 141
Content-Type: application/json

{"status":100,"value":{"error":"invalid argument","message":"Bad capabilities. Specify either app or appTopLevelWindow to create a session"}}

A: It is working fine with the following dependency version:

io.appium : 7.3.0
selenium-java: 3.141.0


text:
Q: VBA Error 'Subscript out of Range' I am trying to create a copy of a large macro enabled (xlsm) file in xlsx format.
Sub Button1_Click()

    Dim wb As Workbook

    Set wb = Workbooks.Open("C:\original.xlsm")

    Dim mySheetList() As String
    ReDim mySheetList(0 To (ThisWorkbook.Sheets.Count) - 1)
    Dim a As Integer
    a = 0

    For Each ws In ActiveWorkbook.Worksheets
        mySheetList(a) = ws.Name
        a = a + 1
    Next ws

    'actually save
    Worksheets(mySheetList).Copy
    ActiveWorkbook.SaveAs Filename:="ORIGINAL_COPY.xlsx" 'default ext
    wb.Close

End Sub

I am getting subscript out of range error at following line:
mySheetList(a) = ws.Name

A: You are sizing the array with ThisWorkbook.Sheets but the loop use ActiveWorkbook.Worksheets. You need the same reference to avoid issues when multiple workbooks are opened.

A: You're using 4 different references to workbooks:
wb, ThisWorkbook and ActiveWorkbook are not necessarily the same thing. Furthermore, when you use Worksheets without prefixing it with a workbook reference, you're implicitly referencing the Activeworkbook. And, when you use Worksheets.Copy without any arguments, you're implictly creating a new workbook.
Currently, if ThisWorkbook has fewer sheets than original.xlsm, then your array will not be large enough to accommodate indexes larger than the count of sheets in ThisWorkbook. That is what is causing your out of bounds error.
I've adjusted the code. This will open the XLSM, copy the sheets, save the new XLSX workbook, and close the original XLSM, leaving the new XLSX workbook open.
Sub Button1_Click()

    Dim wbOriginal As Workbook
    Dim wbOutput As Workbook

    Set wbOriginal = Workbooks.Open("C:\original.xlsm")

    Dim mySheetList() As String
    ReDim mySheetList(0 To (wbOriginal.Sheets.Count) - 1)
    Dim a As Integer
    a = 0

    For Each ws In wbOriginal.Worksheets
        mySheetList(a) = ws.Name
        a = a + 1
    Next ws

    'Unfortunately, Worksheets.Copy isn't a function, so it doesn't
    'return the workbook that it creates, so we have to execute the
    'copy, then find the activeworkbook
    Worksheets(mySheetList).Copy

    Set wbOutput = ActiveWorkbook
    'actually save
    wbOutput.SaveAs Filename:="ORIGINAL_COPY.xlsx" 'default ext
    wbOriginal.Close

End Sub

A: Why bother with all that looping?
Sub MM()

    Dim sourceWB As Excel.Workbook

    Set sourceWB = Workbooks.Open("C:\Original.xlsm")
    sourceWB.SaveAs "C:\ORIGINAL_COPY.xlsx", FileFormat:=xlOpenXMLWorkook
    sourceWB.Close False '// Optional

End Sub

The .SaveAs() method would be far more effective.

As mentioned in other answers, your issue seems to be with wb, ActiveWorkbook and ThisWorkbook being used interchangeably when they are actually different things.

*

*wb is a workbook object that has been set to "C:\original.xlsm". It will always refer to that workbook unless you close the workbook, empty the object, or assign a new object to it.

*ActiveWorkbook refers to the workbook that is currently active in Excel's forefront window. (i.e. The workbook you can see on your screen)

*ThisWorkbook refers to the workbook in which the currently executing code belongs to. To quickly explain the difference:

Workbook A is the only workbook open, and has some code in to open another workbook (let's call it Workbook B).
At the moment, Workbook A is the ActiveWorkbook.
The code in workbook A starts running, workbook A is now the ActiveWorkbook and ThisWorkbook (because the running codes resides in this workbook)
The code opens Workbook B, which naturally opens in the forefront of Excel. Now Workbook B is the ActiveWorkbook and Workbook A is still the ThisWorkbook

Hopefully that clears it up a bit for you...


text:
Q: Update a table when join with other table using Case in Postgresql
I have 2 tables wherein I need the result as follows :
 If the country name is 'United States' then the region should be hardcoded as 'Mexico' & if the country name is 'Taiwan' then the region should be hardcoded as 'China' and for the rest it should be joined with the other table.
I have tried this query in Postgresql:
CASE
    WHEN test.hypno.country_name hp RETURN 'United States'
        THEN UPDATE test.expected_details ed SET ed.place = 'Mexico'
    ELSE UPDATE test.expected_details ed
         SET ed.place = hp.area_region
         WHERE ed.WORK = hp.country_name
END

How do I include another hardcode case for country 'Taiwan'? Also, my query doesn't seem to be working in Postgresql.

A: I cant do the full query because you miss the schema, not sure if you alias hp = hypno or what field join both tables. But you want something like this
How to do an update + join in PostgreSQL?
UPDATE test.expected_details ed
SET ed.place = CASE WHEN hp.country_name = 'United States' THEN 'Mexico'
                    WHEN hp.country_name = 'Taiwan' THEN 'China'
                    ELSE hp.area_region
               END
FROM test.hypno hp
WHERE ed.work = hp.country_name


text:
Q: Cross including the same table relations in EF Code Throws an error Multiplicity constraint violated I have cross relations with the same table, in 3rd object.
When I try to insert new object, got an error :

Multiplicity constraint violated. The role
  'OrgOwners_Organisation_Target' of the relationship
  'GBankDataSource.OrgOwners_Organisation' has multiplicity 1 or 0..1.

I've tried to annotate [ForeignKey("...")] in any of the classes, but nothing happend. EF allways choose one field (OrgRefID in this sample) and use it or both relations, while OrgID are not used.
public class OrganisationInfo
{
    [Key]
    public int OrgID { get; set; }
...
    public virtual List<OrgOwners> OrgOwners { get; set; } // object that throws error

}

public class OrgOwners
{
    [Key]
    public int OrgOwnerID { get; set; }

    public int OrgID { get; set; } //Suppose to be a ForeignKey for (OrganisationInfo OrgOwners List)
    public int? OrgRefID { get; set; }
...
    [ForeignKey("OrgRefID")]
    public virtual OrganisationInfo Organisation { get; set; } //(Suppose to use OrgRefID as ForeignKey)

}

When I add a record to OrgOwners without Organisation  ( Organisation =null) - it is OK. But when I do
var first = new OrganisationInfo(); //First organisation DB.OrganisationInfoes.Add(first);
var nextOrg = new OrganisationInfo(); //second organisation
first.OrgOwners = new list();
var Owner = new OrgOwners(); Owner.Organsiation = nextOrg;
first.OrgOwners.Add(Owner); // Add Owner with the second organisation to the First one.
I got an error.

Multiplicity constraint violated.

OrgOwner.Organisation - is NOT the same OrganisationInfo as in root of OrgOwners list. It must be different OrganisationInfo items, related to OrgRefID ForeignKey.

A: It's because EF by default automatically "pairs" the navigation properties where possible to form a relationship. In your case, it pairs OrganizationInfo.OrgOwners collection navigation property with OrgOwners.Organization reference navigation property, hence takes and uses the associated with it OrgRefID FK.
One way to resolve the issue is to add a second reference navigation property to OrgOwners and associate it with the OrgID property via ForeignKey attribute and OrganizationInfo.OrgOwners collection navigation property via InverseProperty attribute:
public int OrgID { get; set; } //Suppose to be a ForeignKey for (OrganisationInfo OrgOwners List)

[ForeignKey("OrgID")]
[InverseProperty("OrgOwners")]
public virtual OrganisationInfo OwnerOrganization { get; set; }

To do that without changing the entity model, you should configure the relationship via fluent API:
modelBuilder.Entity<OrganisationInfo>()
    .HasMany(e => e.OrgOwners)
    .WithRequired() // no inverse navigation property
    .HasForeignKey(e => e.OrgID); // <--

A: Full worked example:
public class OrganisationInfo
{
    [Key]
    public int OrgID { get; set; }
    public virtual List<OrgOwners> OrgOwners { get; set; }

}

public class OrgOwners
{
    [Key]
    public int OrgOwnerID { get; set; }
    public int OrgID { get; set; }
    public int? OrgRefID { get; set; }

    [ForeignKey("OrgRefID")]
    public virtual OrganisationInfo Organisation { get; set; }

}

modelBuilder.Entity<OrganisationInfo>()
                    .HasMany(e => e.OrgOwners)
                    .WithRequired()
                    .HasForeignKey(e => e.OrgID);


text:
Q: Ubuntu desktop not working after adjusting effects on compiz config manager I unable to disable the desktop or anything, but when I reboot, all I can see is the mouse and a dialog appear saying that compiz has crashed. The terminal (Ctrl+Alt+t) doesn't work, and neither control alternative delete to log out works. What can I do to restore everything?

A: Try this:

*

*Press Control + Alt + F1 and log in.

*In terminal run unity --reset.


text:
Q: error at root position 1, line 1 I am using the following snippet to get the xml content but get the above mentioned error. In a webbrowser like chrome I get a nice formatted result. Other requests on the same site go well but this one gives me an error.
   Dim sWebUrlXml As String = "http://publications.elia.be/Publications/Publications/InternetImbalance.v1.svc/GetImbalanceMeasuresByTime"
   Dim reader As XmlTextReader = New XmlTextReader(sWebUrlXml)
        Do While (reader.Read())
....
....

http://publications.elia.be/Publications/Publications/InternetImbalance.v1.svc/GetImbalanceMeasuresByTime


text:
Q: Is there a way to store ArrayList information when "newing" up a class without it emptying out the ArrayList to avoid information changing? In this example, I have a Database class that takes in new Question("Genre", "Question", "ArrayListOfStrings choices, "Answer", "Fun Fact").
What I want is for when I add the choices to a specific question to stay those choices. But when I remove the choices after adding a new Question, the choices switches to the ones that have been added. Is there any way to bypass this?
public static ArrayList<Question> allInitialQuestions(ArrayList<Question> q)
    {

    ArrayList<String> c = new ArrayList<String>();

    // These choices would be added to the choices ArrayList
    c.add("Pacific");
    c.add("Atlantic");
    c.add("Arctic");
    c.add("Indian");

    // Then what is stored in c at this moment should stay there
    // This question should have the aquatic choices
    q.add(new Question("Geography","Which ocean is the largest?", c, "Pacific", "The Pacific Ocean stretches to an astonishing 63.8 million square miles!"));

    // However, when I remove everything on the ArrayList,
    // it automatically updates the other ArrayList to display
    // the ones that have been added to it.
    c.removeAll(c);

    c.add("192");
    c.add("195");
    c.add("193");
    c.add("197");

    q.add(new Question("Geography", "How many countries are in the world?", c, "195", "Africa has the most countries of any continent with 54."));

    c.removeAll(c);

    c.add("Mississippi");
    c.add("Nile");
    c.add("Congo");
    c.add("Amazon");

    q.add(new Question("Geography", "What is the name of the longest river in the world?", c, "Nile","Explorer John Hanning Speke discovered the source of the Nile on August 3rd, 1858."));

    c.removeAll(c);

    c.add("United States");
    c.add("China");
    c.add("Japan");
    c.add("India");

    q.add(new Question("Geography","Which country has the largest population?" ,c, "China", "Shanghai is the most populated city in China with a population of 24,870,895."));

    c.removeAll(c);

    c.add("Mars");
    c.add("Mercury");
    c.add("Venus");
    c.add("Jupiter");

    q.add(new Question("Geography","Which planet is closest to Earth?",c,"Venus","Even though Venus is the closest, the planet it still ~38 million miles from Earth!"));

    c.removeAll(c);

    c.add("Sega");
    c.add("Nintendo");
    c.add("Sony");
    c.add("Atari");

    q.add(new Question("Video Games", "Which company created the famous plumber Mario?", c, "Nintendo", "Nintendo created Mario in 1981 for the arcade game Donkey Kong."));

    c.removeAll(c);

    c.add("Sonic");
    c.add("Tales");
    c.add("Knuckles");
    c.add("Amy");

    q.add(new Question("Video Games", "What is the name of the famous video character who is a blue hedgehog?",c,"Sonic", "In some official concept art, Sonic was originally meant to be a rabbit."));

    c.removeAll(c);

    c.add("Wii Sports");
    c.add("Grand Theft Auto V");
    c.add("Tetris");
    c.add("Minecraft");

    q.add(new Question("Video Games","As of 2022, which of the following is the best selling video game of all time?",c,"Minecraft","As of 2022, Minecraft has sold over 238 million units."));

    return q;
}

A: Rather than removing all entries, instantiate a new List
c = new ArrayList<String>();


text:
Q: Терминология. Synchronization 1)

In designing applications, it's important to differentiate between
  requirements imposed on bounded code and unbounded code. If your class
  makes undue requirements on unbounded code, that's usually a sign that
  encapsulation is out the window.

В разрабатываемых приложениях важно различать требования, наложенные на статический(ограниченный) и динамический(неограниченный) код. Если ваш класс не подходит по требованиям к динамическому(неограниченному) коду, то есть признак что инкапсуляция вышла из окна.
Что такое "bounded code and unbounded code" и как понять последнее предложение?
2)А это что
Caller-provided locking и caller-ensured locking?
Synchronisation


text:
Q: Swift floating-point number and cpu architecture I search a lot about CGFloat, Float and Double in swift, but still not fully understand:

*

*From Apple doc: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

Double represents a 64-bit floating-point number.
Float represents a 32-bit floating-point number.

So in 32-bit CPU architecture, i personally understand that only float is the max accuracy available in swift and there will be no Double, isn't? Or they have to do something like sudo-Double? Since Apple recommends using Double over Float.

*For CGFloat: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Cocoa64BitGuide/64BitChangesCocoa/64BitChangesCocoa.html#//apple_ref/doc/uid/TP40004247-CH4-SW9

Floating point quantities in the Core Graphics framework (Quartz), which are float on 32-bit architectures, are being expanded to double to provide a wider range and accuracy for graphical quantities. Core Graphics declares a new type for floating-point quantities, CGFloat, and declares it conditionally for both 32-bit and 64-bit

It means that Apple want to take advantage of CPU architecture: 32 or 64 bit to maximize accuracy?


text:
Q: SugarCRM - How to add "More Info" icon that displays module "Description" field on mouseover This is for SugarCRM v6.3
I need to add a "More Info" icon to the History subpanel, which, when moused-over, displays the relevant module's Description field, similar to how the More Info icon works in the Accounts ListView.
For starters I added new "History/metadata" folders to custom/modules/ and copied the subpaneldefs.php file from the core History/metadata folder.
In the subpaneldefs file, at the end of each of the module's column definitions, I added this as a test:
array ( 'customCode' => '', ),

That didn't seem to affect anything at all.
Not sure if it was just that I needed more than an image for the column to show, I then tried adding all of the code I thought was supposed to go there:
array (
'name' => 'nothing',
'module' => 'Notes',
'related_fields' => array ('id'),
'customCode' => ''

),
This is, as you can see, intended for the Notes in the History subpanel, and I changed it accordingly for each of the other modules' column definitions in the subpaneldefs.php file. I modeled the code after some custom code I found that someone else here at work did for a dashlet, which shows details when an account name is moused over.
Unfortunately, that didn't work, either.
How do I accomplish this?

A: The only way to do this is by defining a new SugarWidget field for the field in question. Here's a good guide I found for it:
http://www.mediaart.lt/programming/sugarcrm-adding-custom-field-in-subpanel/


text:
Q: WCF RIA Services SP1, Entity Framework 4, updating only changed columns I use LinqToEntitiesDomainService class to update database with Silverlight 4 client.
There's AttachAsModified extended method for entity framework ObjectContext which allows you supply original entity property values:
Order original = this.ChangeSet.GetOriginal(currentOrder);
this.ObjectContext.Orders.AttachAsModified(currentOrder, original);

By default, WCF RIA Services doesn't send original values to the server, so one needs to
apply [RoundtripOriginal()] attribute to his/her entity.
However, even if I supply original values, SQL generated by Entity framework updates all columns, not only changed ones. Since AttachAsModified() method isn't native ObjectContext class method (it's extended method defined in ObjectContextExtensions class), I tried to use
ApplyOriginalValues method which is defined in ObjectSet class. No change.
It seems entity framework 4.1, which was released recently may have solution (not sure). How about entity framework 4? Is it possible EF to generate sql to update only changed columns?

A: AttachAsModified will mark the entity as modified.  Subsequently (quote from MSDN):

When you change the EntityState of an
  entity object entry to Modified, all
  of the properties of the object are
  marked as modified, regardless of the
  current or original values.

Caveat; I haven't done this but, it should work.
Instead of using AttachAsModified, mark the entity as UnChanged using the ChangeState method.
Then use the SetModifiedProperty method on the properties that have changed to have them included in an update.
EDIT:  If you want a way to find which properties have changed, there are a couple of articles out there explaining how to do so using the ObjectStateManager such as this one

A: I did ask similar question on MSDN forums, and it is confirmed that WCF RIA Services will change all columns. Alternative is,
You can fetch a copy from database, compare and mark SetModifiedProperty manually by using reflection.
// change state of entity as Unmodified/Unchanged...
original.EntityState = Unchanged;

// this is copy form database...
// Use different context
MyOrderContext context = new MyOrderContext();
Order dbOriginal = context.Orders.First( x=>x.OrderID == original.OrderID);

foreach(PropertyInfo p in copy.GetTypes().GetProperties()){
   Object originalValue = p.GetValue(dbOriginal);
   Object newValue = p.GetValue(original);
   if(originalValue!=null && newValue!=null
       && originalValue.Equals(newValue)){
       continue;
   }
   // resetting this will
   // make entity's only current
   // property as changed
   p.SetValue(original,originalValue);
   p.SetValue(original,newValue);
}

You may have to change code as per situation, check if property is readonly or not and this is just a sample but it will help you to build upon it.

A: I managed to do this by first attaching the object and then calling ApplyOriginalValues on the EntitySet. You'll need an object with the original values to do this. This method can also be used to prevent a column from being updated, e.g. for row level security.
NOTE: This unfortunately does not work without retrieving the original entity from the database first. Otherwise only properties that are set to its default value are excluded from the update...


text:
Q: How to efficiently model this simple data structure? catId(INT)  |  userId(INT)  | catName(VARCHAR)
   0               1             Cat1
   1               1             Cat2
   2               2             U2Cat1
   3               2             U2Cat2

I want to most efficiently access all the categories of a single userId (say SELECT * WHERE userId = 1)
So, imagine say, a 100 000 users, each with about 10 categories. What would be the most efficient way of modeling this.
"How to make the DB cluster this efficiently,and feel free to talk about how it would look in memory if you understand it at least on a basic level (I'm a programmer)."
Thank you.
Edit:
Here is some help to understand the question more easily:
Which of these data structures would a DB store the above table in by default, would it choose automatically between one of these in the link bellow, or do I have ways or have to force it.
http://en.wikipedia.org/wiki/Database_storage_structures
I guess I would be thankful if you happen to know of a tutorial that explains how rows and columns relate to data structures in the DB, that would help me picture it (and the correct solution, hopefully).
Thank you.

A: If you simply want to increase the efficiency of a query, the CREATE INDEX command may interest you: http://dev.mysql.com/doc/refman/5.0/en/create-index.html
There are different index types and I believe the most common are B-Tree and hash indices. If you are interested in how the DBMS stores data then reading up on these topics may interest you.


text:
Q: still have error no current navigation node even after using navigation 2.2.1 I have tried to read this but it doesn't solve my issue
so I navigate to next destination using this code
 val nextDirection = CreateEventNameFragmentDirections.actionToCreateEventType(userKM, newEvent)
 findNavController().navigate(nextDirection)

but it crash after I rotate the device with error

java.lang.IllegalStateException: no current navigation node

i update the gradle using this

implementation 'android.arch.navigation:navigation-fragment-ktx:2.2.1'
implementation 'android.arch.navigation:navigation-ui-ktx:2.2.1'

but it still doesn't work , it still crash. what should I do ? here is my MainActivity
class MainActivity : AppCompatActivity(), NavController.OnDestinationChangedListener {

    private lateinit var navController : NavController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Initial Setup views
        navController = Navigation.findNavController(this,R.id.nav_host_fragment)

        setupBottomNavMenu()
        setupActionBar()

        // Add Listeners
        navController.addOnDestinationChangedListener(this)

    }

    private fun setupBottomNavMenu() {
        bottom_nav.setupWithNavController(navController)
    }

    private fun setupActionBar() {

        generalToolbar.title = ""
        searchToolbar.title = ""
        searchWithBackButtonToolbar.title = ""

        // set up top hierarchy destination
        val appBarConfiguration = AppBarConfiguration(setOf(
            R.id.destination_home,
            R.id.destination_search,
            R.id.destination_user_control,
            R.id.destination_create_event,
            R.id.destination_inbox,
            R.id.destination_verified_user_control)
        )

        if (include_toolbar_general.visibility == View.VISIBLE) {
            setSupportActionBar(generalToolbar)
            generalToolbar.setupWithNavController(navController,appBarConfiguration)
        } else if (include_toolbar_search.visibility == View.VISIBLE) {
            setSupportActionBar(searchToolbar)
            searchToolbar.setupWithNavController(navController,appBarConfiguration)
        } else if (include_toolbar_search_with_back_button.visibility == View.VISIBLE) {
            setSupportActionBar(searchWithBackButtonToolbar)
            searchWithBackButtonToolbar.setupWithNavController(navController,appBarConfiguration)
        }

    }

    override fun onDestinationChanged(controller: NavController, destination: NavDestination, arguments: Bundle?) {

        setUpShadowInToolbar(destination)
        setToolbarVisibility(destination)
        setBottomNavigationViewVisibility(destination)

    }

    private fun setUpShadowInToolbar(destination: NavDestination) {

        // set up shadow below the toolbar
        if (destination.id == R.id.destination_search || destination.id == R.id.destination_keyword_result) {
            searchToolbar.elevation = 0.0f
        } else {
            generalToolbar.elevation = 4.0f
        }

    }

    private fun setToolbarVisibility(destination: NavDestination) {

        if (destination.id == R.id.destination_authentication ||
            destination.id == R.id.destination_loginUsingEmail ||
            destination.id == R.id.destination_registerUsingEmail ||
            destination.id == R.id.destination_change_password ||
            destination.id == R.id.destination_create_event_finished_info ||
            destination.id == R.id.destination_photo_view ||
            destination.id == R.id.destination_on_boarding_1 ||
            destination.id == R.id.destination_on_boarding_2 ||
            destination.id == R.id.destination_on_boarding_3 ||
            destination.id == R.id.destination_report_event_confirmation ||
            destination.id == R.id.destination_user_control ||
            destination.id == R.id.destination_verified_user_control

        ) {

            include_toolbar_general.visibility = View.GONE
            include_toolbar_search.visibility = View.GONE
            include_toolbar_search_with_back_button.visibility = View.GONE

        } else if (

            destination.id == R.id.destination_search

        ) {

            include_toolbar_general.visibility = View.GONE
            include_toolbar_search.visibility = View.VISIBLE
            include_toolbar_search_with_back_button.visibility = View.GONE

        } else if (

            destination.id == R.id.destination_keyword_result

        ) {

            include_toolbar_general.visibility = View.GONE
            include_toolbar_search.visibility = View.GONE
            include_toolbar_search_with_back_button.visibility = View.VISIBLE

        } else {

            include_toolbar_general.visibility = View.VISIBLE
            include_toolbar_search.visibility = View.GONE
            include_toolbar_search_with_back_button.visibility = View.GONE

        }

        setupActionBar()

    }

    private fun setBottomNavigationViewVisibility(destination: NavDestination) {

        if (destination.id == R.id.destination_authentication ||
            destination.id == R.id.destination_loginUsingEmail ||
            destination.id == R.id.destination_registerUsingEmail ||
            destination.id == R.id.destination_choose_user_location ||
            destination.id == R.id.destination_change_password ||
            destination.id == R.id.destination_create_event_finished_info ||
            destination.id == R.id.destination_photo_view ||
            destination.id == R.id.destination_on_boarding_1 ||
            destination.id == R.id.destination_on_boarding_2 ||
            destination.id == R.id.destination_on_boarding_3 ||
            destination.id == R.id.destination_report_event_confirmation
        ) {

            bottomNavigationView.visibility = View.GONE

        } else if (

            destination.id == R.id.destination_home ||
            destination.id == R.id.destination_search ||
            destination.id == R.id.destination_create_event ||
            destination.id == R.id.destination_user_control ||
            destination.id == R.id.destination_verified_user_control ||
            destination.id == R.id.destination_inbox

        ) {

            bottomNavigationView.visibility = View.VISIBLE

        } else {

            bottomNavigationView.visibility = View.GONE

        }

    }

    fun setBottomNavigationMenu() {

        // this method will be called in home, loginUsingEmail and Authentication fragment

        val user = sharedPrefManager.loadUserData() ?: return

        if (user.verified && bottomNavigationView.menu.findItem(R.id.destination_verified_user_control) == null) {
            // set different bottom navigation menu for verified user, if bottom_navigation_verified_menu have NOT been inflated yet
            bottomNavigationView.visibility = View.INVISIBLE
            bottomNavigationView.menu.clear()
            bottomNavigationView.inflateMenu(R.menu.bottom_navigation_verified_menu)

        } else if (!user.verified && bottomNavigationView.menu.findItem(R.id.destination_verified_user_control) != null) {

            bottomNavigationView.visibility = View.INVISIBLE
            bottomNavigationView.menu.clear()
            bottomNavigationView.inflateMenu(R.menu.bottom_navigation_menu)
        }

        // when trying to clear the menu and then inflate with the new one above
        // it will create weird menu item transition
        // thats why we hide the bottom navigation view and then show it again by using delay below

        Handler().postDelayed({
            bottomNavigationView.visibility = View.VISIBLE
        }, 200)

    }

}

A: I finally can solve it by using this
implementation "androidx.navigation:navigation-fragment-ktx:2.3.0-alpha04"
implementation "androidx.navigation:navigation-ui-ktx:2.3.0-alpha04"

A: I was extending my fragment with NavHostFragment changed it to Fragment and it started working fine

A: This is an incompatible androix plugin problem. Slav rightly mentioned if you are using useAndroidX=true then, pls use version 2.2.0 onwards
// Navigation
    implementation "androidx.navigation:navigation-fragment-ktx:2.3.0"
    implementation "androidx.navigation:navigation-ui-ktx:2.3.0"


text:
Q: Spectrum of an integral operator. For any $f\in C([0,1],\mathbb{R})$ set
$$
Tf(x) = \int_0^1 [\min\{x,y\}\cdot f(y)]dy.
$$
I have just proved that $T$ is a compact operator from  $C([0,1],\mathbb{R})$ into itself. I would like to know how to calculate his spectrum. (Since $T$ is compact I know that his spectrum is made of only eigenvalues.) Thank you for your help.

A: here's my solution:
The function $\min \{ x, y \}$ can be written as follows:
$$
\min\{x, y \}=
\begin{cases}
 & y, \mbox{ if } 0 \le y \le x \\
               & x, \mbox{ if } x \le y \le 1
\end{cases}
$$
so we found the form for $T$:
$$
Tf(x) = \int_0^x yf(y) \, dy + x \int_x^1 f(y) \, dy.
$$
Now let $Tf = \lambda f, \lambda \ne 0$. So we have:
$$
\lambda f(x) = \int_0^x yf(y) \, dy + x \int_x^1 f(y) \, dy.
$$
 Observe that $f(0)=0$. Now derive once and obtain:
$$
\lambda f'(x) = \int_x^1 f(y) \, dy,
$$
and here we found $ \lambda f'(0) = \int_0^1 f(y) \, dy $. Now derive another time and obtain the condition:
$$
\lambda f''(x) = - f(x),
$$
so the eigenvector solves the differential equations:
\begin{cases}
& \lambda f'' + f = 0, \\
& f(0) = 0, \\
& \lambda f'(0) =  \int_0^1 f(y) \, dy.
\end{cases}
Now we only had to solve the system; I don't write the computations right now.
However if my calcula are corrects, putting for every $k \in \mathbb{N}$, $k \ne 0$
$$
f_k (x) = \sin \left ( \left (\frac{3 \pi}{2} + 2k \pi \right )x \right )
$$
We find that $f_k$ if an eigenvector for the eigenvalue
$$
\lambda_k = \frac{4}{\pi^2 (3+ 4k)^2}.
$$
I hope they're correct!
Saluti da Pisa, il DM


text:
Q: Pass value from jquery to rails form's hidden_field I have jquery which renders a value inside an html element

Which is nothing but a number/integer. Now I want to pass value rendere inside the above code into my form's hidden_field.
How do I do it?
Thanks
UPDATE:  I need to pass the value inside the rails form hidden field, something like <%= f.hidden_field :data, :value => ValueGoesHere %>

A: Assume
<input type="hidden" id="hiddenObject"/>

then
you need below code
 $("#hiddenObject").val($("#serialsNewFormatted").html());


text:
Q: PHP: How to get $ to print using echo I'm very new to PHP and having a hard time finding this answer as $ denotes a variable in PHP.
I'm trying to echo a total for items, such as:
echo "Your total is ${$total}";

The problems is the $ in front causes it to do nothing. I tried doing '$' but it prints the
' ' around the $. How do I get the $ to print in front of the variable?

A: Just use single quotes.
echo 'Your total is $' . $total;
Check this article for more information regarding the differences between single and double quotes in PHP.
http://v1.jeroenmulder.com/weblog/2005/04/php_single_and_double_quotes.php

A: If you use double quotes ("), you have to escape the $ character :
echo "Your total is \${$total}";

A: Last but not least:
printf('Your total is $%.2f', $total);

A: You need to escape the dollar sign: echo "\$";.

A: echo "Your total is $" . $total;

You don't have to use variable parsing in every possible situation. Very often it is much easier (both to write and to understand) when simply writing as a string concatenation..


text:
Q: How do you express the product of three matrices as a weighted sum of outer products? How do you express the matrix ABC as the weighted sum of outer products of vectors extracted from A and C and with weights coming from matrix B?
I'm not sure how to approach this problem. I tried the outer products of the columns of A with the rows of C, with the entries $B_{ij}$ of the middle matrix serving as the weights. Since B has as many columns as C has rows and as many rows as A has columns, we would have as many outer products in our sum as B has entries. But it didn't work out.

A: Let us consider the $2 \times 2$ case for the sake of simplicity:
$$\begin{pmatrix}a&b\\c&d\end{pmatrix}\begin{pmatrix}t&u\\v&w\end{pmatrix}\begin{pmatrix}e&f\\g&h\end{pmatrix}=t\begin{pmatrix}a\\c\end{pmatrix}\begin{pmatrix}e&f\end{pmatrix}+u\begin{pmatrix}a\\c\end{pmatrix}\begin{pmatrix}g&h\end{pmatrix}+...$$
Indeed, if you denote by $C_1,C_2$ the columns of the first matrix and by $R_1,R_2$ the rows of the 3rd matrix, you just do block products (all with compatible dimensions) like this:
$$\begin{pmatrix}C_1&C_2\end{pmatrix}\begin{pmatrix}t&u\\v&w\end{pmatrix}\begin{pmatrix}R_1\\R_2 \end{pmatrix}=\begin{pmatrix}(C_1t+C_2v)&(C_1u+C_2w)\end{pmatrix}\begin{pmatrix}R_1\\R_2\end{pmatrix}$$
$$=(C_1t+C_2v)R_1+(C_1u+C_2w)R_2=tC_1R_1+vC_2R_1+uC_1R_2+wC_2R_2$$
This process can be extended to any dimensions, not only to $n \times n$ square matrices but more generally to products of rectangular matrices as long as their dimensions are compatible, i.e., with dimensions:
$$(m \times n) \times (n \times p) \times (p \times q)$$
A similar question asked in the other direction.


text:
Q: Java Regular Expression Two Question marks (??) I know that /? means the / is optional. so "toys?" will match both toy and toys. My understanding is that if I make it lazy and use "toys??" I will match both toy and toys and always return toy. So, a quick test:
private final static Pattern TEST_PATTERN = Pattern.compile("toys??", Pattern.CASE_INSENSITIVE);
public static void main(String[] args) {
    for(String arg : args) {
        Matcher m = TEST_PATTERN.matcher(arg);
        System.out.print("Arg: " + arg);
        boolean b = false;
        while (m.find()) {
            System.out.print(" {");
            for (int i=0; i<=m.groupCount(); ++i) {
                System.out.print("[" + m.group(i) + "]");
            }
            System.out.print("}");
        }
        System.out.println();
    }
}

Yep, it looks like it works as expected
java -cp .. regextest.RegExTest toy toys
Arg: toy {[toy]}
Arg: toys {[toy]}

Now, change the regular expression to "toys??2" and it still matches toys2 and toy2. In both cases, it returns the entire string without the s removed. Is there any functional difference between searching for "toys?2" and "toys??2".
The reason I am asking is because I found an example like the following:
private final static Pattern TEST_PATTERN = Pattern.compile("</??tag(\\s+?.*?)??>", Pattern.CASE_INSENSITIVE);

and although I see no apparent reason for using ?? rather than ?, I thought that perhaps the original author (who is not known to me) might know something that I don't, I expect the later.

A: ?? is lazy while ? is greedy.
Given (pattern)??, it will first test for empty string, then if the rest of the pattern can't match, it will test for pattern.
In contrast, (pattern)? will test for pattern first, then it will test for empty string on backtrack.

Now, change the regular expression to "toys??2" and it still matches toys2 and toy2. In both cases, it returns the entire string without the s removed. Is there any functional difference between searching for "toys?2" and "toys??2".

The difference is in the order of searching:

*

*"toys?2" searches for toys2, then toy2

*"toys??2" searches for toy2, then toys2
But for the case of these 2 patterns, the result will be the same regardless of the input string, since the sequel 2 (after s? or s??) must be matched.

As for the pattern you found:
Pattern.compile("</??tag(\\s+?.*?)??>", Pattern.CASE_INSENSITIVE)

Both ?? can be changed to ? without affecting the result:

*

*/ and t (in tag) are mutually exclusive. You either match one or the other.

*> and \s are also mutually exclusive. The at least 1 in \s+? is important to this conclusion: the result might be different otherwise.

This is probably micro-optimization from the author. He probably thinks that the open tag must be there, while the closing tag might be forgotten, and that open/close tags without attributes/random spaces appears more often than those with some.
By the way, the engine might run into some expensive backtracking attempt due to \\s+?.*? when the input has <tag followed by lots of spaces without > anywhere near.


text:
Q: How do you populate Django models in an SQLite database in an Asynchronous way? I have a model that I would like to populate with csv data, I have followed a few tutorials on this and am now trying to do it on my own. This is the code that I have so far;
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings')

import django
django.setup()

#Import models
from app_name.models import Instance

# Third Party Imports
import pandas as pd

# Pull csv data into script
file  = 'path/to/file/filename.csv'
collected_data = pd.read_csv(file,index_col='Timestamp')
# this is a dataframe with three columns and a datetime index

for timestamp, row in collected_data.iterrows():
    info1 = row[0]
    info2 = row[1]
    info3 = row[2]

    inst = Instance.objects.get_or_create(timestamp = timestamp,
            info1 = info1,
            info2 = info2,
            info3 = info3)[0]

I am getting the following error, which I don't really understand, as I am quite new to Django.
SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
Let me know if there is any more information needed for a MCVE

A: Try to put your script into management command. Then you would have no problem with running only the ORM in standalone.
The example you can find here:
https://gist.github.com/kharandziuk/08de1d24845b05dfaa6acfbfda3cd28e
There is a long answer here: stackoverflow.com/questions/937742/use-django-orm-as-standalone


text:
Q: Strange File-Server I/O Spikes - What Is Causing This? I am currently having a problem with a small Linux server that is providing file-sharing services to four Windows 7 32-bit clients.  The server is an AMD PhenomX3 with two Western Digital 10EADS (1TB) drives, attached to a Gigabyte GA-MA770T-UD3 mainboard and running Ubuntu Server 10.04.1 LTS.
The client machines are taking an extremely long time to access/transfer data on the file server.  Applications often become non-responsive while trying to open files located remotely, or one program attempting to open a file but having to wait will prevent other software from accessing network resources at all.  Other examples include one image taking 20 seconds or more to open, and in one instance a user waited 110 seconds for Microsoft Word 2007 to save a document.
I had initially thought the problem was network-related, but this appears not to be the case.  All cables and switches have been tested (one cable was replaced) for verification.  This was additionally confirmed when closing down all client machines and rebooting the server resulted in the hard-drive light staying on solid during the startup process.  For the first 15 minutes during boot, logon and after logging on (with no client machines attached), the system displayed a load average of 4 or higher.  Symptoms included waiting several minutes for the logon prompt to appear, and then several minutes for the password prompt to appear after typing in a user name.  After logon, it also took upwards of 45 seconds for the 'smartctl' man page to appear after the command 'man smartctl' was issued.  After 15 minutes of this behaviour, the load average dropped to around 0.02 and the machine behaved normally.
I have also considered that the problem is hard-drive-related, however diagnostic programs reveal no drive problems. Western Digital DLG, Spinrite and SMARTUDM show no abnormal characteristics - the drives are in perfect health as far as the hardware is concerned.
I have thus far been completely unable to track down the cause of this problem, so any help is greatly appreciated.
Requested Information:
Output of 'free'
hxxp://pastebin.com/mfsJS8HS (stupid spam filter)
The command 'hdparm -d /dev/sda1' reports: HDIO_GET_DMA failed: Inappropriate ioctl for device (the BIOS is set to AHCI - I probably should have mentioned that).

A: If it wasn't a 'modern' Ubuntu I'd say your hard drive has DMA disabled; check with hdparm. If memory serves me well it should be hdparm -d1 but you might want to check the manual page first.
Perhaps the controller you're using for the disk does not have DMA enabled by default, and it's relying on CPU for I/O?
Another thing could be some concurrency on the hard drive; or no more swap space.

A: It sounds like you've made sure that the physical network infrastructure is sound. Have you ruled out a configuration problem? Some things I would try in your situation:

*

*Make sure that other internal resources are accessible so that I could rule out DNS, firewall and the such. For example see if mounting the share by IP address makes the problem go away.

*Set up a linux machine as a client and see if the problem is reproduced regardless of the OS

A: Answering my own question, it turns out that one of the hard drives in the system was indeed faulty, but as I originally pointed out, none of the usual diagnostic programs would detect the fault.  Eventually, out of frustration, I copied all critical data off the server and placed the two drives into two identical desktop systems I had been working on and attempted to install Linux.  One worked fine, but the other would almost always lock up during formatting of the drive.  Replacing the drive that locked during format solved the problem, but I was still unable to determine the specific fault.  Western Digital replaced the drive regardless.


text:
Q: Having trouble with composition C++ I'm trying to declare a member-object in a class in C++, like so:
class bankAccount
{
public:
  bankAccount(int, int, int, string, int);
private:
  bankBranch homeBranch;
};

bankAccount::bankAccount(int accountNumber, int accountBalance, int homebsbnumber,
string homeaddress, int homepostcode) : homeBranch(homebsbnumber, homeaddress, homepostcode) {}
class bankBranch
{
public:
/** bankBranch(const int& bsbNumber, const string& address, const int& postCode)
{
    this->bsbNumber = bsbNumber;
    this->address = address;
    this->postCode = postCode;
}; **/

bankBranch(int, string, int);
void setPostCode()
{
    cout << "Please type in the postal code of your bankBranch: " << endl;
    cin >> postCode;
}
void setBsbNumber()
{
    cout << "Please type in the BSB Number of your bankBranch: " << endl;
    cin >> bsbNumber;

}
void setAddress()
{
    cout << "Please type in the address of your bankBranch " << endl;
    cin >> address;
}
// Return methods for bsb number, address and post code
int getBsbNumber()
{
    return this->bsbNumber;
}
string getAddress()
{
    return this->address;
}
int getPostCode()
{
    return this->postCode;
}
private:
  int bsbNumber;
  string address;
  int postCode;
};
bankBranch::bankBranch(int bsbnum, string bankaddress, int bankpostcode) {

bsbNumber = bsbnum;
address = bankaddress;
postCode = bankpostcode;

}

I am getting these erros:

*

*sytax error : missing ';' before identifier 'homeBranch'

*missing type specifier - int assumed (confused because it is obviously an object?)

*'bankAccount' : illegal member initialization: 'homebranch' is not a base or member

I have tried many things and cannot seem to fix these errors, could anyone provide me with some insight on how to properly add the member-object bankBranch homeBranch to the class bankAccount? And how to properly use initialization lists.

A: C++ is an (almost) single-pass, top-to-bottom language. The compiler must see the declaration of a thing before it's used. Move the definition of class bankBranch above that of class bankAccount.

A: Just put the definition of bankBranch before your class bankAccount. See a live example here: http://ideone.com/LuMzBt
Don't forget to include string and iostream in you code.

A: It isn't recognising your BankBranch as a data type.
Removing the comments might help you.
And defining the bankbranch class before the other class might also help.
Also, it is good practice to define classes in separate header files, then include them separately in all the files.
Just an advice!


text:
Q: SQL returning info not stored in another table I have two tables Treatment and Prescription.
Treatment contains the patient_no, reason etc.
Prescription contains the Patient_no, drug_code etc.
Want I want to do is return the reason from the treatment table where the patient_ID isnt contained in the prescription table, in other words Returning patients who have been treated who have not been given a prescription.
I have tried this and another numerous combinations and not getting the required results.
Select Treatment.Reason
From Treatment LEFT OUTER JOIN Prescription
ON Treatment.Patient_No = Prescription.Patient_No

Any pointers or directions.

A: You nearly have it correct with a LEFT OUTER JOIN. To find patients with no prescription, look for NULLs in the prescriptions column:
SELECT
   DISTINCT Treatment.Reason
FROM
   Treatment
   LEFT OUTER JOIN Prescription ON Treatment.Patient_No = Prescription.Patient_No
WHERE Prescription.Patient_No IS NULL


text:
Q: The program does not executes after m+=z. Why is this happeing? Consider the code below:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
k = len(a)
i = 0
m = []
while i < k:
      if a[i] < 5:
          z = a[i]
          m += z
          i += 1
      else:
          break

print(m)

When I am trying to execute it, I get:

m += z
TypeError: 'int' object is not iterable

Why is that?

A: m is a list; the += operator for it expects another iterable to add the items from one at a time (so += [1, 2, 3] adds three items, not a single list, to the list), not a single item to add.
x is an int, so this doesn't work. You likely want:
m.append(x)

This would also work:
m += [x]

but using append is clearer (and last I checked, slightly faster).


text:
Q: HAProxy Docker Container is Not able to load balance across my Cockroach DB docker containers using localhost I have a docker compose file that contains my HAProxy container and 3 Cockroach DB (CKDB) containers. All run with network mode host.
I am able to join the CKDB nodes using localhost and their associated ports, but my HAProxy container fails to access the CKDB nodes using "localhost". If I use the IP address of the host machine, it works.
Is this a constraint on HAProxy or could it be something wrong with my configurations?
Here's the HAProxy config file:
global
  maxconn 4096

defaults
    mode                tcp
    timeout connect     10s
    timeout client      1m
    timeout server      1m
    option              clitcpka

frontend ckdb_nodes
    bind *:26257
    option tcplog
    option httpchk GET /health?ready=1
    mode tcp
    use_backend ckdb_nodes

backend ckdb_nodes
    mode tcp
    balance roundrobin
    option ssl-hello-chk
    server cockroach1 localhost:26254 check port 8081
    server cockroach2 localhost:26255 check port 8082
    server cockroach3 localhost:26256 check port 8083

frontend ckdb_admin_ui
    bind *:8080
    option tcplog
    mode tcp
    use_backend ckdb_admin_ui

backend ckdb_admin_ui
    mode tcp
    balance roundrobin
    option ssl-hello-chk
    server cockroach1 localhost:8081 check
    server cockroach2 localhost:8082 check
    server cockroach3 localhost:8083 check

Here is the docker compose file:
services:
  ckdb-e1-haproxy:
    image: ${IMAGE_STAGING_E1_HAPROXY}:${BUILD_VERSION_STATIC}
    ports:
      - ${COCKROACH_E1_HAPROXY_PORT}:${COCKROACH_E1_HAPROXY_PORT}
      - ${COCKROACH_ADMIN_UI_E1_HAPROXY_PORT}:${COCKROACH_ADMIN_UI_E1_HAPROXY_PORT}
    network_mode: "host"
    container_name: ${PROJECT}_ckdb-e1-haproxy
    depends_on:
      - ckdb-e1-node1
      - ckdb-e1-node2
      - ckdb-e1-node3

  ckdb-e1-node1:
    image: cockroachdb/cockroach:${CKDB_VERSION}
    command: start --certs-dir=${CKDB_CONTAINER_HOST_DIR} --port=${STAGING_E1_NODE1_CKDB_APP_PORT} --http-port=${STAGING_E1_NODE1_CKDB_ADMIN_UI_PORT}
    ports:
      - ${STAGING_E1_NODE1_CKDB_APP_PORT}:${STAGING_E1_NODE1_CKDB_APP_PORT}
      - ${STAGING_E1_NODE1_CKDB_ADMIN_UI_PORT}:${STAGING_E1_NODE1_CKDB_ADMIN_UI_PORT}
    volumes:
      - type: bind
        source: ${CKDB_STAGING_E1_CERTS_DIR}
        target: ${CONTAINER_CKDB_CERTS_PATH}
      - type: volume
        source: staging-app-db-data-e1-node1
        target: ${CONTAINER_CKDB_DATA_PATH}
    container_name: ${PROJECT}_ckdb-e1-node1
    network_mode: "host"

  ckdb-e1-node2:
    image: cockroachdb/cockroach:${CKDB_VERSION}
    command: start --certs-dir=${CKDB_CONTAINER_HOST_DIR} --port=${STAGING_E1_NODE2_CKDB_APP_PORT} --http-port=${STAGING_E1_NODE2_CKDB_ADMIN_UI_PORT} --join=localhost:${STAGING_E1_NODE1_CKDB_APP_PORT}
    ports:
      - ${STAGING_E1_NODE2_CKDB_APP_PORT}:${STAGING_E1_NODE2_CKDB_APP_PORT}
      - ${STAGING_E1_NODE2_CKDB_ADMIN_UI_PORT}:${STAGING_E1_NODE2_CKDB_ADMIN_UI_PORT}
    volumes:
      - type: bind
        source: ${CKDB_STAGING_E1_CERTS_DIR}
        target: ${CONTAINER_CKDB_CERTS_PATH}
      - type: volume
        source: staging-app-db-data-e1-node2
        target: ${CONTAINER_CKDB_DATA_PATH}
    container_name: ${PROJECT}_ckdb-e1-node2
    depends_on:
      - ckdb-e1-node1
    network_mode: "host"

  ckdb-e1-node3:
    image: cockroachdb/cockroach:${CKDB_VERSION}
    command: start --certs-dir=${CKDB_CONTAINER_HOST_DIR} --port=${STAGING_E1_NODE3_CKDB_APP_PORT} --http-port=${STAGING_E1_NODE3_CKDB_ADMIN_UI_PORT} --join=localhost:${STAGING_E1_NODE1_CKDB_APP_PORT}
    ports:
      - ${STAGING_E1_NODE3_CKDB_APP_PORT}:${STAGING_E1_NODE3_CKDB_APP_PORT}
      - ${STAGING_E1_NODE3_CKDB_ADMIN_UI_PORT}:${STAGING_E1_NODE3_CKDB_ADMIN_UI_PORT}
    volumes:
      - type: bind
        source: ${CKDB_STAGING_E1_CERTS_DIR}
        target: ${CONTAINER_CKDB_CERTS_PATH}
      - type: volume
        source: staging-app-db-data-e1-node3
        target: ${CONTAINER_CKDB_DATA_PATH}
    container_name: ${PROJECT}_ckdb-e1-node3
    depends_on:
      - ckdb-e1-node1
      - ckdb-e1-node2
    network_mode: "host"

A: Here's my full configuration for reference:
docker-compose.yml
version: '3.7'

networks:
  roachnet:
    driver: bridge

services:
  # CockroachDB Load Balancer
  crdb-lb:
    hostname: crdb-lb
    image: haproxy:2.0.7
    volumes: ['./crdb-lb.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro']
    networks: ["roachnet"]
    ports:
      - "26257:26257"
      - "8080:8080"
      - "8081:8081"
    links:
      - roach1
      - roach2
      - roach3

  # CockroachDB default topology - 3 nodes
  roach1:
    # see https://hub.docker.com/r/cockroachdb/cockroach/tags
    image: cockroachdb/cockroach:v19.1.5
    hostname: roach1
    networks:
      - roachnet
    volumes: ["./cockroach-data/roach1:/cockroach/cockroach-data"]
    command: "start --insecure --cache=.25 --max-sql-memory=.25"
    ulimits:
      nproc: 65535
      nofile:
        soft: 65535
        hard: 65535
  roach2:
    # see https://hub.docker.com/r/cockroachdb/cockroach/tags
    image: cockroachdb/cockroach:v19.1.5
    hostname: roach2
    networks: ["roachnet"]
    volumes: ["./cockroach-data/roach2:/cockroach/cockroach-data"]
    command: "start --insecure --join=roach1 --cache=.25 --max-sql-memory=.25"
    depends_on: ["roach1"]
    ulimits:
      nproc: 65535
      nofile:
        soft: 65535
        hard: 65535
  roach3:
    # see https://hub.docker.com/r/cockroachdb/cockroach/tags
    image: cockroachdb/cockroach:v19.1.5
    hostname: roach3
    networks: ["roachnet"]
    volumes: ["./cockroach-data/roach3:/cockroach/cockroach-data"]
    command: "start --insecure --join=roach1 --cache=.25 --max-sql-memory=.25"
    depends_on: ["roach1"]
    ulimits:
      nproc: 65535
      nofile:
        soft: 65535
        hard: 65535

And my crdb-lb.cfg which I map via Docker compose to haproxy.cfg:
global
    maxconn 4096
    nbproc 1
    nbthread 4

defaults
    mode                tcp
    # Timeout values should be configured for your specific use.
    # See: https://cbonte.github.io/haproxy-dconv/1.8/configuration.html#4-timeout%20connect
    timeout connect     10s
    timeout client      30m
    timeout server      30m
    # TCP keep-alive on client side. Server already enables them.
    option              clitcpka

listen cockroach-db
    bind :26257
    mode tcp
    balance roundrobin
    option httpchk GET /health?ready=1
    server roach1 roach1:26257 check port 8080
    server roach2 roach2:26257 check port 8080
    server roach3 roach3:26257 check port 8080

listen cockroach-ui
    bind :8080
    mode tcp
    balance roundrobin
    option httpchk GET /health
    server roach1 roach1:8080 check port 8080
    server roach2 roach2:8080 check port 8080
    server roach3 roach3:8080 check port 8080

listen stats
    bind :8081
    mode http
    stats enable
    stats hide-version
    stats realm Haproxy\ Statistics
    stats uri /

Before connecting of course make sure that you create the user that you want to connect with. You can easily get a shell by doing docker-compose exec roach1 ./cockroach sql --insecure and then you can create your db and user from there.
DROP DATABASE IF EXISTS mydb;
CREATE DATABASE mydb;
CREATE USER IF NOT EXISTS myuser;
GRANT ALL ON DATABASE mydb TO myuser;

Then in my Golang application I just connect by hitting localhost on port 26257 like this:
db, err := sql.Open("postgres", "postgresql://myuser@localhost:26257/mydb?sslmode=disable")
if err != nil {
    log.Fatal("error connecting to the database: ", err)
}


text:
Q: Split the data into three arrays based on the time I want to split the data array into three arrays - past, today, later - based on the time.
For today's array, only data with today's date and the time greater than today's time should be there.
Here's my code. There is no bug in it (as far as I know). I am getting the desired result, but I want to know if this code can be more optimized.
$current_date = date('Y-m-d');
$current_time = date('H:i:s');

foreach($data as $key => $value) {
    if(date('Y-m-d', $value->meeting_scheduled_at) > $current_date) {
        $calendar_data['later'][] = $value;
    } elseif (date('Y-m-d', $value->meeting_scheduled_at) < $current_date
              || ( (date('Y-m-d', $value->meeting_scheduled_at) == $current_date)
                   && (date('H:i:s', $value->meeting_scheduled_at) < $current_time) )
    ) {
        $calendar_data['past'][] = $value;
    } else {
        $calendar_data['now'][] = $value;
    }
}

$value->meeting_scheduled_at is in timestamp
EDIT: I am using this in a Laravel project.
So, if the meeting is scheduled at today's date, and time is evening 6 PM. It will come into today array till the 6 PM. After 6 PM, it goes into the past array. In short, nothing should be there in later array, unless and until it is next day.

A: date('Y-m-d', $value->meeting_scheduled_at) should be calculated only once before you use its result in the conditions.

A: I like to use the DateTime class for this kinda thing. It takes into account daylight savings etc and can be compared really easily.
$now         = new DateTime();
$tomorrow    = new DateTime();
$meetingDate = new DateTime();

$tomorrow->add(new DateInterval('P1D'))->setTime(0,0,0);

foreach ($data as $key => $value) {
    $meetingDate->setTimestamp($value->meeting_scheduled_at);

    // if $value->meeting_scheduled_at format YYYY-MM-DD then
    // we'd create the $meetingDate object here like this
    // $meetingDate = new DateTime($value->meeting_scheduled_at);

    if ($meetingDate < $now) {
        $calendar_data['past'][] = $value;
    } else if ($meetingDate >= $tomorrow) {
        $calendar_data['later'][] = $value;
    } else {
        $calendar_data['now'][] = $value;
    }
}

A: Make it easier
$now = time();
// Midnight due to discussion with Kevin Nagurski in comments :)
$tommorow = strtotime('tomorrow');
foreach($data as $key => $value)
    if ($value->meeting_scheduled_at) < $now) $calendar_data['past'][] = $value;
    elseif ($value->meeting_scheduled_at) >= $tommorow) $calendar_data['later'][] = $value;
    else $calendar_data['now'][] = $value;

A: You can use timestamp instead.
$now = time();
$today_limt = strtotime("today 6 PM");

 foreach($data as $key => $value) {
        $meeting_time = strtotime($value->meeting_scheduled_at);
        if($meeting_time > $today_limit) {
            $calendar_data['later'][] = $value;
        } elseif($meeting_time < $now) {
            $calendar_data['past'][] = $value;
        } else {
            $calendar_data['now'][] = $value;

        }
 }


text:
Q: Summarising data frame by multiple columns I would like to know how to summarize more columns in R.
I have a data.frame (df) like this:
device  customer  message  count_today  count_yesterday
1       x          a        5              3
1       x          b        1              2
2       y          c        0              1
3       z          a        5              2
1       x          a        7              4

I would like to get a summary of the message counts per customer.
This is the result I hope to get:
customer  count_today  count_yesterday
x          13            9
y          0             1
z          5             2

I tried the summarise function to get partial results for count_today and count_yesterday, however it seems to be summarizing the number of occurrences of each device.
This is the code I tried:
df_today <- select(df, customer, count_today) %>%
  group_by(cutomer) %>%
    summarise(count_today=n()) %>%
      arrange(., customer)

df_yesterday <- select(df, customer, count_yesterday) %>%
  group_by(cutomer) %>%
    summarise(count_yesterday=n()) %>%
      arrange(., customer)

df_final <-merge(x = df_today, y = df_yesterday, by = "customer", all.x = TRUE, all.y = TRUE)

All I am getting is this:
customer  count_today  count_yesterday
x          3            3
y          1            1
z          1            1

Coul you please help me with this?
Thanks for any suggestions.

A: By summarising with sum instead of n, you'll get the result you're after.
library(dplyr)

df %>%
  group_by(customer) %>%
  summarise_at(c("count_today", "count_yesterday"), sum)

# A tibble: 3 x 3
  customer count_today count_yesterday
  <chr>          <int>           <int>
1 x                 13               9
2 y                  0               1
3 z                  5               2


text:
Q: Cloning the entire tr table entity in a given table row I want to be able to clone a table tr with a textarea in it. each parent table row should have its own add and remove icons. So when I click the add icon, a new textarea is created, which th code does perfectly for the first row, but I have a problem removing. Another problem is that if I click the second add icon in row 2, it adds the textarea to row 1.
Here is the code:

                <textarea  id="p_new" rows="1" cols="10" name="data[]" value="" placeholder="Input Value" ></textarea><img src="<?php echo base_url(); ?>img/add.png" alt="+" width="15px" height="15px">

                <textarea  id="p_new_1" rows="1" cols="10" name="data[]" value="" placeholder="Input Value" ></textarea><img src="<?php echo base_url(); ?>img/add.png" alt="+" width="15px" height="15px">

A: 1) use class for addNew instead of id.
2) You are appending new row to column (not sure why you want that)
Check here DEMO http://jsfiddle.net/yeyene/CgwCC/
Adding and removing is working now.
$(document).ready(function(){
    var i = 1;

    $('.addNew').on('click', function() {
        $('
<textarea  id="p_new'+i+'" rows="1" cols="10" name="data[]" value="" placeholder="I am New" ></textarea>-
').appendTo($(this).parent('td'));
        i++;

        return false;
    });

    $('.remNew').live('click', function() {
        var id = $(this).parentsUntil('tr.clone').attr('id');
        if( id != '1' ) {
          $(this).parentsUntil('tr.clone').remove();
          i--;
        }
        return false;
    });
});


text:
Q: Xcode + LLDB: trying to change variable value using 'expression' I am trying to improve my debugging skills, so started reading around here. I have the following piece of code:
var label = "tom"
self.label.text = label
print(label)

I have a break point in each of the lines, and in each of them I type
expression label = "jones"
po label

So, when I type po label I get the expected result, which is jones, but the text presented in the label and the console (from print(label)) is tom.
The tutorial I linked states that the changes should take effect for the entire run of the program. Is it false, or am I doing something wrong?
I am using Xcode Version 8.2.1 (8C1002) with an iPhone 7 Plus simulator.
Thanks!

A: I'm not sure this helps, but what is going on is a little more complicated than you think.
Swift strings are actually structs, so if you stopped on the line before you assign to self.text.label, and assign a new value to your label var, you are actually changing the contents of the struct, which should by all rights mean that when you assign to self.text.label from that struct, it really should pick up the new value...
The reason that doesn't work is that the swift compiler is smart about unboxing these structs so that it doesn't do unnecessary dereferences when possible.  This happens even at -Onone.
So for instance, in your example the swift compiled code has already unboxed the string and emitted code that directly references the contents.  Changing the actual string contents doesn't change the references to the unboxed contents already in the assignment code, and so your change doesn't take.
You can see this IRL: if you make the compiler unable to know what the contents of the string are, it can't do this unboxing, and then you will see your debugger changes take effect.
Using this example code:
class HasLabel
{
  var label : String = "Default Value"
}

func
main ()
{
  var myLabel = HasLabel()
  var string = "set in code"

  string.removeSubrange(string.startIndex..<string.endIndex)
  string.append("Different string in code")
  myLabel.label = string  // Set a breakpoint here
  print ("Did it change? string: \"\(string)\" Label: \"\(myLabel.label)\"")
}

main()

in the debugger, I see:
(lldb) br s -p "Set a breakpoint here"
Breakpoint 1: where = tryme`tryme.main () -> () + 499 at tryme.swift:14, address = 0x0000000100001e93
(lldb) run
Process 8323 launched: '/private/tmp/tryme' (x86_64)
Process 8323 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
    frame #0: 0x0000000100001e93 tryme`tryme.main () -> () at tryme.swift:14
   11
   12     string.removeSubrange(string.startIndex..<string.endIndex)
   13     string.append("Different string in code")
-> 14     myLabel.label = string  // Set a breakpoint here
          ^
   15     print ("Did it change? string: \"\(string)\" Label: \"\(myLabel.label)\"")
   16   }
   17
(lldb) expr string = "Set in debugger"
(lldb) c
Process 8323 resuming
Did it change? string: "Set in debugger" Label: "Set in debugger"
Process 8323 exited with status = 0 (0x00000000)

There you see the debugger change actually took.  But if you comment out the string.removeSubrange and string.append, then the change will no longer take.


text:
Q: nltk for python 3.6 in windows64 I'm new to python, I'm using Windows 10 and have  python36  and I basically have to use nltk for my project and i basically have two questions.

*

*1 I heard pip is automatically downloaded for versions 3+ but when I type pip install nltk in command prompt im getting the following error even though i added its path "C:\Users\dheeraj\AppData\Local\Programs\Python\Python36\Scripts\pip36" in advanced settings and ya in above path i tried pip36 and pip in both cases result is same.

'pip' is not recognized as an internal or external command,"

*2 In www.nltk.org I found nltk for mac, unix and windows32 but not for windows64 ,does that mean it doesnt support for 64bit or is there any way for me to install nltk.

A: I had the same problem as you, but I accidentally found pip.exe in my python directory, so I navigated to said directory with CMD and ran the command pip install -U nltk and it worked.

A: Run the Python interpreter and type the commands:
import nltk>>>
nltk.download()>>>
A new window should open, showing the NLTK Downloader. Click on the File menu and select Change Download Directory. For central installation, set this to C:\nltk_data (Windows), /usr/local/share/nltk_data(Mac), or /usr/share/nltk_data (Unix). Next, select the packages or collections you want to download.
If you did not install the data to one of the above central locations, you will need to set the NLTK_DATA environment variable to specify the location of the data. (On a Windows machine, right click on "My Computer" then select Properties > Advanced > Environment Variables > User Variables > New...)
Test that the data has been installed as follows. (This assumes you downloaded the Brown Corpus):
from nltk.corpus import brown>>>
brown.words()>>>
['The', 'Fulton', 'County', 'Grand', 'Jury', 'said', ...]
Installing via a proxy web server
If your web connection uses a proxy server, you should specify the proxy address as follows. In the case of an authenticating proxy, specify a username and password. If the proxy is set to None then this function will attempt to detect the system proxy.
nltk.set_proxy('http://proxy.example.com:3128', ('USERNAME', 'PASSWORD'))>>>
>>> nltk.download()
Command line installation
The downloader will search for an existing nltk_data directory to install NLTK data. If one does not exist it will attempt to create one in a central location (when using an administrator account) or otherwise in the user's filespace. If necessary, run the download command from an administrator account, or using sudo. The recommended system location is C:\nltk_data (Windows); /usr/local/share/nltk_data (Mac); and/usr/share/nltk_data `(Unix). You can use the -d flag to specify a different location (but if you do this, be sure to set the NLTK_DATA environment variable accordingly).
Run the command python -m nltk.downloader all. To ensure central installation, run the command sudo python -m nltk.downloader -d /usr/local/share/nltk_data all.
Windows: Use the "Run..." option on the Start menu. Windows Vista users need to first turn on this option, using Start -> Properties -> Customize to check the box to activate the "Run..." option.

A: Directly Search for pip folder and navigate throught that path example:
C:\Users\PAVAN\Environments\my_env\Lib\site-packages\pip>
Run cmd
and then run the command
    pip install -U nltk

A: Following are the steps I followed to resolve this issue:

*

*Click on Python 3.6 Module Docs (32 bit). This will open in your default browser.

*Click on pip(Package), displayed at the end of the page.

*You will be redirected to a page displaying details of the package. Find the exact path from there. It will be something like c:\users\grove\appdata\local\programs\python\python36-32\lib\site-packages\pip

*Run this on cmd prompt.

*Once you're in pip folder type pip install -U nltk

*Go back to Python Shell and type import nltk

A: I will recommend you to use the Anaconda on Windows. Anaconda has nltk version for Python 64-bit. Now I'm using Python 3.6.4 64-bit and nltk.
Under python shell run:
import nltk
 nltk.download()

then the downloader will be open in new window and you can download what you want.

A: First install the module
like pip install -U nltk
and the use the import statment in the command prompt or IDLE
import nltk


text:
Q: Plotting with while loop I have a some x and y coordinates like this:
x = [None, 5, 7, None, None, 9]
y = [1, 2, 3, 4, 5, 6]

I want a while loop to go through each list item in turn and plot a circle marker if it has an x and y coordinate and then the plot must stay there as it continues to plot more values, eventually it will have plotted every value from the lists.
Code:
i = 0
while i < 100:
    plt.plot((b[i]), (a[i]), marker='o')
    plt.ion()
    plt.pause(1)
    i += 1

Some reason, it seems to plot the marker and then it disappears, any ideas?

A: You question gives lists x and y and then uses a and b in the loop, so I'll just make something up for a and b and assume you have the filtering out of None's working.
a = [1, 5, 7, 1, 1, 9]
b = [1, 2, 3, 4, 5, 6]

You just need to set interactive once - not over and over in the loop. But this isn't the cause of the problem - just saying
plt.ion()

for (x, y) in zip(a,b):
    plt.plot(x, y, marker = 'o')
    plt.pause(1)

What I observe is that the points are showing up - but the scale changes to show the new point - others are off the screen. If I zoom out enough all the points are actually there.
You may wish to give some thought to your axes scale; something like
plt.xlim([min(a)-1, max(a)+1])
plt.ylim([min(b)-1, max(b)+1])

should make all your data fit on the same plot without points seeming to disappear


text:
Q: ID Not Submitting To Query I appreciate your responses in advance.
I have several pages of orders that I am dealing with, however I am sure fixing one will provide me with enough knowledge to fix the others. In this case, I will show you the daytasks.php section. Basically, I can make function changes to the first line, but the second, third, etc. lines cannot be modified. Using the function buttons does nothing for those lines. daytasks.php calls upon fetchdaytasks.php to get the information based on date, which calls upon ./functions/additions.js to perform the Javascript, which calls upon  the functions corresponding script to perform the action requested.
e.g. I have two orders, each in their own separate
, I can modify the first row, which is ID #28 with any of the functions, but the second row, ID #35 I cannot modify, it will simply not make any changes.
Portion of daytasks.php

                        <input type="date" id="search_text" name="search_text" />

Portion of fetchdaytasks.php
if(mysqli_num_rows($result) > 0)
 {
    while($row = mysqli_fetch_array($result))
     {
         $id=$row['id'];
         $orderdate=$row['date'];
         $order=$row['order'];
         $status=$row['status'];
 echo "
                $id
                $orderdate
                $order
                $status
                <form>
                <button type='button' name='btn_ship' id='btn_ship' class='btn btn-xs btn-success' data-id='$id'>SHIP</button> <button type='button' name='btn_unship' id='btn_unship' class='btn btn-xs btn-danger btn_delete'>UNSHIP</button> <button type='button' name='btn_bo' id='btn_bo' class='btn btn-xs btn-danger btn_delete'>BACKORDER</button> <button type='button' name='btn_fbo' id='btn_fbo' class='btn btn-xs btn-danger btn_delete'>FBO</button>

            <button type='button' name='btn_cancel' id='btn_cancel' class='btn btn-xs btn-danger btn_delete'>CANCEL</button> <button type='button' name='btn_return' id='btn_return' class='btn btn-xs btn-danger btn_delete'>RETURN</button> <button type='button' name='btn_dam' id='btn_dam' class='btn btn-xs btn-danger btn_delete'>DAMAGED</button> <button type='button' name='btn_lost' id='btn_lost' class='btn btn-xs btn-danger btn_delete'>LOST</button>
            </form>

            ";
     }
 }
 else
 {
     echo "No Orders For This Date";
 }

Portion of additions.js
    $("#btn_ship").click(function(){
var changeid = $( this ).data('id');
 var myData={"changeid":changeid};
 $.ajax({
    url : "./functions/shiporder.php",
    type: "POST",
    data : myData,
    success: function(data,status,xhr)
     {
        $("#status_text").html(data);
        $('#changeid').val();
     }
});
});

$("#btn_fbo").click(function(){
 var changeid = $('#changeid').val();
 var myData={"changeid":changeid};
 $.ajax({
    url : "./functions/fboorder.php",
    type: "POST",
    data : myData,
    success: function(data,status,xhr)
     {
        $("#status_text").html(data);
        $('#changeid').val();
     }
});
});

./functions/fboorder.php
<?php
include_once('/home/brandina/public_html/eldis/config/config.php');
 $changeid = $_POST['changeid'];
 if(mysqli_query($connect, "UPDATE `orders` SET `status`='FBO' WHERE `id`='$changeid'"))
 ?>

./functions/shiporder.php
<?php
include_once('/home/brandina/public_html/eldis/config/config.php');
 $changeid = $_POST['changeid'];
 if(mysqli_query($connect, "UPDATE `orders` SET `status`='SHIP' WHERE `id`='$changeid'"))
 ?>

A: Because you are looping in fetchdaytasks, this line will be repeated:
<input type='hidden' id='changeid' name='changeid' value='$id' />
That means you will have multiple elements with an "id" of 'changeid'. In your JS you have var changeid = $('#changeid').val();
This does not know which #changeid you are talking about.
So I would get rid of the hidden input and work with "data-XXX" and put that on the buttons or on the form.
So <button type='button' name='btn_ship' id='btn_ship' class='btn btn-xs btn-success' data-id='$id'>SHIP</button> or <form data-id='$id'>
And then get the id in the JS like:
var changeid = $( this ).data( 'id ); in case you do it on the button.


text:
Q: Zodb process Killed after reading multiple fs I have used ZODB BTrees to store some data (~1-2GB per file). I created the ZODB files using:
storage = FileStorage(os.path.join(zodb_dir, 'trainPatches.fs'))
db = DB(storage)

connection = db.open()
root = connection.root()

root.patches = BTrees.OOBTree.BTree()
# take columns from a pandas data frame and insert into zodb
for col in df.columns:
    root.patches[col] = df[col]

transaction.commit()

db.close()
connection.close()

and now I am reading them (and converting back into dataframes) using:
        db = DB(FileStorage(file_name))
        connection = db.open()
        root = connection.root()
        # this is the key to the BTree that the files we're saved as
        pp = root.patches
        p_list = list(pp.items())

        # from ZODB is stored as a list of tuples, need to separate out names and data
        column_names = [names[0] for names in p_list]
        data_ = [names[1] for names in p_list]

        # insert into data frame
        patches_df = pd.DataFrame()

        for i, c in enumerate(column_names):
            patches_df[c] = data_[i]

        connection.close()
        db.pack()
        db.close()

But after reading ~30 of them, the process is Killed in terminal. I'm new to using ZODB but perhaps the memory is being eaten up by this write/read sequence?


text:
Q: How to write Integration Test for rabbit template with confirm and return callback I have publisher that publish the message to exchange and associated rabbit template is configured to have confirm and return call back. I just would like to know How do I write integration test for this class using mock or any other frame work.
I have publisher that publish the message to exchange and associated rabbit template is configured to have confirm and return call back. I just would like to know How do I write integration test for this class using mock or any other frame work.
Code :

    @Configuration
    public class TopicConfiguration {

        private static final Logger LOGGER = LoggerFactory.getLogger(TopicConfiguration.class);

        @Autowired
        RabbitMqConfig rabbitMqConfig;

        @Autowired
        EPPQ2Publisher eppQ2Publisher;

         /**
         * Caching connection factory
         * @return CachingConnectionFactory
         */
        @Bean
        public CachingConnectionFactory cachingConnectionFactory() {
            CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(rabbitMqConfig.getPublisherHosts(),
                    rabbitMqConfig.getPublisherPort());
            cachingConnectionFactory.setUsername(rabbitMqConfig.getPublisherUsername());
            cachingConnectionFactory.setPassword(rabbitMqConfig.getPublisherPassword());
            cachingConnectionFactory.setVirtualHost("hydra.services");
            cachingConnectionFactory.createConnection();
            cachingConnectionFactory.setPublisherReturns(true);
            cachingConnectionFactory.setPublisherConfirms(true);
            cachingConnectionFactory.setConnectionNameStrategy(f -> "publisherConnection");
            return cachingConnectionFactory;
        }

        /**
         * Bean RabbitTemplate
         * @return RabbitTemplate
         */
        @Bean
        public RabbitTemplate template(
                @Qualifier("cachingConnectionFactory") CachingConnectionFactory cachingConnectionFactory) {
            final RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
            rabbitTemplate.setMessageConverter(producerJackson2MessageConverter());
            RetryTemplate retryTemplate = new RetryTemplate();
            ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
            backOffPolicy.setInitialInterval(500);
            backOffPolicy.setMultiplier(10.0);
            backOffPolicy.setMaxInterval(10000);
            retryTemplate.setBackOffPolicy(backOffPolicy);
            rabbitTemplate.setRetryTemplate(retryTemplate);
            rabbitTemplate.setExchange(rabbitMqConfig.getPublisherTopic());
            rabbitTemplate.setUsePublisherConnection(true);
            rabbitTemplate.setMandatory(true);

            rabbitTemplate.setConfirmCallback((correlation, ack, reason) -> {
                if (correlation != null) {
                    LOGGER.info("Received " + (ack ? " ack " : " nack ") + "for correlation: " + correlation);
                    if (ack) {
                        // this is confirmation received..
                        // here is code to ack Q1. correlation.getId() and ack it !!
                        eppQ2Publisher.ackMessage(new Long(correlation.getId().toString()));
                    } else {
                        // no confirmation received and no need to do any thing for
                        // retry..
                    }
                }

            });
            rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
                LOGGER.error("Returned: " + message + "\nreplyCode: " + replyCode + "\nreplyText: " + replyText
                        + "\nexchange/rk: " + exchange + "/" + routingKey);
            });
            return rabbitTemplate;
        }

        /**
         * Bean Jackson2JsonMessageConverter
         * @return Jackson2JsonMessageConverter
         */
        @Bean
        public Jackson2JsonMessageConverter producerJackson2MessageConverter() {
            return new Jackson2JsonMessageConverter();
        }

    }

    ````java
    @Component
    public class EPPQ2PublisherImpl implements EPPQ2Publisher{
        @Autowired
        RabbitMqConfig rabbitMqConfig;

        @Autowired
        private RabbitTemplate rabbitTemplate;

        private Channel channel;

        /**
         * Method sendMessage for sending individual scrubbed and encrypted message to publisher queue (Q2).
         * @param msg - message domain object
         * @param deliveryTag - is message delivery tag.
         */
        @Override
        public void sendMessage(Message msg,Long deliveryTag) {
            rabbitTemplate.convertAndSend(rabbitMqConfig.getRoutingKey(), msg,new CorrelationData(deliveryTag.toString()));
        }

        /**
         * sendMessages for sending list of scrubbed and encrypted messages to publisher queue (Q2)
         * @param msgList - is list of scrubbed and encrypted messages
         * @param channel - is ampq client channel
         * @param deliveryTagList - is list of incoming message delivery tags.
         */
        @Override
        public void sendMessages(List<Message> msgList, Channel channel, List<Long>deliveryTagList) {
            if(this.channel == null) {
                this.channel = channel;
            }
            for (int i = 0 ; i < msgList.size(); i ++) {
                sendMessage(msgList.get(i),deliveryTagList.get(i));
            }
        }

        /**
         * Method ackMessage for sending acknowledgement to subscriber queue (Q1).
         * @param  deliveryTag - is deliveryTag for each individual message.
         */
        @Override
        public void ackMessage(Long deliveryTag)  {
            try {
                channel.basicAck(deliveryTag, false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

could some one guide me with reference or example is available that would be great.
Some junit and integration testing for rabbit template with confirm and returns would be a great help.

A: There are lots of test cases in the framework itself...
RabbitTemplatePublisherCallbacksIntegrationTests
and RabbitTemplatePublisherCallbacksIntegrationTests2
and RabbitTemplatePublisherCallbacksIntegrationTests3


text:
Q: writing aggregate MongoDB query to calculate field count ids I'm writing an aggregate query for the following records and output.
Data:
[
    {
        "_id" : ObjectId("5f3b2626927b18001db86884"),
        "collections" : [
            Art, Craft
        ]
     },{
        "_id" : ObjectId("5f3b2626927b18001db86885"),
        "collections" : [
            Craft
        ]
     },{
        "_id" : ObjectId("5f3b2626927b18001db86886"),
        "collections" : [
            Apex, Art
        ]
     },
     ...
]

Expected Output:
count of collections id
{
   Art : 2,
   Craft : 2,
   Apex : 1
}

Right now, we are looping through the collection to calculate count for each collections as the desired output, but it is low in performance because this collection is consists of 10,000 of records.
So, I was thinking to build an aggregate query and if someone can help me to start or point towards a right direction that would be really appreciated. Thank you.

A: *

*$unwind

*$group

*$group

*$replaceRoot
db.collection.aggregate([
  {
    $unwind: "$collections"
  },
  {
    "$group": {
      "_id": "$collections",
      "v": {
        "$sum": 1
      }
    }
  },
  {
    "$group": {
      "_id": null,
      "collections": {
        "$push": {
          $arrayToObject: [
            [ { "k": "$$ROOT._id", "v": "$$ROOT.v" } ]
          ]
        }
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: "$collections"
      }
    }
  }
])

mongoplayground

A: I have figured a solution after checking for a while.
db.getCollection("collectionName").aggregate(
    [
        // get all the records with at least one collection name
        {
            $match: {
                "collections.0": { $exists: true }
            }
        },

        // populate the collection record
        {
            $lookup: {
                from: "from_collection",
                localField: "localField",
                foreignField: "foreignField",
                as: "collections"
            }
        },

        // unwind
        { $unwind: "$collections" },

        // group by the collections._id
        { $group: { _id: "$collections._id", collections: { $push: "$$ROOT.ID" } } },

        // project with collection contains _id, and count
        {
            $project : {
                 collections: "$collections",
                 count: { $size: "$collections" }
            }
        }
    ]
).toArray();

output:
[
    {
        "_id" : ObjectId("61c4c42d68579f00311dd3e1"),
        "collections" : [
            "015151",
            "015152",
            "015153"
        ],
        "count" : 3.0
    },
    {
        "_id" : ObjectId("615f38016f40710033699939"),
        "collections" : [
            "014871"
        ],
        "count" : 1.0
    },
    {
        "_id" : ObjectId("611fed5ee0d12c00337cb009"),
        "collections" : [
            "014788",
            "014786",
            "014789",
            "014787",
            "014884",
            "014893",
            "014967",
            "014968",
            "015016",
            "015017"
        ],
        "count" : 10.0
    }
    ...
]


text:
Q: Copy and move through inheritance hierarchy Consider a simple
class Foo
{
public:
   Foo(const std::string& name) : _name{name}

private:
   std::string _name;
};

we know can be optimized by a copy and move
class Foo
{
public:
   Foo(std::string name) : _name{std::move(name)}

private:
   std::string _name;
};

but consider now the hierarchy:
class Base
{
protected:
   Base(const std::string& name) : _name{name}

private:
   std::string _name;
};

class Derived : public Base
{
public:
   Derived(const std::string& name) : A(name) {}
};

class Derived2 : public Derived
{
public:
   Derived2(const std::string& name) : Derived(name) {}
};

What is the correct way to implement the copy and swap idiom here? Does it even have sense use copy and swap rather than passing the const reference?
Edit: Please explains downvotes.

A: Passing by const reference is still the conventional wisdom
And will in all likely-hood continue to be, see code guidelines concerning this.
Despite what you may read on blogs, etc. you should stick with passing const reference for all normal use cases of objects that can potentially be expensive to copy - semanticly you shouldn't need to worry about how type X performs move and copy wise. This is still the conventional wisdom that is recommended and gives the needed flexible to change implementations at a later stage. If you leave the code inline in the header, any decent compiler is able to optimize that anyway (or perhaps with whole program optimization if not in header).
Also, using the copy and move is only (sometimes) faster for rvalues - not lvalues. lvalues is actually now worse off and have to take a copy of the object first and then move it.
std::string is particularly interesting here due to small string optimization
- so for a lot of small strings that could in worst case be a performance degration of close to a factor 2. Why ? for small strings a move is as expensive as a copy and neither move or copy is trivial meaning an optimization miss if using the copy and move idiom.
In the linked to post from commments, the author also has to write:

That, again, is a cheap constant-time operation, whereas copying is a
  linear-time operation, so in many cases that will be a price well
  worth paying.

Also, not all types are cheap to move anyway (example std::array).
If and only if, you have had this shown up in a profiler and you are still really really concerned about it - then you probably want to use a forward reference && instead of the plain copy (if not the solution is something third) - then call std::forward for forwarding to base classes (perfect forwarding).


text:
Q: how to edit /arch/x86/kernel/setup.c? i would like to add a print statement to this setup.c file and would like to see it in my messages when kernel executes start_kernel()...
     printk(KERN_INFO "m_name (put your name here): setup_arch(): command_line=%s\n",*command_line);

which would print
 my real name: setup_arch(): first_value_of_command_line

in /var/log/messages
i do have LXR and 14.04.1-Ubuntu
anyone can list steps here of how to do this?

A: In the terminal  type following commands.
First you have to login as super user.
sudo su
cd /var/log/messages
nano setup.c

this will open up setup.c file in nano editor.
then add the line you want to where ever you want .
after doing all the changes press CTRL+O  key combination to save the file.if it is asking for Confirmation give Y and press enter. then CTRL+X to Exit.
Done


text:
Q: How do you access the menu model from a Zotonic template? I want to write my own style of menu, but I would prefer to do it in the templates rather than making my own menu scomp.
I basically want to be able to do something like:
{% if m.menu %}

  {% for top_level_id in m.menu %}
    {% with m.rsc[top_level_id] as top_level %}

{{ top_level.title }}
      {% if top_level.menu %}

        {% for mid_level_id in top_level.menu %}
          {% with m.rsc[mid_level_id] as mid_level %}

{{ mid_level.title }}

          {% endwith %}
        {% endfor %}

      {% endif %}

    {% endwith %}
  {% endfor %}

{% endif %}

How do you access the menu model from a Zotonic template?

A: The (upcoming) 0.5-release and tip of Zotonic use a template to display the menu.  Check mod_menu/templates/_menu.tpl.
This template is called by the menu scomp.

A: To add to my previous answer. The standard _menu.tpl receives a list with all menu items.  This list is the result of a depth-first tree walk of the complete menu.  Every menu is a record with
{MenuRscId, DepthOfMenu, NrInSubMenu, HasSubMenuFlag}

Where the top level menu has a depth of 1 and the first menu item in a menu has a nr of 1.
All menu items that the current user is not allowed to see are filtered out.
The code of the default template:

{% for mid,depth,nr,has_sub in menu %}
  {% if not mid %}{% if depth > 1 %}

{% endif %}
  {% else %}
     {% if nr == 1 and not forloop.first %}
{% endif %}

         {{ m.rsc[mid].short_title|default:m.rsc[mid].title }}
   {% if not has_sub %}
{% endif %}
 {% endif %}
{% endfor %}
{% if forloop.last %}{% include "_menu_extra.tpl" %}{% endif %}


text:
Q: Google map api - V3 Distance between two polygons
On one project , I recovered all the coordinates of the polygons of different postal code.
When I search a zip code, I draw the polygon using the google api.
Now I would like to know whether a given polygon is so much distance from another .
Is that possible ?
By parsing all my geojson , I need to know if a random polygon is 5km from the polygon drawn .
There is computeDistanceBetween method from the geometry library...but its for two points. Is there the same for the distance between two polygons ?
Thx u for your help

A: Not sure if this would solve your problem but you can somehow use this library to compute distances within your polygon.
BDCCgeo.js
There is a function called bdccGeoDistanceToPolyMtrs(), you can measure the distance between a point and a polygon edge or polyline. Perhaps you can get a certain point on your first polygon and compare with with the second using this function.
Reference:
Distance from point within a polygon to polygon edge