text:
Q: How to re-estimate a theoretical outcome knowing rng is imperfect I have 3 regular dice with six sides. I am playing a game where I win when I match all three dice to the same side. My expected shannon bits of entropy H(X) evaluates to 7.754887502 bits. However, my dice aren't very good as a random number generator and the entropy is actually measured at 6.965784285. How do I recalculate my new theoretical win rate?
$$
P_{expected} = (\frac 1 6) ^ 2
$$

A: First, I believe $P_{expected}=(\frac{1}{6})^2$ because it doesn't matter what the first die is, just that the other 2 match. The value you give for $P_{expected}$ is the value for a specific value, say, 6. There are six such values, so $(\frac{1}{6})^3•6=(\frac{1}{6})^2$.Second, there is a difference between theoretical probability and experimental probability. I wouldn't recalculate my theoretical probability; I would re-run my experiment again (and again and again), updating the experimental probability by averaging the results. If your experimental probability continues to differ significantly from your theoretical probability, I wouldn't change the theoretical model; I would get better dice. :)


text:
Q: Facebook javascript SDK FB.login is not working in Facebook iFrame We are using Facebook JavaScript SDK to authenticate our Facebook application. The application is configured with the Canvas URL as http://facebook.elgifto.com/Home/Index/. Following is the code we are using to authenticate the Facebook user.

<fb:login-button onlogin="initiateLogin()" perms="email,user_about_me,user_birthday,friends_about_me,friends_birthday">Login with Facebook</fb:login-button>

The above code is not working in the Facebook when accessed as http://apps.facebook.com/giftguru. However we are able to access it through http://facebook.elgifto.com/Home/Index

A: The issue is related to pop-up blocking by browser. (the fact that is working for you outside of Facebook is probably because you're allowed to do so sometimes before, for me it's blocked as well as within application).
You should never call FB.login without interaction from user (like element click or form submit) to ensure browser isn't blocking log-in window.
Update:
You mixing many things here:

*

*Page on http://facebook.elgifto.com/Home/Index is using Application #316853928368079 (this app and have no namespace!)

*Your URL for OAuth Dialog have ' (apostrophe) around client_id which is wrong!

*OAuth Dialog isn't working (probably also due to app settings, App Domain?)

*Application located on http://apps.facebook.com/giftguru is Application #83808922524 and have wrong Canvas URL! Proof:

A:

Login with Facebook

A: Also check if your app on deveopers.facebook.com isn't in sandbox mode. I had an issue login worked fine with my main account (which was app admin), but not with other facebook accounts. Later I realized fb app was still in sandbox mode and I had to add each account who was testing as Tester or Developer or disable sandbox mode.

A: Facebook suddenly switched from using their Facebook dialog method to display the authentication window to old-fashioned popup-windows today. Until now, popup windows have only been used when running apps outside a Facebook tab/canvas. This means that you can no longer run FB.login on load and use a click event instead to avoid popup blockers.
The only documentation from Facebook we've found on this is at https://developers.facebook.com/docs/concepts/login/permissions-login-dialog/, but apparently, this popup-window method has been available for games for several weeks now.

redpajama_set_name: RedPajamaStackExchange


text:
Q: The most efficient way to access a mysql database extracting multiple data for website I'm running a classified ads page, i'm using mysql with php.
my ads table as a simplified form is something like:
ad id -> int
ad title -> text
ad description  -> text
ad description  -> text
ad type -> boolean (if 0 is a private add, if is 1 is abusiness ad)
ad op -> boolean  if zero is a used item if 1 is a new item)

What I whant is to get the number of private and public ads
and the number of used and new items without making 4 calls to the database, is that even possible?
Right now I'm making 5 calls, since I show 20 ads per page
my calls to the database are:

*

*get the data of the 20 ads using select * table.... LIMIT 1,20

*count the number of private adds using num_rows;

*count the number of business adds using num_rows;

*count the number of used adds using num_rows;

*count the number of new adds using num_rows;

Is there some method to do the same but with less calls to the database ?

A: You can merge last 4 points into one single query, using Count() with If():
SELECT
  COUNT(IF (`type` = 0, id, NULL)) AS private_ads_count,
  COUNT(IF (`type` = 1, id, NULL)) AS business_ads_count,
  COUNT(IF (`op` = 0, id, NULL)) AS used_ads_count,
  COUNT(IF (`op` = 1, id, NULL)) AS new_ads_count
FROM ads_table

Alternate approach is using SUM() function with IF():
SELECT
  SUM(IF (`type` = 0, 1, 0)) AS private_ads_count,
  SUM(IF (`type` = 1, 1, 0)) AS business_ads_count,
  SUM(IF (`op` = 0, 1, 0)) AS used_ads_count,
  SUM(IF (`op` = 1, 1, 0)) AS new_ads_count
FROM ads_table

Note that type is a Reserved Keyword, so we need use backticks (`) around it.


text:
Q: Failed to open \EFI\BOOT\grubx64.efi - Not Found (Dual Boot Ubuntu with Windows 10) Background
I have a Windows 10 machine with a SSD where I have installed Ubuntu LTS 20.04.
This setup worked wonderfully for months. When I turn my machine on I get to choose which operative system to use.
Problem
That is, until yesterday. Yesterday I logged on my Windows boot, did nothing special and then turned the machine off. Windows probably installed some updates after I left.
Today I turned my machine on and realized I couldn't log on to my Ubuntu partition, where all of my work is:
Failed to open \EFI\BOOT\grubx64.efi - Not Found
Failed to load image \EFI\BOOT\grubx64.efi: Not Found
start_image() returned Not Found

Research
I did some searching around but it looks like this problem has a specific solution for each case.
So I installed Boot-repair, and got the following diagnostics link:
https://paste.ubuntu.com/p/TdbRzdmQsZ/
I didn't run the "Recommended Repair" option yet, as this was discouraged in a similar problem in favor of asking advice to the community first:
Error: "Failed to open \EFI\BOOT\grubx64.efi..." (Dual-Booting)
Questions
My Ubuntu partition is where all of my work is. I cannot stress the importance of this dual boot working properly. With this in mind I have the following questions:

*

*How can I fix the issue now?

*How can I prevent it from ever happening again?

A: As the error states, you are missing grubx64.efi in the UEFI directory EFI/ubuntu.  How that happened is anyone's guess, since a bad install would not have been working for months.
To fix, just copy grubx64.efi to the EFI/ubuntu directory.  Your install media should have a copy.  from the install media, you can mount the  UEFI partition, say at /mnt, so the copy target would look like /mnt/EFI/ubuntu/grub.x64.efi (caps matter, make the target match what is actually there).
Your UEFI partition (ESP) is on nme0n1p1, from the running install media, mount it at /mnt:
sudo mount -tvfat /dev/nvme0n1p1 /mnt

You should now see the location you need to put the grubx64.efi file in /mnt/efi/ubuntu.  Take a look with ls, you should have shimx64.efi and grub.cfg there already according to your boot-repair report.
Copy grubx64.efi to that location.  The install media should have a copy of grubx64.efi in /EFI/boot/grubx64.efi, so the command is:
sudo cp /EFI/boot/grubx64.efi /mnt/efi/ubuntu

Unmount the /mnt, remove the install media, and reboot.
With grubx64.efi present in the same directory as shimx64.efi, the grub UEFI boot should work.


text:
Q: Sort distributed couples from two lists Having two lists, I want to get all the possible couples. (a couple can be only one element from list 1 and another from list 2)
If I do a double "foreach" statement, I get it immediately (I am using python):
couples = []
for e1 in list_1:
    for e2 in list_2:
        couples.append([l1, l2])

How can I sort couples list in a way that elements be placed in a more distributed way?
for example:
list_1 = [a,b,c]
list_2 = [1,2]

I will get:
[a, 1]
[a, 2]
[b, 1]
[b, 2]
[c, 1]
[c, 2]

And expect to be sorted to something like this:
[a, 1]
[b, 2]
[c, 1]
[a, 2]
[b, 1]
[c, 2]

What algorithm should I use to get this results?

A: You should check out itertools.product() from the stdlib.
Edit: I meant product(), not permutations().
import itertools

list_1 = ['a','b','c']
list_2 = [1,2]

# To pair list_1 with list_2
paired = list(itertools.product(list_1, list_2))
# => [('a', 1), ('a', 2), ('b', 1), ('b', 2), ('c', 1), ('c', 2)]

# To get the sorting you desired:
wanted = sorted(paired, key=lambda x: x[1])
# [('a', 1), ('b', 1), ('c', 1), ('a', 2), ('b', 2), ('c', 2)]

Since product() returns an iterator, you don't need to cast it to a list() (and with large lists you probably shouldn't.) I just added that for illustration in this example should decide to test it yourself and want to print the values.

A: from itertools import islice, izip, cycle

list_1 = ['a','b','c']
list_2 = [1,2]

list(islice(izip(cycle(list_1), cycle(list_2)), len(list_1)*len(list_2)))

Returns [('a', 1), ('b', 2), ('c', 1), ('a', 2), ('b', 1), ('c', 2)]

A: To do the the way you want and you could flip the values:
>>> z = [[k, l] for l in x for k in y]
>>> z
[[1, 'a'], [2, 'a'], [3, 'a'], [1, 'b'], [2, 'b'], [3, 'b'], [1, 'c'], [2, 'c'], [3, 'c']]
>>> z.sort()
>>> z
[[1, 'a'], [1, 'b'], [1, 'c'], [2, 'a'], [2, 'b'], [2, 'c'], [3, 'a'], [3, 'b'], [3, 'c']]
>>> T = [[x[1], x[0]] for x in z]
>>> T
[['a', 1], ['b', 1], ['c', 1], ['a', 2], ['b', 2], ['c', 2], ['a', 3], ['b', 3], ['c', 3]]

A: In pseudo code (not pretty sure about python's syntax) :
given list_1 of size n, and list_2 of size m:
couples = []
for i=0 to n-1
   for j=0 to m-1
      couples.append( [ list_1[i], list_2[ (i+j) % m] ] )


text:
Q: Why does the call to a parent class constructor not call the parent's methods that are overriden in the child class? As shown in the code below, given a superclass Parent with a method calculate() that is called in Parent's constructor, but also overriden in the class Child, why does the implicit call to Parent's constructor within Child's constructor not call Parent's calculate() instead of Child's calculate()?
class Parent {
    Parent() {
        calculate();
        System.out.println("Empty parent ctor.");
    }
    void calculate() {
        System.out.println("Parent calculating...");
    }
}

class Child extends Parent {
    Child() {
        System.out.println("Empty child ctor.");
    }
    @Override
    void calculate() {
        System.out.println("Child calculating...");
    }
}

public class ParentConstructor {
    public static void main(String [] args) {
        Parent child = new Child();
    }
}

Output:
Child calculating...
Empty parent ctor.
Empty child ctor.

I would have thought that to correctly construct a Parent object, its constructor should always be called with its own method definitions?

A: The method in the parent will never be called by a child or subclass that overrides the method unless you explicitly call it with the super statement. That is because during a method call, which method(parent class or child class) is to be executed is determined by the object type.
This process in which a call to the overridden method is resolved at runtime is known as dynamic method dispatch.
class Child extends Parent {
    Child() {
        System.out.println("Empty child ctor.");
    }
    @Override
    void calculate() {
        super.calculate(); // calling parent implementation
        System.out.println("Child calculating...");
    }
}

A:
I would have thought that to correctly construct a Parent object, its constructor should always be called with its own method definitions?

No.  It is assumed that if you permit a method to be overridden, and choose to override the method, that the overridden behavior is the right one.
(Methods to prevent this overriding including marking your method final or private.)


text:
Q: BigQuery - nested json - select where nested item equals Having the following table in BigQuery database, where the f0_
Row  |  f0_
1    | {"configuration":[{"param1":"value1"},{"param2":[3.0,45]}]}
2    | {"configuration":[{"param1":"value2"},{"param2":[3.0,45]}]}
3    | {"configuration":[{"param1":"value1"},{"param2":[3.0,36]}]}
4    | {"configuration":[{"param1":"value1"},{"param2":[3.0,46]}]}
5    | {"configuration":[{"param1":"value1"},{"param2":[3.0,30]}]}
6    | {"configuration":[{"param1":"value1"}]}

f0_ column is a pure string.
Is there a way to write a select query, where the "param2" value is equal to [3.0, 45] array meaning it would only return rows 1 and 2? Preferably would be great to accomplish it without directly indexing the first element in the "configuration" array as the order might not be guaranteed.

A: Below is for BigQuery Standrad SQL
#standardSQL
SELECT line
FROM `project.dataset.table`
WHERE REGEXP_EXTRACT(JSON_EXTRACT(line, '$.configuration'), r'{"param2":(.*?)}') = '[3.0,45]'

You can test, play with above using sample data from your question as in example below
#standardSQL
WITH `project.dataset.table` AS (
  SELECT '{"configuration":[{"param1":"value1"},{"param2":[3.0,45]}]}' line UNION ALL
  SELECT '{"configuration":[{"param1":"value2"},{"param2":[3.0,45]}]}' UNION ALL
  SELECT '{"configuration":[{"param1":"value1"},{"param2":[3.0,36]}]}' UNION ALL
  SELECT '{"configuration":[{"param1":"value1"},{"param2":[3.0,46]}]}' UNION ALL
  SELECT '{"configuration":[{"param1":"value1"},{"param2":[3.0,30]}]}' UNION ALL
  SELECT '{"configuration":[{"param1":"value1"}]}'
)
SELECT line
FROM `project.dataset.table`
WHERE REGEXP_EXTRACT(JSON_EXTRACT(line, '$.configuration'), r'{"param2":(.*?)}') = '[3.0,45]'

with result
Row line
1   {"configuration":[{"param1":"value1"},{"param2":[3.0,45]}]}
2   {"configuration":[{"param1":"value2"},{"param2":[3.0,45]}]}

Preferably would be great to accomplish it without directly indexing the first element in the "configuration" array as the order might not be guaranteed.

Note: this solution does not depend on position of "param2" in the configuration array

A: You can use some of BQ's neat JSON functions as described here.
Based on that, you can locate param2 and check if its value matches what you're looking for. If you aren't sure of the configuration order, you can iterate through the array to find param2, but it's not particularly efficient. I recommend you try to find a way where param2 is always the second field in the array. I was able to get the correct results like so:
SELECT json_text AS correct_configurations
FROM UNNEST([
  '{"configuration":[{"param1":"value1"},{"param2":[3.0,45]}]}',
  '{"configuration":[{"param1":"value2"},{"param2":[3.0,45]}]}',
  '{"configuration":[{"param1":"value1"},{"param2":[3.0,36]}]}',
  '{"configuration":[{"param1":"value1"},{"param2":[3.0,46]}]}',
  '{"configuration":[{"param1":"value1"},{"param2":[3.0,30]}]}',
  '{"configuration":[{"param1":"value1"}]}'
  ])
AS json_text
WHERE JSON_EXTRACT(json_text, '$.configuration[1].param2') LIKE "[3.0,45]";

Gives a result of:
Row | correct_configurations
1   | {"configuration":[{"param1":"value1"},{"param2":[3.0,45]}]}
2   | {"configuration":[{"param1":"value2"},{"param2":[3.0,45]}]}


text:
Q: send Dynamic list to Controller from View I am getting quite responses when I add/delete rows.
When page is loaded the default rows 3 will be added.(But user can delete those rows)
When I am trying to add new row then 4 value rows are coming in controller but when I am trying to delete any default row then it is not showing the newly added row.
Here is my below code.
@model ProductRegistration.Models.InstalledProductInformationModel
@using (Html.BeginForm())
{
    @for (int i = 0; i < ((Model != null && Model.listInstallProducts != null) ? Model.listInstallProducts.Count : 3); i++)
    {

                @Html.TextBoxFor(m => m.listInstallProducts[i].SerialNumber, new { @class = "form-control input-sm input-Serial", @placeholder = "Enter serial number", @maxlength = 50, @OnKeypress = "return alphanumeric_only(event);" })
                @Html.ValidationMessageFor(m => m.listInstallProducts[i].SerialNumber)

                @Html.DropDownListFor(m => m.listInstallProducts[i].ModelNumber, new SelectList(string.Empty, "Value", "Text"), "--Select Model--", new { @class = "form-control input-sm input-Model" })
                @Html.ValidationMessageFor(m => m.listInstallProducts[i].ModelNumber)

                @Html.TextBoxFor(m => m.listInstallProducts[i].InstallationDate, new { @class = "form-control input-sm input-Date", @maxlength = 50, @placeholder = "DD/MM/YYYY" })
                @Html.ValidationMessageFor(m => m.listInstallProducts[i].InstallationDate)

    }
    <input class="btn btn-primary top-padding" type="submit" value="Previous" id="back-step" name="direction"/>
}

In Controller:
public ActionResult InstalledProductInfo(InstalledProductInformationModel InstalledProducts, string direction)
{
    if(ModelState.IsValid)
    {
        return RedirectToAction("EquipmentOwnerInfo");
    }
    return View(InstalledProducts);
}

Model is:
public class InstalledProductInformationModel : InstalledProductInformation
{
    public InstalledProductInformation installedProductInformation { get; set; }
    public List<InstalledProductInformation> listInstallProducts { get; set; }
}

please help me out.

A: List indexes are enumerated continuously, so there can be no gap. If You remove one row, the list index is no more continuous. The new row should be there if You will deal with indexes.

A: By default, the DefaultModelBinder required collection indexers to start at zero and be consecutive. If you delete the first item (indexer = 0) then no items will be bound. If you delete the 3rd item (indexer = 2) then only the first 2 items will be bound.  You can override this behavior by adding an input for a special property named Index where the value equals the indexer.
@for (int i = 0; i < ((Model != null && Model.listInstallProducts != null) ? Model.listInstallProducts.Count : 3); i++)
{

      @Html.TextBoxFor(m => m.listInstallProducts[i].SerialNumber, new { @class = "form-control input-sm input-Serial", @placeholder = "Enter serial number", @maxlength = 50, @OnKeypress = "return alphanumeric_only(event);" })
      @Html.ValidationMessageFor(m => m.listInstallProducts[i].SerialNumber)

    ....

      // Add the following input
      <input type="hidden" name="listInstallProducts.Index" value="@i" />

}
<input class="btn btn-primary top-padding" type="submit" value="Previous" id="back-step" name="direction"/>

Side note: You should be adding the 3 items in the controller before you pass the model to the view so you get proper model binding and then simply use @for (int i = 0; i < Model.listInstallProducts.Count; i++)


text:
Q: Can anyone recommend any UML tools with validation Unfortunately I'm not familiar with UML (yet) and I don't know what validations are in place in the standard tools. But after reading this it seems validation is missing so I ask SO for advice.
I want it to find stuff like

*

*logical inconsistencies

*disconnected parts (islands)

*unreachable parts (for example a state with only from transitions)

*missing cases (a item is defined with 3 transitions but only 2 is used)

*Other things I don't know about but someone used to UML would want.

A: No, I'm not aware of any UML tools that do these things.  I've done a fairly recent survey of tools for my employer, and I didn't see any such features.
You realize, of course, just what a high level of functionality you're asking for.  You write as if you expect these to be common.

A: Sparx Enterprise Architect does a lot of those validations. I don't know if it does all of them.

A: If you use Visual Studio, you might try the RC release of VS 2010 Ultimate. You can generate dependency graphs for .NET code to find disconnected or unreachable code. You can create layer diagrams from dependency graphs or from existing artifacts, draw the permitted dependencies, and then use layer validation to make sure invalid dependencies aren't introduced. This version also includes 5 UML diagrams: class, component, sequence, use case, and activity.
How to: Generate Graph Documents from Code: http://msdn.microsoft.com/en-us/library/dd409453%28VS.100%29.aspx#SeeSpecificSource

You can use Visual Studio Ultimate to explore the relationships and organization in existing code by
  generating directed graph documents. These graphs represent code elements and their relationships
  as a set of nodes that are connected by links, or edges. You can use these graphs to help you
  visualize, explore, and analyze code.

How to: Find Code Using Architecture Explorer: http://msdn.microsoft.com/en-us/library/dd409431%28VS.100%29.aspx

You can select vertical sections or "slices" of code that you want to visualize by using
  Architecture Explorer. You can explore source code in a Visual Studio solution or
  compiled managed code in .dll files or .exe files. You can use Architecture Explorer to browse
  other domains by installing additional providers. When you find the code that you want to
  visualize, you can generate graphs to explore the relationships in that code.

How to: Create Layer Diagrams from Artifacts: http://msdn.microsoft.com/en-us/library/dd465141%28VS.100%29.aspx

...use layer diagrams to visualize the high-level architecture of your system and to verify that
  the code complies with this design. To perform this task, organize and associate the
  artifacts from a Visual Studio solution into logical, abstract groups, or layers. These layers
  describe major tasks that these artifacts perform or the major components of your system. Arrows
  between the layers represent the interdependencies that exist or should exist between these
  artifacts. To enforce architectural constraints on the code, describe the intended dependencies on
  the diagram and then validate the code against the diagram. By using layer diagrams in this
  manner, you can help make the code easier to understand, reuse, and maintain.

Layer Diagram http://i.msdn.microsoft.com/Dd465141.UML_LayerRefReading(en-us,VS.100).png
How to: Validate Code Against Layer Diagrams: http://msdn.microsoft.com/en-us/library/dd409395%28VS.100%29.aspx

Validating code against a layer diagram helps you enforce architectural constraints on the code
  as it evolves. When you perform this task, dependencies in the code are compared with dependencies
  on the diagram.

RC download: http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=457bab91-5eb2-4b36-b0f4-d6f34683c62a.
Visual Studio 2010 Architectural Discovery & Modeling Tools forum: http://social.msdn.microsoft.com/Forums/en-US/vsarch/threads

A: I could point to some research prototype tools, specially for the verification and validation of class diagrams with or without OCL constraints (e.g. my own verification tool http://gres.uoc.edu/UMLtoCSP/ or http://www.db.informatik.uni-bremen.de/projects/USE/) but
these are tools are just that: research tools (with all the limitations this implies).
I'm not really aware of any commercial CASE tool that offers advanced verificacion/validation capabilities.


text:
Q: iterating "This" properties in a method of a class C# I been search but have no luck with this, im trying to call a method in a class from a table in a DB this method call another that find a entry and fill the object however i want to pass this object to my instance of the class
 public class ProductCategory
    {
        public int ProductCategoryID { get; set; }

        public string Name { get; set; }

        public Guid rowguid { get; set; }

        public DateTime ModifiedDate { get; set; }

        public void FindItem<T1>(T1 id)
        {
            try
            {

                var obj = Activator.CreateInstance(this.GetType());
                obj = Dal.ObjFind(obj, id); //this fill the object
                //i want something like
                foreach properties in obj
                this.propertie = obj.propertie

            }
            catch (Exception e)
            {
                throw e;
            }

        }

    }

in a way that i can call that method like
ProductCategory test = new ProductCategory();
test.Find(1);

and after that my object is loaded, i would really appreciate any help with this and sorry for the bad English or if i not explain clearly
Regards

A: Ok i found a way to achieve as Pac0 say with reflection you can do this
public  void FindItem<T1>(T1 id)
        {
            try
            {

                var obj = this;
                // fill the object with the DB data
                obj = Dal.ObjFind(new Production.ProductCategory(), id);

                PropertyDescriptorCollection PropertyObj =
                 TypeDescriptor.GetProperties(this);
                //iterating the properties in the instance of the class
                foreach (PropertyDescriptor prop in PropertyObj)
                {
                    //Get the value for each properties in the filled Obj
                    //and set that value for each properites in "this"
                    prop.SetValue (this,prop.GetValue(obj));
                }

            }
            catch (Exception e)
            {
                throw e;
            }

        }

in that way you can call your instalce like "test.FindItem(1)" and the object will be load, thanks!

A: To get information at runtime about the some class durig runtime is called *reflection** (this term should help you in your searches)
To get all the properties of a Type, you can use Type.GetProperties() .
have a look at GetProperty as well.
With this, you should be able to achieve what you want.
However, I'm not convinced it's the simplest way to go. Probably someone will come up with a better way to solve your underlying issue.


text:
Q: ¿Porque cuando recargo la pagina me sale el 404 en angularjs? Soy nuevo en AngularJS y estoy aprendiendo como hacer enrutamiento. Logré hacer que funcionara correctamente el ruteo de varias vistas en una misma pagina sin tener que recargar la página principal, todo bien hasta ahí.
Mi problema ya se presenta es cuando veo que la URL tiene unos símbolos (estos exactamente #!) cuando navega entre las diferente paginas de la siguiente manera:
http://localhost:8080/Proyectos/AngularJS/Routing/#!/Vista1

Encontré que para quitarlos debo usar la funcion $locationProvider.html5Mode(true) y la etiqueta base de html para poder quitar esos símbolos de la URL y que quedara más limpia, lo hice y funcionó.
El problema es que si intento recargar la página en la que estoy, como por ejemplo esta http://localhost:8080/Proyectos/AngularJS/Routing/Vista1 me dice

"Objeto no encontrado Error 404"

Si recargo en la raíz, es decir asi: http://localhost:8080/Proyectos/AngularJS/Routing/ si funciona normal.
Quisiera saber, ¿A qué se debe esto? y ¿Qué puedo hacer para que pueda recargar la página no importando la página en la que me encuentre?
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <base href="/ProyectosCristian/AngularJS/Routing/">

    <title>Routing</title>

            <menu></menu>

A: Lo tengo funcionando
Simplemente agregando un archivo .htaccess en la raíz
<IfModule mod_rewrite.c>
    RewriteEngine on

    # Don't rewrite files or directories
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]

    # Rewrite everything else to index.html
    # to allow html5 state links
    RewriteRule ^ index.html [L]
</IfModule>

A: Ok, proba con este código, en vez de <base href="/ProyectosCristian/AngularJS/Routing/">
escribe
    <!DOCTYPE html>

            <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">

            <title>Routing</title>


text:
Q: What is the approximate row limit for an html table using jQuery DataTables before the page becomes too slow? If you had an html table of 10 or so columns,
and you apply the jQuery DataTables plugin to the table,
at what point (approximately) should one expect
the number of table rows to adversely affect browser-rendering
performance?

A: I think it really depends on what you're rendering in each table row element and how many columns you have. If you're just doing text, I've experienced slowdown after a few hundred rows, with a mysql server on the same machine as the webhost. If you're placing image elements or event handlers with each row, expect slowdown to happen with fewer rows. A good idea is to get a browser that easily shows you load times, like Chrome, Safari, and Firefox+firebug.


text:
Q: Target unkown after Android 4.3 update I updated my Samsung Galaxy S3 from 4.1.2 to 4.3 and eclipse shows my target device as unknown (with the orange triangle). Querying for adb devices from command prompt shows my device name but has its state as 'unauthorized'. I have updated the sdk to the latest, toggled USB debugging on my device, restarted eclipse, tried to use adb to kill-server and start-server but none of these approaches seems to solve my problem. One peculiar behavior is that on toggling debugging and reconnecting to my pc, I do not get a RSA key fingerprint popup requesting for permission.
I would appreciate any help on this matter.
Thanks,
Arun

A: You need to enable the developer options again after updating:
Enable Hidden Dev Options

A: I have encountered the same problem with my galaxy S4.
After many hours of research and trying all of what you suggested and even factory resetting - I discovered that it is some bug / issue with Samsung devices running 4.3
I had 4.2.2 running fine, upgraded to 4.3 and like you say - phone became unrecognized, Logcat did not show anything.
At last, I downgraded back to 4.2.2 and everything was back to normal.
Take note that it happens for no obvious reason, and only on some devices - not all.
So, unfortunately, the only probable solution is to revert back to your old Android version and then it should work fine.
Cheers..

A: For me, the phone shows up in the eclipse but under unintelligible name and cannot be used. Switching to MTP and then back to PTP on the phone under USB options helps.

A: download and install samsung kies 3
in kies 3, select tools-> setup driver again
this solved my problem


text:
Q: Unchecked Cast While Generating Signed APK I receive an arrayList intent as follows
 val b = activity?.getIntent()?.extras
        returnedArray = (b!!.getSerializable("questions") as ArrayList<bring>?)!!

But am unable to build my apk because of this related error
Unchecked cast: Serializable? to kotlin.collections.ArrayList? /* = java.util.ArrayList? */
How can i fix this?

A: In android to pass a user-defined object around, your class should implements Parcelable instead of Serializable interface.


text:
Q: pyo3 optionally generate python bindings for rust struct I have defined a few structs in my code and if a certain feature is enabled on the crate, I would like to generate Python bindings for those structs as well. Right now I am not able to get it correctly. Let's say I have a struct MyStruct for which I want to optionally generate Python Bindings.
I have tried something like the following
cfg_if! {
    if #[cfg(feature = "python-bindings")] {
        #[pyclass]
    }
    else {
    }
}
struct MyStruct{
   value: i32
}

I would like to only add #[pyclass] if feature python-bindings is enabled and not otherwise.
This works fine if python-bindings is not enabled. But if I compile with --features python-bindings, I get the following error.
error: expected item after attributes
As far as possible I do not want to duplicate the code. like
cfg_if! {
    if #[cfg(feature = "python-bindings")] {
        #[pyclass]
        struct MyStruct{
           value: i32
        }
    }
    else {
        struct MyStruct{
            value: i32
        }
    }
}

Is there a way of doing it without duplicating the code?

A: Yes, with #[cfg_attr]:
#[cfg_attr(feature = "python-bindings", pyclass)]
struct MyStruct {
    value: i32
}


text:
Q: Delimited \def's and expansion I try to understand how work the macro named \separator in MWE .
\documentclass[]{article}

\def\separator#1\separator#2{%
\unexpanded{#1}%
\ifx*#2%
\else
, \expandafter\separator\expandafter#2%
\fi
}%

    \def\stcs{\separator One\separator Two\separator three}

    \tracingmacros 1
    \begin{document}

    \stcs\separator*

    \end{document}

Trace of \separator is following:
\stcs ->\separator One\separator Two\separator three

\separator #1\separator #2->\unexpanded {#1}\ifx *#2\else , \expandafter \separator \expandafter #2\fi
#1<-One
#2<-T

\separator #1\separator #2->\unexpanded {#1}\ifx *#2\else , \expandafter \separator \expandafter #2\fi
#1<-Two
#2<-t

\separator #1\separator #2->\unexpanded {#1}\ifx *#2\else , \expandafter \separator \expandafter #2\fi
#1<-three
#2<-*

What have I see.
At the first stage:

First: \separator gets  a #1 as 'One' -this is normal for me.
Second: \separator gets  a #2 only 'T' but not 'Two'. Why?
At the second stage:

First: \separator gets  a #1 as 'Two'. Why not 'T', as one can see from the first stage? And what had become of this 'T'? It lost?
\LaTeX pdf output is normal "One, Two, three".
Thus, what is happen with #2?

A: #1 is a delimited argument that consists of all tokens up to the specified delimiter, \separator here. LaTeX doesn't really support the definition of such arguments (hence the use of \def rather than \newcommand.
#2 is a normal non-delimited argument. So this takes a single token or {} group.
In the case you trace it just gets T just as if you go \fbox abc  the argument of \fbox is just a.
#2 is just used for testing and if you are not at the end it is put back here:
\expandafter\separator\expandafter#2%

so when that \separator is expanded it sees
Two\separator three
in the input stream The T having been put back, so takes Two as #1 and t as #2 and the loop continues.


text:
Q: How to enable IPv6 Autoconfiguration with static address in Linux (RHEL) I have  a static IPv6 address I would like to assign.  When I add the address to the /etc/sysconfig/network-scripts/ifcfg-eth0 file and restart networking I realize I get several IPv6 addresses.  The first one is my static address (Prefix::host) and the second one is my autoconfiguration address (Prefix::MAC_ADDRESS).
I realized traffic was going out of the autoconfiguration address so my solution was to disable it.  I added "IPV6_AUTOCONF=no" to the /etc/sysconfig/network-scripts/ifcfg-eth0 file.  That solved the issue since the autoconfiguration address was gone.
However since there is no autoconfiguration I was not getting the default gateway.  I believe Solaris has something called "token based IPv6" where you can specify the host portion of the address and autoconfiguration still runs to assign the prefix, dns, and default gateway.  Can I do this in linux?

A: Token IPv6 addresses is a thing in Linux, man ip-token. Essentially,
ip token set ::123/64 dev eth0
There isn't really configuration supporting this in EL scripts, so I just dump it in a /sbin/ifup-local script.
Auto configuration addresses are not necessarily based on your MAC address.
    sysctl -w net.ipv6.conf.default.use_tempaddr=1
should turn on privacy extensions and also prefer your static global addresses, if you want that kind of predictability.  Save to /etc/sysctl.d/  if you are happy with it and want it permanently. See ip-sysctl.txt for other options.

A: You need to accept the Router Advertisement (RA) messages from the router.  That will have the prefix (network) and prefix length as well as the default gateway.
Check out the kernel config vars
net.ipv6.conf.default.accept_ra
net.ipv6.conf.all.accept_ra
and make sure they are set to (typically) 1
Also, make sure that something on your network (usually your router) is sending the RAs.

A: One possible answer is DHCPv6 (on the network side).  In my own experience where some type of IPv6 advertisement service (instead of DHCPv6) is available for addressing is that if I want my own "static" address, I have to statically define the rest (gateway, etc) as well.


text:
Q: DLL VCTRS not found when loading ggplot2 I use R 4.1.3. My problem is that after I installed ggplot2, I try to load the package by typing library(ggplot2), however the following message comes up:

Error: package or namespace load failed for 'ggplot2' in
library.dynam(lib, package, package.lib): DLL not found: maybe not
installed for this architecture?

When I look in my R/win-library/4.1 folder (which oddly is placed in my onedrive, don't know how to change that), I can see that a folder called VCTRS already is installed, but not sure if this has anything to do with my problem.
I tried reinstalling everything, installing r tools and installing the package and restarting my pc but nothing seems to be working.


text:
Q: Can't install cvxopt on Mac? I tried installing cvxopt using Terminal but I keep getting the following message :

lipo: can't figure out the architecture type of:
  /var/folders/p2/_njkvzqj50zg3_568vpqc68r0000gn/T//ccRX9bFW.out error:
  command 'gcc-4.2' failed with exit status 1

What is causing this problem ?

A: I don't think cvxopt supports OSX 10.8 yet. (you may ask on their googlegroups )
I know, however, that in principle it is possible to build cvxopt on OSX 10.8, via Sage (www dot sagemath dot org - argh, I can only have 2 hyperlinks in the post :)). This is highly experimental at present, as Sage does not officially support OSX 10.8 yet.


text:
Q: Get SQL data individually for days between now and 30 days ago I'm building an analytics chart where I need to display the number of visits for each day, for the past 30 days. I've tried using the loop below, but it fails to pull certain data and drastically slows down page load time, due to 30 queries being sent in one request.
Are there any better ways to get this data from the MySQL database while saving server resources and improving the load time of the page? Any help is appreciated.
              $conn = new mysqli("localhost", "db_host", "db_pwd", "db_name");

              $d2 = date('c', strtotime('-29 days'));

              $date = date("Y-m-d");

              $begin = new DateTime($d2);
              $end = new DateTime($date);
              $end = $end->modify('+1 day');

              $interval = new DateInterval('P1D');
              $daterange = new DatePeriod($begin, $interval ,$end);

              foreach($daterange as $date){

                $current = $date->format("Y-m-d");

                $sql = "SELECT COUNT(*) FROM stats WHERE link_id=$_GET[id] AND date='$current'";
                $result = mysqli_query($conn, $sql);
                if (mysqli_num_rows($result) > 0) {
                  while($row = mysqli_fetch_assoc($result)) { echo $row["COUNT(*)"]; }
                } else { echo "no results";}
              }

              $conn->close();

A: If you have at least one visit per day, you can just use aggregation:
select date(dt) as dt_day, count(*) as cnt_visits
from stats
where link_id = ? and dt >= current_date - interval 29 day
group by date(dt)
order by dt_day

Having a column called date is somehow misleading (although MySQL allows it). For the sake of clarity, I renamed the column to dt in the query.
If there are days without visits, and you still want to display them, with a count of 0 visits, then it is a bit more tricky. You need to generate the dates first, then left join the table. You would typically use a calendar table - or, in MySQL 8.0, you can do this on the fly with a recursive common table expression:
with recursive cte as (
    select current_date as dt_day
    union all
    select dt_day - interval 1 day from cte where dt_day > current_date - interval 29 day
)
select c.dt_day, count(s.dt) as cnt_visits
from cte c
left join stats s
    on  s.link_id = ?
    and s.dt >= c.dt_day
    and s.dt < c.dt_day + interval 1 day
group by c.dt_day
order by c.dt_day


text:
Q: RuntimeError: :json is not registered on Faraday::Request I am fairly new to ruby and I am trying to execute a spec and I receive this error:

RuntimeError:
             :json is not registered on Faraday::Request

I am trying to use this gem:  https://github.com/Chicago/windy
Mac OS X 10.7.4
Ruby 1.9.3, using RVM

A: I've just run into this when upgrading Faraday. The json request middleware was removed from Faraday in 0.8. It is now in the faraday_middleware gem. You should gem install faraday_middleware and require it in the file that creates the Faraday object.
See https://github.com/lostisland/faraday_middleware/wiki/Changes-0.8


text:
Q: Image sliding in jquery I have an image slider widget in my application. I am using jquery cycle for that.. I have a drop down menu where I can change the effects of the slider. But I need to insert this image slider in more than one place in a single page. And for the drop down menu I have used id.. so when I insert the image in more than one page in a single page the effect would be same for all (as I hve used the id).. So I wanted to give a class name for drop down menu.. In that case how would i assign the effects value in jquery.. Please find the code below.. Any thoughts on this would be appreciated.?/ (I am just learning jquery and JS).
Jquery code:
var effects_id = document.getElementById('slideshow_effects').value;

Drop down menu:
<select id="slideshow_effects">
<option value="fade">Fade</option>
<option value="fadeZoom">FadeZoom</option>
<option value="cover">Cover</option>
<option value="toss">Toss</option>
<option value="blindY">BlindY</option>
</select>

A: In these cases I would the following structure:

    <select class='drop' >...</select>

now in js:
$(".slider").each(slider_init);

function slider_init(index, el)
{
    var drop = $(el).find(".drop");
    var slideshow = $(el).find(".slideshow");

    // now initialize slider here for drop and slideshow
    slideshow.cycle({
        fx: drop.val(),
        speed: 1000,
        timeout: 2000
    });});
}

actually this way you initialize each occurrence of your slider individually and for each initialization the code finds the relevant select element.
This way no matter how many "sliders" you have on page, each will work individually


text:
Q: libGDX: how to make a world to move I'm a newbie in libgdx and  working on a simple 2d game and I want that my box2d world(or background) move with the input touch(move upward when I press the button) but I don't know how to move the world and place my player on the center. I want to know:

*

*How to move my world with the input control.

*Place my player in the center.

and also it looks like that my player is moving whenever I play that game, not the world.
if you can just provide an example with your answer.
so, Here is my code
 public void show() {
        world = new World(new Vector2(0, 25), true);
        renderer = new Box2DDebugRenderer();
        cam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
      /*  cam.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0);
        cam.update();*/

        shapeRenderer = new ShapeRenderer();

        batch = new SpriteBatch();
        texture = new Texture("img/imgs.png");
        sprite = new Sprite(texture);
        sprite.setSize(10, 10);
        sprite.setOrigin(sprite.getWidth() / 2, sprite.getHeight() / 2);
        sprite.setPosition(Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2);
        //sprite.setBounds(200, 200, 64, 64);
        //sprite.setPosition(Gdx.graphics.getWidth()/2 -sprite.getWidth()/2, Gdx.graphics.getHeight()/2-sprite.getHeight()/2);

       /* //Body definition
        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyDef.BodyType.DynamicBody;
        bodyDef.position.set(0, Gdx.graphics.getHeight() / 2 - 250);

        box = world.createBody(bodyDef);

        //Polygon Shape
        PolygonShape shape = new PolygonShape();
        shape.setAsBox(10, 20);

        //fixture definition
        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = shape;
        fixtureDef.density = 5f;
        fixtureDef.friction = .5f;

        box.createFixture(fixtureDef);

        box.setUserData(sprite);

        shape.dispose();

*/    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        world.step(1 / 60f, 6, 2);
        cam.translate(0, 12);
        cam.update();
        batch.setProjectionMatrix(cam.combined);

        if(Gdx.input.isKeyPressed(Input.Keys.A))
            spriteY += Gdx.graphics.getDeltaTime() * spriteSpeed;
        if(Gdx.input.isKeyPressed(Input.Keys.D))
            spriteY += Gdx.graphics.getDeltaTime() * sprite1Speed;

        batch.begin();
        batch.draw(sprite, spriteX, spriteY);
        batch.end();

        shapeRenderer.setColor(Color.RED);
        shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
        shapeRenderer.rect(0, 200, 50, 50);
        shapeRenderer.translate(1, 0, 0);
        shapeRenderer.end();

    }

    @Override
    public void resize(int width, int height) {
        cam.viewportWidth = width;
        cam.viewportHeight = height;
        cam.update();

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {
        dispose();
    }

    @Override
    public void dispose() {
        //world.dispose();
        shapeRenderer.dispose();
        batch.dispose();

    }

}

Sorry, for the mess(I'm a novice) in code and I want that my world moves upwards with input controls and my sprite just placed in the center.
Thank you in advance.

A: Your question sounds like you want to create a platformer or kinda.
I'll let you know that the best way to build your logic on when creating a (2d) platformer game is your character should always keep it's position the same and the background and other solid objects should move towards the player (based on input controls or automatic) so giving the look like your player is naturally moving and the background & objects appear in his way.
My answer is pretty general as your question is pretty general. If you need code you must provide us code so we know where you're stuck. Good luck :)


text:
Q: send selected values from JavaScript to Controller in CodeIgniter? this is my view from which i want to send the data. when i select class name i want to send it to Controller by Ajax
<select class="form-control" name="persent_class" id="class">
<?php foreach ($all_classes as $class) : ?>
  <option value="<?php echo $class['class_name']?>"><?php echo
  $class['class_name']?></option>
  <?php endforeach; ?>
          </select>

this is my ajax function:
<script type="text/javascript">
    $(document).ready(function () {
        $("#class").change(function () {
            var c = $("#class").val();
            $.ajax({
                type: "POST",
                url: "<?=base_url()?>index.php/Welcome/get_class_name",
                data: {"c":c},
                dataType:"json",
                cache: "false",

            });
        });
    });
</script>

and this is my controller function:
public function get_class_name()
        {
            $id=$this->input->post('c');
            echo json_encode($id);

        }

A: Try it with this script, some line changed and you forget echo base_url:
<script type="text/javascript">
    $(document).ready(function () {
        $("#class").change(function () {
            var optionSelected = $(this).find("option:selected");
            var valueSelected  = optionSelected.val();
            $.ajax({
                type: "POST",
                url: "<?php echo base_url(); ?>index.php/Welcome/get_class_name",
                data: {"c":valueSelected},
                dataType:"json",
                cache: "false",

            });
        });
    });
</script>


text:
Q: How to enable automatic migration in production I know the basics of enabling automatic migration using this link.
Could anyone tell what is the best way to enable automatic migration in production without any hassle and how to do the automatic migration in scenarios where the connection string is provided during runtime?

A: The EF DB version check will be performed at runtime. If you have enabled migration in your project (like in the link you provided, with MigrateDatabaseToLatestVersion), migration will be applied on first context initialisation.

A: I have this in place for my production platform, note that the command is only executed when the build is done in something other then debug mode.
#if !DEBUG
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<VerbekeContext, Default.Migrations.Configuration>());
#endif

this is added in my global.asax of an MVC project in the startup function, so if you have any other application you should execute this @ startup
Or you could set the AutomaticMigrationsEnabled to true in the configuration.cs in the migrations folder. If you add the debug switch, set it to false in debug and true in other build modes.
namespace Default.Migrations
{
using System.Data.Entity.Migrations;

public sealed class Configuration : DbMigrationsConfiguration<Context>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }

    protected override void Seed(Context context)
    {
       ///
    }
}
}


text:
Q: how to read properties from GWT host page? What's the best way to read properties from the GWT host page?
I'm trying to find a simple way to embed properties into the host page and access them from Java.
It seems like Dictionary is the recommended way to go, but it's somewhat fragile in that your dictionary must exist in the host page, or it errors with MissingResourceException. Similarly, Dictionary.get() will throw a resource error if the key you request does not exist.
I'm writing a library, and I'd prefer a more robust solution that won't error out if the user doesn't specify the dictionary or key. Should I just catch exceptions thrown by the Dictionary and return null?  Is there a more robust way to do this?
EDIT: at the moment, I'm using the following:
protected Dictionary dict;

public ClientConfiguration(String configName)
{
    try
    {
        dict = Dictionary.getDictionary(configName);
    } catch (MissingResourceException e)
    {
        dict = null;
    }
}

public String getString(String key)
{
    return dict == null ? null : dict.keySet().contains(key) ? dict.get(key) : null;
}

A: I would say, your solution is very robust already. It's absolutely ok to catch - without rethrowing -

*

*a specific Exception (MissingResourceException)

*which you expect to occur (the resource could be missing),

*and which will only occur under the circumstances you expect (it would be bad to catch a NullPointerException, because there can be many reasons for that Exception).

You could even change your getString() method a little bit:
public String getString(String key) {
  try {
    return dict == null ? null : dict.get(key);

  } catch (MissingResourceException e) {
    return null;
  }
}

This should make the method almost twice as fast, because you save the extra call to dict.keySet().contains(key), which takes approximately as long as dict.get(key).


text:
Q: Android - Pick shortcut - I get shortcut intent and title but can't get shortcut icon I already wrote a working code for showing a list of all available shortcuts from all apps and capturing the intent for the chosen shortcut as weell as the name of the app and the shortcut. But I can't seem to find how to get the shortcut icon. In the onActivityResult I tried the data.getStringExtra(Intent.EXTRA_SHORTCUT_ICON) function but this produces a string which returns empty. Can someone help?
(I want the shortcut icon...not the app icon)
   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    Log.w("on activity result ston action picker","aaaa");
    if(resultCode == Activity.RESULT_OK && data != null) {
        switch (requestCode){
        case pick_shortcut:
                Intent j = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
                String shortcut_name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
                ComponentName componentName2 = j.getComponent();
                String packageName2 = componentName2.getPackageName();
                PackageManager packageManager2 =  getPackageManager();
                ApplicationInfo applicationInfo2 = null;
                try {
                    applicationInfo2 = packageManager2.getApplicationInfo(packageName2, 0);
                } catch (final NameNotFoundException e) {}
                String title2 = (String)((applicationInfo2 != null) ? packageManager2.getApplicationLabel(applicationInfo2) : "???");
                Log.w(shortcut_name,title2);
           }
       }
    }

A: You was almost there.
Intent.EXTRA_SHORTCUT_ICON should be a pacelled Bitmap, not a String.
So instead of using:

data.getStringExtra(Intent.EXTRA_SHORTCUT_ICON)

You should be looking at something like:

Bitmap icon = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);

EDIT:
As a side note, if your dealing with third party applications, EXTRA_SHORTCUT_ICON could be null, and EXTRA_SHORTCUT_ICON_RESOURCE may be passed instead.
EXTRA_SHORTCUT_ICON_RESOURCE is a ShortcutIconResource, which is a class that contains two Strings: packageName and resourceName.
(These could be used to load the third party app's resources, then grab the Bitmap resource using the resource name.)


text:
Q: PHP table sorting, filtering and pagination I've been trying to find I good solution to using MySQL query data for Ajax tables with pagination, sorting and filtering.   I've tried DataTables and really don't like it.  I started trying FooTables but for some reason I'm having difficulty finding one good complete example of using FooTables with PHP and MySQL data.
What would you recommend for achieving Ajax driven Pagination, Sorting and Filtering with PHP right now that has a good piece of complete working example source code to learn from?
I'm using jQuery but not Bootstrap right now for my web pplications.
Thanks!

A: http://jtable.org/ might be a good candidate. I am using https://datatables.net/ now but I have used this in the past with good success. Jtable has good documentation and a pretty flexible plugin. The documentation also has sample code with mysql and php.


text:
Q: Create File Stream Enabled Database in Network File (NAS Server) I want to create a filestream enabled SqlServer database using NAS server as the storage. I already passed the creation of DB step. Look at my previous question https://stackoverflow.com/questions/16516515/creating-sql-server-database-with-data-and-log-file-on-synology-nas-server. I can create an ordinary db but couldn't managed to create filestream enabled DB. Is it possible to do this?

A: I didn't used Filestream enabled database before. Recently I had to install one for a document tracking and archiving software. I wanted to put the db on nas server because I don't have too much space on server harddisk. After some research I found out even I can put data and log files on nas I can not create filestream enabled database using nas so I installed totally on server instead.
"Thank You" for Whom Who Viewed my question.
Ferda


text:
Q: Python Pygame doesn't display images correctly I'm new to Python and I started learning with "Python crash course" by Eric Matthes. I'm in the beginning of Pygame chapter and I follow the code, but my loaded images always look damaged and I don't know why. Code is from the book. First file:
    import pygame
    class Ship():
        def __init__(self, screen):
            """Initialize the ship and set its starting position."""

    # Load the ship image and get its rect.
            self.image = pygame.image.load('ship.bmp')
            self.screen = screen
            self.rect = self.image.get_rect()
            self.screen_rect = screen.get_rect()
    # Start each new ship at the bottom center of the screen.
            self.rect.centerx = self.screen_rect.centerx
            self.rect.bottom = self.screen_rect.bottom
        def blitme(self):
            self.screen.blit(self.image, self.rect)

Second file:
    import sys
    import pygame
    from settings import Settings
    from ship import Ship
    def run_game():
        # Initialize game and create a screen object.
        pygame.init()
        ai_settings = Settings()
        screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
        pygame.display.set_caption("Alien Invasion")
        ship = Ship(screen)
        bg_color = (230, 230, 230)

        # Start the main loop for the game.
        while True:
            # Watch for keyboard and mouse events.
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
            # Make the most recently drawn screen visible.

            screen.fill(ai_settings.bg_color)
            ship.blitme()

            pygame.display.flip()

    run_game()

Settings file:
class Settings():
       """A class to store all settings for Alien Invasion."""
       def __init__(self):
           """Initialize the game's settings."""
           # Screen settings
           self.screen_width = 800
           self.screen_height = 600
           self.bg_color = (230, 230, 230)

My bmp look like that:

I tried to add different image, but no luck:

How can I fix it?

A: I presume you are on a Mac, with a relatively new version of SDL. The issue is not with your code, but newer versions of SDL having a bug with Mac OS.
To resolve, you either need to downgrade your SDL to a version prior to around version 1.2 (it's around there, forgot the exact version), or work on a different operating system.
It's very annoying.. I ended up installing virtualbox and running Linux on my Mac just to be able to code pygame!


text:
Q: SonarQube API result limit I have a question about the limit restriction of results in the web api.
There was a restriction to max. 500 results in prior versions. See this
open bug (https://jira.codehaus.org/browse/SONAR-2920) and an old
documentation entry (
http://docs.codehaus.org/pages/viewpage.action?pageId=229743280).
This part is not included in the current documentation (
http://nemo.sonarqube.org/api_documentation#api/resources) and my tests
have shown that the api of version 5.1 as well as 4.5.4 is able to deliver
more than 500 results.
So, can the bug be closed and there is no more restriction or do you have a
bug that there is no limitation?
Cheers,
Stefan

A: There's indeed a bug in this WS, the result should always be limited to 500 : http://jira.sonarsource.com/browse/SONAR-6584
Regards


text:
Q: Magento move search result For some reason when somebody performs a search on my site the search results do not display underneath the search box, they appear on the far left of the screen.
Any ideas of what file this would be configured in?
Let me correct myself it's not the search results but the search suggestions

A: I can't offer a direct solution to your problem, but turning on template hints might point you in the right direction.  In the Admin, go to System > Configuration,  Select your store view from the scope drop down at the top left.  Unless you're running multi-store, or have changed the name of the default store it'll be called "Default Store View".  Then scroll down to "Developer" and open up the "Debug" section.  Turn on both Template Path Hints" and "Add Block Names to Hints".  This will add a div with a red border around each template in your layout and a heading which includes the name of the template.  It will liklely completely screw up your page layout, but will show you which template generated every tag on the page and help you track down the issue.
The DeveloperToolbar extension makes turning this on/off quickly much easier, but I wouldn't recommend deploying it to a production site.
Alan Storm's indispensable CommerceBug is another tool which is very handly for tracking down front end issues.  CommerdeBug can show you the layout handles and the aggregate layout XML used to generate the current page.  Both of which are useful for determing why a specific block was (or wasn't) included.

A: So in case anybody else runs into this or wants to move where their search suggestions display it is in styles.css  under .searchautocomplete.


text:
Q: Pandas - resample timeseries without loss of information I want to aggregate the following dataframe from minute to 10 minutes. I've been trying to use resample but I realized that I was losing another column. Is it possible to avoid this? I'm guessing this involves some sort of group by as well?
Dataframe looks like this, where date_time is the index, after comes a name column and a count column.
date_time           name        count
2022-06-03 17:00:00 LoveToKnow  165
2022-06-03 17:00:00 Investing Channel   176
2022-06-03 17:00:00 D17 14
2022-06-03 17:00:00 IFLScience  58
2022-06-03 17:00:00 MotherJones 1
.................
2022-06-03 17:01:00 LoveToKnow  100
2022-06-03 17:01:00 Investing Channel   15
2022-06-03 17:01:00 D17 1
2022-06-03 17:01:00 IFLScience  5
2022-06-03 17:01:00 MotherJones 1
.................

If I were to perform a resample like below, it would group the values and sum them but I would be losing the name column during the process.
df.resample('10min').agg({'count': 'sum'}) or
df.resample('10min').sum()

date_time           count
2022-06-03 17:00:00 81816
2022-06-03 17:10:00 77504
2022-06-03 17:20:00 73605
2022-06-03 17:30:00 70994
2022-06-03 17:40:00 68658

The output that I am expecting should be as follows:
date_time           name        count
2022-06-03 17:00:00 LoveToKnow  1200
2022-06-03 17:00:00 Investing Channel   125
2022-06-03 17:00:00 D17 300
2022-06-03 17:00:00 IFLScience  900
2022-06-03 17:00:00 MotherJones 8
............
2022-06-03 17:10:00 LoveToKnow  700
2022-06-03 17:10:00 Investing Channel   25
2022-06-03 17:10:00 D17 400
2022-06-03 17:10:00 IFLScience  400
2022-06-03 17:10:00 MotherJones 80
.....

A: I think you need grouping by name with DataFrame.resample with aggregate sum:
df1 = df.groupby('name').resample('10min').sum().swaplevel(1,0).reset_index()
print (df1)
            date_time               name  count
0 2022-06-03 17:00:00                D17     15
1 2022-06-03 17:00:00         IFLScience     63
2 2022-06-03 17:00:00  Investing Channel    191
3 2022-06-03 17:00:00         LoveToKnow    265
4 2022-06-03 17:00:00        MotherJones      2

Or solution with Grouper:
df1 = df.groupby([pd.Grouper(freq='10Min'), 'name']).sum().reset_index()
print (df1)
            date_time               name  count
0 2022-06-03 17:00:00                D17     15
1 2022-06-03 17:00:00         IFLScience     63
2 2022-06-03 17:00:00  Investing Channel    191
3 2022-06-03 17:00:00         LoveToKnow    265
4 2022-06-03 17:00:00        MotherJones      2

If need only first name per 10minutes ouput is different:
df2 = df.resample('10min').agg({'name': 'first', 'count': 'sum'})
print (df2)
                           name  count
date_time
2022-06-03 17:00:00  LoveToKnow    536


text:
Q: Manage Bugs between Dev, QA and Production My software team have just started using Jira to manage bugs, so I am fairly new to the process that is available to Jira.
The systems we build are internally facing applications or customer facing web applications, and we release to these environments on a change request by change request basis, rather than through a product lifecycle type of development lifecycle.
The way we plan to use Jira, is for each project (which is usually a single CR) to have its own project created in Jira. Our process is then as follows

*

*Developers code and unit tests, until ready for integration testing

*Developers start integration testing and any bugs are raised in Jira, under a version named Development.

*Once all development bugs are fixed, we then move into QA, where we hand over the build to the testing team. A new version 'QA' is created, and all bugs found in QA are logged against this verison.

*Once all bugs are closed, the project goes Live, and the project is closed in Jira.

From what I have seen of the more agile product type uses of Jira, I suspect we are using the version fields in the wrong way, but as I am new to Jira I am not sure if we are, or if there is a better way of doing it.
Would appreciate hearing from someone who has used Jira in this type of environment to see what the right way to use Jira is.

A: Here's what I'd recommend after using JIRA in a number of different environments, with varying team sizes and types of project.

*

*Use JIRA projects to denote large but discrete functional areas of work that correspond to a subset of team members in your organization, e.g. a new web application or internal customer app.

*If the project or the team working on it is big enough to warrant it, use JIRA components to define different functional areas.  You can then assign component leads who will automatically be assigned new issues against their components, and you'll be able to track which functional areas have the most bugs and maybe need more attention from the test team.

*For versions, you can certainly set up development, live and QA versions as you've described, but these are more traditionally mapped to the JIRA issue status.  With the standard JIRA workflow an issue will be Open while a developer is working on it, Resolved after the feature or bug fix is completed, and then Closed if QA verifies the feature or fix, or Open again if QA identifies a problem.

*If you have long-lived applications where you get multiple CRs that specify new features for the same app, I would use JIRA versions to define the different releases of the app, based on a feature set and / or time schedule.

With the approach above you'll be able to track the work of each team or individual developer / tester and know when all issues on an app have been addressed so that you're ready to do into test or deployment.  I see you mentioned that you're not using a traditional product lifecycle, but unless your organization is very small and you develop apps that are thrown away after their first version is ready, I think you'll get a lot of benefit from this approach.


text:
Q: How can insert new line after each syndicationitem when using SynicationFeed class in dotnet 3.5? How can insert new line after each syndicationitem when using SynicationFeed class in dotnet 3.5?
when you see result of googlebot fetch (in webmasters), it its  ONE LINE!!!!!!

A: When you create your XMLWriter you can pass into the constructor some XMLWriterSettings and set the indent property to true. This will format your code. Here is an example of the feed and item creation using the AtomFormatter. I have not populated the feed and items with any date for readability.
//Create your feed and fill with data
SyndicationFeed feed = new SyndicationFeed();

//Create an item and fill with data
SyndicationItem item = new SyndicationItem();

//Add item to list and add list to feed
List<SyndicationItem> items = new List<SyndicationItem>();
feed.Items = items;

//Create XML file and serialize feed with XMLWriterSettings to indent code
XmlWriter writer = XmlWriter.Create("D:\\MyTestFile.xml", new XmlWriterSettings { Indent = true });
Atom10FeedFormatter formatter = new Atom10FeedFormatter(feed);
formatter.WriteTo(writer);
writer.Close();


text:
Q: Use python client to create Kubernetes CronJob from yaml I am trying to use the K8S python client to create a bunch of cronjobs on my cluster. I can't seem to find a create_from_yaml for cornjobs or any resources other than deployments for that matter. What I want to do is:
from kubernetes import client, utils

batchv1beta1 = client.BatchV1beta1Api()
utils.create_from_yaml(batchv1beta1, 'jobs/job-01.yaml')

But this doesn't work obviously since this is not a valid attribute. Any guidance is appreciated!

A: Actually, utils.create_from_yaml supports any Kubernetes objects. This should work:
from kubernetes import client, utils

k8s_client = client.ApiClient()
utils.create_from_yaml(k8s_client, 'jobs/job-01.yaml')


text:
Q: Do two SCHED_FIFO tasks with equal priority get processing time within each period in Linux? Do two SCHED_FIFO tasks with equal priority get processing time within each period in Linux, granted neither of the tasks finish before the period ends?
Linux documentation says SCHED_FIFO processes can get preempted only by processes with higher priority, but my understanding is that CFS operates on a higher layer, and assigns timeslots to each of the two tasks within each period.

A:
Linux documentation says SCHED_FIFO processes can get preempted only by processes with higher priority

This is correct, in addition to this, they can also be preempted if you set RLIMIT_RTTIME (getrlimit(2)) and that limit is reached.
The only other reasons why another SCHED_FIFO process (with the same priority) can be scheduled is if the first sleeps or if it voluntary yields (voluntary preemption).
CFS has nothing to do with SCHED_FIFO, it only takes care of SCHED_NORMAL, SCHED_BATCH and SCHED_IDLE.


text:
Q: Searching by date criteria OR Logic Here is what I am looking to do:
I currently have a report that I need to be able to search on either the post date or the admit date and the location. So for this logic I have something like this. The problem I get right now is that I get errors because date fields and not strings. Is there a way I modify this to work? Thanks!
({HSP_TRANSACTIONS.TX_POST_DATE}  in {?Start Date} or
({?Start Date} = '' and not isnull({HSP_TRANSACTIONS.TX_POST_DATE}))) and

({HSP_ACCOUNT.ADM_DATE_TIME} in {?Admit Date} or
({?Admit Date} = '' and not isnull ({HSP_ACCOUNT.ADM_DATE_TIME}))) and

(If {?Location} = "X" then ({HSP_ACCOUNT.ACCT_CLASS_HA_C} = '160' or {CLARITY_DEP.RPT_GRP_SIX} in[7,8])
else If {?Location} = "Y" then {HSP_ACCOUNT.ACCT_CLASS_HA_C} <> '160' or isnull({HSP_ACCOUNT.ACCT_CLASS_HA_C})=true
or {CLARITY_DEP.RPT_GRP_SIX} <> [7,8] or isnull({CLARITY_DEP.RPT_GRP_SIX})=true)

A: You're right: you cannot compare your parameter to an empty string because they are two different data types. If you want your {?Start Date} parameter to be optional you have to set it to be optional (by editing the parameter and setting Optional Prompt=True). Then, in your record selection formula you can check to see if that parameter has a value by using the hasvalue() function.

A: This is another way that I was able to do this for selection criteria that worked. I went and set default value of 1/1/1900 in my paramters for dates. Then:
(
if {?Start Date} = date(1900,1,1) then
{HSP.POST_DATE} = {HSP.POST_DATE}
else
{HSP.POST_DATE} in {?Start Date}
)
AND
(
if {?Admit Date} = date(1900,01,01) then
{HSP.DATE_TIME} = {HSP.DATE_TIME}
else
{HSP.DATE_TIME} > {?Admit Date}
)
AND
(If {?Location} = "X" then ({HSP.ACCT_CLASS} ='160' or {DEP.RPT_GRP_SIX} in[7,8])
else If {?Location} = "Y"
then {HSP.ACCT_CLASS} <> '160' or isnull({HSP.ACCT_CLASS})=true
or {DEP.RPT_GRP_SIX} <> [7,8] or isnull({DEP.RPT_GRP_SIX})=true)


text:
Q: PowerShell Ast for injection detection I am generating a ScriptBlock based on DB input which I invoke later in the script. I now want to ensure that a malicious user is not injecting any PS code in the DB varchar field that then gets executed.
First, I filtered the String Script Block for forbidden chars such as $ or ;. But I want to take it one step further and use AST to check if there is any executable code in the DB field.
When I use $Ast.FindAll for a specific element such as ForEachStatementAst it works fine.
However, I also want to be able to detect cmdlets etc in the String.
Examples that should be recognised as being ok:

*

*abc

*123

*'a','b'

*true

Examples that should be recognised as being not ok:

*

*Write-host or Remove-Item or any other get-command cmdlet.

*`$(MySubExpression)

When using AST visualisation, I get the same tree for both examples. ('abc', 'Write-Host')
ScriptBlockAst-> NamedBlockAst -> PipelineAst -> CommandAst -> StringConstantExpressionAst
Is there any way I can use AST to determine whether the DB field (or any string) contains only allowed entries such as non PS keywords / cmdlets, numbers etc but nothing that could be used as a PS command and that could be invoked?
The following code works for the test cases but I wonder if this can be achieved in a better way. If Res.count > 0, the input was not ok, if =0, it was ok.
$DebugPreference = 'Continue'
[System.Collections.Generic.List[System.String]]$InputStringList = New-Object -TypeName "System.Collections.Generic.List[System.String]"
$InputStringList.Add("foreach (`$x in @('a','b')){;}")
$InputStringList.Add("New-item -Path 'C:\Test.txt' -ItemType File")
$InputStringList.Add("Write-host 'as'")
$InputStringList.Add("abc")
$InputStringList.Add("a,b,c")
$InputStringList.Add("123")
$InputStringList.Add("true")
[System.Collections.Generic.List[System.Type]]$TypeList = New-Object -TypeName "System.Collections.Generic.List[System.Type]"
$TypeList.Add([System.Management.Automation.Language.StringLiteralToken])
$TypeList.Add([System.Management.Automation.Language.ScriptBlockAst])
$TypeList.Add([System.Management.Automation.Language.NamedBlockAst])
$TypeList.Add([System.Management.Automation.Language.StringConstantExpressionAst])
$TypeList.Add([System.Management.Automation.Language.ConstantExpressionAst])
$TypeList.Add([System.Management.Automation.Language.CommandExpressionAst])
$TypeList.Add([System.Management.Automation.Language.CommandAst])
$TypeList.Add([System.Management.Automation.Language.PipelineAst])
$TypeList.Add([System.Management.Automation.Language.ArrayLiteralAst])
[String[]]$CommandArray = (Get-Command | Select-Object -ExpandProperty 'Name')
[System.Management.Automation.ScriptBlock]$Predicate =
{
    param([System.Management.Automation.Language.Ast]$AstObject)
    Write-Debug -Message $AstObject.GetType().FullName
    if($AstObject -is [System.Management.Automation.Language.StringConstantExpressionAst])
    {
        if($AstObject.Value -in $CommandArray)
        {
            return $true
        }
        else
        {
            return $false
        }
    }
    else
    {
        return (-not($AstObject.GetType() -in $TypeList))
    }
}
$InputStringList.GetEnumerator() | ForEach-Object -Process `
{
    Write-Debug -Message ("Processing string: "+$PsItem.ToString())
    $ast = [System.Management.Automation.Language.Parser]::ParseInput($PsItem, [ref]$null, [ref]$null)
    $res=$ast.FindAll($Predicate, $true)
    Write-Debug -Message $res.count.ToString()
}

A: As commented, what you trying to do is creating your own restricted languagemode. Meaning that it would probably be easier to invoke the concerned scriptblock in an restricted runspace.
Derived from @mklement0 great answer for Automatically retrieve Allowed Types for Constrained Language mode:
Function Invoke-Restricted {
    [CmdletBinding()]param([String]$Expression)
    $Restricted = [powershell]::Create()
    $Restricted.Runspace.SessionStateProxy.LanguageMode = 'Restricted'
    Try { $Restricted.AddScript($expression).Invoke() }
    Catch { $PSCmdlet.ThrowTerminatingError($_) }
}

Restricted expression
Invoke-Restricted @'
    @{
        string    = 'abc'
        int       = 123
        array     = 'a','b'
        hashtable = @{ a = 1; b = 2 }
        boolean   = $true
    }
'@

Yields
Name                           Value
----                           -----
array                          {a, b}
int                            123
boolean                        True
string                         abc
hashtable                      {b, a}

Invalid expression
Invoke-Restricted @'
    @{
        TimeSpan = [TimeSpan]'12:34:45'
    }
'@

Throws an error:
Invoke-Restricted: Exception calling "Invoke" with "0" argument(s): "At line:1 char:1
+ [TimeSpan]"12:34:45"
+ ~~~~~~~~~~
The type TimeSpan is not allowed in restricted language mode or a Data section."

Yet, it has some limitations as it does not prevent e.g. the use of cmdlets.
For an easy and secure way to retrieve a (structured) configuration file I would depend on a serialized format as JSON using the ConvertFrom-Json cmdlet
Related: #12377 Running partly trusted PowerShell code in a restricted security environment.


text:
Q: How to detect if RDTSC returns a constant rate counter value? It seems most newer CPUs from both AMD and Intel implement rdtsc as a constant rate counter, avoiding the issues caused by frequency changing as a result of things like TurboBoost or power saving settings.
As rdtsc is a lot more suitable for performance measurements than QueryPerformanceCounter because of its much lower overhead, I would like to use it whenever possible.
How can I detect reliably if the rdtsc is a constant rate counter or not?

A: You can use CPUID to tell you. From the docs on CPUID Fn8000_0007_EDX bit 8:

TscInvariant: TSC invariant. The TSC rate is ensured to be invariant across all P-States, C-States, and stop grant transitions (such as STPCLK Throttling); therefore the TSC is suitable for use as a source of time. 0 = No such guarantee is made and software should avoid attempting to use the TSC as a source of time.

A: I know it's a long time since the original question was asked, but can I just point out that checking the generation/model of the processor is absolutely the WRONG thing to do. First of all, it's very easy to get the code wrong so that it doesn't work on future generation processors (because the family/model numbers aren't always "linear"), and secondly, just because a processor is "a later family/model" than the ones you knew this works on, it's not a guarantee that the feature is there. It's LIKELY, but I've seen plenty of code that does this badly, and thus "new processor comes out, and the code gets things wrong".
Use the CPUID bit to check if the processor has the correct bit or not.

A: just use CPUID to detect the generation of the CPU, see if its using constant counters. I'd however, suggest using a profiling API instead though, something like AMD's codeanalyst sdk would do well

A: I do count the number o ticks in a second and then compare to the informed clock at /proc/cpuinfo. It only works with dynamic clock disabled. See the source: https://github.com/petersenna/rdtscbench


text:
Q: Error Installing PG Gem on Windows I'm using XAMPP as my installation folder for PostgreSQL 9.3.

C:\xampp\pgsql\9.3

And now I'm trying to install PostgreSQL gem using that directory as a reference:
gem install pg -- --with-pg-include="C:\xampp\pgsql\9.3\include" --with-pg-lib="C:\xampp\pgsql\9.3\lib" --with-pg-config="C:\xampp\pgsql\9.3\bin\pg_config"

But this command failed with errors listed below:
ERROR:  Error installing pg:
        ERROR: Failed to build gem native extension.

    C:/Ruby/Ruby200/bin/ruby.exe extconf.rb --with-pg-include=C:\xampp\pgsql\9.3
\include --with-pg-lib=C:\xampp\pgsql\9.3\lib --with-pg-config=C:\xampp\pgsql\9.
3\bin\pg_config
Using config values from C:\xampp\pgsql\9.3\bin\pg_config
checking for libpq-fe.h... yes
checking for libpq/libpq-fs.h... yes
checking for pg_config_manual.h... yes
checking for PQconnectdb() in -lpq... no
checking for PQconnectdb() in -llibpq... no
checking for PQconnectdb() in -lms/libpq... no
Cant find the PostgreSQL client library (libpq)
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=C:/Ruby/Ruby200/bin/ruby
        --with-pg
        --without-pg
        --with-pg-config
        --with-pg-dir
        --without-pg-dir
        --with-pg-include=${pg-dir}/include
        --with-pg-lib=${pg-dir}/
        --with-pqlib
        --without-pqlib
        --with-libpqlib
        --without-libpqlib
        --with-ms/libpqlib
        --without-ms/libpqlib

extconf failed, exit code 1

Gem files will remain installed in C:/Ruby/Ruby200/lib/ruby/gems/2.0.0/gems/pg-0
.17.1 for inspection.
Results logged to C:/Ruby/Ruby200/lib/ruby/gems/2.0.0/extensions/x86-mingw32/2.0
.0/pg-0.17.1/gem_make.out

When I checked inside pgsql, there was actually a file named libpq.dll inside of

C:\xampp\pgsql\9.3\lib

So why did the error say it couldn't find the PostgreSQL client library (libpq)??
Is there any solutions for this error?
FYI, I'm using:

*

*Windows    8.1   64-bit

*Ruby       2.0.0 64-bit

*Rails      4.1.1

*Devkit     4.7.2 64-bit

*PostgreSQL 9.3.4 64-bit

And I'm trying to install PG Gem version 0.17.1

A: As a follow-up to the comments, it looks like you've got to use 32-bit Postgres on Windows.
This is most likely to do with the idea that the pg gem works with mingw32, although I'm not totally sure


text:
Q: MVC - Manually set form submit value from ViewData In a web app I'm creating, I have a list of clients. And each client has a sub-list of projects.
This is my Client model:
Public Class ppClient
    <Key()>
    Public Property ClientID As Integer
    Public Property Name As String

    Public Overridable Property Projects As ICollection(Of ppProject)
End Class

And here is my Project model:
Public Class ppProject
    <Key()>
    Public Property ProjectID As Integer
    Public Property ClientID As Integer
    Public Property ProjectTitle As String

    Public Overridable Property Client As ppClient
End Class

The problem I am encountering is that I am trying to manually add a form value when a new project is being created. I have the ClientID saved in ViewData, and so I don't want to ask the user for it. This is my view and form submission:
ModelType MVCnewDB.ppProject

@Using Html.BeginForm()
    @Html.ValidationSummary(True)

    @* Needs to submit ClientID *@

    Html.EditorFor(Function(model) model.ProjectTitle)
    Html.ValidationMessageFor(Function(model) model.ProjectTitle)
    @<input type="submit" value="Create Project" />
End Using

<div>
    @Html.ActionLink("Back", "Index")
</div>

So how do I get the form to submit ClientID as my ViewData value? Can I make a call to Html.HiddenFor and stuff a value into it or something?
Any help would be appreciated.

A: Ah okay - I've found what I was looking for. I was looking for @Html.Hidden("ClientID", ViewData("key")) which submits the given ViewData value to the form as the ClientID field.

A: You just need to add a hidden field.  I don't know how you would do it in VB, but in C# it would be like this:
@Html.HiddenFor(x => ViewBag.ClientID)

or
@Html.HiddenFor(x => ViewData["ClientID"])

A: This is how I interpret your question:

*

*You are on a page with a model bound to your ppProject class

*You have a ClientID somewhere and you want to know where to put it on the form so that...

*You want the form submission to include the ClientID so you can relate the ppProject to a client.

Is this correct?
If so, you have a couple options. If you've included your ClientID in a ViewBag, you can use a hidden field to store the value and submit it. On your action, you can actually specify more than one parameter. The first can be the ppProject class you want the model binder to bind your fields to, and another string parameter with the same name as the hidden field containing your ClientID value. As long as the parameter matches the hidden field name exactly, the model binder will match the two up and you'll get the ClientID.
(In C# because my VB.NET skills are too rusty for it to make sense:)
public ActionResult NewProject(ppProject projectInfo, string ClientID)
{
  ...
}

The above assumes you keep your view as-is but you add something like this:
<input type="hidden" name="ClientID" value="@ViewBag.ClientID" />

Or possibly (just a guess!):
Html.HiddenFor(Function(model) ViewBag.ClientID)

This assumes you've matched the ViewBag property name to the parameter name on your ActionResult in your controller. (Just replace the ViewBag with whatever you're using to store the ClientID value.)


text:
Q: Sharing same SQLite DB for two android apps I would like to maintain single sqlite DB for two applications. I have seen other links and this was helpful Share SQLite database between 2 android apps?
But still when I declare the shared user ID and shared context, I could not achieve it.
In my first app- SQLite is created with few tables.
In my second app=- I would to create tables in the same DB which I created in first app
And also in few posts, I read that this can be achieved through remote Database.
Please can some one suggest me good tutorial where I can have some idea on how to proceed?

A: I would recommend what you've asked about - which is using a remote database.
Check out this: how to use free cloud database with android app?
Look into a hosted database in the cloud. Quite a few of them will let you get started for free. I know IrisCouch lets you get going for free and it's very easy. http://www.iriscouch.com/ The nice thing about CouchDB is you can do all your work via HTTP - which isn't too hard from an Android device.


text:
Q: Internationalization (i18n) using JSF Facelets: Messages in Java-classes I have successfully implemented i18n in my project. Now I'm stuck in my Bean...
private String pageTitle;
public List<Product> getProductsByCategory(String category) {
  if(validate(category)) {
    pageTitle = category;
    return service.getProductsByCategory(String category);
  } else {
    pageTitle = "Random products";
    return service.getRandomProducts();
  }
}

As you can see, I would like to let my pageTitle depend on the result of the provided method. All fine, but this is not fine considering internationalization. I have tried using a Properties.load(new FileInputStream) approach, but this does not work considering the files are name base.properties, base_en_US.properties and so on.
Does anyone know the best practice in this kind of situation? Thanks in advance!

A: You need to use the same way as JSF is under the covers using to load resource bundles: using the ResourceBundle API. Here's an example assuming that the base name is com.example.i18n.base (exactly the value as you'd use in <f:loadBundle> in view or <resource-bundle> in faces-config.xml)
ResourceBundle bundle = ResourceBundle.getBundle("com.example.i18n.base",
    FacesContext.getCurrentInstance().getViewRoot().getLocale());
String pageTitle = bundle.getString("page.title");
// ...


text:
Q: appengine-web.xml - XML error validating when I try to deploy my App Engine Project, the following Valditation Error is shown:

An internal error occurred during: "Deploying Guestbook to Google".
  XML error validating C:\Users\Adrian\workspace\Guestbook\war\WEB-INF\appengine-web.xml against C:\eclipse\plugins\com.google.appengine.eclipse.sdkbundle_1.5.0.r36v201105092302\appengine-java-sdk-1.5.0\docs\appengine-web.xsd

Here is my appengine-web.xml:
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
    <application>adrianschaeferandroid</application>
    <version>1</version>

    <system-properties>
        <property name="java.util.logging.config.file" value="WEB-INF/logging.properties" />
    </system-properties>
    <static-files>
        <include path="/favicon.ico" />
    </static-files>
    <static-files>
        <include path="stylesheets/main.css" />
    </static-files>

</appengine-web-app>

Can anyone see the Validation Error? Shall I post the appengine-web.xsd?

A: you can only have 1 static-files element. if you have multiple include, you should nest them all within a static-files element.
thus the correct appengine-web.xml should be:
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
    <application>adrianschaeferandroid</application>
    <version>1</version>

    <system-properties>
        <property name="java.util.logging.config.file" value="WEB-INF/logging.properties" />
    </system-properties>
    <static-files>
        <include path="/favicon.ico" />
        <include path="stylesheets/main.css" />
    </static-files>

</appengine-web-app>

A: You will find it a lot easier to not make such errors if you configure your app GAE/Java app using an app.yaml file to generate both the web.xml and appengine-web.xml: https://developers.google.com/appengine/docs/java/configyaml/appconfig_yaml


text:
Q: Enabling LOAD DATA LOCAL INFILE in mysql LOAD DATA LOCAL INFILE is not enabled by default. Normally, it should be enabled by placing local-infile=1 in my.cnf. But it does not work for all installations. In my experience, it worked for Debian 7, but not Debian 7 minimal, though both installations come from the same precompiled deb package. Both on OpenVZ VPS.
How to debug why local-infile=1 does not work for an installation, and how to safely activate LOAD DATA LOCAL INFILE?

A: If the MySQL Debian-7 minimal cannot use local_infile, look around all the make files used for compiling to see if it is disabled by default or if local_infile is enabled for the Debian-7.
Before taking that kind of time, please run the following:
SHOW GLOBAL VARIABLES LIKE 'local_infile';
SET GLOBAL local_infile = 'ON';
SHOW GLOBAL VARIABLES LIKE 'local_infile';

It should echo the following:
mysql> SHOW GLOBAL VARIABLES LIKE 'local_infile';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile  | OFF   |
+---------------+-------+
1 row in set (0.00 sec)

mysql> SET GLOBAL local_infile = 'ON';
Query OK, 0 rows affected (0.06 sec)

mysql> SHOW GLOBAL VARIABLES LIKE 'local_infile';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile  | ON    |
+---------------+-------+
1 row in set (0.00 sec)

mysql>

If it still says 'OFF', then look deep within the compiler settings to enable it.
If it sets to 'ON', you are OK.
Please note I did not say
SET GLOBAL local_infile = 1;

I said use
SET GLOBAL local_infile = 'ON';

The option local_infile is Boolean, not numeric.
If setting this in my.cnf
[mysqld]
local_infile=ON

and restarting mysql does not work either,  you will have to start up mysql with something like this:
echo "SET GLOBAL local_infile = 'ON';" > /var/lib/mysql/init_file.sql
chown mysql:mysql /var/lib/mysql/init_file.sql
service mysql stop
service mysql start --init-file=/var/lib/mysql/init_file.sql
rm -f /var/lib/mysql/init_file.sql

or perhaps adding this to my.cnf
[mysqld]
init-file=/var/lib/mysql/init_file.sql

then restart mysql.
Give it a Try !!!

A: For default installation of MySQL 8.0.20 on Windows:

*

*Look for the initialization file located at C:\ProgramData\MySQL\MySQL Server 8.0\my.ini.

*Open my.ini file with a text editor.

*Look for the headers [client], [mysql] under the CLIENT section & [mysqld] under the SERVER section.

*Add the following statement under each of these headers:
local_infile=ON

*Save the file and restart MySQL80 service under the Windows local services.
It should work.


text:
Q: join two CSVs by IDs I have two CSV files like:
first.csv:
1,A B C
2,A D
3,T Q

second.csv:
1,
2,P A
3,
4,A O

Is is possible to join these two CSVs to make a CSV in similar format using pandas?
The output CSV should be like:
1,A B C
2,A D P
3,T Q
4,A O

A: Loop over each row of both of the CSVs and make a set of the combined lines:
import csv

with open('1.csv') as f1:
 with open('2.csv') as f2:
  with open('output.csv', 'w') as outfile:

   second_csv = csv.reader(f2.readlines())
   for first_row in csv.reader(f1.readlines()):
     second_row = second_csv.next()
     outfile.write(set(first_row+second_row)

A: Try:
import pandas as pd
first = pd.DataFrame('first.csv')
second = pd.DataFrame('second.csv')
third = pd.merge(first,second,  how='inner')

Pandas is king for loading csv data in and manipulating it later.

A: Here is one that does what you want; it doesn't use Pandas, but it also doesn't assume the file rows are in any particular order.
import csv
from itertools import chain
from collections import defaultdict

def load_csv(fname):
    with open(fname, 'rb') as inf:
        in_csv = csv.reader(inf)
        for row in in_csv:
            yield row

def write_csv(fname, rows):
    with open(fname, 'wb') as outf:
        csv.writer(outf).writerows(rows)

def main():
    # load data from several .csv files
    files = ['first.csv', 'second.csv']
    data = defaultdict(set)
    for key,items in chain(*(load_csv(f) for f in files)):
        data[key].update(items.split())

    # reorder data for output
    rows = ([key, ' '.join(sorted(data[key]))] for key in sorted(data.keys()))

    # write merged .csv file
    write_csv('output.csv', rows)

if __name__=="__main__":
    main()


text:
Q: Objective-C Location to label text I'm pretty new to objective c development.
I'm trying to get the longitude and latitude coordinates and assign the to labels.
However, when I load the app my labels don't update with the coordinates.
I'm sure that I am doing something very basic wrong but any help would be greatly appreciated!
.h :
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import "ViewController.h"

@interface StartCycleViewController : UIViewController <NSXMLParserDelegate, CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *longitudeLabel;
@property (weak, nonatomic) IBOutlet UILabel *latitudeLabel;
@property (nonatomic,strong) CLLocation *currentCycleLocation;
@property (nonatomic,strong) CLLocationManager *cycleLocation;

- (void) stopLocationManager;

@end

.m :
#import "StartCycleViewController.h"

@interface StartCycleViewController ()

@end

@implementation StartCycleViewController

@synthesize cycleLocation = _cycleLocation;
@synthesize currentCycleLocation = _currentCycleLocation;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self startCycleLocation];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - startCycleLocation

- (void)startCycleLocation{

    if (!_cycleLocation){
        _cycleLocation = [[CLLocationManager alloc]init];
        _cycleLocation.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
        _cycleLocation.distanceFilter = 10;
        _cycleLocation.delegate = self;

    }
    [_cycleLocation startUpdatingLocation];

}

-(void) cycleLocation:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
         fromLocation:(CLLocation *)oldLocation {

    NSLog(@"didUpdateToLocation: %@", newLocation);
    CLLocation *currentLocation = newLocation;

    if (currentLocation != nil) {
        self.longitudeLabel.text = [NSString stringWithFormat:@"%.8f",          currentLocation.coordinate.longitude];
        self.latitudeLabel.text = [NSString stringWithFormat:@"%.8f",   currentLocation.coordinate.latitude];
    }

}

- (void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"%@",error);

    if ( [error code] != kCLErrorLocationUnknown ){
        [self stopLocationManager];
    }
}

- (void) stopLocationManager {
    [self.cycleLocation stopUpdatingLocation];
}

@end

A: I would have left this as a comment, but I don't have the reputation to do so.
What is going on in the line where you update the label?
self.longitudeLabel.text = [NSString stringWithFormat:@"%.8f",      c    currentLocation.coordinate.longitude];

Why is that lone c there?
EDIT: So I realized this method
-(void) cycleLocation:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

was never getting called. After digging around I saw the method should be this instead:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

Replace the old signature with that one and it should work.


text:
Q: How to swap parameters in this debug case with php 7.4? – join() I'm updating an older website with a newer version of kirby (2.2.3 to 2.5.14) and php (5.6. to 7.4) and I'm getting this debug. I'm quite new to php and don't know how it should be written correctly with newer version of php. I checked existing questions/answers and I tried swapping parameters but didn't succeed yet. Any ideas? Thanks in advance!
anchors:[<?php echo "'" . join($pages->visible()->pluck('uri'), "','") . "'" ; ?>],

debug screenshot

A: Use implode like this -
echo "'" . implode("','", $pages->visible()->pluck('uri')) . "'" ;

Just swap the params.
Look for the docs on the web site here, make sure you use some sort of code inspection tool as a first step. Then check if you have any breaking changes and fix that. Then you check the new features for the next version and do the same up to the version you are on.


text:
Q: rsync - unexpected remote arg I am trying to rsync a folder from remote to local but get an error below. I have looked in many threads but can't find a solution that works.
kong@kong-P15SM:/media/kong/Elements$ rsync -r -i /home/kong/.ssh/id_rsantu --exclude=dataset/ e130167@35.123.456.78:~/sgan-original/ ./sgan-original/
Unexpected remote arg: e130167@35.123.456.78:~/sgan-original/
rsync error: syntax or usage error (code 1) at main.c(1348) [sender=3.1.1]

A: You seem to think that the option -i to rsync specifies the SSH key file like for ssh. It doesn't.

-i, --itemize-changes       output a change-summary for all updates

So your command basically is
rsync localdir user@host:remotedir localdir

If you have more that one source (everything except the last parameter), they all must be local.
Edit
What you want to use is probably
rsync -r -e "ssh -i /home/kong/.ssh/id_rsantu" --exclude=dataset/ e130167@35.123.456.78:~/sgan-original/ ./sgan-original/