text:
Q: WPF Combobox DataBound to a DataTable, Refresh automatically I have one combobox that I am databinding to a DataTable which is fetching the data from database as follows:
SqlDataAdapter adp = new SqlDataAdapter
    (@"SELECT [CategoryID],[CategoryName]FROM [Northwind].[dbo].[Categories]",
     @"Integrated Security=SSPI;Initial Catalog=Northwind;Data Source=AKSHAY-PC\SQLEXPRESS");

DataTable tbl = new DataTable();
adp.Fill(tbl);

cmbCities.ItemsSource = ((IListSource)tbl).GetList();

cmbCities.DisplayMemberPath = "[CategoryName]";
cmbCities.SelectedValuePath = "[CategoryID]";

When the table data is changed(added/removed rows), the combobox does not get refreshed because IList does not have the change notification built it.
Is there any way it can be made possible?
If it's not possible, is there any way to "refresh" the databinding so that the datatable will fetch the data again. In this case, what I will do is execute the above code when the window is initialized and then refresh it again without needing to execute the same code again. Something like cmbCities.Data.Refresh().

A: Below code will clear and fill the combobox from your sql adapter when you click the corresponding buttons.
XAML:
<Window x:Class="TestApp.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">

    <StackPanel>
        <ComboBox Name="cmbCities" />
        <Button Content="Clear" Click="OnClear"/>
        <Button Content="Fill" Click="OnFill"/>
    </StackPanel>

</Window>

Code behind:
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Windows;

namespace TestApp
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            _adp.Fill(_tbl);

            cmbCities.ItemsSource = ((IListSource)_tbl).GetList();

            cmbCities.DisplayMemberPath = "[CategoryName]";
            cmbCities.SelectedValuePath = "[CategoryID]";

            DataContext = this;
        }

        private void OnClear(object sender, RoutedEventArgs e)
        {
            _tbl.Clear();
        }

        private void OnFill(object sender, RoutedEventArgs e)
        {
            _adp.Fill(_tbl);
        }

        private DataTable _tbl = new DataTable();
        private SqlDataAdapter _adp = new SqlDataAdapter(@"SELECT [CategoryID],[CategoryName]FROM [Northwind].[dbo].[Categories]", @"Integrated Security=SSPI;Initial Catalog=Northwind;Data Source=AKSHAY-PC\SQLEXPRESS");

    }
}


text:
Q: Integration over a bounded set Let $S$ be a bounded set; let $f:S\to \mathbb{R}$ be a bounded continuous function. Let $A=\operatorname{int} S$, give an example where $\int_Af$ exists and  $\int_Sf$ does not (i'm working with Riemann integrals).
This proves that the converse of the following theorem is not always true:
If $f$ is Riemann-integrable over the bounded set $S$, then is also Riemann-integrable over $\operatorname{int} S$.

A: Consider $S=(\Bbb{Q} \cap [0,1] ) \cup [2,3]$ and $f(x)=1$. Clearly $f$ is continuous on $S$ since it is constant, and both $f$ and $S$ are bounded.
Now, $f$ is not Riemann integrable on $S$, but it is on $\operatorname{int} S =(2,3)$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pattern in a set of words and group them I need to find how related multiple words are to each other in a set of 5000 samples.
Sample:-

*

*mango, guava, litchi, apple

*mango, guava, litchi, orange

*mango, guava, pineapple, grape

*pen, pencil, book, copy, notebook

*pen, pencil, book, copy, scale

We see that 1 and 2 are very close to each other. 3 is almost close to 1 and 2. also we have 4 and 5 very close to each other.
What approach and technique we can use to check this correlation ?
Thanks in advance !
Revision : Need help in grouping as well , like group A consisting of line 1, 2, 3 and group B containing 4 and 5. ?

A: Here is one way to tackle this problem. I transform each list to document-term matrix using scikit-learn. Then compute cosine similarity matrix between each rows using scipy.spacial.distance.
from sklearn.feature_extraction.text import CountVectorizer
from scipy.spatial import distance

count_vect = CountVectorizer(tokenizer=lambda x: x.split(', '))

ls = ['mango, guava, litchi, apple',
      'mango, guava, litchi, orange',
      'mango, guava, pineapple, grape',
      'pen, pencil, book, copy, notebook',
      'pen, pencil, book, copy, scale']

X = count_vect.fit_transform(ls).toarray()
D = distance.cdist(X, X, metric='cosine')

Output is distance matrix between each row. It looks like following:
[[ 0.  ,  0.25,  0.5 ,  1.  ,  1.  ],
 [ 0.25,  0.  ,  0.5 ,  1.  ,  1.  ],
 [ 0.5 ,  0.5 ,  0.  ,  1.  ,  1.  ],
 [ 1.  ,  1.  ,  1.  ,  0.  ,  0.2 ],
 [ 1.  ,  1.  ,  1.  ,  0.2 ,  0.  ]])

For example D[0, 1] means that row 1 is close to row 2 because the distance between two row is small. Also, you can see that D[3, 4] is small which means row 4 is close to row 5.
note you can also consider using distance.pdist(X, metric='cosine') which give lower diagonal of the matrix only because lower and upper diagonal are equal.
Grouping documents
To be more fancy, you can cluster each rows together with calculated distance matrix using hierarchical clustering.
from scipy.cluster import hierarchy

D = distance.pdist(X, metric='cosine')
Z = hierarchy.linkage(D, metric='euclidean')
partition = hcluster.fcluster(Z, t=0.8, criterion='distance') # [2, 2, 2, 1, 1]

which means document 1,2,3 are grouped together in group 2 and 4,5 are grouped together in group 1. If you plot the dendrogram, you can see how each rows get clustered together
from scipy.cluster.hierarchy import dendrogram
import matplotlib.pyplot as plt

hierarchy.dendrogram(Z, above_threshold_color='#bcbddc',
                     orientation='top')

A: Another approach, or maybe another idea of a new start to solve your question:
import re
from itertools import chain

a = ['mango, guava, litchi, apple',
      'mango, guava, litchi, orange',
      'mango, guava, pineapple, grape',
      'pen, pencil, book, copy, notebook',
      'pen, pencil, book, copy, scale']

def get_words(lst):
    return [re.findall(r'[\w]+', k) for k in a]

def get_percent(lst):
    groupped_valid_dict = {}
    for k in range(len(lst)):
        sub = []
        for j in range(k+1, len(lst)):
            s = sum([1 if m == n else 0 for m, n in zip(lst[k], lst[j])])
            #percent = (1 - float(len(lst[k]) - s)/len(lst[k])) * 100
            #fmt = '%.2f%%' % percent
            #print 'Words of lines: %d and %d are %s close' %(k+1, j+1, fmt)
            if s > 0:
                sub.append("Line{}".format(j+1))
        if sub:
            groupped_valid_dict["Line{}".format(k+1)] = sub
    return groupped_valid_dict

lst = get_words(a)
lines  = get_percent(lst)
groups = [[k] + lines[k] for k in lines if k not in chain.from_iterable(lines.values())]
groups.sort(key=lambda x: x[0])

for k, v in enumerate(groups, 1):
    print "Group%d" %k, v

Output:
Group1 ['Line1', 'Line2', 'Line3']
Group2 ['Line4', 'Line5']


text:
Q: Live() function not working with some elements I'm trying to bind some change events to a select element which has been previously been transformed by jqTransform (http://www.dfc-e.com/metiers/multimedia/opensource/jqtransform/).
As change() function does not work after this transformation, I've followed this excellent advice from Code-Pal. Then I'm trying to apply a click function with the live() event (as future forms will be called with Ajax).
So far I've got this, which does not work:
$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper ul li a").live('click', function(e) {
console.log("Testing");
});

Strangely, this DOES work:
$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper ul li a").bind('click', function(e) {
console.log("Testing");
});

And even this:
$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper").live('click', function(e) {
console.log("Testing");
});

So it's not that jqTransform is still not loaded. For some reason, live() stops working as soon as I'm selecting elements from a list. Any idea of what could be happening?
This is the html code after the jqtransform:

    Tarjeta estándar

      Tarjeta estándar

      Tarjetas cantos redondos

      Tarjetas doble

      Tarjeta PVC

      Tarjeta adhesiva

  <select id="id-subproducto" class="jqTransformHidden" name="subproducto" style="">
    <option value="1">Tarjeta estándar</option>
    <option value="2">Tarjetas cantos redondos</option>
    <option value="3">Tarjetas doble</option>
    <option value="4">Tarjeta PVC</option>
    <option value="5">Tarjeta adhesiva</option>
  </select>

Thanks in advance!

A: I dont have exactly the same selectors but it all seems to be working:
http://jsfiddle.net/HenryGarle/DeYH2/1/
$("div#caracteristicas-form-wrap div.jqTransformSelectWrapper ul li a").live('click', function(e) {
   alert("Testing");
});

Edit: Updated to use the same selectors

A: If you're having trouble with jQuery live you might want to check out delegate instead.
Also have a look at Why You Should Never Use jQuery Live

A: Well guys, after struggling with jqTransform for too many projects, I've switched to UniformJS. Working with it is easier, my life is nicer, the colors in the sky are brighter and girls smile et me when I'm walking down any street.
I recommend it.


text:
Q: ST_Intersects PostGIS returns empty table Here is a link to download the two layers I am working with (as geopackages).
I have two tables in a PostgreSQL database, 'WataugaResidential' and 'zone1shape'. I'm trying to use ST_Intersects function from PostGIS to see where they overlap. Using QGIS, if I run the Vector > Research Tools > Select by Location I get the following result:

Trying to do the same in PostgreSQL, I get an empty table returned as my result. Here is the SQL code I'm using:
SELECT res.*
FROM public."WataugaResidential" as res, public."zone1shape" as z1
WHERE ST_Intersects(res.geom, z1.geom);

Pretty simple stuff. But my result is an empty table. All the columns are there, but no data. Result:

Why is nothing returned?


text:
Q: About AVL tree and their height - is there a mistake in our readings script? I learn for exam and I use our script too for learn. I agree with all step but I don't understand the red circle ) I make it read for you). Because there is the tree root balance -1. How can this be correct?
The balance of the left subtree of the root 10 is -4, its right subtree has balance +2, so in total we have -4+2 = -2 = unbalanced after insertion of 8. But how our professor has -1 as result?
I understand something wrong here?

A: You essentially have the exact same weight difference in step 2 and 4. Yes, the tree is imbalanced, and that's being marked by *p and φp , which I assume you were taught are the rotation points
The negative one is just the notation of the weight "lean"


text:
Q: How to check if a file is in read-only mode in C How I can check if a file is in read-only mode in C? I would like to check if it is possible write in a file before opening it.

A: This is a case where it is easiest and most reliable to try opening the file for writing, and react appropriately if the open fails ('Easier to Ask for Forgiveness than for Permission') than to try and determine whether it will fail first ('Look Before You Leap') — see LBYL vs EAFP.
You can use stat(), but it is modestly tricky to determine the permissions correctly.  Also, there could be ACLs that mean you can access the file for writing even if the permissions reported by stat() indicate that you can't (or vice versa).  You could use access(filename, W_OK), and it will usually give you the correct answer — unless your program is running with effective UID different from real UID.
However, any LBYL strategy also suffers from TOCTOU — Time of Check, Time of Use — issues.  The permissions on the file, or one of the directories leading to it, might change between the time when you check the file permissions and the time when you actually try to open the file.  The permissions might have said "it is OK" but the file could have been removed, or changed to read-only since then.

A: You can use fstat() function.
See man 2 fstat for details:
http://linux.die.net/man/2/fstat

A: You can use fopen, and check for the return value. Check here: http://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm

A: While retrieving the file permissions with the fstat/stat functions will give you good hints is the usual cases, I would recommend not to trust them too much as there are corner ones where the file will be writable despite being reported read only, for example if you are root, and also cases you won't be able to write the file despite being reported writeable, for example if it is located on a read-only file system.
ACLs might also play a similarly confusing role by reversing what the st_mode is reporting.


text:
Q: Keep a single document in mongoDB collection using mongoose I created a collection but that one should keep a single document inside.
How do I ensure that there is a single document in mongoose schema?

A: You can create "capped" collections, where you can set limit of documents, you can store in it.
It does not however prevent adding another document (not sure, if you need that functionality) - if you add another document, the old one would be deleted.
db.createCollection('mycappedcol',{capped: true, size:999999, max:1})

Also you cant delete documents from capped collections, you can only replace them with new ones or drop the whole collection.
PS : In capped collections, you have to specify size in bytes, which is also a limit (collection cant be bigger than specified size). If you do not care about size, but you care only about limit, just set size big enough.


text:
Q: What setting do I use to enable live feedback on what code would give compilation error in the minizinc IDE? The title basicly says it all:
What setting do I use to enable live feedback on what code would give compilation error in the minizinc IDE?
Right now, I have to use ctrl + S to save before I can see the red squiggly line.


text:
Q: How to eliminate dead code in Dymola/Modelica I am trying to slim down a very complex model to improve performance, and noticed big performance changes when I add or remove variables into the signal bus, especially multi-body frames.
I am wondering if there is any setting that can eliminate code that isn't involved in generating outputs from the model.
I tried setting the bus connector to "protected" to ensure it doesn't become an output but the code to calculate them is still being generated.
I also tried these flags but it doesn't eliminate the dead code:
Advanced.Embedded.OptimizeForOutputs=true;
Advanced.SubstituteVariablesUsedOnce=true;
Evaluate=true;
Advanced.EvaluateAlsoTop=true;
Advanced.SubstituteVariablesUsedOnce=true;

This is a simple model to replicate the scenario:

model TestBusConnector
  extends Modelica.Icons.Example;
protected
        Modelica.Blocks.Examples.BusUsage_Utilities.Interfaces.ControlBus controlBus
    annotation (Placement(transformation(extent={{-20,-20},{20,20}})));
public
  Modelica.Blocks.Sources.Sine sine(freqHz=1)
    annotation (Placement(transformation(extent={{-40,-50},{-20,-30}})));
  Modelica.Blocks.Sources.Constant const(k=0)
    annotation (Placement(transformation(extent={{-10,50},{10,70}})));
  Modelica.Blocks.Interfaces.RealOutput y
    annotation (Placement(transformation(extent={{90,-10},{110,10}})));
equation
  connect(y, const.y) annotation (Line(points={{100,0},{60,0},{60,60},{11,60}}, color={0,0,127}));
  connect(sine.y, controlBus.testBusVariable)
    annotation (Line(points={{-19,-40},{0,-40},{0,0}}, color={0,0,127}));
  annotation (experiment(__Dymola_fixedstepsize=0.001, __Dymola_Algorithm="Euler"),
      __Dymola_experimentFlags(Advanced(
        InlineMethod=0,
        InlineOrder=2,
        InlineFixedStep=0.001)),
    __Dymola_experimentSetupOutput(
      states=false,
      derivatives=false,
      inputs=false,
      outputs=false,
      auxiliaries=false,
      equidistant=false,
      events=false));
end TestBusConnector;

Code generated from Dymola 2019 FD01 is shown below:
include <dsblock6.c>

PreNonAliasNew(0)
StartNonAlias(0)
DeclareVariable("sine.amplitude", "Amplitude of sine wave", 1, 0.0,0.0,0.0,0,513)
DeclareVariable("sine.freqHz", "Frequency of sine wave [Hz]", 1, 0.0,0.0,0.0,0,513)
DeclareVariable("sine.phase", "Phase of sine wave [rad|deg]", 0, 0.0,0.0,0.0,0,513)
DeclareVariable("sine.offset", "Offset of output signal", 0, 0.0,0.0,0.0,0,513)
DeclareVariable("sine.startTime", "Output = offset for time < startTime [s]", 0,\
 0.0,0.0,0.0,0,513)
DeclareVariable("sine.y", "Connector of Real output signal", 0.0, 0.0,0.0,0.0,0,512)
DeclareVariable("const.k", "Constant output value", 0, 0.0,0.0,0.0,0,513)
DeclareVariable("const.y", "Connector of Real output signal", 0, 0.0,0.0,0.0,0,513)
DeclareOutput("y", "", 0, 0.0, 0.0,0.0,0.0,0,513)
DeclareAlias2("controlBus.testBusVariable", "Connector of Real output signal", \
"sine.y", 1, 5, 5, 1028)
EndNonAlias(0)

#define DymolaHaveUpdateInitVars 1
#include <dsblock5.c>

DYMOLA_STATIC void UpdateInitVars(double*time, double* X_, double* XD_, double* U_, double* DP_, int IP_[], Dymola_bool LP_[], double* F_, double* Y_, double* W_, double QZ_[], double duser_[], int iuser_[], void*cuser_[],struct DYNInstanceData*did_,int initialCall) {
}
StartDataBlock
EndDataBlock

The translated modelica code (dsmodel.mof) still has the calculation for the sine block.
// Translated Modelica model generated by Dymola from Modelica model
//  TEMP.TEST.TestBusConnector

// -----------------------------------------------------------------------------

// Initial Section
  sine.amplitude := 1;
  sine.freqHz := 1;
  sine.phase := 0;
  sine.offset := 0;
  sine.startTime := 0;
  const.k := 0;
  const.y := 0;
  y := 0.0;

// -----------------------------------------------------------------------------

// Conditionally Accepted Section
  sine.y := (if time < 0 then 0 else sin(6.283185307179586*time));

// -----------------------------------------------------------------------------

// Eliminated alias variables
  // To have eliminated alias variables listed, set
  //   Advanced.OutputModelicaCodeWithAliasVariables = true
  // before translation. May give much output.

Ideally, I would like the model to translate to:
y := 0.0;

A: The reason the other answers don't work is that your model is not consistent with your question:
"I am wondering if there is any setting that can eliminate code that isn't involved in generating outputs from the model."
By connecting the control-bus to sine.y you implicitly create an output, and thus sine.y is involved in generating outputs from the model.
That can be avoided in one of the following ways:

*

*Remove the connection between sine.y and controlBus

*Change controlBus to be protected

*Change so that controlBus isn't at the top-level

A: It's not a direct answer to your question, but still it could help to improve performance. Part of the computational effort you are trying to avoid is generated by computing variables in the result file. This can be avoided by the settings below:

This can be set as an annotation in the model itself using:
  annotation (__Dymola_experimentSetupOutput(
      states=false,
      derivatives=false,
      inputs=false,
      auxiliaries=false));

A: There is another flag which could help. It does not give the result you expected, but it might be still useful:
Advanced.Define.AutoRemoveAuxiliaries = true;

The Dymola User Manual 2 describes the flag as follows:

Removes code for auxiliary variables that neither influences the
  simulation state nor the outputs. This improves performance a bit.

From this description my expectation was that the code is generated like you asked for, but unfortunately it is not the case.


text:
Q: Why do Apple's 2012 MacBook Pros cap the RAM limit at 8GB? According to apple's latest documentation (at the time of writing), the cap on the 2012 MacBook Pros is 8GB RAM.
The Mac Pros, however, can take up to 32GB RAM.
So, why do the MacBooks have this cap? Is it a hardware issue, because I don't think it's a software one.
The OS X that runs on the Mac Pros is the same that runs on the MacBook Pros. Being 64-bit software on top of a 64-bit Architecture (both the MacBooks and the Mac Pros), it's obvious that the OS can use as much as 32 GB of RAM.
Is it simply because manufactures don't make RAM sticks larger than 4GB for laptops?

A: Anyone who knows isn't saying.  But apparently they can use up to 16GB. Other World Computing tests various machines for their actual (not specified) maximum useable memory and sells a 16GB memory kit for the current MacBook Pro.

A: The limitation imposed is based on the chipsets used on the computer's motherboard. For example, the noted Apple maximums you mentioned for the MacBook Pro and the Mac Pro, are smaller than the maximums that those machines can address in practice. The MacBook Pro tested maximum is 16 GB according to EveryMac's MacBook Pro max RAM listing. And as for the Mac Pro, its maximum is 128 GB according to EveryMac's Mac Pro max RAM listing.
As noted on Intel's Specs, the CPU supports a different maximum than the chipset on the motherboard does. The Xeon X5670 used in the Mac Pro supports up to 288 GB.
And as for the i7s e.g. a i7-2860QM used in the MacBook Pros, it supports up to 32 GB.
So these limitations come from engineering decisions made by Apple based on what kinds of chipsets are selected to be installed on the motherboard and what those chips support is what enforces the maximum amount of RAM that a particular Mac can address at or below what the CPU can actually address.
As for why Apple underrates their maximum numbers for RAM on some Macs, that's for Apple to know and for us to wonder. However, admittedly it is a nice practice to under promise and over deliver for whatever reason Apple has. Although, the Mac Pro supports more RAM than Mac OS X can address, according to OWC's testing on Mac Pros, where they discovered Mac OS X unofficially will not address more than 96GB of RAM, but other 64-bit operating system can get to the full 128GB.

A: The Apple specs are never updated. For the MacbookPro 2012 it was 8GB of Ram. Later it has been tested by many many users to be max 16GB. Mine has 18GB from the beginning even (1 week after I bought it in 2012). The only point that you must "obey" is that the Ram has the exact specs as prescribed by Apple specs. There are many producers of Ram for mac.
If you want the modern or updated limits, download Mactracker from http://mactracker.ca/ or from the AppStore

A: Because they want to make more money by having you pay for more ram. I work with windows all the time. I have a dual boot on my mac. The mac end only sees 8gb of ram installed but windows utilizes all 16. hardware that meets the specifications required will work in the hardware world. It is the software that determines how it's utilized. Trust me I build gaming rigs all the time.


text:
Q: Find the root of $x(t;A)=0$ for ordinary differential equation $\ddot{x}(t;A)=A(p(t)\dot{x}(t;A)+q(t)x(t;A))$ It is given an ordinary differential equation $\ddot{x}(t;A)=A(p(t)\dot{x}(t;A)+q(t)x(t;A))$ with real parameter $A$, initial conditions $x(t=0;A)=1,\dot{x}(t=0;A)=0$ for all real $A$. If $r(A)$ is the root of $x(t;A)=0$, i.e. $x(r(A);A)=0$, is it possible to determine $r(A)$ (or at least determine some properties of it) in terms of the forms of $p(t),q(t)$? Especially important is the correlation between $r(A)$ and $A$, e.g. whether they are correlated linearly, exponentially, etc, given the forms of $p(t)$ and $q(t)$.
The $x(t;A)$ that I am dealing in my actual problem only has one root, so whenever necessary, this can be taken as an assumption. If the general case is unsolvable, then it is also good if the problem can be solved for special  forms of $p(t),q(t)$, e.g. $p(ct)=c^\gamma p(t), q(ct)=c^\gamma q(t)$ for some real/complex $\gamma$.


text:
Q: Cannot modify Derived that was static_pointer_cast from a vector> The title describes the situation, but the underlying problem might be something completely different.
I am trying to make a simple ECS game engine. I have a bunch of entities where each one contains a vector<shared_ptr<Component>>. Component is the base class for all the derived components.
During the game loop i have different Systems that update entities with certain components. The way I get the correct component for the system is with the following function
        template <typename T>
        inline T& GetComponent(std::uint32_t type)
        {
            std::shared_ptr<Component> baseComponent = this->components[this->typeToIndexMap[type]];
            std::shared_ptr<T> component = std::static_pointer_cast<T>(baseComponent);
            return *(component.get());
        }

The issue is that when I try to modify the component in the system  (inputComponent.lastX = 5.f;) it does not work. The next frame the values are the same. I am guessing that there happens some kind of cutoff because i am storing Component but am not sure how to solve this. Any ideas if that is actually the case and how I can solve it ?
Edit : Additional info
Entity holds components in a vector<shared_ptr<Component>>
Adding a Component
void Entity::AddComponent(std::shared_ptr<Component> component)
{
    this->components.push_back(component);
    this->componentBitset = this->componentBitset | component->GetComponentType();
    this->typeToIndexMap[component->GetComponentType()] = this->components.size() - 1;
}

Component Creation
std::shared_ptr<InputComponent> inputComponent = std::make_shared<InputComponent>(InputComponent());
entity->AddComponent(inputComponent);

Component Structure
class Component
{
public:
    // Constructor / Destructor
    Component(std::uint32_t type);
    ~Component();
    std::uint32_t GetComponentType();

private:
    std::uint32_t type;
};

Input Component
class InputComponent : public Component
{
    public:
        InputComponent();
        ~InputComponent();

        double lastX;
        double lastY;
};

Finally we have the system
void InputSystem::Update(GLFWwindow* window, std::vector<std::shared_ptr<Entity>>& entities)
{
    for (int i = 0; i < entities.size(); i++)
    {
        if (entities[i]->IsEligibleForSystem(this->primaryBitset))
        {
            InputComponent component = entities[i]->GetComponent<InputComponent>(ComponentType::Input);
            double x, y;
            glfwGetCursorPos(window, &x, &y);
            // some other things are happening here
            component.lastX = x;
            component.lastY = y;
        }
    }
}

A: The problem is here:
InputComponent component = entities[i]->GetComponent<InputComponent>(ComponentType::Input);

You actually gets the InputComponent by value. Try to change GetComponent so it will return T*, and the first line I mentioned here change to:
InputComponent *component = entities[i]->GetComponent<InputComponent>(ComponentType::Input);


text:
Q: Cannot reduce "SELECT" queries with "select_related()" and "prefetch_related()" in one-to-one relationship in Django I have Person and PersonDetail models in one-to-one relationship as shown below. *I use Django 3.2.16:
class Person(models.Model):
    name = models.CharField(max_length=20)

    def __str__(self):
        return self.name

class PersonDetail(models.Model):
    person = models.OneToOneField(Person, on_delete=models.CASCADE) # Here
    age = models.IntegerField()
    gender = models.CharField(max_length=20)

    def __str__(self):
        return str(self.age) + " " + self.gender

Then, I have 5 objects for Person and PersonDetail models each:

Then, I iterate PersonDetail model from Person model as shown below:
for obj in Person.objects.all():
    print(obj.persondetail)

Or, I iterate PersonDetail model from Person model with select_related() as shown below:
for obj in Person.objects.select_related().all():
    print(obj.persondetail)

Or, I iterate PersonDetail model from Person model with prefetch_related() as shown below:
for obj in Person.objects.prefetch_related().all():
    print(obj.persondetail)

Then, these below are outputted on console:
32 Male
26 Female
18 Male
27 Female
57 Male

Then, 6 SELECT queries are run as shown below for all 3 cases of the code above. *I use PostgreSQL and these below are the query logs of PostgreSQL and you can see my answer explaining how to enable and disable the query logs on PostgreSQL:

So, I cannot reduce 5 SELECT queries with select_related() and prefetch_related() in one-to-one relationship in Django.
So, is it impossible to reduce SELECT queries with select_related() and prefetch_related() in one-to-one relationship in Django?

A: You will have to specify the name of the related field which in this case is persondetail, so:
for obj in Person.objects.select_related("persondetail").all():
    print(obj.persondetail)


text:
Q: Point vs dot: when to use what? I would like to know how the punctuation in the following would be spoken when dictating letter by letter.
Although there are already some partial answers to the question when to say "point" and when to say "dot" there are still cases missing, and there is no comparison that connects it to the different usages of the symbol ".".
Therefore my question: how would I read the points/dots in the following examples?
(In some cases they will usually not be pronounced at all.)

*

*the number 3.42

*the amount €156.76

*the IP address 1.92.34.76

*the enumeration 1. paragraph

*the regular sentence Just because.

*the unusual sentence Do. Not. Ask.

*the abbreviation St. Germain

*the abbreviation Main St.

*the URL stackoverflow.com

A: "Point" is usually used when dealing with decimal numbers, that is an abbreviation of "decimal point", for example:
1.25 would be pronounced: "One point two five"
In aviation - a safety critical environment with lots of radio traffic and many non-english speakers this would be pronounced:
"Wun desceemal two fife", [One decimal two five], simply because this has been found to convey the correct meaning to someone on the other end of a radio transmission.  Similarly [just for fun...] . Three is pronounced "Tree", but I digress...
So:
The number 3.42                                 Point...
the amount €156.76                              One hundred and fifty six, seventy six [Euro]
the IP address 1.92.34.76                       Point or decimal, useful if reading to some one over the phone / radio, as above...
the enumeration 1. paragraph                    Point . Also in section headings 1.1.1 = "Section one point one point one"
the regular sentence Just because.              Full stop or 'Period' - if necessary (USA)!
the unusual sentence Do. Not. Ask.              Bad grammar, I might use an ellipsis to convey a brief pause for emphasis:  "Do... Not... Ask!"
the abbreviation St. Germain                    Full stop - normally omitted in UK as now considered archaic, i.e. Mr Bloggs in UK (I must be getting old because I still use it!), so probably 'Period' as its use carries more favour in the US: Mr. Bloggs.
the abbreviation Main St.                       Full stop, as above
the URL stackoverflow.com                       Dot, as in "Dot Com" (XYZ.com), or "Dot Co, Dot UK" (XYZ.co.uk)

A: Partial answer:
3.42 is read "three point four two".
The amount 156.76€ should be written €156.76. With some currency amounts, the unit symbol goes after the numeral, but with euros the symbol goes before. €156.76 might be read "156 euros 76", or, more fully, "156 euros and 76 cents". The "." isn't specifically mentioned.
I don't know what you mean by "1. paragraph". It's the custom in German to write 1., 2. etc. where we'd write 1st, 2nd. In a case like that, we'd say the full word that the abbreviation stands for. For example "First paragraph".
"stackoverflow.com" is read as "stackoverflow dot com".


text:
Q: How to get last sms from the device? I have been developing the application which must recognize SMS commands. So, I need to know how I can get the last sms. I know that I need to use BroadcastReceiver (and I use it), but I don't know how I can get the last sms in this class. Please, help me with it, I hope you can do it. Thank you in advance.

A: thanks Bo for the link to my blog.
To get the last message from your embeded android database (sqlite) you have at first create a cursor instance.
Cursor cursor = context.getContentResolver().query("content://sms", null, null, null, null);

and then move to the first sms (the first is the last receiver ;))
cursor.moveToFirst();

Look at my blog how I did it as Bo told you ;)
// removed link
Cheers

A: see below code it may help you.
                    Uri myMessage = Uri.parse("content://sms/");

                    ContentResolver cr = con.getContentResolver();
                    Cursor c = cr.query(myMessage, new String[] { "_id",
                            "address", "date", "body", "read" }, null,
                            null, null);

                    startManagingCursor(c);
                    Main_calss.getSmsLogs(c, con);

public static final ArrayList<String> sms_num = new ArrayList<String>();
public static final ArrayList<String> sms_body = new ArrayList<String>();

public static void getSmsLogs(Cursor c, Context con) {

    if (sms_num.size() > 0) {
        sms_num.clear();
        sms_body.clear();
    }

    try {

        if (c.moveToFirst()) {
            do {
                Log.d("error",
                        ""
                                + c.getString(c
                                        .getColumnIndexOrThrow("address")));
                if (c.getString(c.getColumnIndexOrThrow("address")) == null) {
                    c.moveToNext();
                    continue;
                }

                String Number = c.getString(
                        c.getColumnIndexOrThrow("address")).toString();
                String Body = c.getString(c.getColumnIndexOrThrow("body"))
                        .toString();

                sms_num.add(Number);

                sms_body.add(Body);
            } while (c.moveToNext());
        }
        c.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

now get last massage you have to do this.
sms_num.get(sms_num.size()-1);
sms_body.get(sms_num.size()-1);

if it is correct then make it right.


text:
Q: Python - Determine if Item is in a List Using a Function I'm trying to write a function in Python to determine whether or not an item is in a list. I've been trying variations of this code.
No matter how I try it, it always returns a FALSE Boolean value. Even if I put the print commands inside the functions, it only prints with the results for a false value. I'm pretty sure I'm passing the list to the function properly, but I can't figure out why it only determines FALSE values. Any ideas?
def newFunction(x, y, z):
   z = 0
   if y in x:
      z = True
   else:
      z = False
   return (z)

newList = [2,4,6,8,10]
r = input ('Enter a number: ')
s = 0
newFunction(newList, r, s)
if s == True:
   print ('The no. IS in the list.')
else:
   print ('The no. IS NOT in the list.')

A: There are a few things going on here:

*

*input() returns a string, so you need to convert it into an int.

*You're not doing anything with the value returned by the function.

*Related to the above, you don't need the z parameter in the function. Were you expecting the value of the variable outside the function to change?

*If you absolutely need to explicitly compare a value with a boolean, use is, not ==. In this case, if found: is all you need.

*The if statement inside the function can be removed entirely.

*Variable and function names should follow the lower_case_with_underscores style.

A refactored version of your code would look something like this:
def in_list(targ_list, elem):
    return elem in targ_list

nums_list = [2, 4, 6, 8, 10]
num_in = int(input("Enter a number: "))

res = in_list(nums_list, num_in)

print(res)

if res:
    print('The no. IS in the list.')
else:
    print('The no. IS NOT in the list.')

A: You should save the result of your function and convert the input to an integer for it to work.
def newFunction(x, y, z):
   z = 0
   if y in x:
      z = True
   else:
      z = False
   return (z)

newList = [2,4,6,8,10]
r = input ('Enter a number: ')
s = 0
found = newFunction(newList, int(r), s)
print(found)
if found == True:
   print ('The no. IS in the list.')
else:
   print ('The no. IS NOT in the list.')

You can also improve your current implementation by having a simpler function.
def newFunction(valueList, userInput):
   return userInput in valueList

A: You are not setting the s - you run the function but it does not assign to s so change to:
s = newFunction(newList, r, s)

You can also remove the 'z' as an argument and instead return False/True in each If condition.

A: There is a simpler way to do this. Do note that the input would be type string, so you need to convert to int.
newList = [2,4,6,8,10]

def newFunction(x, newList):
    if x in newList:
        return True
    else:
        return False

x = int(input("Enter a number"))
if newFunction(x, newList) == True:
    print("it is in the list")
else:
    print("it is not in the list")

Shorter way:
newList = [2,4,6,8,10]

x = int(input("enter a number"))
if x in newList:
    print("it is in the list")
else:
    print("it is not in the list")


text:
Q: UserInfo.getProfileId(); on test class I'm writing a test class where I need to create an activity with the current user's userid. The test class passes, but no matter what I do Salesforce will not let me upload it. The problem is the user.profileid field.

*

*If I do not include this field in my test class, it tells me this is a required field and I have to have it.

System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [ProfileId]: [ProfileId]

*If I make up a fake profile id, it tells me the profile id is invalid.

System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []
      Stack Trace: Class.ActivityHistoryOnProposalTest.getUserId: line 18, column 1

*If I set the id to UserInfo.getProfileId(), Salesforce complains that I have a duplicate username.

System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_USERNAME, Duplicate Username.The username already exists in this or another Salesforce organization. Usernames must be unique across all Salesforce organizations. To resolve, use a different username (it doesn't need to match the user's email address). : [Username]
      Stack Trace: Class.ActivityHistoryOnPropertyTest.getUserId: line 20, column 1

There seems to be no way to correctly write this test class.
Class:
public class ActivityHistoryOnProposal{

public String currentUser = UserInfo.getUserId();
public String oldUser;

public String currentP = ApexPages.currentPage().getParameters().get('id');
    public String taskList {get;set;}
    public String soql {get;set;}

    public Task[] getListTasks() {

     oldUser=[select old_ID__c from User where id=:currentUser limit 1]
 [0].old_ID__c;

 taskList = 'select whoid,subject,status, ActivityDate, LastModifiedDate, WhatID, Description, Primary_Contact_Phone_Number__c, Primary_Contact_Email_Address__c, Call_Result__c, Last_Call_Date__c, Last_Call_Agent__c from task WHERE (CreatedbyId=\''+currentUser+'\' OR OLDOWNERID__C=\''+oldUser+'\') AND WhatID =\''+currentP+'\' order by ActivityDate desc limit 20000';
 System.debug('~~~~~~'+tasklist);

   //sort out the Listings records
   List<Task> tskList = new List<Task>();
   List<Task> tskListPreSort= Database.query(taskList);

 for (task i:tskListPreSort)
{
if (i.whatid!=NULL){
Id thisId=i.whatid;
String objectAPIName = thisId.getSObjectType().getDescribe().getName();
system.debug(thisId+':'+objectAPIName);
if(objectAPIName=='Proposal__c'){
tskList.add(i);
system.debug(i+' added');
}
else {system.debug('didnt add');}
}
else{system.debug('null');}
}

system.debug('type2:'+tskList);

for (task i:tskList)
{
if (i.whatid!=NULL){
Id thisId=i.whatid;
String objectAPIName = thisId.getSObjectType().getDescribe().getName();
system.debug('2'+thisId+':'+objectAPIName);
}
else{system.debug('null');}
}

        return tskList;

}

   public ActivityHistoryOnProposal(ApexPages.StandardController controller){}

}

Test Class:
@IsTest()
public class ActivityHistoryOnProposalTest {

    static testMethod void getUserId() {

        User user = new User();
        user.Alias = 'test';
        user.Email = 'test@test.com';
       user.EmailEncodingKey = 'UTF-8';
        user.LastName = 'tester';
        user.LanguageLocaleKey = 'en_US';
        user.LocaleSidKey = 'en_US';
        user.TimeZoneSidKey = 'America/Los_Angeles';
        user.Username = 'tester@test.com';
        user.IsActive = true;
        user.profileid=UserInfo.getProfileId();
        insert user;

        String currentUser = User.id;

        Proposal__c pr=new Proposal__c();

        Task t = new Task();
        t.WhatId=pr.id;
        insert t;

       ApexPages.currentPage().getParameters().put('id', user.old_ID__c);
        Task tsttask = new Task();
        ApexPages.StandardController sc = new ApexPages.StandardController(tsttask);
        ActivityHistoryOnProposal objActivityHistory = new ActivityHistoryOnProposal(sc);
        objActivityHistory.getListTasks();
    }
}

A: The problem is that 'tester@test.com' is probably taken. You need a unique user name in order to proceed. Here's how I usually create a user name:
user.username = Math.random()+'@'+Math.random();

This will create a user name like '0.5147472965109129@0.563726937822533', which probably won't collide with any user in any org anywhere (unless someone decides to do this just to spite me).
You can set the ProfileId of the current user (which would usually be a system administrator), or you could query for a specific profile if you need a specific type of user to test with.


text:
Q: How to Create new project in Rally using RallyRestApi In the following code I am trying to create a new project using RallyRestApi,
RallyMain {

    public static void main(String[] a) {

        BasicConfigurator.configure();
        try {
            RallyRestApi restApi = new RallyRestApi(new URI(
                    "https://rally1.rallydev.com"), "_APIKey");
            restApi.setApplicationName("RallyRestExample");
            restApi.setWsapiVersion("v2.0");

            JsonObject newProject = new JsonObject();
            newProject.addProperty("Name", "Sample Project One");
            newProject.addProperty("Description", "Sample project for testing API");
            //newProject.addProperty("Owner", "nmuthusamy");
            newProject.addProperty("Workspace", "/workspace/Workspace 1");

            CreateRequest createRequest = new CreateRequest("Project", newProject);
            CreateResponse createResponse = restApi.create(createRequest);
            System.out.println("Response "+createResponse.wasSuccessful());
        } catch (Exception e) {
            System.out.println("Exception \n"+e);
        }
    }
}

When I run the above code new project was not created on the Rally workspace.System.out.println("Response "+createResponse.wasSuccessful()); always prints false. Here ScreenShot of my rally workspace I have also attached the screen of my Workspace
I have even followed the answer given in this link Stackoverflow but it is not woking.
Following is the console log which I get when I run the main method.
0 [main] DEBUG org.apache.http.impl.conn.BasicClientConnectionManager  - Get connection for route {s}->https://rally1.rallydev.com:443
15 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnectionOperator  - Connecting to rally1.rallydev.com:443
448 [main] DEBUG org.apache.http.client.protocol.RequestAddCookies  - CookieSpec selected: default
449 [main] DEBUG org.apache.http.client.protocol.RequestAuthCache  - Auth cache not set in the context
449 [main] DEBUG org.apache.http.client.protocol.RequestTargetAuthentication  - Target auth state: UNCHALLENGED
450 [main] DEBUG org.apache.http.client.protocol.RequestProxyAuthentication  - Proxy auth state: UNCHALLENGED
450 [main] DEBUG com.rallydev.rest.client.ApiKeyClient  - Attempt 1 to execute request
450 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnection  - Sending request: POST /slm/webservice/v2.0/project/create.js?fetch=true HTTP/1.1
450 [main] DEBUG org.apache.http.wire  -  >> "POST /slm/webservice/v2.0/project/create.js?fetch=true HTTP/1.1[\r][\n]"
451 [main] DEBUG org.apache.http.wire  -  >> "zsessionid: _F99sUCMTR7OsOz4IpiCWp5Xl1UYRJ0wFqBpg5Wz5kFg[\r][\n]"
451 [main] DEBUG org.apache.http.wire  -  >> "X-RallyIntegrationLibrary: Rally Rest API for Java v2.2.1[\r][\n]"
451 [main] DEBUG org.apache.http.wire  -  >> "X-RallyIntegrationVersion: 2.2.1[\r][\n]"
451 [main] DEBUG org.apache.http.wire  -  >> "X-RallyIntegrationName: RallyRestExample[\r][\n]"
451 [main] DEBUG org.apache.http.wire  -  >> "X-RallyIntegrationVendor: Rally Software, Inc.[\r][\n]"
451 [main] DEBUG org.apache.http.wire  -  >> "Accept-Encoding: gzip,deflate[\r][\n]"
451 [main] DEBUG org.apache.http.wire  -  >> "Content-Length: 125[\r][\n]"
451 [main] DEBUG org.apache.http.wire  -  >> "Content-Type: text/plain; charset=UTF-8[\r][\n]"
451 [main] DEBUG org.apache.http.wire  -  >> "Host: rally1.rallydev.com[\r][\n]"
451 [main] DEBUG org.apache.http.wire  -  >> "Connection: Keep-Alive[\r][\n]"
451 [main] DEBUG org.apache.http.wire  -  >> "User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_40)[\r][\n]"
451 [main] DEBUG org.apache.http.wire  -  >> "[\r][\n]"
452 [main] DEBUG org.apache.http.headers  - >> POST /slm/webservice/v2.0/project/create.js?fetch=true HTTP/1.1
452 [main] DEBUG org.apache.http.headers  - >> zsessionid: _ApiKey
452 [main] DEBUG org.apache.http.headers  - >> X-RallyIntegrationLibrary: Rally Rest API for Java v2.2.1
452 [main] DEBUG org.apache.http.headers  - >> X-RallyIntegrationVersion: 2.2.1
452 [main] DEBUG org.apache.http.headers  - >> X-RallyIntegrationName: RallyRestExample
452 [main] DEBUG org.apache.http.headers  - >> X-RallyIntegrationVendor: Rally Software, Inc.
452 [main] DEBUG org.apache.http.headers  - >> Accept-Encoding: gzip,deflate
452 [main] DEBUG org.apache.http.headers  - >> Content-Length: 125
452 [main] DEBUG org.apache.http.headers  - >> Content-Type: text/plain; charset=UTF-8
452 [main] DEBUG org.apache.http.headers  - >> Host: rally1.rallydev.com
452 [main] DEBUG org.apache.http.headers  - >> Connection: Keep-Alive
452 [main] DEBUG org.apache.http.headers  - >> User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_40)
452 [main] DEBUG org.apache.http.wire  -  >> "{"Project":{"Name":"Sample Project One","Description":"Sample project for testing API","Workspace":"/workspace/Workspace 1"}}"
1719 [main] DEBUG org.apache.http.wire  -  << "HTTP/1.1 200 OK[\r][\n]"
1720 [main] DEBUG org.apache.http.wire  -  << "Date: Sat, 10 Jun 2017 07:59:30 GMT[\r][\n]"
1720 [main] DEBUG org.apache.http.wire  -  << "Content-Type: application/json;  charset=utf-8[\r][\n]"
1720 [main] DEBUG org.apache.http.wire  -  << "Content-Length: 176[\r][\n]"
1720 [main] DEBUG org.apache.http.wire  -  << "Connection: keep-alive[\r][\n]"
1720 [main] DEBUG org.apache.http.wire  -  << "Set-Cookie: __cfduid=dc354f67bed2fd443e4bbd5081140f56d1497081569; expires=Sun, 10-Jun-18 07:59:29 GMT; path=/; domain=.rallydev.com; HttpOnly[\r][\n]"
1720 [main] DEBUG org.apache.http.wire  -  << "X-XSS-Protection: 1; mode=block[\r][\n]"
1720 [main] DEBUG org.apache.http.wire  -  << "RallyRequestID: qd-app-071j56j3qgdx7xfhnyq78y1yxw7.qd-app-075984713[\r][\n]"
1720 [main] DEBUG org.apache.http.wire  -  << "Expires: Thu, 01 Jan 1970 00:00:00 GMT[\r][\n]"
1720 [main] DEBUG org.apache.http.wire  -  << "Set-Cookie: JSESSIONID=qd-app-071j56j3qgdx7xfhnyq78y1yxw7.qd-app-07;Path=/;Secure;HttpOnly[\r][\n]"
1720 [main] DEBUG org.apache.http.wire  -  << "Set-Cookie: SUBBUCKETID=108;Path=/;Domain=rally1.rallydev.com;Secure;HttpOnly[\r][\n]"
1720 [main] DEBUG org.apache.http.wire  -  << "Set-Cookie: SUBSCRIPTIONID=122108;Path=/;Domain=rally1.rallydev.com;Secure;HttpOnly[\r][\n]"
1720 [main] DEBUG org.apache.http.wire  -  << "Vary: Accept-Encoding[\r][\n]"
1720 [main] DEBUG org.apache.http.wire  -  << "Content-Encoding: gzip[\r][\n]"
1721 [main] DEBUG org.apache.http.wire  -  << "P3P: CP="NON DSP COR CURa PSAa PSDa OUR NOR BUS PUR COM NAV STA"[\r][\n]"
1721 [main] DEBUG org.apache.http.wire  -  << "Cache-Control: private,max-age=0,must-revalidate[\r][\n]"
1721 [main] DEBUG org.apache.http.wire  -  << "Strict-Transport-Security: max-age=31536000; includeSubDomains; preload;[\r][\n]"
1721 [main] DEBUG org.apache.http.wire  -  << "Set-Cookie: SERVERID=2dd8f75e6436014e8021e4a12eb0016859253e05; path=/[\r][\n]"
1721 [main] DEBUG org.apache.http.wire  -  << "Server: cloudflare-nginx[\r][\n]"
1721 [main] DEBUG org.apache.http.wire  -  << "CF-RAY: 36cacaa1dd7c2ee7-DEL[\r][\n]"
1721 [main] DEBUG org.apache.http.wire  -  << "[\r][\n]"
1722 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnection  - Receiving response: HTTP/1.1 200 OK
1722 [main] DEBUG org.apache.http.headers  - << HTTP/1.1 200 OK
1722 [main] DEBUG org.apache.http.headers  - << Date: Sat, 10 Jun 2017 07:59:30 GMT
1722 [main] DEBUG org.apache.http.headers  - << Content-Type: application/json;  charset=utf-8
1722 [main] DEBUG org.apache.http.headers  - << Content-Length: 176
1722 [main] DEBUG org.apache.http.headers  - << Connection: keep-alive
1722 [main] DEBUG org.apache.http.headers  - << Set-Cookie: __cfduid=dc354f67bed2fd443e4bbd5081140f56d1497081569; expires=Sun, 10-Jun-18 07:59:29 GMT; path=/; domain=.rallydev.com; HttpOnly
1722 [main] DEBUG org.apache.http.headers  - << X-XSS-Protection: 1; mode=block
1722 [main] DEBUG org.apache.http.headers  - << RallyRequestID: qd-app-071j56j3qgdx7xfhnyq78y1yxw7.qd-app-075984713
1722 [main] DEBUG org.apache.http.headers  - << Expires: Thu, 01 Jan 1970 00:00:00 GMT
1722 [main] DEBUG org.apache.http.headers  - << Set-Cookie: JSESSIONID=_jsessionid;Path=/;Secure;HttpOnly
1722 [main] DEBUG org.apache.http.headers  - << Set-Cookie: SUBBUCKETID=108;Path=/;Domain=rally1.rallydev.com;Secure;HttpOnly
1722 [main] DEBUG org.apache.http.headers  - << Set-Cookie: SUBSCRIPTIONID=122108;Path=/;Domain=rally1.rallydev.com;Secure;HttpOnly
1722 [main] DEBUG org.apache.http.headers  - << Vary: Accept-Encoding
1723 [main] DEBUG org.apache.http.headers  - << Content-Encoding: gzip
1723 [main] DEBUG org.apache.http.headers  - << P3P: CP="NON DSP COR CURa PSAa PSDa OUR NOR BUS PUR COM NAV STA"
1723 [main] DEBUG org.apache.http.headers  - << Cache-Control: private,max-age=0,must-revalidate
1723 [main] DEBUG org.apache.http.headers  - << Strict-Transport-Security: max-age=31536000; includeSubDomains; preload;
1723 [main] DEBUG org.apache.http.headers  - << Set-Cookie: SERVERID=_serverid; path=/
1723 [main] DEBUG org.apache.http.headers  - << Server: cloudflare-nginx
1723 [main] DEBUG org.apache.http.headers  - << CF-RAY: 36cacaa1dd7c2ee7-DEL
1736 [main] DEBUG org.apache.http.client.protocol.ResponseProcessCookies  - Cookie accepted [__cfduid="_cfduid", version:0, domain:rallydev.com, path:/, expiry:Sun Jun 10 13:29:29 IST 2018]
1736 [main] DEBUG org.apache.http.client.protocol.ResponseProcessCookies  - Cookie accepted [JSESSIONID="_jsessionid", version:0, domain:rally1.rallydev.com, path:/, expiry:null]
1736 [main] DEBUG org.apache.http.client.protocol.ResponseProcessCookies  - Cookie accepted [SUBBUCKETID="108", version:0, domain:rally1.rallydev.com, path:/, expiry:null]
1737 [main] DEBUG org.apache.http.client.protocol.ResponseProcessCookies  - Cookie accepted [SUBSCRIPTIONID="999999", version:0, domain:rally1.rallydev.com, path:/, expiry:null]
1737 [main] DEBUG org.apache.http.client.protocol.ResponseProcessCookies  - Cookie accepted [SERVERID="_serverid", version:0, domain:rally1.rallydev.com, path:/, expiry:null]
1738 [main] DEBUG com.rallydev.rest.client.ApiKeyClient  - Connection can be kept alive indefinitely
1750 [main] DEBUG org.apache.http.wire  -  << "[0x1f]"
1750 [main] DEBUG org.apache.http.wire  -  << "[0x8b]"
1750 [main] DEBUG org.apache.http.wire  -  << "[0x8]"
1750 [main] DEBUG org.apache.http.wire  -  << "[0x0]"
1750 [main] DEBUG org.apache.http.wire  -  << "[0x0][0x0][0x0][0x0][0x0][0x3]"
1750 [main] DEBUG org.apache.http.wire  -  << "M[0xce][0xb1][\n]"
1751 [main] DEBUG org.apache.http.wire  -  << "[0xc2]@[0xc][0x6][0xe0]W[0x9][0x99][0xa5][0x88]c7[0xa9][0xe][0x1d]D[0xd1][0xa1][0x83]-r[0xb6][0xb1][0xb4][0x1c]I[0xc9][0xdd][\r]R[0xfa][0xee]FEp[0x9][0xe4]#[0xf9][0x93][0x19][0xb]%[0x17][0xe9]L![0xf9][0x88]9[0xcc]xS[0xe7][0xfd]s{*[0xf]n[0x14]5[0xc2][\r][0xae][0xe0][0x8f][0x7][0xfe][0xf2][0xfa][0xcd]{U[0xd1]`[0xed][0x15][0xb]I[0xbe][0x3][0x96][0x8][0x16][0xd9][0xe5]p[0xbc][0x8f][0xd4][0xc6][0xf]<$qgUX[0xee]r[0xe0][0xe4]=6[0x96]Q9[0xe5][0x81][0xfb]oJ[0x19]a[0x8][0xb6][0x4]^[0xb8]'[0x5][0xa6][0x96]Bp[0xfa][0x84]([0xe0][0xa6][0x89],[0xa8][0xc6]l[0xc]5[0xbe][0xa5][0xba][0xd8]Kv0HR[0x1b][0xcc][0xb0]Y[0x96][0x17][0xef][0xff][0xd1]?[0xd5][0x0][0x0][0x0]"
1751 [main] DEBUG org.apache.http.impl.conn.BasicClientConnectionManager  - Releasing connection org.apache.http.impl.conn.ManagedClientConnectionImpl@23986957
1751 [main] DEBUG org.apache.http.impl.conn.BasicClientConnectionManager  - Connection can be kept alive indefinitely
Response false

Thanks,
Nithyananth

A: Check out the errors in your response.  The fact that wasSuccessful returns false means there were problems with your create.
String errors = createResponse.getErrors();
System.out.println(errors[0]);

One problem is that your workspace reference is by name- they need to be by ref (which is of the format /[type]/[objectid])
newProject.addProperty("Workspace", "/workspace/12345");


text:
Q: c# help with building where clause to query i am newbie in c#,
i want to build query string , i do some conditions , every condition add another condition to where clause
i want something like that :
    // BUILD SELECT QUERY
     string where = "";
     string[] where_arr = new string[];
     if (condition1)
     {
           where_arr[index++] = " field = 5 ";
     }
      if (condition2)
     {
           where_arr[index++] = " field2 = 7 ";
     }

     if (where_arr.Count>0)
        where = " where" +  String.Join(" and ", where_arr);
     string sql = "select count(*) as count from mytable " + where;

but i do not know exactly how to declare all the variables like where_arr

A: // BUILD SELECT QUERY
string where = "";
List<string> where_arr = new List<string>();

if (condition1)
{
    where_arr.Add(" field = 5 ");
}

if (condition2)
{
    where_arr.Add(" field2 = 7 ");
}

if (where_arr.Count > 0)
    where = " where" + String.Join(" and ", where_arr.ToArray());
string sql = "select count(*) as count from mytable " + where;


text:
Q: Location.getAltitude() starts returning identical invalid values after a certain time period I need your help.
I wrote a very simple Android widget that shows the altitude which I get in the onLocationChanged method:
public void onLocationChanged(Location location) {
    double myAltitude = -99;
    if (location.hasAltitude()) {
        myAltitude = location.getAltitude();
        Log.d("SAT-LOG","Current Altitude is : "+myAltitude);
        Log.d("SAT-LOG","Current Coordinatees : "+location.getLatitude()+"-"+location.getLongitude());
    }
    ...
}

Here how I request the location update:
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.registerGnssStatusCallback(gnssActivity);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, gnssActivity);

I also tried this:
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
criteria.setAltitudeRequired(true);
criteria.setSpeedRequired(true);
criteria.setCostAllowed(true);
criteria.setBearingRequired(false);
criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.registerGnssStatusCallback(gnssActivity);
locationManager.requestLocationUpdates(1000,1,criteria,gnssActivity,null);

I noticed that location.hasAltitude() is always true.
After 10/15 minutes the value is stuck: location.getAltitude() returns the same value until the device reboot (for the record I am using a car tablet).
Instead, the location latitude/longitude are always correct.
I took some log in order to share the behavior:
Timestamp            Coordinates        Altitude/Elevation
13:52:51.989    37.6911584,15.1052294   577,6
13:52:52.981    37.691106,15.1052072    576,6
13:52:53.990    37.6910536,15.1051881   576,3
13:52:54.985    37.6910032,15.1051709   576,1
13:52:56.019    37.6909561,15.1051632   575,4
13:52:57.032    37.6909104,15.1051537   573,7
13:52:57.993    37.6908579,15.105138    572,6
13:52:58.984    37.6908022,15.105121    572,1
13:52:59.982    37.690747,15.1051034    571,5
13:53:00.984    37.6906914,15.1050854   571,2
13:53:02.021    37.6906406,15.1050694   571,9
13:53:02.974    37.6906027,15.1050565   572,2
13:53:03.983    37.6905802,15.1050451   621,7000122 <-Invalid Values
13:53:04.984    37.6905657,15.1050349   621,7000122
13:53:05.985    37.6905537,15.1050258   621,7000122
13:53:06.990    37.6905363,15.1050178   621,7000122
13:53:07.982    37.6905103,15.1050077   621,7000122
13:53:08.981    37.6904757,15.1049966   621,7000122
13:53:10.027    37.6904339,15.1049828   615,6000366
13:53:10.982    37.6903825,15.1049643   615,6000366
13:53:11.982    37.6903202,15.1049418   615,6000366
13:53:12.980    37.6902507,15.104916    615,6000366
13:53:14.021    37.6901782,15.1048888   615,6000366
13:53:14.988    37.690104,15.10486      615,6000366
13:53:15.985    37.6900287,15.1048412   615,6000366
13:53:16.990    37.6899508,15.1048195   615,6000366
...
...
...
13:54:34.982    37.6830799,15.1036726   615,6000366
13:54:35.986    37.6829489,15.1036597   615,6000366
13:54:36.984    37.6828161,15.1036388   615,6000366
13:54:37.988    37.6826812,15.1036125   615,6000366 <- Invalid Values ends here
13:54:38.985    37.6825483,15.1035831   551,6 <-Valid Values again
13:54:39.989    37.6824177,15.1035502   551,6
13:54:40.986    37.6822904,15.1035137   551,7
13:54:41.989    37.6821635,15.1034749   551,5
13:54:42.980    37.6820341,15.1034429   551,9
13:54:43.986    37.6818938,15.1034188   551,4
13:54:44.986    37.6817466,15.1034      551,1

As you can see from 13:53:03.983 to 13:54:37.988 the methods returns invalid altitude values (the coordinates are right). More or less, 95 invalid samples (consecutive). In the log at 14:04 I have another sequence of 99 invalid values.
If I open the App GPSTest, I see the correct value of altitude.
Can someone help me to understand the issue ?
Is there a better way to get the altitude/elevation?

A: Huawei Location Kit may help with your issue.Check Docs.
You can obtains the altitude of the current location by using Location Kit.

For Detail,pls kindly refer:
HWLocation
getAltitude()


text:
Q: Why does "from _ import _" run and access all of "from" I don't understand how "from _ import _" seems to be behaving...
Somehow, when I run the following line:
from athletelist import AthleteList

It ALSO executes (in my IDLE Terminal) the print statements at the end of my athletelist file that aren't even a part of the AthleteList class.
Why, when I write "FROM athletelist IMPORT AthleteList", does this statement also run the print() commands that aren't even a part of the AthleteList class?


text:
Q: Calling a subprocess in Python 3.4 and handling errors if a command is invalid? I am trying to execute an external process in Python 3.4. When my "command" is wrong the program just crashes. How can I handle the errors gracefully and recover?
    # Call a system process
    try:
        pipe = subprocess.Popen(command,
                                stdout=subprocess.PIPE)
    except (OSError,
            subprocess.CalledProcessError) as error:
        print("Failed to execute command")
        print(command)
        print("Error: " + error.output)

    while True:
        output = pipe.stdout.readline()
        if not output:
            print("Finished...")
            break

        output = output.decode()
        output = output.strip("\r")
        output = output.strip("\n")
        print(output)

When I call an invalid command. I get a crash like:
C:\SDKs\Python34\python.exe C:\Users\user\Documents\GitHub\PyQtApps\QtDeploy\src\main.py
Traceback (most recent call last):
Executing:  windeployqt.exe  C:\Users\user\Documents\GitHub\SpaCentralSoftBin\GUIController.exe
  File "C:\Users\user\Documents\GitHub\PyQtApps\QtDeploy\src\forms\maindialog.py", line 81, in execute_windeployqt
Failed to execute command
    stdout=subprocess.PIPE)
windeployqt.exe  C:\Users\user\Documents\GitHub\SpaCentralSoftBin\GUIController.exe
  File "C:\SDKs\Python34\lib\subprocess.py", line 858, in __init__
    restore_signals, start_new_session)
  File "C:\SDKs\Python34\lib\subprocess.py", line 1111, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\user\Documents\GitHub\PyQtApps\QtDeploy\src\forms\maindialog.py", line 159, in on_buttonBox_clicked
    self.execute_windeployqt()
  File "C:\Users\user\Documents\GitHub\PyQtApps\QtDeploy\src\forms\maindialog.py", line 86, in execute_windeployqt
    print("Error: " + error.output)
AttributeError: 'FileNotFoundError' object has no attribute 'output'

A: The larger problem is printing an error message does not "handle" an error in any meaningful sense of "handle" (although many people think it does).
Log an error message if you want and then exit your program. There are few instances where you can handle an error, for example if a configuration file can't be read, see if you can read a global configuration file or KeyboardInterrupt can be passed up to a main loop that is reading commands.
In your example, if you didn't fault in the except block, the output = pipe.stdout... would yield:
NameError: name 'pipe' is not defined

and if you caught that, there'd still be nothing meaningful to do to recover the state your code expects to be in. You'll also move the traceback you do get to a place where the fault isn't.
A good idiom for your situation is
except SomeError:
    log what you want
    raise

where an empty raise re-raises the last exception which will propagate up, forming a full stacktrace which will give you a better idea of where the fault is. If you don't do this, you are discarding useful information.

A: FileNotFoundError' object has no attribute 'output'

Use
print("Error: " + error)

FileNotFoundErrr has these properties which might be useful:
 args
 characters_written
 errno
 filename
 filename2


text:
Q: redis cluster nodes is reporting wrong self ip address i have setup redis cluster on 3 ubuntu 20 nodes with identical network configs. (eno1 interface for management and enp1s0f1 for internal network )
in the /etc/redis/redis.conf i have it bind to the enp1s0f1 interface like so in the 3 nodes
bind 172.19.101.2x

i then create the redis cluster like so
redis-cli --cluster create 172.19.101.23:6379 172.19.101.24:6379 172.19.101.25:6379

the cluster gets created ok and cluster info also reports OK
but when i do cluster nodes it reports the management ip instead of the internal ip just for 1 node like so.
administrator@slave-node2:~$ redis-cli -h 172.19.101.24 cluster nodes
33c4484ca50aa7916b8727723f4eb5576c7b94ab 172.19.101.25:6379@16379 master - 0 1623764502745 4 connected 10923-16383
e099188cb0ae8bcc32ca7d81f0c8659a2b4ebb7b **10.110.3.166**:6379@16379 myself,master - 0 1623764500000 3 connected 5461-10922
3afa9cb15e166254a9f5182ba1b0df46137f954b 172.19.101.23:6379@16379 master - 0 1623764501741 2 connected 0-5460

So now when clients connect to this redis cluster they get this error - Can't connect to master: redis://10.110.3.166:6379 with slot ranges: [[5461-10922]]
BTW if i do redis-cli cluster nodes by connecting to other node in the cluster it reports ok like so
administrator@slave-node2:~$ redis-cli -h 172.19.101.25 cluster nodes
e099188cb0ae8bcc32ca7d81f0c8659a2b4ebb7b 172.19.101.24:6379@16379 master - 0 1623765101198 3 connected 5461-10922
3afa9cb15e166254a9f5182ba1b0df46137f954b 172.19.101.23:6379@16379 master - 0 1623765100194 2 connected 0-5460
33c4484ca50aa7916b8727723f4eb5576c7b94ab 172.19.101.25:6379@16379 myself,master - 0 1623765099000 4 connected 10923-16383

So question is

*

*why redis picking the management ip for this node ?

*is there anyway to restrict it to required ip / interface ?

*is there a way to change it in the cluster nodes ?

thanks for any pointers to this

A: I think you can set the following in redis.conf .
cluster-announce-ip


text:
Q: short url for joomla k2 extension Joomla 3.2/k2 2.6.5
I use this code to make seo url for k2 items link.
$item->link = urldecode(JRoute::_(K2HelperRoute::getItemRoute($item->id.':'.urlencode($item->alias), $item->catid.':'.urlencode($item->categoryalias))));

and It gives me an Url path like this:
MYSITE.COM/CAT/SUBCAT/SUB2cat/ITEM.HTML
Is there any way to convert it to one of these addresses?
MYSITE.COM/ITEM.HTML
MYSITE.COM/CAT/ITEM.HTML
MYSITE.COM/SUB2CAT/ITEM.HTML


text:
Q: How to get Closed Captions from a live video stream using VLC I want to be able to stream live TV but also include the closed captions.  My workflow is to use a Blackmagic Designs Decklink card (video source is SDI) and use VLC to capture and transcode the video, then send that to a Wowza server to be packetized for HTTP streaming.  I have this working for Video, but I cannot figure out how to get the closed captions to appear in my player.  I am using a VLC Player, Quicktime, Flowplayer on a web page, iPad, and iPhone to view the streams, none of them show the closed captioning in the source video.  The closed captions are both 608 and 708.  I have spent the last 3 days reading everything I can about vlc and closed captions, wowza and closed captions, and x264 and closed captions, vbi, teltext, and even subtitles, but I am no where closer than when I started.  I sincerely that someone here will be able to help me.
I am using a core i7 with 4GB ram, runign ubuntu 10.04 64bit.  I compiled vlc with the following:
./configure  '--enable-xvideo' '--enable-sdl' '--enable-avcodec' '--enable-avformat' '--enable-swscale' '--enable-mad' '--enable-a52' '--enable-libmpeg2' '--enable-dvdnav' '--enable-faad' '--enable-vorbis' '--enable-ogg' '--enable-theora' '--enable-mkv' '--enable-flac' '--enable-caca' '--enable-alsa' '--enable-qt4' '--enable-ncurses' '--enable-realrtsp' '--enable-twolame' '--enable-real' '--enable-x264' '--with-decklink-sdk=/home/bimls/bmd/Blackmagic_Decklink_SDK_9.6.4/Linux' '--enable-zvbi'

I use the following to capture and stream the live video:
cvlc decklink:// --decklink-card-index="0" --decklink-mode="ntsc" --rtsp-timeout 0 --sout='#transcode{venc=x264{subme=1, ref=1, bframes=16, b-adapt=1, bpyramid=none, weightp=0 }, vcodec=h264, vb=1300, acodec=mp4a, ab=96, threads=4}:rtp{dst=127.0.0.1:8888,mux=ts}'' --vbi-page=100 --no-vbi-opaque --vbi-position=0

Some of the question I have are:

*

*Is this the proper way to get the closed captions to appear? if not please what am I doing wrong?

*How does one
know what vbi-page to look for as the range seems to be "--vbi-page integer [-2147483648 .. 2147483647]>"

*Does transcoding destroy
closed caption data?

So, Please any help will be greatly appreciated! Thank you!


text:
Q: eclipse export Revision graph in picture

I have a big repository to browse, I use revision graph in eclipse.
I want to save revision graph in picture for local use ?
I look to export option but no one !!!

Thanks,

A: Windows + PrintScreen, then paste it to mspaint with Ctrl+V? Or any screen capture tools like Jing?


text:
Q: SharePoint 2010 Content Organizer Rule Issue I am facing problem with the content organizer processing and in dropoff library. In my scenario what is required is: when a user upload a document in Record center the document should go Drop off library and from there as per the content organizer rule defined should move to the Record center library (as per the Record Center functionality).
But what I am getting is whenever any user uploads document the document remains in dropoff library and a copy gets moved inside Record center as well, also it sends the mail for "Additional Infomation required" to the admins. Not sure about this why dropoff behaving this way? If it is not saving the complete data then hows it moving a copy to Record Center library? Anyone faced such issue please help me.. and in drop off library when I press edit document property button and press save it again moves the document to Record Center library with some random words addition in the document title. :(
Again there is a query when in edit properties page of Drop off library it is not asking to enter any required field why the system generating "Additional Information Required" mails every time a new document is uploaded?

A: The Drop Off library serves as the location where  Documents to which rules cannot be matched are moved into, which also generates email messages to Content Stewart, according to your settings (digest or immediate). You would probably need to check your rules, if by any chance you do not have a rule that plays like a "catch-all", also it is recomanded that you do create your own Content types and do not use the Default Document Content type as this will definitely be more dificult to differentiate and could generate mentioned behavior.
Also check if you do not have by any chance a workflow (e.g. IM policies rules in the Records Center libraries by default enabled).

A: The random letters being added is set in the Content Organizer rules under the Site Settings. Go there and decide if you want it to add those letters when you have a duplicate file, or if you want it to make a new version of the existing file. There is also a choice there about whether or not to send files to the Drop Off Library first.  Pick Yes or No. Those choices should all be set up before you allow people to start uploading files. :) Then go to the Organizer Rules link (Again Site Settings), and put in your Content Type, and your conditions.


text:
Q: How to disable ssl verification when generating documentation with sphinx ? (working behind a proxy) Generating the documentation gives me the following error:
loading intersphinx inventory from https://docs.python.org/3/objects.inv...
WARNING: failed to reach any of the inventories with the following issues:
intersphinx inventory 'https://docs.python.org/3/objects.inv' not fetchable due to <class 'requests.exceptions.SSLError'>: HTTPSConnectionPool(host='docs.python.org', port=443): Max retries exceeded with url: /3/objects.inv (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))

I work behind a company proxy.
Is there any way to disable ssl verification ? Like anaconda does with: conda config --set ssl_verify false ?

A: Per the Sphinx documentation, you can modify one of two variables in conf.py to specify a path to your cert or turn off verification all together.

*

*tls_verify (boolean) - If true, Sphinx verifies server certifications LINK

*tls_cacert (str) - A path to a certification file of CA or a path to directory which contains the certificates LINK

It would look like this in your conf.py:
# uncomment this if you don't want to verify at all
# tls_verify = False

tls_cacert = "/path/to/cert"


text:
Q: variable conflicts in rails index action I am a rails newbie so i hope someone can help me.
Here is my code
def index
  @todos = Todo.order(sort_column + " " + sort_direction)  #sorts table columns
  @todos = Todo.page(params[:page]).per(1)                 #pagination
  @todos = Todo.search(params)                             #search filter

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @todos }
  end
end

the sorting, pagination, and searching all work perfectly on their own, but obviously it is causing a conflict when declaring all three variables at once.
I'm not sure how to get around the problem of giving these variables different names, so that they'll still work in the context of the app.
Any help is appreciated.

A: You can chaining the calls:
 @todos = Todo.order(sort_column + " " + sort_direction).search(params).page(params[:page]).per(1)

I've changed the order a bit because, supposing you're using Kaminari, the pagination should always be the last method to call. This will work only if you're search method returns an ActiveRecord Relation.
EDIT
Reading the comments, I suppose you're using tire. It seems to support Kaminari but there is some effort you have to do. Please the a look at this discussion. unfortunately, I'm not that familiar with Tire.


text:
Q: Correct PHP Function for If Statement I have an if statement that is at the end of a for each loop that adds the | character at the end of a generated unordered list.
My goal is to add | after "not the last two".
<?php if (! $_link->getIsLast()):?>|<?php endif;?>

I was hoping I could input a value in the getIsLast or getIsFirst functions like this:
<?php if (! $_link->getIsLast(2)):?>|<?php endif;?>

I was hoping the above statement would add the | character for each generated list item except for the last two.  However, it doesn't seem to be working.
Does anyone know the proper syntax to do something like this?
The for each loops is below:
<ul class="links pull-right"<?php if($this->getName()): ?> id="<?php echo $this->getName() ?>"<?php endif;?>>
    <?php foreach($_links as $_link): ?>
        <?php if ($_link instanceof Mage_Core_Block_Abstract):?>
            <?php echo $_link->toHtml() ?>
        <?php else: ?>
            <li<?php if($_link->getIsFirst()||$_link->getIsLast()): ?> class="<?php if($_link->getIsFirst()): ?>first<?php endif; ?><?php if($_link->getIsLast()): ?> last<?php endif; ?>"<?php endif; ?> <?php echo $_link->getLiParams() ?>><?php echo $_link->getBeforeText() ?><a href="<?php echo $_link->getUrl() ?>" title="<?php echo $_link->getTitle() ?>" <?php echo $_link->getAParams() ?>><?php echo $_link->getLabel() ?><?php echo $_link->getAfterText() ?>

        <?php endif;?>
        <?php if (! $_link->getIsLast()):?>|<?php endif;?>
    <?php endforeach; ?>

A: Try this.
<ul class="links pull-right"<?php if($this->getName()): ?> id="<?php echo $this->getName() ?>"<?php endif;?>>
    <?php
        $numberOfRows = count($_links);
        $currentIndex=0;
        foreach($_links as $_link):
    ?>
        <?php if ($_link instanceof Mage_Core_Block_Abstract):?>
            <?php echo $_link->toHtml() ?>
        <?php else: ?>
            <li<?php if($_link->getIsFirst()||$_link->getIsLast()): ?> class="<?php if($_link->getIsFirst()): ?>first<?php endif; ?><?php if($_link->getIsLast()): ?> last<?php endif; ?>"<?php endif; ?> <?php echo $_link->getLiParams() ?>><?php echo $_link->getBeforeText() ?><a href="<?php echo $_link->getUrl() ?>" title="<?php echo $_link->getTitle() ?>" <?php echo $_link->getAParams() ?>><?php echo $_link->getLabel() ?><?php echo $_link->getAfterText() ?>

        <?php endif;?>
        <?php if ($currentIndex<$numberOfRows-2):?>|<?php endif;?>
    <?php
    $currentIndex++;
    endforeach; ?>

 |


text:
Q: Memory Aquired by Java String & HashMap memory size in java with UTF-8 string I have a hashmap in java which is type of <String,String>.
My requirement is i want to know how much memory it is taking in my system.
Please consider below details as well.
String Type is : UTF-8
MapType: HashMap<String, String>=new HashMap();
lenght of Map is: 7200000 (72 lacks key value pair)
Avg Length of key is : 75 (example: IUCC_SESSION_IUCC_SESSION_CALL_SUCC_-1102343625_2022-09-20T18:45:41.000000Z)
The length of the value is : 5 (example: VALUE)
Thanks in advance.


text:
Q: Highlight Search Terms in PHP without breaking anchor tags using regex I'm searching through some database search results on a website & trying to highlight the term in the returned results that matches the searched term. Below is what I have so far (in php):
$highlight = trim($highlight);
if(preg_match('|\b(' . $highlight . ')\b|i', $str_content))
{
    $str_content = preg_replace('|\b(' . $highlight. ')(?!["\'])|i', "$1",
    $str_break;
}

The downside of going this route is that if my search term shows up in the url permalink as well, the returned result will insert the span into the href attribute and break the anchor tag. Is there anyway in my regex to exclude "any" information from the search results that appear in between an opening and closing HTML tag?
I know I could use the strip_tags() function and just spit out the results in plain text, but I'd rather not do that if I didn't have to.

A: DO NOT try to parse HTML with regular expressions:
RegEx match open tags except XHTML self-contained tags
Try something like PHP Simple HTML DOM.
<?php
// get DOM
$html = file_get_html('http://www.google.com/search?q=hello+kitty');

// ensure this is properly sanitized.
$term = trim($term);

// highlight $term in all
...
 elements
foreach($html->find('div.result') as $e){
   echo str_replace($term, ''.$term.'', $e->plaintext);
}
?>

Note: this is not an exact solution because I don't know what your HTML looks like, but this should put you pretty close to being on track.

A: I think assertions is what your looking for.

A: I ended up going this route, which so far, works well for this specific situation.
<?php

if(preg_match('|\b(' . $term . ')\b|i', $str_content))
{
    $str_content = strip_tags($str_content);
    $str_content = preg_replace('|\b(' . $term . ')(?!["\'])|i', "$1", $str_content);
    $str_content = preg_replace('|\n[^<]+|', '

', $str_content);
    break;
}

?>

It's still html encoded, but it's easier to parse through now without html tags


text:
Q: python stock price real time data feed (script debug) i'm just beginning to learn to code and i want to apologize in advance if this question is trivial.
ive been trying to find a way to feed stock market data into python real time and came across this blog
    http://www.quantatrisk.com/2015/05/07/hacking-google-finance-in-pre-market-trading-python/
Below is the script i copied and pasted.
import urllib2  # works fine with Python 2.7.9 (not 3.4.+)
import json
import time

def fetchPreMarket(symbol, exchange):
    link = "http://finance.google.com/finance/info?client=ig&q="
    url = link+"%s:%s" % (exchange, symbol)
    u = urllib2.urlopen(url)
    content = u.read()
    data = json.loads(content[3:])
    info = data[0]
    t = str(info["elt"])    # time stamp
    l = float(info["l"])    # close price (previous trading day)
    p = float(info["el"])   # stock price in pre-market (after-hours)
    return (t,l,p)

p0 = 0
while True:
    t, l, p = fetchPreMarket("AAPL","NASDAQ")
    if(p!=p0):
        p0 = p
        print("%s\t%.2f\t%.2f\t%+.2f\t%+.2f%%" % (t, l, p, p-l,
                                                 (p/l-1)*100.))
    time.sleep(60)

it seems to be a great code except when i run it, i get the following error message
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-11-012ec6dc7b0c> in <module>()
     18 p0 = 0
     19 while True:
---> 20     t, l, p = fetchPreMarket("AAPL","NASDAQ")
     21     if(p!=p0):
     22         p0 = p

<ipython-input-11-012ec6dc7b0c> in fetchPreMarket(symbol, exchange)
     10     data = json.loads(content[3:])
     11     info = data[0]
---> 12     t = str(info["elt"])    # time stamp
     13     l = float(info["l"])    # close price (previous trading day)
     14     p = float(info["el"])   # stock price in pre-market (after-hours)

KeyError: 'elt'

I tried modifying fetchPreMarket such that it just outputs info = data[0] but when i tried 'print info', nothing came of it.
Thanks in advance

A: So... The Google Finance API has been discontinued. I am surprised that link works, but there is no "etl" (or "el") key in the data.
And so, you'll get KeyError: 'elt' at info["elt"]
For reference,
{
"id": "22144"
,"t" : "AAPL"
,"e" : "NASDAQ"
,"l" : "95.52"
,"l_fix" : "95.52"
,"l_cur" : "95.52"
,"s": "0"
,"ltt":"2:34PM EST"
,"lt" : "Feb 24, 2:34PM EST"
,"lt_dts" : "2016-02-24T14:34:54Z"
,"c" : "+0.83"
,"c_fix" : "0.83"
,"cp" : "0.88"
,"cp_fix" : "0.88"
,"ccol" : "chg"
,"pcls_fix" : "94.69"
}

You may have better luck with the googlefinance or yahoo-finance python modules rather than directly calling the API address.
It is worth noting that the Yahoo API is not "realtime", though. It is about a 15 minute delayed quote.

A: If you don't want to use googlefinance package, you can create your own parser with BeautifulSoup.
Check code in online IDE that uses BeautifulSoup.
from bs4 import BeautifulSoup
import requests, json, lxml, re
from itertools import zip_longest

def scrape_google_finance(ticker: str):
    # https://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls
    params = {
        "hl": "en" # language
        }

    # https://docs.python-requests.org/en/master/user/quickstart/#custom-headers
    # https://www.whatismybrowser.com/detect/what-is-my-user-agent
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36",
        }

    html = requests.get(f"https://www.google.com/finance/quote/{ticker}", params=params, headers=headers, timeout=30)
    soup = BeautifulSoup(html.text, "lxml")

    ticker_data = {"ticker_info": {},
                    "right_panel_data": {},
                    "finance_perfomance": {"table": []}
                    }

    ticker_data["ticker_info"]["title"] = soup.select_one(".zzDege").text
    ticker_data["ticker_info"]["current_price"] = soup.select_one(".AHmHk .fxKbKc").text

    right_panel_keys = soup.select(".gyFHrc .mfs7Fc")
    right_panel_values = soup.select(".gyFHrc .P6K39c")

    for key, value in zip_longest(right_panel_keys, right_panel_values):
        key_value = key.text.lower().replace(" ", "_")

        ticker_data["right_panel_data"][key_value] = value.text

    if soup.select(".slpEwd .roXhBd"):
        # https://regex101.com/r/Sf2TaC/1
        fin_perf_col_2 = re.search(r"\w+\s?\d{4}", soup.select_one(".PFjsMe+ .yNnsfe").text).group(0)                # e.g. JUN 2022
        fin_perf_col_3 = soup.select_one(".PFjsMe~ .yNnsfe+ .yNnsfe").text       # e.g. Year/year change

        for fin_perf in soup.select(".slpEwd .roXhBd"):
            if fin_perf.select(".rsPbEe"):
                perf_key = fin_perf.select_one(".rsPbEe").text                   # e.g. Revenue, Net Income, Operating Income..
                perf_value_col_1 = fin_perf.select_one(".QXDnM").text            #  48.23B, ...

                try:
                  perf_value_col_2 = fin_perf.select_one(".gEUVJe .JwB6zf").text # -21.82%, ...
                except:
                  perf_value_col_2 = None  #

                ticker_data["finance_perfomance"]["table"].append({
                    perf_key: {
                        fin_perf_col_2: perf_value_col_1,
                        fin_perf_col_3: perf_value_col_2
                    }
                })
    else:
        ticker_data["finance_perfomance"]["error"] = f"No 'finence perfomance table' for {ticker}."

    return ticker_data

data = scrape_google_finance(ticker="AAPL:NASDAQ")

print(json.dumps(data, indent=2))

Example output
[
    {
  "ticker_info": {
    "title": "Apple Inc",
    "current_price": "$174.55"
  },
  "right_panel_data": {
    "previous_close": "$173.03",
    "day_range": "$172.57 - $176.15",
    "year_range": "$129.04 - $182.94",
    "market_cap": "2.81T USD",
    "avg_volume": "68.49M",
    "p/e_ratio": "28.84",
    "dividend_yield": "0.53%",
    "primary_exchange": "NASDAQ",
    "ceo": "Tim Cook",
    "founded": "Apr 1, 1976",
    "headquarters": "Cupertino, CaliforniaUnited States",
    "website": "apple.com",
    "employees": "154,000"
  },
  "finance_perfomance": {
    "table": [
      {
        "Revenue": {
          "Jun 2022": "82.96B",
          "Y/Y change": "1.87%"
        }
      },
      {
        "Operating expense": {
          "Jun 2022": "12.81B",
          "Y/Y change": "15.10%"
        }
      },
      {
        "Net income": {
          "Jun 2022": "19.44B",
          "Y/Y change": "-10.59%"
        }
      # ...
]

There's a scrape Google Finance Ticker Quote Data in Python blog post if you need to scrape more data from Google Finance.


text:
Q: isNil can't be used on literals echo 0.isNil

type mismatch: got < int literal(0)>
  but expected one of:
  proc isNil[T: proc](x: T): bool
  proc isNil[T](x: ptr T): bool
  proc isNil(x: cstring): bool
  proc isNil(x: pointer): bool
  proc isNil(x: string): bool
  proc isNil[T](x: seq[T]): bool
  proc isNil[T](x: ref T): bool

How are we supposed to write generic code when we can't have expressions like 0.isNil ?

A: You don't need to use isNil on types that can't be nil, that just doesn't make sense. When going generic (let's say you're implementing MyContainer[T]) you just introduce a new notion of emptiness (whatever that means to you) and use it in your generic code.
proc isEmptyElement[T](v: T): bool {.inline.} =
  when compiles(isNil(v)):
    isNil(v)
  elif T is SomeNumber:
    v == 0
  else:
    # Whatever else you mean by emptiness. Let's say is v the default value of T
    var d: T # Default value
    v == d

proc myContainerAdd[T](c: MyContainer[T], v: T) =
  if not v.isEmptyElement():
    # proceed

Note isEmptyElement can be simplified, it has more branches than actually needed just to demonstrate different approaches.

A: Implement all the types!
proc isNil(x: int): string = "meme"

echo 0.isNil


text:
Q: Nopcommerce shop configuration I'm working on my first NC shop(online Perfumery) version 3.30.
I added two main categories: 'Ladies' and 'Gentlemen' and i also added some manufacturers:

Now, ofter selecting one of the main categories, the user sees all products that are mapped to that main category and on the left side of the page, is the manufacturers list available(that is what i want). But here, ofter clicking one of the manufacturers, are all the products of that manufacturer listed(both 'Ladies' products as the products of Gentlemen). This is not good. what i want, is that here only the products are listed, that are mapped to the selected main category and not All products of that manufacturer.
How can i get this good?

A: You should consider wrapping these in some if statements. Here is a C# example:
if (genderLSelected == true)
 { <Code to display products for ladies>}
else if (genderMSelected == true)
 {<code to display products for men>}
else
 {<code to display all products>}

The buttons would have to have an onClick method for changing those bools - another if statement would do well here. Also, you'd need to write some code to stop both genders being selected at the same time. You could include this in the onClick methods for your buttons.


text:
Q: Multi-Threaded pinging hundreds of hosts solution for fsockopen in php I'm running a website which monitors some servers and there are more servers added daily.
Sadly my current solution is very slow (about 10 seconds loadtime for 31 servers). I'm using fsockopen which checks the IP and port. Because I parse a XML with the entries (host and port) I had to create a function and use this function in the parser so the visitors of the website can see the online or offline status of the server.
My current "checkserver" function looks like this:
function checkServer($ip, $port)
{
    $fsockopen = @fsockopen($ip, $port, $errorNo, $errorStr, 1);
    if (!$fsockopen)
        return false;

    else return true;
}

And in the parser the "if" rule for the server status looks like this:
if (checkServer((string)$server->host, (string)$server->port))
    {
        echo "SERVER ONLINE!";
    }
else
    {
        echo "SERVER OFFLINE!";
    }

Where $server is every single listed server in the XML <serverlist></serverlist> tag.
I already tried to change the timeout of fsockopen from 1 to 0.1 but some servers appear offline then and the loadtime is still at 8-10 seconds.
How could I speedup the loadtime? Could someone please help me with this?.. the project is very important for me. Thank you! I really appreciate every helpful answer!

A: First of all I would suggest caching. I am not sure how many users will open the page, but if you have multiple users per second opening the page you will have a lot of traffic to handle which on long term could create issues.
You have 2 solutions :

*

*Using asynchronous events can allow you to do what you wish.T here are some libraries outhere doing this that can help you. I have used none sofar so I can't say which is best.

*Using a library that cheats and uses exec & command lines : https://github.com/oliverde8/PHP-AsynchronousJobs

*Using pthread library, this isn't a library coded in php, so it binaries you need to add to your http://pthreads.org/. You can add another library ontop to make the usage easier

*Finally using javascript, so you open your page, then some ajax calls your php individually for each server & ask status.


text:
Q: VSCode underline hides wavy line Underlines which signify Types and Namespaces obscure wavy underlines which signify errors and warnings. This makes it difficult for me to find the location of errors and warnings visually.
Has anyone else encountered this problem? Any solutions?
This particular example is with the Rust language, but I imagine the problem might show up in other languages.


text:
Q: Apply a function to multiple rows of a pandas DataFrame I'm trying to apply a function to different readings of each measure. Is it possible to do it without transforming the dataframe?
import random
import pandas as pd

df = pd.DataFrame({
    'index': sorted(['A', 'B']*3),
    'measure': [i for i in range(0,3)]*2,
    'reading': [random.random() for i in range(0,6)]
})

  index  measure   reading
0     A        0  0.260492
1     A        1  0.805028
2     A        2  0.548699
3     B        0  0.014042
4     B        1  0.719705
5     B        2  0.398824

How can I apply a function like basic difference to different readings for each index?
Here I assumed function applied to reading 0 and 1. It should be part of the call as I need to calculate it for different values of measure.
Desired output looks like this:
  index  applied
0     A  0.5445359999999999
1     B  0.705663

A: Try this
import random
import pandas as pd
import numpy as np

df = pd.DataFrame({
    'index': sorted(['A', 'B']*3),
    'measure': [i for i in range(0,3)]*2,
    'reading': [random.random() for i in range(0,6)]
})

print(df)

# index  measure   reading
# 0     A        0  0.869707
# 1     A        1  0.120680
# 2     A        2  0.772035
# 3     B        0  0.565548
# 4     B        1  0.577074
# 5     B        2  0.290668

start = 0
stop = 1

# I decided to specify start and stop value separately, the absolute difference is
# calculated via np.sum(). If the difference between start and stop is always 1, you
# can omit the np.sum() call.

df = df.groupby('index').agg(applied=('reading', lambda x: np.sum(np.diff(x)
[start:stop])))

print(df)

#         applied
# index
# A     -0.749027
# B      0.011526


text:
Q: Plug in numbers to find relationship between numbers A total of k passengers went on a bus trip. Each of the n buses that were used to transport the passengers could seat a maximum of x passengers. If one bus had 3 empty seats and the remaining buses were filled, which of the following expresses the relationship among n,x, and k?
I only desire a plugging in numbers approach to solve this problem. No algebra.
The problem is I can't think of numbers that would work. Can you help?
A. nx-3=k
B. nx+3=k
C. n+x+3=k
D. nk=x+3
E. nk=x-3

A: $k$ passengers were divided among $n$ buses:

*

*$1$ bus was filled with $x-3$ passengers

*$n-1$ buses were filled with $x$ passengers

Therefore, $k = 1\cdot(x-3)+(n-1)\cdot{x} = nx-3$.


text:
Q: How to read reads a file containing text. Read each line and send it to the output file, preceded by line numbers this program does not create the files
Scanner in = new Scanner(System.in);

System.out.print("Input file: ");
String Mary = in.next();
System.out.print("Output file: ");
String outMary = in.next();

File inFile = new File ("Mary.txt");
Scanner inputFile = new Scanner(inFile);
PrintWriter outFile = new PrintWriter("Mary2.txt");

while (inputFile.hasNext())
{
  String input = in.nextLine();
  outFile.println(input);
}

I want to read a file I created and copy its contents into another with line numbers before each line.

A: try this code, this will create new file for output. Note, this will erase file, if it existed before writing
           File inFile = new File("Mary.txt");
            Scanner inputFile = new Scanner(inFile);

          try(BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Mary2.txt")))) {
              int i=0;
              while (inputFile.hasNext()) {
                  String input = inputFile.next();
                  bw.write(i+"\\ ");
                  i++;
              }
              bw.flush();
          }


text:
Q: I need help to empty text area on particular conditions I have text area controls in my page and I had code it such way that when user click on text area or hit 'ENTER' key that time it will create bullet-list in text area. But problem is that if user click on text area and it will create bullet-list but if user does not type anything in text area then it should get empty and bullet should be removed. In simple way text area bullet-list should get removed if it has no data in it.
And one more thing is to prevent user deleting bullet from text area.
here is my code :
<textarea name="MondayAcomp" id="MondayAcomp" cols="45" rows="5"  onKeyDown="if(event.keyCode == 13) return false;" onKeyUp="bulletOnEnter(this.id)" onFocus="onfoc(this.id)" onBlur="onFocOff(this.id)" style="margin: 0px; width: 200px; height: 219px;"></textarea>

Javascript functions:
function onfoc(id) {
    if (document.getElementById(id).value == "") {
        document.getElementById(id).value += '• ';
    }
}

function onFocOff(id) {
    if (document.getElementById(id).value == '• ') {
        document.getElementById(id).empty;
    }
}

function bulletOnEnter(id) {
    var keycode = (event.keyCode ? event.keyCode : event.which);

    if (keycode == '13') {
        event.preventDefault();
        document.getElementById(id).value += '\n• ';
    }

    var txtval = document.getElementById(id).value;

    if (txtval.substr(txtval.length - 1) == '\n') {
        document.getElementById(id).value = txtval.substring(0, txtval.length - 1);
    }
}

jsfiddle here

A: *

*It is not .empty, it is .value = "";.

*For the keyCode you need to pass event parameter to your callback function too.

*You can prevent adding empty lines, by checking the last line in your return key callback too.

*Only way I can imageine, to prevent deleting the bullets, is a loop at the end and check each line start.

function onfoc(id) {
    if( document.getElementById(id).value == '' ) {
        document.getElementById(id).value +='• ';
    }
}

function onFocOff(id) {
    if( document.getElementById(id).value == '• ' ) {
        document.getElementById(id).value = '';
    }
}

function bulletOnEnter(event, id) {
    event = event || window.event;

    // handle 'return' key
    var keycode = event.keyCode || event.charCode || event.which;
    var txtval = document.getElementById(id).value;
    if( keycode == 13 && txtval.substr(txtval.length - 2) != '• ' ) {
        event.preventDefault();
        document.getElementById(id).value += '\n• ';
    }

    // remove possible last empty line
    txtval = document.getElementById(id).value;
    if( txtval.substr(txtval.length - 1) == '\n' ) {
        document.getElementById(id).value = txtval.substring(0, txtval.length - 1);
    }

    // check if each line starts with a bullet
    var lines = document.getElementById(id).value.split('\n')
    for( var i = 0, l = lines.length; i < l; i++ ) {
        if( lines[i].substr(0, 1) !== '•' ) {
            lines[i] = '•' + lines[i];
        }
    }
    document.getElementById(id).value = lines.join('\n');
}
<textarea id="MondayAcomp" onKeyDown="if(event.keyCode == 13) return false;" onKeyUp="bulletOnEnter(event, this.id)" onFocus="onfoc(this.id)" onBlur="onFocOff(this.id)"></textarea>

As additional answer, I converted the code to use jQuery instead of plain JS, because you tagged your question with jQuery.

$('#MondayAcomp').on({
    focus: function() {
        if( $(this).val() == '' ) {
            $(this).val($(this).val() + '• ');
        }
    },
    blur: function() {
        if( $(this).val() == '• ' ) {
            $(this).val('');
        }
    },
    keydown: function(e) {
        if( e.keyCode == 13 ) {
            e.preventDefault();
        }
    },
    keyup: function(e) {
        var element = $(this),
            value = element.val();

        // handle 'return' key
        if( e.keyCode == 13 && value.substr(-2) != '• ' ) {
            e.preventDefault();
            element.val((value += '\n• '));
        }

        // remove possible last empty line
        if( value.substr(-1) == '\n' ) {
            element.val((value = value.substring(0, value.length - 1)));
        }

        // check if each line starts with a bullet
        var lines = element.val().split('\n')
        for( var i = 0, l = lines.length; i < l; i++ ) {
            if( lines[i].substr(0, 1) !== '•' ) {
                lines[i] = '•' + lines[i];
            }
        }
        element.val(lines.join('\n'));
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="MondayAcomp"></textarea>