text:
Q: Expected an assignment or function call and instead saw an expression no-unused-expressions- ReactJs I am trying to create a reservation app. I am quite new to React, and I tried searching and I can't seem to find what the problem is.
As my code has over 400 lines I will post only the ones I'm getting an error at.
I am following this article https://medium.com/@kris101/building-appointment-scheduler-app-in-react-and-nodejs-d01f7294a9fd
Error screenshot
The specific errors are:
Line 136:11:  Expected an assignment or function call and instead saw an expression  no-unused-expressions
  Line 139:11:  Expected an assignment or function call and instead saw an expression  no-unused-expressions
  Line 147:7:   Expected an assignment or function call and instead saw an expression  no-unused-expressions
I tried disabling eslint but when I do so I'm getting more errors.
handleDBReponse(response) {
    const reservations = response;
    const today = moment().startOf("day"); //start of today 12 am
    const initialSchedule = {};
    initialSchedule[today.format("YYYY-DD-MM")] = true;
    const schedule = !reservations.length
      ? initialSchedule
      : reservations.reduce((currentSchedule, reservation) => {
          const { slot_date, slot_time } = reservation;
          const dateString = moment(slot_date, "YYYY-DD-MM").format(
            "YYYY-DD-MM"
          );
          !currentSchedule[slot_date]
            ? (currentSchedule[dateString] = Array(8).fill(false))
            : null;
          Array.isArray(currentSchedule[dateString])
            ? (currentSchedule[dateString][slot_time] = true)
            : null;
          return currentSchedule;
        }, initialSchedule);

    for (let day in schedule) {
      let slots = schedule[day];
      slots.length
        ? slots.every(slot => slot === true) ? (schedule[day] = true) : null
        : null;
    }

    this.setState({
      schedule: schedule
    });
  }

A: I can see lots of linting issue in the above code.As of now I have fixed Expected an assignment or function call issue.
Please check the below code and let me know if it works
handleDBReponse(response) {
    const reservations = response;
    const today = moment().startOf('day'); // start of today 12 am
    const initialSchedule: any = {};
    initialSchedule[today.format('YYYY-DD-MM')] = true;
    const schedule = !reservations.length
        ? initialSchedule
        : reservations.reduce((currentSchedule: any, reservation: any) => {
            const tempSchedule = currentSchedule;
            const { slot_date, slot_time } = reservation;
            const dateString = moment(slot_date, 'YYYY-DD-MM').format('YYYY-DD-MM');
            tempSchedule[dateString] = !tempSchedule[slot_date] ? (tempSchedule[dateString] = Array(8).fill(false)) : null;
            if (Array.isArray(tempSchedule[dateString])) {
                tempSchedule[dateString][slot_time] = true;
            }
            return test;
        }, initialSchedule);

    for (const day in schedule) {
        const tempSchedule = schedule;
        const slots = tempSchedule[day];
        const checkEverySlot = slots.every((slot: boolean) => slot === true);
        if (slots.length && checkEverySlot) {
            tempSchedule[day] = true;
        }
    }

    this.setState({
        schedule,
    });
}

Note: It is good practice to write identifier in camel case.

A: This issue is around your use of ternary statements;
!currentSchedule[slot_date] ? (currentSchedule[dateString] = Array(8).fill(false)) : null;

Array.isArray(currentSchedule[dateString]) ? (currentSchedule[dateString[slot_time] = true) : null

slots.length ? slots.every(slot => slot === true) ? (schedule[day] = true) : null : null;

You can't use ternary statements in this way, you should replace these with individual if statements
e.g
if(currentSchedule[slot_date]) currentSchedule[dateString] = Array(8).fill(false)

An example of a proper use of ternaries would be when assigning a variable:
let myVar = x === 10 ? 'x is 10' : 'x is not 10'

A: The function handleDBReponse doesn't seems to be a well defined function. Try adding public before its name. Like public handleDBReponse(response) {...}.


text:
Q: Why are my gems not found when I do 'bundle install'? When I add a gem to my gemfile like so:
gem 'activeadmin'
gem 'meta_search', '>= 1.1.0.pre'
gem 'will_paginate', '~> 3.0.4'

and go to my terminal and type:
bundle install

I get this:
Using rake (10.1.0)
Using i18n (0.6.4)
Using minitest (4.7.5)
Using multi_json (1.7.7)
Using atomic (1.1.10)
Using thread_safe (0.1.0)
Using tzinfo (0.3.37)
Using activesupport (4.0.0)
Using builder (3.1.4)
Using erubis (2.7.0)
Using rack (1.5.2)
Using rack-test (0.6.2)
Using actionpack (4.0.0)
Using mime-types (1.23)
Using polyglot (0.3.3)
Using treetop (1.4.14)
Using mail (2.5.4)
Using actionmailer (4.0.0)
Using activemodel (4.0.0)
Using activerecord-deprecated_finders (1.0.3)
Using arel (4.0.0)
Using activerecord (4.0.0)
Using coffee-script-source (1.6.3)
Using execjs (1.4.0)
Using coffee-script (2.2.0)
Using thor (0.18.1)
Using railties (4.0.0)
Using coffee-rails (4.0.0)
Using hike (1.2.3)
Using jbuilder (1.4.2)
Using jquery-rails (3.0.4)
Using json (1.8.0)
Using bundler (1.3.5)
Using tilt (1.4.1)
Using sprockets (2.10.0)
Using sprockets-rails (2.0.0)
Using rails (4.0.0)
Using rdoc (3.12.2)
Using sass (3.2.9)
Using sass-rails (4.0.0)
Using sdoc (0.3.20)
Using sqlite3 (1.3.7)
Using turbolinks (1.3.0)
Using uglifier (2.1.2)

The gems listed are okay here and that was from the initial install of this app, but adding new gems to the gemfile will not let them get installed, so when I run a command that is explicit to that gem, I get errors like so:
rails generate active_admin:install
Could not find generator active_admin:install

I am not sure if this is an issue with my gemfile.

A: I got it working in the end.
The rails 4 version does not like the current version of active_admin so I had to use the edge method of getting my gemfile working for these gems to install. Which as as follows for anyone who wants to know:
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.0.rc2'

gem 'activeadmin',         github: 'gregbell/active_admin', branch: 'rails4'
gem 'ransack',             github: 'ernie/ransack',         branch: 'rails-4'
gem 'inherited_resources', github: 'josevalim/inherited_resources'
gem 'formtastic',         github: 'justinfrench/formtastic', branch: 'rails4beta'

The reason it never worked in the first place was a conflict in my gemfile with a version of rails, so I restarted my machine and started again and it worked.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Understanding Kontsevich's "Topics in Algebra - Deformation Theory" I am trying to understand some things stated in these notes on Kontsevich's lectures of 1994 on deformation theory. I am especially interested on the part on SHLA (strong homotopy Lie algebras, or $L_\infty$-algebras). It is around page 27.
By definition, a SHLA is a cofree cocommutative coalgebra $C = S^c(V)$ endowed with a square-zero differential $d_C$ (the operations of the SHLA are then given by the projection of the action of $d_C$ onto $V=C^{(1)}$, the weight $1$ part). In the notes Kontsevich works on the tangent space of $C$.

Question 1: What is the tangent space of $C$? I find the definition given in the notes very vague (also, I'm not familiar with supermanifolds).

If I understand correctly, he then defines the Maurer-Cartan locus as some leaf of a foliation in $C$ (maybe as $\ker[d_C,-]$, but he might also be working in the tangent space), and gauge equivalences as induced by $\mathrm{im}[d_C,-]\subseteq\ker[d_C,-]$, or something like that.

Question 2: What is the correct picture? What is the correct definition for the Deligne groupoid in the context of SHLAs (seen as coalgebras)?

I would be grateful for any help or references.

A: The following is a partial answer.
I found the answer to my question 1 reading Kontsevich's Deformation Quantization of Poisson Manifolds. There (section 4), he says that we look at $C$ as a formal pointed manifold (whatever that means; I think that the idea behind this is that, at least in the finite dimensional case, the dual of $C$ is a graded commutative algebra, and thus a higher analogue of an affine variety), and he explains that $V$ is the tangent space of $C$ at the basepoint (i.e. the point $0$). But $C$ has only one geometric point, so this is all the data we need.
A vector field on $C$ is then given by a map $Q:C\to V$, which automatically determines a morphism $C\to C$ by universal property. If $Q$ is odd and $[Q,Q]=0$, by noticing that $[Q,Q] = 2Q^2$ we have that $Q$ is the same thing as a differential on $C$ (and in particular its first Taylor coefficient makes $V$ into a chain complex).
I am still unclear on the good settings for Maurer-Cartan elements. Kontsevich says some things about formal neighborhoods and such, but I don't know enough about that yet. Any help or comments are more than welcome.

Edit: In section 4.5.2, he explains how to think of Maurer-Cartan elements in the $L_\infty$ algebra tensored by a finite dimensional, nilpotent commutative algebra (i.e. the maximal ideal of a local aritinian algebra). I think I more or less understand what is going on, but I would like to understand what the Deligne groupoid is for the original $L_\infty$-algebra, without tensoring by something nice.
A possible idea would be to consider another cocommutative algebra
$$M:=\prod_{n\ge1}k\cdot a^{\otimes n}$$
with coproduct defined in a way similar to the cofree cocommutative coalgebra, and look at the morphisms $M\to C$ landing in the kernel of $Q$. But what is a gauge equivalence in this setting? And in particular, why should gauge equivalences be preserved by $L_\infty$ morphisms?


text:
Q: How do I fix the getAge() to get the age of the oldest student in my code? import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class Student {

public Student(String name, int age, String major, String SSN) {

    }

public static void main(String[] args) {

        List<Student> studentList = new ArrayList<>();

        studentList.add(new Student("Alice", 22, "Computer Science", "603-28-5324"));
        studentList.add(new Student("Arthur", 19, "Math","402-23-5463"));
        studentList.add(new Student("Kim", 20, "English","607-34-5463"));
        studentList.add(new Student("Jack", 24, "Science","537-52-6324"));
        studentList.add(new Student("Bob", 27, "Computer Science", "345-23-4354"));
        studentList.add(new Student("Sarah", 21, "Music", "355-67-5352"));
        studentList.add(new Student("Mariah", 19, "Business", "567-45-8774"));
        studentList.add(new Student("Robert", 18, "Art", "732-65-7364"));

        Optional<Student> optional = studentList.stream()
                .max((p1, p2) -> p1.getAge() - p2.getAge());
        if (optional.isPresent()) {
            Student oldest = optional.get();
            System.out.println("The Oldest Student is: " +oldest.getAge() + "(" + oldest.getAge() + ")");

            //getAge() doesn't work. How do I make it so that it will be able to recognize the age in the array and print out the name with the age?

        }
    }
}

A: you should create member variables and assign them in the constructor
    public class Student {

        String name;
        int age;
        String major;
        String SSN;

        public Student(String name, int age, String major, String SSN) {
            this.name=name;
            this.age=age;
            this.major=major;
            this.SSN=SSN;
        }
        int getAge(){
            return age;
        }
        String getName()
        {
            return name;
        }

//and so on for all your variables
    }


text:
Q: In android, Empty activity launched while tapping mime type nfc tag, then fetched data from server? In android, I wrote mime type text/plain with package name in nfc tag. When app in closed state, if I tapped, it launched the specific activity. OnResume() called and load the data from server. In this case, it shows empty activity page,(No images or labels) then server fetched the data and displayed.
Two screens shown while tapping the mime type nfc tag. I want to show the page with data retrieved from server. Please help me out for this issue. Thanks in advance.
 if (MyUtils.isNetworkAvailable(Details.this)) {
            homeViewModel.getList();
        } else {
            List<GetModelResponse.ListData> listData = queries.getList();
            if (listData.size() > 0) {
                String[] separated = str.split(":");

                for (int i = 0; i < listData.size(); i++) {
                    if (separated[0].equalsIgnoreCase(String.valueOf(listData.get(i).getId()))) {
                        listData.get(i).setDate(MyUtils.getCurrentDate());
                        queries.insertPendingPay(listData.get(i));
                        break;
                    }
                }
            }

Fetching data from server api.


text:
Q: Restrict access to iframed domain through anything but its parent frame / domain I have a site on one domain (say, iframedomain.com), which is loaded via iframe through another domain (say, parentdomain.com) and I want to prevent users from accessing it directly. How do I ensure that anyone attempting to access iframedomain.com get redirected to parentdomain.com without hindering SEO to iframedomain.com?

A: Solved this issue using this script here:
http://geekswithblogs.net/rashid/archive/2007/01/13/103518.aspx


text:
Q: Code first : Sequence contains more than one matching element - multiple classes with multiple references I'm getting the "Sequence contains more than one matching element" error message while attempting to run the "Add-Migration" command. I believe that the issue is stemming from the fact that I have multiple classes that have multiple references to a shared class.
class User {
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid UserId {get; set;}
    public string Name {get; set;}
// other stuff removed for display purposes
    [InverseProperty("CreateUser")]
    public virtual ICollection<Foo> FooCreateUser { get; set; }
    [InverseProperty("ModifyUser")]
    public virtual ICollection<Foo> FooModifyUser { get; set; }

    [InverseProperty("CreateUser")]
    public virtual ICollection<Bar> BarCreateUser { get; set; }
    [InverseProperty("ModifyUser")]
    public virtual ICollection<Bar> BarModifyUser { get; set; }
}

class Foo {
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid FooId {get; set;}

    [InverseProperty("FooCreateUser")]
    public User CreateUser {get; set;}

    [InverseProperty("FooModifyUser")]
    public User ModifyUser {get; set;}
}

class Bar {
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid BarId {get; set;}

    [InverseProperty("BarCreateUser")]
    public User CreateUser {get; set;}

    [InverseProperty("BarModifyUser")]
    public User ModifyUser {get; set;}
}

What is wrong with the above code?
Do I have to change the field names in the [Bar] and [Foo] database tables to be unique?
i.e. change [Foo][CreateUser] to [Foo][Foo_CreateUser]?
I need to have a "CreateUser" and "ModifyUser" field on multiple database tables and it doesn't make any sense (from a database design perspective) to have all of those fields uniquely named.
How do I tell CodeFirst to do that?


text:
Q: The Guid Is not passed Correctly in MVC4? Hi the GUID is not passed  correctly.
My Tables
Customer
CustomerID uniqueidentifier primarykey not null,
DisplayName varchar(100)
PrintName varchar(100)
CustomerAddress Table
CustomerAddressID uniqueidentifier primarykey not null,
CustomerID uniqueidentifier null,
AddressID  uniqueidentifier null
Address
AddressID uniqueidentifier primarykey not null,
DisplayName varchar(100)
Street varchar(100)
Location varchar(100)
AreaID Uniqueidentifier null,
Pincode varchar(100)
My Model
public class CustomerModel1
    {
        public System.Guid CustomerID { get; set; }
        public string DisplayName { get; set; }
        public string PrintName { get; set; }
}

public partial class CustomerAddressModel
    {
        public System.Guid CustomerAddressID { get; set; }
        public Nullable<System.Guid> CustomerID { get; set; }
        public Nullable<System.Guid> AddressID { get; set; }

   }

 public partial class AddressModel
    {
        public System.Guid AddressID { get; set; }
        public string DisplayName { get; set; }
        public string Street { get; set; }
        public string Location { get; set; }
        public Nullable<System.Guid> AreaID { get; set; }
        public string PinCode { get; set; }
   }

My ViewModel
   public class CustomerViewModel
   {
    public System.Guid CustomerID { get; set; }
    public string CustomerName { get; set; }
    public System.Guid CustomerAddressID { get; set; }
    public System.Guid AddressID { get; set; }
    public string Address { get; set; }
    public string Street { get; set; }
    public string Location { get; set; }
    public Nullable<System.Guid> AreaID { get; set; }
    public string PinCode { get; set; }
 }

public class VisitorsEntities1 : DbContext
{

public DbSet   Customer { get; set; }
public DbSet CustomerAddress { get; set; }
public DbSet Address { get; set; }
}

My Controller
  public ActionResult Create()
    {
        VisitorsEntities1 db = new VisitorsEntities1();

 ViewBag.AreaID = new SelectList(db.Area, "AreaID", "DisplayName",   "PrintName");

   return View();
    }

    [HttpPost]
   public ActionResult Create(CustomerViewModel viewmodel)
    {

 ViewBag.AreaID = new SelectList(db.Area, "AreaID", "DisplayName",   viewmodel.AreaID);
       var Cusobj = Guid.NewGuid();
       var CusAddobj = Guid.NewGuid();
       var Addobj = Guid.NewGuid();

      var Customerobj = new Customer()
        {
            CustomerID = Cusobj,
        DisplayName = viewmodel.CustomerName,
        PrintName = viewmodel .CustomerName
   };

  var CustomerAddressobj = new CustomerAddress()
        {
            CustomerAddressID = CusAddobj,
            CustomerID = viewmodel.CustomerID,
            AddressID = viewmodel.AddressID
         };

      var Addressobj = new Address()
        {
            AddressID = Addobj,
            DisplayName= viewmodel.CustomerName,
            Street=viewmodel.Street,
            Location= viewmodel.Location,
            AreaID = viewmodel.AreaID,
            PinCode= viewmodel.PinCode
  };
     db.Customer.Add(Customerobj);
        db .CustomerAddress.Add(CustomerAddressobj );
        db.Address.Add(Addressobj);

   db.SaveChanges();

   return View()
 }

Here the AreaID is SubForm So I used ViewBag to bring dropdown in the View and Pass the Guid. Now my issue is with Customer Address Table.
 var CustomerAddressobj = new CustomerAddress()
        {
            CustomerAddressID = CusAddobj,
            CustomerID = viewmodel.CustomerID,
            AddressID = viewmodel.AddressID
         };

Here CustomerAddressID is new Guid is working fine. But

   CustomerID = viewmodel.CustomerID,
   AddressID = viewmodel.AddressID

The Guid is not passed correctly for this two lines . In table these column is 00000-0000-0000-0000 It didnt show any error and also its not passing the GUID correctly. I donno what the issue is. Please any one help to resolve these problem?
Error
My Error
Thanks.

A: Try using specual attributes to automatically generate Guid key on insert.
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public System.Guid CustomerID  { get; set; }

Here Key says it is primary key, DatabaseGenerated instructs to make key field auto-generated
EDIT
Note, that auto-generated identity fields are assigned to new entity only after save:
using (var db = new Context())
{
    var customer = new Customer();

    // Here customer.CustomerID is empty

    db.Customers.Add(customer);
    db.SaveChanges();

    // Here customer.CustomerID is assigned
}


text:
Q: Is $x^2y^2-z^3$ an irreducible element in $\Bbb Q[x,y,z]$? Is $x^2y^2 - z^3$ an irreducible element in $\Bbb Q[x,y,z]$?
I want to prove $\Bbb Q[x,y,z]/(x^2y^2-z^3)$ is an integral domain, so I need to show $(x^2y^2 - z^3)$ is a prime ideal of $\Bbb Q[x,y,z]$. I tried to show $x^2y^2-x^3$ is an irreducible element, and I tried to apply Eisenstein's criterion of prime ideals, but each variable $x,y,z$ has more degree greater than $2$. Therefore I need to use another method, but nothing comes upon to me.

A: Think of $z^3-x^2y^2$ as a monic cubic in $z$. If it had a factor, it would have a linear factor
of the form $z-\phi$ where $\phi\in\Bbb Q[x,y]$ and $\phi^3=x^2y^2$. There is no such $\phi$.


text:
Q: How to pass anonymous type to method as a parameter?
Possible Duplicate:
What's the return type of an anonymous class

I'm creating an anonymous type with query like the following:
Caller code:
 var query= from p in _db.ExecuteDataSet(SQL).Tables[0].AsEnumerable()
                        select new {
                                       ProductCode = p.Field<string>("PRODUCT_CODE"),
                                       ProductName = p.Field<string>("PRODUCT_NAME")
                                   };
 foreach(var product in query)
 {
     WriteProduct(product);
 }

Method is like:
void WriteProduct(object prod)
{
  //   access the product
}

I fail to get the correct Parameter Type for the WriteProduct method. Please help me.

A: There are 3 ways to talk to an anonymous type:

*

*reflection (obtain the properties via obj.GetType().GetProperties() / prop.GetValue(obj, null), etc)

*dynamic (i.e. obj.ProductCode and obj.ProductType, for dynamic obj) - an optimized and prettier version of the above

*cast-by-example : DO NOT USE

Your WriteProduct must use one of those; or alternatively : use something other than an anonymous type; a Tuple<...>, maybe (although that tends to make it hard to know what the data is) - or an appropriately defined custom interface, class or struct.

A: Correct me if I'm wrong, but I think you should create a temporary class to store the product.
select new TempProduct {
    productCode = p.Field<string>("PRODUCT_CODE"),
    productName = p.Field<string>("PRODUCT_NAME")
};

With e.g a class like this
public class TempProduct
{
    public String productCode { get; set; }
    public String productName { get; set; }
}

A: This isn't exactly what you are asking for, but your select has only two properties, so how about passing these two to the method?
foreach(var product in query)
{
    WriteProduct(product.ProductCode, product.ProductName);
}
// ...
void WriteProduct(string productCode, string productName)
{
    // ...
}

A: Yes you can.
public class Program
{
    private static void Thing(dynamic other)
    {
        Console.WriteLine(other.TheThing);
    }

    private static void Main()
    {
        var things = new { TheThing = "Worked!" };
        Thing(things);
    }
}

But as a small, minor detail, DON'T!
Anonymous types are anonymous for a reason, they aren't first class entities in your code, they're more of a convenience.  If a type is that important, define it as such.


text:
Q: Can people picker resolve NTLM users only in an FBA extended I have implemeted FBA with LDAP and NTLM Authentication, I want people picker only resolve names for NTLM users not for FBA.
Please help...
Thanks

A: I don't think this exact situation is possible. You can configure peoplepicker to only pick from non-AD users, but not the other way around. Check out http://technet.microsoft.com/en-us/library/gg602075.aspx. You might be able to configure it to a specific AD group, which may trick it into ignoring FBA accounts.


text:
Q: Dynamically building an Mongoose aggregate query in Node.js I am trying to build a mongoose aggregate query dynamically based on the content of an array variable passed in a POST api call as shown below, yet I am always receiving error "$or/$and/$nor entries need to be full objects" so was wondering if anyone can review my code below please let me know what I might be missing / doing wrong?
static search (searchData) {
    let { searchTerm, filterBy } = searchData;
    searchTerm = Utils.escapeRegexSpecialCharacters(searchTerm);

    let filterByElementsLength = filterBy.length;
    if(filterByElementsLength === 0) {
        query.push({
            $match: { 'bookTitle': new RegExp(searchTerm, 'i') },
        });
    }else if (filterByElementsLength > 0) {
        query.push({
            $match: { $and: [
                { 'bookTitle': new RegExp(searchTerm, 'i') },
                filterBy
            ] }
        });
    }
}

Taking in consideration that filterBy content is posted as JSON (Application/json) using Postman with the following content example:
"filterBy": [{"author": "Michael White" }, { "Price_Less_Than": "100" }],

Thanks for your support

A: Found a solution, posting it here below:
        let matchQry = [];
        matchQry.push({ 'bookTitle': new RegExp(searchTerm, 'i') });

        for(let i = 0; i < filterByElementsLength; i++) {
            matchQry.push(filterBy[i]);
        }
        query.push({
            $match: { $and: matchQry }
        });

If anyone think there could be a better solution, please let me know. Thanks for your support


text:
Q: AG Grid inserting rows with applyTransaction Is there a way to insert rows at a specific index rather than at the end of the grid?
Example would if I want to insert a row 10 rows from the top? Or in the middle?
I did find an old ag grid method called insertItemAtIndex(index, [rows]);
but this isn't working and says it's deprecated. Is there a way to do this with applyTransaction(transaction)?

A: The RowDataTransaction interface has an optional addIndex property -
export interface RowDataTransaction {
    /** deprecated */ addIndex?: number;
    add?: any[];
    remove?: any[];
    update?: any[];
}

Although it is marked deprecated, it is working for me.
Usage : this.gridApi.applyTransaction({ add: newItems, addIndex: 2});
It denotes the index  from which new rows will be inserted.
I have tried playing around on this example from docs and is working fine.
A related question for old way of updating rows. (without transaction)

A: As addIndex didn't work for me (using tree data in v26.1), I created a new column just for ordering. It is hidden, has sort set to 'asc' and has a valueGetter that generates the correct order.


text:
Q: Using jQuery to do an onClick div refresh This should work right? I have not a clue as to why it's not. I have to be doing something wrong.

text

    click

A: What happen if you do this?
click


text:
Q: jpa native query control entity(part 3)
*

*Retrieve company table
GetEntity.java
String table = "company";
String q = "select * from " +table;

Query query = em.createNativeQuery(q, Company.class);
List<Company> list = query.getResultList();
...

*Retrieve staff table
GetEntity.java
String table = "staff";
String q = "select * from " +table;

Query query = em.createNativeQuery(q, Staff.class);
List<Staff> list = query.getResultList();
...

*My questions is how do I control the ? from the following:
em.createNativeQuery(q, ?);
List<?> list = q.getResultList();

Any ideas or suggestion?

A: Another option is to pass the Class entityClass as an argument to your find method and then you can try and derive table name from entityClass by using reflection and use the entityClass as the type argument to your createNativeQuery method.
Hope this helps!


text:
Q: android add view over surfaceView i just want to make an video call layout and i faced this problem
i want to add some of imageView and button over surfaceView for swithc camera , mute , end call and some information and this is my xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
    >

<org.webrtc.SurfaceViewRenderer
    android:id="@+id/preview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<LinearLayout
    android:id="@+id/rind"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
      <!-- here my ImageView and button -->

     </LinearLayout>

</RelativeLayout>

SurfaceViewRenderer its extend surfaceView

now when i run this i cant see my camera in surfaceView and i add red background  for my SurfaceViewRenderer and its appear without my camera display i just search and i found mySurfaceView.setZOrderOnTop(true); i add its and now its show the display of camera but i can't see my view (mute, end call ...)
also i try
   mySurfaceView.setZOrderMediaOverlay(true);

   mySurfaceView.getHolder().setFormat(PixelFormat.TRANSPARENT);

no effect
i just want to make layout like this
before i use surfaceView i tried glsurfaceview but its same and i read i can't do it (add view over glsurfaceview) in glsurfaceview

A: Try this hope this will help you
and set for the top serface setZOrderMediaOverlay(true) and setZOrderMediaOverlay(false) for the next one

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"
  tools:context="com.discuss.app.call.CallScreen" android:id="@+id/backgroundImage" android:background="@color/black" android:windowSoftInputMode="stateHidden">

  <LinearLayout android:layout_width="wrap_content" android:id="@+id/remoteVideoContainer" android:layout_height="wrap_content" app:layout_constraintTop_toTopOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintBottom_toBottomOf="parent" android:background="@color/black">
    <org.webrtc.SurfaceViewRenderer android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/remoteVideoViewSurface" android:visibility="gone" android:backgroundTint="@color/darkBackgroundColor" />
  </LinearLayout>

  <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintEnd_toStartOf="parent" app:layout_constraintStart_toEndOf="parent" app:layout_constraintBottom_toTopOf="parent" app:layout_constraintTop_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.284" app:layout_constraintVertical_bias="0.492" android:id="@+id/localVideoContainer" android:elevation="7dp" android:background="@color/black">
    <org.webrtc.SurfaceViewRenderer android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/localVideoViewSurface" android:visibility="gone" />
  </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

A: Try this hope this will help you:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<FrameLayout
    android:clipChildren="false"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<!--local view-->
<com.example.gwl.apprtc.PercentFrameLayout
    android:id="@+id/local_video_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<org.webrtc.SurfaceViewRenderer
        android:id="@+id/local_video_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
<!--remote View -->
</com.example.gwl.apprtc.PercentFrameLayout>
<com.example.gwl.apprtc.PercentFrameLayout
    android:id="@+id/remote_video_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<org.webrtc.SurfaceViewRenderer
        android:id="@+id/remote_video_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</com.example.gwl.apprtc.PercentFrameLayout>
<!---->
</FrameLayout>
<FrameLayout
    android:id="@+id/buttons_call_container"
    android:orientation="horizontal"
    android:layout_marginBottom="@dimen/marginBottom_32dp"
    android:layout_gravity="bottom|center"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

<ImageButton
            android:id="@+id/button_call_disconnect"
            android:background="@drawable/disconnect"
            android:contentDescription="@string/disconnect_call"
            android:layout_width="@dimen/layoutWidth_48dp"
            android:layout_height="@dimen/layoutHeight_48dp"/>

<ImageButton
            android:id="@+id/button_call_toggle_mic"
            android:background="@android:drawable/ic_btn_speak_now"
            android:contentDescription="@string/toggle_mic"
            android:layout_marginRight="@dimen/marginRight_10dp"
            android:layout_width="@dimen/layoutWidth_48dp"
            android:layout_height="@dimen/layoutHeight_48dp"/>

<ImageButton
            android:id="@+id/button_call_switch_camera"
            android:background="@android:drawable/ic_menu_camera"
            android:layout_marginEnd="8dp"
            android:layout_width="48dp"
            android:layout_height="48dp"/>

</LinearLayout>

</FrameLayout>

</FrameLayout>


text:
Q: required if validation with email adress I am trying to validate one paypal id field based on payment option selected.
If payment option selected paypal then paypal_id must be present and type of email id.
If payment option is credit then paypal id is not required.
$rule = [
            "paypal_id" => "required_if:payment-option,paypal|email"
        ];

But it gives me error "The paypal id must be a valid email address"
When i select credit option.
The paypal payment option works perfectly.
Any suggestions will helpful.

A: You can do:
$rules = [/*... all rules except paypal_id ...*/];

if ($request->input("payment-option") == "paypal") {
    $rules["paypal_id"] =  "required|email";
}

$this->validate($request, $rules);

A: try this:
$rule = [
        "paypal_id" => "sometimes|required_if:payment-option,paypal|email"
    ];


text:
Q: How to join the three different code boxes from jsfiddle.net into a HTML page? I've been trying to create a web site just with a jsfiddle.net application.
I'd like to know how to join the three different code boxes from jsfiddle.net into a HTML page.
The HTML code for my page is
<html>
    <head>
    <style type="text/css">
        ***CSS box***
        </style>
</head>
    <body>
    ***HTML box***

        <script language="JavaScript"  type="text/javascript">
        ***Javascript box***
        </script>
    </body>
</html>

The problem is that I can't make it work
What am I doing wrong?
Thank you very much.

A: Just copy and paste the respective sections in a new HTML file on say your desktop.
<html>
    <head>
    <style type="text/css">
        // CSS Content
        </style>
</head>
    <body>
    <!-- some html elements -->

        <script language="JavaScript"  type="text/javascript">
            // more js here.
        </script>
    </body>
</html>

And then link in any dependencies such as jQuery within your head element.


text:
Q: password_verify() returning false when passwords match I'm creating a site where a user can login. When they make an account, I save the hashed password in the database. I am trying to user password_verify() in order to confirm the password matches, but it returns false.
To confirm that they match, I print out both the hashed version of what the user typed in and the hashed password that is stored in the database.
I know a common problem is that the database password field is too small for the hashed password, but I have tried setting it as both VARCHAR(256) and TEXT to make sure the entire hashed password is stored.
if(isset($_POST['email'])){
     $email = strip_tags(mysqli_real_escape_string($conn, $_POST['email']));
     $password = strip_tags(mysqli_real_escape_string($conn, $_POST['passwd']));
     $sql = "SELECT email, passwd AS hashed_password FROM Accounts WHERE email = '$email'";

     $result = $conn->query($sql);
     $row = mysqli_fetch_array($result,MYSQLI_ASSOC);
     //print the hashed password that is stored in the database
     echo  'stored in the database: '. $row['hashed_password']. '
';
     $hash = hash('sha512', $password);
     //print the hashed version of what the user typed in
     echo 'hashed version of what your submitted: '. $hash. '
';
     if( password_verify($password, $hash)){
         echo "true";
     }
     else{
         echo 'false';
     }

I expect that password_verify() returns true but it returns false
Here is what i have it currently outputting:

stored in the database:
1f40fc92da241694750979ee6cf582f2d5d7d28e18335de05abc54d0560e0f5302860c652bf08d560252aa5e74210546f369fbbbce8c12cfc7957b2652fe9a75
hashed version of what your submitted:
1f40fc92da241694750979ee6cf582f2d5d7d28e18335de05abc54d0560e0f5302860c652bf08d560252aa5e74210546f369fbbbce8c12cfc7957b2652fe9a75
false

A: password_verify() works with the function password_hash();
change:
$hash = hash('sha512', $password);

to:
$hash = password_hash($password, PASSWORD_DEFAULT);


text:
Q: Import package & type Here is my problem and my project structure
src
|-->config
       |--> config.go
|-->otherPackage
       |--> otherFile.go
|-->main.go

I have a type on config.go that I would like to use in otherFile.go
But when I tried to add it to the import here theses issues:

*

*imported and not used.

*undefined: Config
Although I use it in the function declaration
function(target float64, entries [2]float64, config Config)
What is the problem with this?
I tried to import it with
import (
    "fmt"
    "math"
    "../config"
)

A: You cannot "import from a package". All you can do is "import the whole package". That means if you import "full/import/path/of/foo" and that package declared itself to be called foo via package foo at the beginning, then everything in this package has to be qualified by foo:
foo.Config

If you package is called config than declaring a variable config will shaddow the whole package: so you have to:

*

*Rename the config variable to e.g. cfg

*Reference Config from package config with its qualified name config.Config


text:
Q: How would I get the string after the "!" I want to do something of the following,but I am having issues
if "!" in line:
    global after-ex == line.after(!)

the if "!" in line works fine
but I don't know how to do the actual function.perhaps there may be some import's I do not know of.


text:
Q: HttpContext data caching in entity framework I am trying to cache an entity using HttpContext caching. My code in service layer is as follows
public Product GetById(long id)
{
  Product product;
  string storageKey = string.Format("products_{0}",id.ToString());
  product = (Product)HttpContext.Current.Cache.Get(storageKey);
  if (product == null)
  {
     product = _productContext.Products.Find(id);
      HttpContext.Current.Cache.Insert(storageKey, product);
  }
  return product;
}

and using in client like this:
 ProductService productServices = new ProductService(_dbContext);
 var product = productServices.GetById(id);
  //... Populating controls

 //On Update button click
  ProductService productServices = new ProductService(_dbContext);
  var product = productServices.GetById(id);
  //Updating values of product and saveChanges.

While getting the item it is working fine. But when i try to save the item after updating it getting this error:

An entity object cannot be referenced by multiple instances of
  IEntityChangeTracker.

I understand this is due to retrieving and updating using different DbContexts. When using without caching its working fine. Is there any better other methods to do caching in entity framework ?

A: Try to attach cached product to current context:
public Product GetById(long id)
{
   Product product;
   string storageKey = string.Format("products_{0}",id.ToString());
   product = (Product)HttpContext.Current.Cache.Get(storageKey);
   if (product == null)
   {
      product = _productContext.Products.Find(id);
      HttpContext.Current.Cache.Insert(storageKey, product);
   }
   else
   {
       _productContext.Products.Attach(product);
   }
   return product;
}

Also if you are using Asp.Net MVC then consider to use output caching to cache content returned by controller action.


text:
Q: How to subtract one dataframe from subset intersection of another dataframe in pandas python? I have a the following dataframes in python:
dataframe 1
             1  2  3  4  5
dog   dog    0  1  1  0  1
      fox    1  0  0  0  0
      jumps  0  0  0  1  0
      over   1  0  1  0  1
      the    0  1  0  0  0
fox   dog    0  0  1  1  1
      fox    0  0  0  0  0
      jumps  0  0  1  0  1
      over   0  1  0  0  0
      the    0  0  0  1  1
jumps dog    0  0  0  0  0
      fox    0  1  0  1  1
      jumps  0  0  0  0  1
      over   1  0  1  0  0
      the    0  0  0  0  0
over  dog    0  0  1  0  0
      fox    0  1  0  1  1
      jumps  0  0  0  0  0
      over   0  1  0  1  0
      the    1  0  1  0  0
the   dog    0  0  1  0  0
      fox    0  0  0  0  1
      jumps  0  1  0  0  0
      over   0  0  1  1  0
      the    0  1  1  0  1

dataframe 2
             1  2  4  5
dog   dog    1  0  0  0
      fox    0  1  0  1
      jumps  0  1  1  0
      the    0  0  0  0
      horse  1  0  1  0
fox   dog    0  0  0  0
      fox    0  1  0  1
      over   0  0  0  0
      the    0  1  0  1
      cat    0  0  1  0

You can see that dataframe2 contains multiindexes of dataframe1 but it also contains additional multiindexes like horse and cat. Dataframe 2 also doesn't contain all the columns of dataframe 1 as you can see it misses column 3.
I want to subtract dataframe 2 from dataframe 1 in such a way that the function only subtracts the data which is common in both and ignores the rest and the resulting dataframe is in shape of dataframe 2.
Does any know if pandas provides a builtin way of doing this or do I need to construct a function myself. If so, can you point me in the right direction? Any suggestions are highly appreciated. Thank you.
NOTE: This question is similar to another question I posted here apart from the fact that I am not wanting to compare these, instead wanting to do an arithmetic operation of subtraction.

A: IIUC:
In [24]: r = d1.sub(d2, axis=0)

In [25]: r.loc[r.index.intersection(d2.index)]
Out[25]:
             1    2   3    4    5
dog dog   -1.0  1.0 NaN  0.0  1.0
    fox    1.0 -1.0 NaN  0.0 -1.0
    horse  NaN  NaN NaN  NaN  NaN
    jumps  0.0 -1.0 NaN  0.0  0.0
    the    0.0  1.0 NaN  0.0  0.0
fox cat    NaN  NaN NaN  NaN  NaN
    dog    0.0  0.0 NaN  1.0  1.0
    fox    0.0 -1.0 NaN  0.0 -1.0
    over   0.0  1.0 NaN  0.0  0.0
    the    0.0 -1.0 NaN  1.0  0.0

A: I believe you simply want something like:
In [23]: (df2 - df1.drop('3', axis=1)).fillna(df2).dropna()
Out[23]:
             1    2    4    5
dog dog    1.0 -1.0  0.0 -1.0
    fox   -1.0  1.0  0.0  1.0
    horse  1.0  0.0  1.0  0.0
    jumps  0.0  1.0  0.0  0.0
    the    0.0 -1.0  0.0  0.0
fox cat    0.0  0.0  1.0  0.0
    dog    0.0  0.0 -1.0 -1.0
    fox    0.0  1.0  0.0  1.0
    over   0.0 -1.0  0.0  0.0
    the    0.0  1.0 -1.0  0.0

Pandas already automatically aligns on the index, that's part of it's magic, but you just have to fill/drop nans intelligently.
Edit
Whoops, you actually want df1 - df2, but with the shape of df2, a little bit more tricky since then fillna(df1) would prevent us from dropping the right rows, however, you can just use multiply by -1!
In [25]: (df2 - df1.drop('3', axis=1)).fillna(df2).dropna() * -1
Out[25]:
             1    2    4    5
dog dog   -1.0  1.0 -0.0  1.0
    fox    1.0 -1.0 -0.0 -1.0
    horse -1.0 -0.0 -1.0 -0.0
    jumps -0.0 -1.0 -0.0 -0.0
    the   -0.0  1.0 -0.0 -0.0
fox cat   -0.0 -0.0 -1.0 -0.0
    dog   -0.0 -0.0  1.0  1.0
    fox   -0.0 -1.0 -0.0 -1.0
    over  -0.0  1.0 -0.0 -0.0
    the   -0.0 -1.0  1.0 -0.0

Or, if those negative zeros bother you:
In [31]: (-df2 + df1.drop('3', axis=1)).fillna(-df2).dropna()
Out[31]:
             1    2    4    5
dog dog   -1.0  1.0  0.0  1.0
    fox    1.0 -1.0  0.0 -1.0
    horse -1.0  0.0 -1.0  0.0
    jumps  0.0 -1.0  0.0  0.0
    the    0.0  1.0  0.0  0.0
fox cat    0.0  0.0 -1.0  0.0
    dog    0.0  0.0  1.0  1.0
    fox    0.0 -1.0  0.0 -1.0
    over   0.0  1.0  0.0  0.0
    the    0.0 -1.0  1.0  0.0

A: Let us do some thing like
id=df2.index.values.tolist()
dd=df1.loc[list(set(df1.index.values.tolist())&set(id))]
(df2-dd).combine_first(df2).dropna(1)

             1    2    4    5
dog dog    1.0 -1.0  0.0 -1.0
    fox   -1.0  1.0  0.0  1.0
    horse  1.0  0.0  1.0  0.0
    jumps  0.0  1.0  0.0  0.0
    the    0.0 -1.0  0.0  0.0
fox cat    0.0  0.0  1.0  0.0
    dog    0.0  0.0 -1.0 -1.0
    fox    0.0  1.0  0.0  1.0
    over   0.0 -1.0  0.0  0.0
    the    0.0  1.0 -1.0  0.0

A: Use pd.DataFrame.align with the parameter 'inner' to reduce both dataframes to only the common indices.  Then pass results to pd.DataFrame.sub
pd.DataFrame.sub(*df1.align(df2, 'inner'))

           1  2  4  5
dog dog   -1  1  0  1
    fox    1 -1  0 -1
    jumps  0 -1  0  0
    the    0  1  0  0
fox dog    0  0  1  1
    fox    0 -1  0 -1
    over   0  1  0  0
    the    0 -1  1  0

Written in two lines
a, b = df1.align(df2, 'inner')
a - b


text:
Q: Entity Framework Core LINQ expression could not be translated I'm fairly new to EF Core, and I am trying to filter a set of jobs based on whether the appointment date is in the past and the status.
Why would this result in an error?
var maxJobAgeDate = DateTime.Now.AddDays(-14);

JobSummaries.Where(j => DateTime.Parse(j.AppointmentDate) < maxJobAgeDate && j.JobStatus == JobStatus.CompleteSignOffConfirmed);

The error:

The LINQ expression 'DbSet
.Where(j => DateTime.Parse(j.AppointmentDate) < __maxJobAgeDate_0 && (int)j.JobStatus == 4)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

I'm using EF Core.

A: You need to specify the date format while converting in the Non-standard ISO types.
Try this.
JobSummaries.Where(j => DateTime.ParseExact(j.AppointmentDate,"yyyy-MM-dd",CultureInfo.InvariantCulture) < maxJobAgeDate
                && j.JobStatus == JobStatus.CompleteSignOffConfirmed).ToList();

I strongly recommend fixing this at a database level


text:
Q: Replicate Excel's IF and COUNTIF functions in pandas I am trying to replicate the ability of Excel countif and if statements in Pandas.
In Excel, I have the following table:
+---------+-------+------+--------+
| Row/Col |   A   |  B   |   C    |
+---------+-------+------+--------+
|       1 | Name  | Date | Type   |
|       2 | John  | 21/4 | New    |
|       3 | John  | 22/4 | Update |
|       4 | Jacob | 23/6 | New    |
|       5 | Mary  | 24/7 | New    |
|       6 | Jacob | 26/8 | Update |
+---------+-------+------+--------+

In order to get the Type values, I would use the following code in all of column C (for row 2):
=IF(COUNTIF($A2:A2, A2)>1, "Update", "New")

For the same data in a df, how would I implement it, so that I counts only from the first row of the column down, and does not include any row below the row it is calculating for?

A: In panda we have groupby with cumcount
df['C']=df.groupby('A').cumcount().gt(0).map({False:'New',True:'Update'})


text:
Q: HHVM cannot be installed: "packages have unmet dependencies:" I am in Ubuntu 14.04, 64bit and am trying to install HHVM. I have already installed Nginx. When I run the following commands:
sudo apt-get install software-properties-common
sudo apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0x5a16e7281be7a449
sudo add-apt-repository "deb http://dl.hhvm.com/ubuntu $(lsb_release -sc) main"
sudo apt-get update
sudo apt-get install hhvm

I get the following:
hhvm : Depends: libgnutls-deb0-28 but it is not installable
       Depends: libmemcached11 but it is not installable
       Depends: librtmp1 but it is not installable
       Depends: libmagickwand-6.q16-2 but it is not installable

I've tried running the following:
sudo dpkg --configure -a
sudo apt-get clean
sudo apt-get update

I've cleared my sources and re-created them. Synaptic Package Manager shows no broken packages... What am I missing?

A: I solved this by installing Aptitude, to install build-essential:
sudo apt-get install aptitude
sudo aptitude install build-essentials

Then installing some "essentials" i found in a blog post:
sudo apt-get install -y unzip vim git-core curl wget python-software-properties

Then re-installing nginx:
sudo add-apt-repository -y ppa:nginx/stable
sudo apt-get update
sudo apt-get install -y nginx

Then finally installing HHVM:
wget -0 - http://dl.hhvm.com/conf/hhvm.gpg.key | sudo apt-get add -
echo deb http://dl.hhvm.com/ubuntu trusty main | sudo tee /etc/apt/sources.list.d/hhvm.list
sudo apt-get update
sudo apt-get install -y hhvm

A: This sounds very much like the wrong apt repository got added. In particular,
Depends: librtmp1 but it is not installable

The trusty version of HHVM depends on librtmp0 (which does exist for trusty).
Did you actually run the commands as indicated above, including the $(lsb_release -sc) call? Did you accidentally inject the one for vivid first, and apt might still be picking that up?
Can you check your apt configuration, to make sure you have the deb line for trusty and not vivid, and there's only the one apt line?


text:
Q: Can I use Shortcuts to tell me when to leave for a specific appointment based on Map data? I was wondering if anyone knew of an existing Shortcut where I can get the Time that I need to leave My Current location in order to arrive at a specified address at a specified time. So lets say I have a doctors appointment at 6:00 is there a shortcut where I can input the time I need to arrive and the address of my appointment and and the output be the suggested time that I leave from my current location.
Any help is much appreciated.

A: Set up the appointment in Calendar including the actual location as found in maps/
You can then set 2 alerts, one value is Time to leave.
I think the default for the second alert is Time to leave


text:
Q: how to repopulate/recreate autoincrement in mysql I want to know if I can repopulate the autoincrement value in mysql.
Because, I have records that look similar:
ID Name
1  POP
3  OLO
12 lku

Basically , I want a way to update the ID to this
ID Name
1  POP
2  OLO
3  lku

Is there any way to do this in mysql?
Thanks.

A: It's not best practice to fiddle your primary keys - better to let your DB handle it itself. There can be issues if, in between the UPDATE and ALTER, another record is added. Because of this, you must LOCK the table, which might hang other queries and spike load on a busy production server.
LOCK TABLES table WRITE
UPDATE table SET id=3 WHERE id=12;
ALTER TABLE table AUTO_INCREMENT=4;
UNLOCK TABLES

OR - for thousands of rows (with no foriegn key dependencies):
CREATE TEMPORARY TABLE nameTemp( name varchar(128) not null )
INSERT INTO name SELECT name FROM firstTable
TRUNCATE firstTable
INSERT INTO firstTable SELECT name FROM nameTemp

The latter method will only work where you have no foreign keys. If you do, you'll require a lookup table.
CREATE TEMPORARY TABLE lookup( newId INTEGER AUTO_INCREMENT, oldId INTEGER, PRIMARY KEY newId( newId ) );
INSERT INTO lookup (oldId) SELECT id FROM firstTable
[do temp table queries above]

You now have a lookup table with the old to new ids which you can use to update the foreign key dependencies on your other tables (on a test server!)

A: Changing the primary key is a very bad idea as it endangers your referential integrity (what if another table uses the id without having a foreign key with proper "on change"?).
If you really, really have to do it and don't care about bad side-effects:

*

*Create a second table with identical structure

*INSERT INTO new_table (id, [other fields]) SELECT NULL, [other fields] FROM old_table;

*DROP old_table;

*RENAME new_table old_table;

Warning:
This will damage every other table that has foreign keys on this table (but if you had such then you wouldn't be doing this anyways).

A: You may want to try something like...
Create Temporary table MyBackup
(  ID as your autoincrement,
   OldID as Int for backlinking/retention,
   RestOfFields as their type )

insert into MyBackup
(    OldID
     RestOfFields )
select
     ID as OldID,
     RestOfFields
  from
     YourOriginalTable
  order by
     ID  (this is your original ID)

Then you'll have a new table with an autoincrement with new IDs assigned, yet have a full copy of their original ID.  Then, you can do correlated updates against other tables and set the ID = ID where ID = OldID.  By keeping your insert via order by the original ID, it will keep the numbers from replacing out of sequence..  Ex: if your table was orderd as
Old ID = 3, new ID = 1
Old ID = 1, new ID = 3
Old ID = 12, new ID = 2
Your old 3's will become 1's, then the 1's would become 3's, and 12's become 2's
Old ID = 1, new ID = 1
Old ID = 3, new ID = 2
Old ID = 12, new ID = 3
your 3's won't overwrite the higher number, and the 12's won't conflict with the 3's since the threes were already lowered to 2's.


text:
Q: Decoding minus from html I am reading some og tags from sites but I can't seem to decode minus(-) from encoded string.
I tried with HttpUtility.HtmlDecode and HttpUtility.UrlDecode but none of them seem to work. I get – instead on minus.
What is the case with this?

A: What you have is not minus (-), it's a dash (–) which is not the same thing. It's a different character.


text:
Q: Multisite htaccess with domain rewrites The situation is a multisite with SSL and some subsites have their own domain names.
Main site is www.example.com
Subsite is www.example.com/subsite1
Subsite1 has their own name of www.subsite.com
Main site has SSL, subsites should also use SSL
These URLs should do:
http://www.example.com changed to https://www.example.com
http://example.com changed to https://www.example.com
https://example.com changed to http://www.example.com
https://www.subsite.com changed to https://www.subsite.com
https://example.com/subsite1 changed to https://www.subsite.com

I have existing htaccess rule to force SSL
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

The http://subsite.com does not route to https://www.subsite.com , it goes to http://www.example.com .
Site settings in multisite network admin (and that site's wp-options URLs) are set to 'www.subsite.com'.
I have also tried this, it doesn't work for all cases
RewriteEngine On
#RewriteCond %{HTTP_HOST} (?!^www\.)^(.+)$ [OR]
#RewriteCond %{HTTPS} off
#RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L]

What htaccess rules should I have to perform the above rewrites?  And what URL should I put in the substites Network Site settings (and wp-options for that subsite)?
(Note: I realize this is not entirely WP question, but it relates to how WP multisite works with htaccess and subsites having their own domain names, so it was posted here.)


text:
Q: My minimap is not working and my pausemenu is not loading My minimap is not working and my pausemenu is not loading. I changed XML but still my pausemenu is not working. I searched the minimap problem, it said

Settings, click Display, and check if Radar is set to on. If it isn't, then set it to on.

I tried it but it did not work.


text:
Q: Excel 2010 - clearing autofilter conflicts with setting font color in VBA I have a client who uses Excel 2010 and has no plans to upgrade.
I've built a fairly complex spreadsheet for the client that includes several tables and a significant amount of VBA code.  Some of the columns in the tables permit autofilter and some of the custom formulas for the table cells change the cell's font color.
We're seeing a conflict between clearing the autofilter and the VBA code that sets the font color.  Specifically, if the filter is cleared, then an error

-2147417848 Method 'Color' of object 'Font' failed

occurs in the VBA and, more importantly, from that point on the border around any selected cells is no longer shown which makes the sheet difficult to use.  We've also seen corruption of the workbook.  Even if the error is ignored,  the selection border problem occurs.
I've stripped down the large spreadsheet to a very simple one to illustrate.  Obviously this is not the real world code but it does exhibit the same problem.

As can be seen, the formula in cell B2 is "=changeColor(A2)"
The code for "changeColor()" is:
Public Function changeColor(t As String) As String
    changeColor = t
    If t = "Fred" Then
        Application.Caller.Font.Color = vbBlue
    Else
        Application.Caller.Font.Color = vbRed
   End If
 End Function

This all works perfectly until an autofilter is added and then removed.  i.e.:

*

*Click on the down arrow in the Name column header and amend the filter to exclude "Sheila".  This works as expected and row 3 is no longer visible.

*Click on the down arrow again and "Clear filter from Name".  The row is now visible BUT selecting cells with the mouse no longer shows a border around those cells (although they are in fact selected).  The VBA Immediate window confirms that the "Method 'Color' of object 'Font' failed" error occurred.
If calculation is set to manual while the autofilter is cleared, then no problem is seen.  If "changeColor" is modified so that the Font.Color property isn't changed, then no problem is seen.
Does anyone have any idea how to avoid this situation?  It does not occur in Excel 2013 so presumably is a 2010 "feature".   Should I be using different code to set the color, or is there a way to detect that the code is being run while a filter is being cleared?  Any ideas would be greatly appreciated.


text:
Q: Display Floor plane or Indoor map on Mapkit I have a floor-plan or indoor map. I need to represent this map on UI having the basic map functionality. I actually wanted to use MapKit, but the max zoom level is not enough to view that image.
Same problem with Google map and with Mapbox.
My first question, Is it possible to use the Mapkit to display only that/a Image/map?
I tried overlay, but zoom level is the same problem, if i set the image according to the lat-lon the overlaid image on the map is very small. Another solution was to set the image/map by any lat-long and make it bigger on the map, but this seems very weird as outside the image(indoor map), the default map view is visible.
My second question, If Mapkit can not be used to display the single image, then what is my best shot?
I started with the UIScrollView, but it will be a long way to finish those map functionality, is there any third party lib to solve my problem.
My target is to represent the indoor map or floor-plan on a view which will provide all the basic map functionality(zoom, rotate, distance measurement, dropping a pic etc.).
Thank you.


text:
Q: How to read from MS access to JPS I have created this servlet that is used as currency conversion.It converts three currencies (SAR, USD, Euro). I have Access table that has fields to read from with the conversion values .how can I convert this servlet to JSP?..
 public class cur_exchange extends HttpServlet {
    String from = "";
    String to = "";
    double amount = 0.0;
    String message = "";
    double total = 0.0;
    @Override
    public void init() {
    try {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      System.out.println("JDBC driver loaded");
    }
    catch (ClassNotFoundException e) {
      System.out.println(e.toString());
    }
  }
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        display_form(false, request, response, false);
  }
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

        from = request.getParameter("from");
        to = request.getParameter("to");
        boolean error = false;
        try
        {
            amount = Double.parseDouble(request.getParameter("amount").toString());
        }
        catch (Exception e) {
                message = "Error: Please Type Valid Number To Convert";
                error = true;
            }
        if(from.equals(to))
        {
            total = amount;
            display_form(true, request, response, false);
        }
        else
        {
            try {
                  Connection con = DriverManager.getConnection("jdbc:odbc:MS Access Database");
                  System.out.println("got connection");
                  Statement s = con.createStatement();
                  String sql = "SELECT RATE FROM EXCHANGE_RATE WHERE FROM_CUR='"+from+"' AND TO_CUR='"+to+"'";
                  ResultSet rs = s.executeQuery(sql);
                  if (rs.next()) {
                      total = amount * Double.parseDouble(rs.getString(1));
                  }
                  else
                  {
                      s = con.createStatement();
                      sql = "SELECT RATE FROM EXCHANGE_RATE WHERE FROM_CUR='"+to+"' AND TO_CUR='"+from+"'";
                      rs = s.executeQuery(sql);
                      if (rs.next())
                      {
                            total = amount / Double.parseDouble(rs.getString(1));
                      }
                  }
            }
            catch (SQLException e) {
                message = "Error." + e.toString();
                error = true;
            }
            catch (Exception e) {
                message = "Error." + e.toString();
                error = true;
            }
        rs.close();
        s.close();
            con.close();

            if (error)
                display_form(true , request, response, true);
            else
                display_form(true, request, response, false);
        }
    }

    public void display_form(boolean populated, HttpServletRequest request, HttpServletResponse response, boolean error) throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        out.println("");
        out.println("");
        out.println("");
        out.println("");
        out.println("");
        if (error)
            out.println("
"+message+"

");
        out.println("
Currency Converter
");
        out.println("<form action='cur_exchange.java' method='post'>");
        out.println("

From:");
        out.println("<select name='from'>");
        if (populated)
        {
            if (from.equals("SAR"))
            {
                out.println("<option selected='selected'>SAR</option>");
            }
            else
            {
                out.println("<option>SAR</option>");
            }
            if (from.equals("$"))
            {
                out.println("<option selected='selected'>$</option>");
            }
            else
            {
                out.println("<option>$</option>");
            }
            if (from.equals("EURO"))
            {
                out.println("<option selected='selected'>EURO</option>");
            }
            else
            {
                out.println("<option>EURO</option>");
            }
        }
        else
        {
            out.println("<option>SAR</option>");
            out.println("<option>$</option>");
            out.println("<option>EURO</option>");
        }
        out.println("</select>");
        out.println("

To:");
        out.println("<select name='to'>");
        if (populated)
        {
            if (to.equals("SAR"))
            {
                out.println("<option selected='selected'>SAR</option>");
            }
            else
            {
                out.println("<option>SAR</option>");
            }
            if (to.equals("$"))
            {
                out.println("<option selected='selected'>$</option>");
            }
            else
            {
                out.println("<option>$</option>");
            }
            if (to.equals("EURO"))
            {
                out.println("<option selected='selected'>EURO</option>");
            }
            else
            {
                out.println("<option>EURO</option>");
            }
        }
        else
        {
            out.println("<option>SAR</option>");
            out.println("<option>$</option>");
            out.println("<option>EURO</option>");
        }
        out.println("</select>
");
        if(populated)
        {
            out.println("
Amount: <input name='amount' type='text' size='25' maxlength='30' id='amount' value='"+amount+"' />
");
        }
        else
        {
            out.println("
Amount: <input name='amount' type='text' size='25' maxlength='30' id='amount' />
");
        }
        if(populated)
        {
            out.println("
Result: <input name='result' type='text' size='25' maxlength='30' id='result' disabled='disabled' value='"+total+"'/>
");
        }
        else
        {
            out.println("
Result: <input name='result' type='text' size='25' maxlength='30' id='result' disabled='disabled' />
");
        }
        out.println("
<input type='submit' value='Convert'/>");
        out.println("</form>");
        out.println("");
        out.println("");
        out.println("");
    }
}

A: *

*Read one of these tutorials

*Rewrite as a JSP file.


text:
Q: add anchor text on url PHP after click the submit button on my form, how do I add the anchor "#work" in the url without reloading the page?
example: www.test.it/#work
i use header('Location: #work'); but refresh my page.
Update:
I use "jessica" solution:
I think the page is reloaded
But don't work, ca see here: http://www.substellar.it/ftende/contatti/
I think the page is reloaded

A: Just add #work to the action in form for it to show up in the link.
<form action = "url#work">


text:
Q: ordering query by grouped, calculated field In an MS Access 2010 database, I am trying to design a query that will return results ordered by the ratio of the sums of two grouped fields.  But my attempts so far are resulting in an immediate overflow error, before even the query has had a chance to try running.  How do I fix the code below so that my resulting query produces results that are ordered by the calculated field?
Here is the table structure:
Table1
    ID
    NAME

Table2
    ID
    SUBSET
    TOT

Here is the query that causes the overflow dialog box:
SELECT [Table1].[NAME], SUM([Table2].[SUBSET]) As SubsetDays,
    SUM([Table2].[TOT]) As TotalDays,
    ROUND( (SUM([Table2].[SUBSET]) / SUM([Table2].[TOT]) ) , 4) As SubsetPercent
  FROM [Table2] INNER JOIN [Table1] ON [Table2].ID = [Table1].ID
  GROUP BY [Table1].[NAME]
  ORDER BY ROUND( (SUM([Table2].[SUBSET]) / SUM([Table2].[TOT]) ) , 4) DESC;

EDIT#1
As per @TonyStark's comment, I tried changing ORDER BY ROUND( (SUM([Table2].[SUBSET]) / SUM([Table2].[TOT]) ) , 4) DESC; to ORDER BY 4 DESC;, but this change still results in the overflow error.  The only way I can get the query to run is to remove the ORDER BY clause entirely, which defeats the purpose of this question.

EDIT#2
I tried the code suggested in EvDev's answer, but his code also still results in the same overflow error.  There are perhaps 2000 rows in each table, though one of the tables has 250 fields.  The datatypes are text for NAME and number for SUBSET, TOT, and ID.

A: Writing up Answer from comments/troubleshooting:
Overflow in Access is often caused by a division by zero error. In your query:
SELECT [Table1].[NAME], SUM([Table2].[SUBSET]) As SubsetDays,
    SUM([Table2].[TOT]) As TotalDays,
    ROUND( (SUM([Table2].[SUBSET]) / SUM([Table2].[TOT]) ) , 4) As SubsetPercent
  FROM [Table2] INNER JOIN [Table1] ON [Table2].ID = [Table1].ID
  GROUP BY [Table1].[NAME]
  ORDER BY ROUND( (SUM([Table2].[SUBSET]) / SUM([Table2].[TOT]) ) , 4) DESC;

You twice divide by SUM([Table2].TOT). Once in the SELECT clause and once in the ORDER BY clause.
You can adjust those formulas to look for a 0 in the denominator before dividing to avoid the overflow error. Something like:
iif(SUM([Table2].[TOT])=0, <some constant value>, ROUND( (SUM([Table2].[SUBSET]) / SUM([Table2].[TOT]) ) , 4))

The reason that it didn't throw the error when you removed the ORDER BY clause is because Access doesn't calculate the results for every single record unless it needs to for display, or for ORDER BY or some other pre-aggregation type logic. If you had tried to sort the results after running the query without the ORDER BY clause, you would have then received the overflow error.

A: I was able to run your code as is so your problem might be sheer volume of records or something to do with datatypes.  Either way I created an other version of your code using a subquery that may work.
SELECT * from

(select [Table1].[NAME], SUM([Table2].[SUBSET]) As SubsetDays,
SUM([Table2].[TOT]) As TotalDays,
ROUND( (SUM([Table2].[SUBSET]) / SUM([Table2].[TOT]) ) , 4) As SubsetPercent
FROM [Table2] INNER JOIN [Table1] ON [Table2].ID = [Table1].ID
GROUP BY [Table1].[NAME] )

order by SubsetPercent DESC


text:
Q: Creating a table in Mysql with phpadmin I keep getting errors when trying to create a  products table for a  database I'm building.
Here is the code I've tried:
CREATE TABLE Products (
    ProductId int NOT NULL auto_increment primary key,
    Name varchar(255) NOT NULL,
    Price decimal(19, 4),
    on_hand integer,
    supp_id int,
    FOREIGN KEY (supp_id) REFERENCES Suppliers(supp_id)
);

I am  getting this error code:

#1005 - Can't create table 'computer_wholesale.products' (errno: 150

Any help would be  greatly appreciated.

A: I believe your Suppliers table is missing an index, which is required to use a FOREIGN KEY with.


text:
Q: Taking names from Multiple Sheets and having a function Count the number of times the name appears on the different sheets Practically I have around 10 different sheets with names on these sheets in column A. I would like to in a separate sheet have the name and the number of times the name is found in the 10 other sheets. For example, the name Tom is posted three times in sheet-1, four times in sheet-2 and one time in sheet-3. I would like in a new sheet to be able to type "Tom" into column A and then in column B next to Tom show the number of times it was found in the multiple sheets. This needs to be a function that I can put a new name into column A and then it searches for the number of times it is found in the 10 different sheets.
I have done something similar but think I must be formatting wrong for multiple sheets. The function I'm using is =COUNTIF(Sheet1!A2:A,Sheet2!A2:A) this works for comparing just the 2 sheets and will show a correct number but when I try formatting for multiple sheets it will not work. enter image description here this is kind of a what the solution would be like except of course in different sheets. Also note that when adding a new name to the "master list" it should try to find the name. Sheets 1,2, and 3 will be updated automatically so manually I would write the name in the master, and it then gives me the number of times the newly added name appears.

A: You could try the following in your master sheet to get a list of all names present in all sheets against their count:
=query({Sheet1!A2:A;Sheet2!A2:A;...;SheetN!A2:A},"select Col1,count(Col1) where Col1 is not null group by Col1",0)

N.B. we are using an array literal (curly brackets & semicolons) to union the vertical ranges from each source sheet into one long vertical range to then feed into the QUERY function. If any of the source sheets changes then the master sheet will automatically update.


text:
Q: Presenting PHP source on the Web I've written a patch for a GPL'ed JavaScript library. To check how the patch works one needs sample CGI (or PHP) backend.
I want to write a demo PHP to show that my JS works and put the open code on my site.
The question: What it the best way to have PHP on server both executed and viewed as the source?
Note that recently I have ordered a Virtual Private Server with a 5 Gb disk, so there are no troubles with installing new software (if any needed) for me.

A: The official PHP website itself , I believe, is a good example.
For every page, you have a link to its source code at the bottom of it. For example the download page has its source available publicly; by the way, the page which displays the source can display its own source as well.

As a side note, while the concept of showing both the runtime result of the page and its source code is interesting on php.net, make sure to watch only the concept itself, not the source code of the downloads page. After browsing it, I'm quite surprised about how terrible it is.


text:
Q: SSRS Reportviewer in MVC, removing iframe scrollbars by auto-sizing iframe to fit report I have pieced together information on eliminating iframe scrollbars in favour of the browser scroll bars when rendering a reportviewer in an iframe. MVC does not support rendering a report viewer in a view, hence the need for an iframe.
Edit: i struggled to find this solution (below) hence i thought i would share.

In the aspx page (the page that will be rendered in the iframe)
$(function () {//jQuery document.ready
    // attach an event handler, whenever a 'property' of the reportviewer changes, the function will be called to adjust the height of the iframe
    Sys.Application.add_load(function () {
        $find("ReportViewer").add_propertyChanged(viewerPropertyChanged); // $.find("ReportViewer") will return the reportviewer with id "ReportViewer"
    });

    function adjustIframeSize() {
        // you can play around with these figures until your report is perfect
        var extraHeightToAvoidCuttingOffPartOfReport = 100;
        var extraWidthToAvoidCuttingOffPartOfReport = 10;

        // '#ReportViewer_fixedTable' is a portion of the report viewer that contains the actual report, minus the parameters etc
        var reportPage =  $('#ReportViewer_fixedTable');

        // get the height of the report. '#ParametersRowReportViewer' is that top part that contains parameters etc
        var newHeight = reportPage.height() + $('#ParametersRowReportViewer').height() + extraHeightToAvoidCuttingOffPartOfReport;

        // same for width
        var newWidth = reportPage.width() + extraWidthToAvoidCuttingOffPartOfReport;

        // get iframe from parent document, the rest of this function only works if both the iframe and the parent page are on the same domain
        var reportIframe = $('#ReportViewerFrame', parent.document);

        // just make sure that nothing went wrong with the calculations, other wise the entire report could be given a very small value for height and width, thereby hiding the report
        if(newHeight>extraHeightToAvoidCuttingOffPartOfReport)
            reportIframe.height(newHeight);
        if (newWidth > extraWidthToAvoidCuttingOffPartOfReport)
            reportIframe.width(newWidth);
    }

    function viewerPropertyChanged(sender, e) {
        // only change the iframe dimensions when 'isLoading'
        if (e.get_propertyName() == "isLoading") {
            if (!$find("ReportViewer").get_isLoading()) {
                adjustIframeSize();
            }
        }
    };
});

A: Solved a similar problem using a set of extensions in ReportViewer for MVC.
@Html.ReportViewer(
   ViewBag.ReportViewer as Microsoft.Reporting.WebForms.ReportViewer,
   new { scrolling = "no" })


text:
Q: How to add another DataSource in prompt Query? I want to add another data source in Query prompt.
When I launch a form I open the prompt Query.
In my form init method I have:
QueryRun queryRun;

super();

queryRun = new QueryRun(TableA_ds.query());
if (! queryRun.prompt())
{
     element.close();
}

TableA_ds.query(queryRun.query());

In my Form data source, in init method, I have put this code to set my query range:
tableA_ds.query().dataSourceTable(tablenum(TableA)).addRange(fieldnum(TableA,FieldtableA)).value(SysQuery::valueUnlimited() );

I want to add another data source (another table) - TableB.
I used this code:
purchLine_ds.query().dataSourceTable(tablenum(TableB)).addRange(fieldnum(TableB,FieldtableB)).value(SysQuery::valueUnlimited() );

But when I launch a Form I view only record query range from TableA
Relation of TableA to TableB is on field PurchId.
I want to see two ranges. Can someone help me?
Thanks for your time.
Enjoy!

A: I think you can add another datasource with:
    purchLine_ds.query().dataSourcetable(TableA).addDatasource(tablenum(TableB);
    purchLine_ds.query().dataSourcetable(TableB).relations(true)

A: Thanks Alex , for your Help,
I used this code,
in my Form init Method :
query q = new Query();
QueryBuildDataSource qbds, qbds2;
QueryRun queryRun;

qbds = Q.addDataSource(tableNum(TableA));
qbds.addRange(fieldnum(TableA,Field1TableA)).value(SysQuery::valueUnlimited());
qbds2 = qbds.addDataSource(tableNum(TableB));
qbds2.relations(true);

and launch the query ,
work well,
enjoy!


text:
Q: How to compute distance from elements of an array in python? I have a numpy array where each element is a position, like this :
array([[1, 1, 0. ],
       [2 , 2, 0. ],
       [3 , 3, 1 ]])

And I want to compute the distance between each element. So here, the expected output is :
[0, 1.414213, 1.732050]

The distance is calculated as it follows :
For the first element it is 0 because ther isn't any element before. For the second it is sqrt((2 - 1)**2 + (2 - 1)**2 + (0 - 0)**2)) and so on
However, there is a lot of elements (around some thousands), and this operation is repeated multiple times. So I need a way to execute this very fast.
I was wondering if there is a library (or even better a numpy function) that could solve my problem. I used cdist from scipy.spatial.distance before, but it doesn't work anymore (I have problems with scipy dependencies), so I'm searching for another way.

A: Here's a pure numpy solution. a is your input vector array. You first create the distances component wise, then square them, then sum them over each row, and then get the sqrt of each of those sums.
np.sqrt(np.sum((a[1:] - a[:-1])**2, axis=1))

array([ 1.41421356,  1.73205081])


text:
Q: Memory efficiency in If statements I'm thinking more about how much system memory my programs will use nowadays. I'm currently doing A level Computing at college and I know that in most programs the difference will be negligible but I'm wondering if the following actually makes any difference, in any language.
Say I wanted to output "True" or "False" depending on whether a condition is true. Personally, I prefer to do something like this:
Dim result As String

If condition Then
   Result = "True"
Else
   Result = "False"
EndIf

Console.WriteLine(result)

However, I'm wondering if the following would consume less memory, etc.:
If condition Then
   Console.WriteLine("True")
Else
   Console.WriteLine("False")
EndIf

Obviously this is a very much simplified example and in most of my cases there is much more to be outputted, and I realise that in most commercial programs these kind of statements are rare, but hopefully you get the principle.
I'm focusing on VB.NET here because that is the language used for the course, but really I would be interested to know how this differs in different programming languages.

A: The main issue making if's fast or slow is predictability.
Modern CPU's (anything after 2000) use a mechanism called branch prediction.
Read the above link first, then read on below...
Which is faster?
The if statement constitutes a branch, because the CPU needs to decide whether to follow or skip the if part.
If it guesses the branch correctly the jump will execute in 0 or 1 cycle (1 nanosecond on a 1Ghz computer).
If it does not guess the branch correctly the jump will take 50 cycles (give or take) (1/200th of a microsecord).
Therefore to even feel these differences as a human, you'd need to execute the if statement many millions of times.
The two statements above are likely to execute in exactly the same amount of time, because:

*

*assigning a value to a variable takes negligible time; on average less than a single cpu cycle on a multiscalar CPU*.

*calling a function with a constant parameter requires the use of an invisible temporary variable; so in all likelihood code A compiles to almost the exact same object code as code B.

*) All current CPU's are multiscalar.
Which consumes less memory
As stated above, both versions need to put the boolean into a variable.
Version A uses an explicit one, declared by you; version B uses an implicit one declared by the compiler.
However version A is guaranteed to only have one call to the function WriteLine.
Whilst version B may (or may not) have two calls to the function WriteLine.
If the optimizer in the compiler is good, code B will be transformed into code A, if it's not it will remain with the redundant calls.
How bad is the waste
The call takes about 10 bytes for the assignment of the string (Unicode 2 bytes per char).
But so does the other version, so that's the same.
That leaves 5 bytes for a call. Plus maybe a few extra bytes to set up a stackframe.
So lets say due to your totally horrible coding you have now wasted 10 bytes.
Not much to worry about.
From a maintainability point of view
Computer code is written for humans, not machines.
So from that point of view code A is clearly superior.
Imagine not choosing between 2 options -true or false- but 20.
You only call the function once.
If you decide to change the WriteLine for another function you only have to change it in one place, not two or 20.
How to speed this up?
With 2 values it's pretty much impossible, but if you had 20 values you could use a lookup table.
Obviously that optimization is not worth it unless code gets executed many times.

A: If you need to know the precise amount of memory the instructions are going to take, you can use ildasm on your code, and see for yourself. However, the amount of memory consumed by your code is much less relevant today, when the memory is so cheap and abundant, and compilers are smart enough to see common patterns and reduce the amount of code that they generate.
A much greater concern is readability of your code: if a complex chain of conditions always leads to printing a conditionally set result, your first code block expresses this idea in a cleaner way than the second one does. Everything else being equal, you should prefer whatever form of code that you find the most readable, and let the compiler worry about optimization.
P.S. It goes without saying that Console.WriteLine(condition) would produce the same result, but that is of course not the point of your question.


text:
Q: WebRequest returning more source than Browser > view source I am writing a Selenium utility in C# to help with automated testing. I may be missing something completely obvious here, but why is it that if I send an HttpWebRequest off to a server and retrieve the response stream, I end up with more source (i.e more mappable WebElements for Selenium) than I get when I right-click - view page source in my browser?
This means that I am mapping elements that the Selenium driver cant find come runtime.
Me so confuse :S
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());

var src = sr.ReadToEnd();

A: There are a number of possibilities. One likely culprit is the difference in the information you're sending to the server. Browsers typically send various headers, cookies, etc., that a web request does not have unless you explicitly add it.
For example, when I hit www.google.com with my web browser, I get stuff from Google Plus, and I get the fanciest experience possible because I'm on an evergreen browser. Roughly 139000 characters appear in my View Source page.
However, when I do a web request to the same URL (using the following code), I get only 45000 characters in the response stream:
async void Main()
{
    var result = await GetTextAsync("https://www.google.com");
    Console.Write(result.Length);
}

public async Task<string> GetTextAsync(string url){
    var result = await WebRequest.Create(url).GetResponseAsync();
    using (var stream = result.GetResponseStream())
    using (var reader = new StreamReader(stream))
    {
        return await reader.ReadToEndAsync();
    }
}

I suspect that if I were to set the WebRequest to send all the same cookies and headers that Chrome is sending to Google, my results would be much more similar.


text:
Q: How can I make Minimax/Alpha-Beta pruning prioritize shorter paths? I am having problems regarding my implementation of the minimax algorithm in a chess engine. How can I make the algorithm favor the shortest paths to the win?
Take this configuration of the board as an example:

.
The best move here would be to move the queen on the last line, but if the algorithm has a higher depth of search it doesn't matter if the checkmate occurs "faster".

A: A few fairly straightforward changes:

*

*Change the return type of the search function, so that instead of returning a pair like (move, q) where q is a measure of how good the move is, it returns a triple like (move, q, m) where m is the length of the sequence following that move.

*Change the return statements to include the correct sequence length; either 0 for an immediate game end, or (m + 1) where m is the length of the followup sequence found by a recursive call.

*Use the sequence length as a tie-breaker to compare moves with equal q; lower m is preferred.

*If you are short-circuiting by returning a winning move as soon as one is found, change the condition for this so that only an immediately-winning move short-circuits.

Note that this will generally make the algorithm less efficient, since you have to explore more branches after finding a winning move in case there is a quicker winning move in the unexplored branches.


text:
Q: C# WPF Auto Resize Window When Taskbar Height Changed I have a WPF window which has these properties:
-ResizeMode=NoResize
-WindowStyle=None
I made every functionality of a normal window but i can't figure out how can i make  window auto resize itself(when it's maximized) when taskbar's height changes. (Like Microsoft Visual Studio 2017 Window).
I can manually maximize my window but if I hide taskbar there is an empty space between my window and bottom of screen.
Is there any event fired when working area changes?

A: For your problem you can use SystemParameters.WorkArea.
Initially set the MaxHeight of your MainWindow.
MaxHeight="{Binding Height, Source={x:Static SystemParameters.WorkArea}}"

Register to the SystemParameters.StaticPropertyChanged in the codebehind of the MainWindow to receive changes and update your window size.
SystemParameters.StaticPropertyChanged += (sender, args) =>
{
    if (args.PropertyName == nameof(SystemParameters.WorkArea))
    {
         this.Dispatcher.Invoke(() =>
         {
             MaxHeight = SystemParameters.WorkArea.Height;
             Height = SystemParameters.WorkArea.Height;
             WindowState = WindowState.Normal;  // Updates the windows new sizes
             WindowState = WindowState.Maximized;
         });
    }
};

A: Handle the WM_GETMINMAXINFO message for your window, and do whatever re-sizing you need to do
    public MainWindow()
    {
        InitializeComponent();
        SourceInitialized += new EventHandler(win_SourceInitialized);
    }

    private void win_SourceInitialized(object sender, EventArgs e)
    {
        System.IntPtr handle = (new WinInterop.WindowInteropHelper(this)).Handle;
        WinInterop.HwndSource.FromHwnd(handle).AddHook(new WinInterop.HwndSourceHook(WindowProc));
    }

    private const int WM_GETMINMAXINFO = 0x0024;
    private static System.IntPtr WindowProc(
          System.IntPtr hwnd,
          int msg,
          System.IntPtr wParam,
          System.IntPtr lParam,
          ref bool handled)
    {
        switch (msg)
        {
            case WM_GETMINMAXINFO: //https://learn.microsoft.com/en-us/windows/win32/winmsg/wm-getminmaxinfo
                WmGetMinMaxInfo(hwnd, lParam); // <------  Do what you need to here   ---------->
                handled = true;
                break;
        }

        return (System.IntPtr)0;
    }

Note that if you are a borderless, not-resizable window, you may also need to get the monitor info (via the Win32 GetMonitorInfo) and restrict your application to the work area of the monitor it is on.  On our systems, windows does not correctly size the window for 1900x1200 monitors (it makes it too tall, so we have to set the MaxHeight based on the Monitor Info, and pay attention for that to change if the taskbar is resized by continuing to watch the WM_GETMINMAXINFO messages).
This blog can probably help with that if you have those issues as well:
https://blogs.msdn.microsoft.com/llobo/2006/08/01/maximizing-window-with-windowstylenone-considering-taskbar/


text:
Q: Issue accessing class variable from thread The code below is meant to take an arraylist of product objects as an input, spun thread for each product(and add the product to the arraylist 'products'), check product image(product.imageURL) availability, remove the products without images(remove the product from the arraylist 'products'), and return an arraylist of products with image available.
package com.catgen.thread;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.catgen.Product;
import com.catgen.Utils;

public class ProductFilterThread extends Thread{

    private Product product;
    private List<Product> products = new ArrayList<Product>();

    public ProductFilterThread(){
    }

    public ProductFilterThread(Product product){
        this.product = product;
    }

    public synchronized void addProduct(Product product){
         System.out.println("Before add: "+getProducts().size());
         getProducts().add(product);
         System.out.println("After add: "+getProducts().size());
    }

    public synchronized void removeProduct(Product product){
         System.out.println("Before rem: "+getProducts().size());
         getProducts().remove(product);
         System.out.println("After rem: "+getProducts().size());
    }

    public synchronized List<Product> getProducts(){
        return this.products;
    }

    public synchronized void setProducts(List<Product> products){
        this.products = products;
    }

    public void run(){
        boolean imageExists = Utils.fileExists(this.product.ImageURL);
        if(!imageExists){
            System.out.println(this.product.ImageURL);
            removeProduct(this.product);
        }
    }

    public List<Product> getProductsWithImageOnly(List<Product> products){
        ProductFilterThread pft = null;
        try{
            List<ProductFilterThread> threads = new ArrayList<ProductFilterThread>();
            for(Product product: products){
                pft = new ProductFilterThread(product);
                addProduct(product);
                pft.start();
                threads.add(pft);
            }
            Iterator<ProductFilterThread> threadsIter = threads.iterator();
            while(threadsIter.hasNext()){
                ProductFilterThread thread = threadsIter.next();
                thread.join();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("Total returned products = "+getProducts().size());
        return getProducts();
    }
}

Calling statement:
displayProducts = new ProductFilterThread().getProductsWithImageOnly(displayProducts);

Here, when addProduct(product) is called from within getProductsWithImageOnly(), getProducts() returns the list of products, but that's not the case(no products are returned) when the method removeProduct() is called by a thread, because of which the products without images are never removed. As a result, all the products are returned by the module whether or not the contained products have images.
What can be the problem here?
Thanks in advance.
James.

A: You're creating a new ProductFilterThread each iteration in the loop:
new ProductFilterThread(product);

Each ProductFilterThread has its own
private List<Product> products = new ArrayList<Product>();

So when you, in the run method, do
removeProduct(this.product);

you're removing the product from it's own products instance.
I suggest you design it differently, by perhaps giving the products-list the thread should work with, as argument to the ProductFilterThread:
private List<Product> products;

public ProductFilterThread(List<Product> products) {
    this.products = products;
}

But I must say that you should think carefully when working with multiple threads like this. You need to synchronize the access to the data structures carefully.

A: If you want you products list to be shared by all Filter Threads then you'll have to make it static. Fields are confined to a single thread.
Another remark - maybe you should rewrite your getter/setter methods for products to export an unmodifiable list and to read the input in a newly created list. Otherwise this can be the cause for multiple headaches in this multithreaded design (just imagine another thread 'getting' the list and modifying it while the filtering is active..)


text:
Q: Is it possible tests CSS stylesheets with Behat + Mink? Is there some way how to test css parameters (coming from css stylesheet) of some element? E.g. color of paragraph. Or background-color of div etc...
I know that selenium2 test framework can do this, but in Behat + Mink with selenium2 driver I cannot find a way how to do it.
Thanks in advance.

A: Yes, you would need to use Selenium2 driver along with Behat and Mink + custom JS calls to verify specific styles. The below example (Behat 3) uses jQuery to assert that the div.myClass color property is as expected. It sends script to Selenium, which evaluates it and returns the result, which you can process in PHP as usual.
<?php

class MyContext extends RawMinkContext
{

    /**
     * @Then /^The div.myClass color should be black$/
     */
    public function assertCssValue()
    {

        // JS script that makes the CSS assertion in the browser.

        $script = <<<JS
            (function(){
                return $('div.myClass').css('color') === 'rgb(0, 0, 0)';
            })();
JS;

        if (!$this->getSession()->evaluateScript($script)) {
            throw new Exception();
        }
    }
}

You can easily extend this into a more generic instance that will do all different kinds of assertions, but most logic will be in JS.
Besides there are other CSS testing frameworks / alternatives like PhantomCSS, which in theory should work with PhantomJS via Selenium Driver and Mink. Google "css testing framework" for that…