text:
Q: Is it a viable method to load a program and run it from memory in C#? I'm creating a wrapper for WkHtmlToPdf. This executable parses html and returns a pdf document as the name suggests.
You call this as follows: wkHtmlToPdf.exe www.example.com "C:\Results\Result.pdf".
The executable also comes with a few dlls.
Is there an easy solution to load the .exe into memory and call it?
Currently the code I wrote takes the .exe and the .dlls as resources, saves them to the Temp directory and calls them via command line. This current method is working nicely, but the step of saving them to the temp directory to call them sounds unnecessary. Surely there is a something like SomeReflectionMethod.Invoke(Resources.wkHtmlToPdf.exe, "www.example.com \"C:\Results\Result.pdf\"").
I have found similar questions, but am finding it difficult seeing the similarities between my specific question (and henceforth the accuracy of the provided answer).
I also have run into a few scary solutions as defined here.


text:
Q: Unable to connect to Windows computer for file sharing I have a Windows 7 machine to which I am unable to connect from several other computers.
When I try to connect to it from other Windows computers I do get the 0x80070035 error code.
I've tried the solutions described here, such as accessing the computer by IP and not by name, to no avail. Please help.

A: This is what solved my problem:
Disable password protected shared use
Control Panel, Network Center, Advance Sharing configuration, Password Protected shared use --> disable.
After trying all the solutions, that is the option that was causing trouble.

A: Your solution is to Enable the "TCP/IP NetBIOS Helper service" , here is a link on how to do it How to Enable TCP/IP NetBIOS Helper service
And Also you can look here : Enabling Netbios over TCP/IP on Windows 7
I hope this will fix your problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: trying to understand the 'os's {npm packages} system memory analysis I have a very simple code:
const os = require('os')
var num = os.freemem();
console.log('free mem is MB: ' + ((num) / 1024 / 1024));

Now, according to the documentation (https://nodejs.org/api/os.html#os_os_freemem), this returns a number, that supposedly represents the amount of free space in my system.
However, when I try to cross reference the result, I see no place that show the same amount of free space as the number 'os' package gives me.
I tried to find how 'os' does what it does, but I couldn't find the source code anywhere.
Can anyone explain to me how this works? what is the meaning of the number that 'os' returns? is it all hard disks? does it consider VM's? is it size or size on disk?
It's pretty annoying that there is no info about any of this...
thanks to anyone who can help!


text:
Q: Capture only the numeric part with sed regex Why does the following does not work?
INTERNAL_NUM=$(grep -E '\s*internal_num\s*=' file.xml |sed -E 's/internal_num\s*=\s*([0-9]\+)/\1/')
echo "$INTERNAL_NUM"

I would like to print out the actual number but it prints:
internal_num = 1234

The grep command prints internal_num = 1234 so that part is fine. It is the pipe to sed that does not work.

A: If you have GNU grep, you could write
grep -oP '\binternal_num\s*=\s*\K\d+' file.xml

But you should not be parsing XML with regular expressions. Perhaps you need something like this
$ echo '
      <root>
          <tag>
              <tag>
                  <wanted internal_num="1234" />
                  <wanted internal_num = "5678" />
              </tag>
          </tag>
      </root>
  ' | xmlstarlet sel -t -v '//@internal_num' -n

1234
5678

Please show your input file.

A: You are using extended regex, but still escaping \+, therefore it looks for a literal plus sign and does not invoke the substitution.
Try,
INTERNAL_NUM=$(grep -E '\s*internal_num\s*=' file.xml |sed -E 's/internal_num\s*=\s*([0-9]+)/\1/')
echo "$INTERNAL_NUM"

Testcases (tested on GNU sed V4.2.1):
$ echo "internal_num = 1234" | sed -E 's/internal_num\s*=\s*([0-9]\+)/\1/'
internal_num = 1234

$ echo "internal_num = 1234" | sed -E 's/internal_num\s*=\s*([0-9]+)/\1/'
1234

As other answers mention (and explain in good detail), you should seriously consider not using regex to parse XML though.

A: Different tools and implementations/versions of a given tool support different regular expression syntax.
To be portable, you can limit yourself to the POSIX feature set:
s=[[:space:]]
sed -n "s/^\(.*$s\)\{0,1\}internal_num$s*=$s*\([0-9]\{1,\}\).*/\2/p"

(assuming there's only one occurrence per line)
If you know you'll only run it on systems where grep supports -o and -P (for perl-like regexps) à la GNU grep, you can do:
grep -Po '(?<!\S)internal_num\s*=\s*\K\d+'


text:
Q: How to get intellisense on CLR types in SQL Server Management Studio I created a CLR user defined type in C#/Visual Studio and added it to the assemblies with no issue.  All works well, but is there a way to get intellisense working for the properties and methods?  I'm using VS 2019, SQL Server 2019, and SSMS v18.xx
I've turned intellisense off/on and also did a refresh, but no luck.
Thank you.


text:
Q: Google Maps Javascript - Resize event listener not being called I've got a map in a hidden div that gets revealed by a button press. I was initially having issues but they were fixed by triggering a resize event. My issue now is that the map isn't centered on the position that I initialise the map with.
I want to add a map.setCenter(?) call in to the resize or bounds changed event listener but they never seem to be called. I've put alerts in each one to test but nothing happens.
EDIT: Example as requested...
<!DOCTYPE html>

  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">
  <title>Simple markers</title>

Click Me

A: I have tested more deeply your code there is a problem with the scope of the var map
change declaration in this way (in window scope outside the function initMap local scope)


text:
Q: How to change only one byte at address with gdb I'd like to be able to change only one byte at a certain address with gdb.
The set * command always changes 4 counting from an address and if you don't provide all four it fills the rest with zeroes (or ffs depending on the signedness).
The syntax I'm using is set * {address}=0x{bytes}

A: treat address as pointer to char type
(gdb) set {char}address = 0x{bytes}


text:
Q: How to calibrate screen colour in Ubuntu 18.04 LTS? The color on the screen of my Dell XPS 15 is rather blue-ish. The D55 (5500K) profile is too yellow and D60 is too cold.
Ideally I'd like a profile configured at 5700k, or somewhere in that zone. None of the other profiles suit my needs.
UPDATE:
While I have yet to find a proper solution, I managed to tweak the color of my screen with redshift. Not an ideal solution, but it does the trick for the time being.
UPDATE 2:
This can be done with the following command:
gsettings set org.gnome.settings-daemon.plugins.color night-light-temperature <temperature>

A: You can import color profile in Settings -> Devices -> Color (only for X.org sessions).

Select your display and click on Import profile button
You can install default color profiles using sudo apt install icc-profiles or find your profile here
Also you can calibrate your screen manually in settings (unfortunately, that button is disabled in my system and I don't know why) or using gcm-calibrate:
$ sudo apt install gnome-settings-daemon

$ colormgr get-devices # take note of the Device ID of the one with Type: display, e.g. "xrandr-Acme Corp"

$ gcm-calibrate --device="some Device ID"

This method requires an external display calibration hardware. The simplest way is to calibrate your screen in Windows and them export profile and apply it in your Linux system.
For more info, I recommend to take a look at this article at Arch Wiki
Also, AFAIK display calibration might not available in Wayland session for now.


text:
Q: Using action-angle variables in non-periodic system I'm a little confused by the discussion in the last section $\S 50$ of Landau and Lifshitz's (Classical) Mechanics (1960, first English ed.). Here, they consider finite motion of a system whose Hamilatonian is separable (for a Hamilton-Jacobi treatment) and apply the action angle formalism.
As they explain, the abbreviated action can be written as a sum of functions (given the variables' separability):
$$S_0=\sum\limits_i S_i(q_i), \tag{52.1} $$
where each $S_i$ can be written $\int p_i $d$q_i$. They then say

Since the motion is finite, each co-ordinate can take values only in a finite range. When $q_i$ varies 'there and back' in this range, the action increases by
  $$\Delta S_0=\Delta S_i = 2\pi I_i\tag{52.3} $$ where $$I_i\equiv\oint p_i\text{d}q_i/2\pi,\tag{52.4} $$ the integral being taken over the variation just mentioned.

A footnote here on p. 163 then reads,

It should be emphasised, however, that this refers to the formal variation of the coordintae $q_i$ over the whole possible range of values, not to its variation during the period of the actual motion as in the case of motion in one dimension. An actual finite motion of a system with several degree of freedom not only it not in general periodic as a whole, but does not even involve a periodic time variation of each co-ordinate separately."

They then define the action variables as
$$\omega_i=\frac{\partial S_o}{\partial Ii} \tag{52.5}$$
so that over a 'there and back' variation of the $q_i$ corresponds to a change $$\Delta \omega_i=2\pi. \tag{52.8}$$
Now what I'm having trouble with is understanding why the variation of a $q_i$ across the range of its values has any significance in describing the actual evolution of the system (assuming it isn't periodic).
Note: Perhaps I'm simply misunderstanding what they mean by "finite motion" here. I'm taking this to be applicable in any case where you know a finite range of the $q_i$ for some relevant temporal duration. If what they mean is that the possible values of the $q_i$ are bound in some region for all time, then I can see how things would necessarily be conditionally periodic. (I'm thinking of something like Poincare's recurrence theorem here.) However, in this case my question would be whether one can generalise this to all systems in some temporal evolution, modelling the evolution as some portion of a larger periodicity?


text:
Q: Broken Picking Coordinates Directx11 I have for a fair while now been trying to implement a click-based model insertion into my game editor but have run into numerous problems. The most recent is an offset in the placement of the model. So far I have got this code together:
    D3DXVECTOR3 vPickRayDir;
    D3DXVECTOR3 vPickRayOrig;

    float width = (float)d3d->scd.BufferDesc.Width;
    float height = (float)d3d->scd.BufferDesc.Height;

    const D3DXMATRIX* pmatProj = &d3d->matProjection;

    POINT ptCursor;
    GetCursorPos(&ptCursor);
    ScreenToClient(&ptCursor);

    D3DXVECTOR3 v;
    v.x = (((2.0f * ptCursor.x) / (d3d->viewport.Width)) - 1.0f) / pmatProj->_11;
    v.y = -(((2.0f * ptCursor.y) / (d3d->viewport.Height)) - 1.0f) / pmatProj->_22;
    v.z = -1.0f;

    const D3DXMATRIX matView = d3d->matView;
    const D3DXMATRIX _matWorld = matWorld;

    D3DXMATRIX matRotateX, matRotateY, matRotateZ, matTranslate;

    D3DXMatrixTranslation(&matTranslate, 0, 0, 0);
    D3DXMatrixRotationX(&matRotateX, 0);
    D3DXMatrixRotationY(&matRotateY, 0);
    D3DXMatrixRotationZ(&matRotateZ, 0);

    matWorld = (matRotateX * matRotateY * matRotateZ) * matTranslate;

    D3DXMATRIX mWorldView = matWorld * matView;
    D3DXMATRIX m;
    D3DXMatrixInverse(&m, NULL, &mWorldView);

    vPickRayDir.x = v.x * m._11 + v.y * m._21 + v.z * m._31;
    vPickRayDir.y = v.x * m._12 + v.y * m._22 + v.z * m._32;
    vPickRayDir.z = v.x * m._13 + v.y * m._23 + v.z * m._33;
    vPickRayOrig.x = m._41;
    vPickRayOrig.y = m._42;
    vPickRayOrig.z = m._43;

    ModelInstance mi(GetDocument()->GetModel(m_wndModels.m_nodeTree.selectID));

    mi.Translation.at(0).x = (1 * vPickRayDir.x + vPickRayOrig.x);
    mi.Translation.at(0).y = (1 * vPickRayDir.y + vPickRayOrig.y);
    mi.Translation.at(0).z = (1 * vPickRayDir.z + vPickRayOrig.z);
    mi.Translation.at(0).z *= -1;

Why is there an offset and how do I remove it?
P.S. Here's a link the complied program. Click open and open the enclosed fbx file. Once opened, double click the model in the model list and click on the view space to insert.

A: I found the solution here. The last post showed everything that was needed, all I needed to do was change variables to suit DirectX-10.


text:
Q: Camera not detecting text in portrait mode while using react-native-firebase-mlkit? I am using react-native-firebase-mlkit in my app and this package is used to detect the text taken from camera or from the saved images in gallery. It is working fine when I click an image in landscape mode, but it is not able to read image when clicking in portrait mode. This problem is specific to Android. Does anybody have any solutions for this issue?
Does anybody have any solutions for this issue?

A: You must take a picture with fixOrientation: true
camera.current.takePictureAsync({fixOrientation: true})
another important thing is; text which is taken in the photo must be portrait


text:
Q: EntityFramework Error 26 with LocalDb and IndentityDbContext I am creating a DataAccess C# class library for an MVC application. Inside of the class library, I am using EntityFramework and ASP.NET Identity.
When I try to run Update-Database or Add-Migration on the class library, I get an error.
Error 26:A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible.
My UserAccount class derived from IdentityUser is below:
public class UserAccount : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public virtual Address Address { get; set; }
        public virtual PaymentDetail PaymentDetail { get; set; }

        public virtual MediaResource ProfilePicture { get; set; }
        public virtual ICollection<Conversation> Conversations { get; set; }
    }

The implementation of my context class uses this constructor:
public class LouderContext : IdentityDbContext<UserAccount>
    {

        public LouderContext("DefaultConnection") { }

The contents of my App.config file are below:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>

    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v12.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

Things that I have tried:

*

*Changing the parameter of the connection factory to mssqllocaldb or v12.0 from v11.0

*Repairing my visual studio installation

*Manually adding the connection string from the SQL Server Object Explorer into a connectionstring object in App.config

I can access (localdb)\MSSQLLocalDB from SSMS without issue. I can also access LocalDb through a scaffolded MVC project but my issue persists whenever I try to run any commands on my class library via the package manager console. What seems to be the issue? Does anything obvious jump out?

A: EF use the start project as source of the connection string , i think it might be your problem as your start project is the MVC Project try to change the start project to be the class library and then add migration and update-database  .
Edit :
You have two  connection strings with the same name DefaultConnection one at the app.config and one at web.config , change that and in DBContext constructor add the one belongs to app.config Ex :  public LouderContext("AppConfigConnection") { }
another solution :
Get-Help enable-migrations -detailed

You can find this documentation for the -StartupProjectName option:
-StartUpProjectName

Specifies the configuration file to use for named connection strings. If
omitted, the specified project's configuration file is used.

It means that if you use this option to specify a project name, migrations will look for the connection string in the config file of the specified project. (The config file can be web.config or app.config).

A: Either leave your Context constructor blank( i.e. don't call base()), or make sure there is a connectionstring entry in the app.config for DefaultConnection.


text:
Q: Spring Data: How to update a List of childs with unique constraints I am using spring-data to persist data to a mysql db.
I have a parent entity that contains a list of child entitys:
@Entity
public class Parent
{
    private Long id;

    @Unique
    private String name;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "parent_id")
    private List<Child> childs;

    // Getter, Setter
}

and here is the child entity:
@Entity
@Table(
    uniqueConstraints = { @UniqueConstraint(columnNames = { "parent_id", "name" }) }
)
public class Child
{
    private Long id;

    @Unique
    private String name;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "parent_id")
    private Parent parent;

    // Getter, Setter
}

In the database I have the same constraints active like in this two classes.
Now, I want to update the childs of the parent like this:
@Service
public class ParentService
{
    // ...

    @Transactional
    public Parent updateParent(String name, List<Child> newChilds)
    {
        Parent existingParent = parentRepository.findByName(name);
        existingParent.setChilds(newChilds);
        return parentRepository.save(existingParent);
    }

    // ...
}

But then the unique constraint (name + parent_id) for the child will fail, if they have the same name. How can I get sure, that the old childs are deleted before the new childs are persisted?

A: I would suggest to use
existingParent.getChilds().clear();
parentRepository.save(existingParent)
existingParent.getChilds().addAll(newChilds);

because of (Hibernate JPA: @OneToMany delete old, insert new without flush)
And if you are on default transaction behaviour, you can change
return parentRepository.save(existingParent);

to
return existingParent;

Loaded and then changed entities are automatically saved on transaction commit, so you are actually saving twice.


text:
Q: What is the greatest number of points that can be placed inside a circle? Singapore Math Competition Question I'm just doing some practice papers when this question came.
What is the greatest number of points that can be placed inside a circle such that the distance between any two points is greater than the radius of a circle?
I have a catch that the answer should be 5 or 6. However, I do not know which one should be correct.
Anyone help?

A: Let's examine placing a particular point $P$ in the circle $C$. Then a circular region of radius $r$ (the region in which no other points can be placed) around $P$ and inside $C$ includes $\textit{all}$ of the circular region of radius $r$ around $P'$ and inside $C$, where $P'$ is the closest point to $P$ on the perimeter of the circle.

Note that if $P$ starts at the center of $C$, then the whole of $C$ is excluded, so we can do better by choosing $P'$ anywhere else.
Hence, a maximum arrangement of points greater than $r$ away from each other can be obtained when all points are on the perimeter (note that there can still be maximum arrangements with every point inside the circle, we have just proved that if there is one of those, then we could also draw a maximum arrangement on the perimeter).
The minimum distance two points need to be away from each other is $r$, so every two points must be greater than $\frac{1}{3}\pi r$ away from each other along the perimeter of the circle (we can see this by noting that when two points on the perimeter are exactly $r$ distant from each other, then the angle between them measured from the center of the circle is $\frac{1}{3}\pi$). However, the total length of the perimeter is $2\pi r$, so by the pigeon hole principle, if we have $6$ points arranged on the circle, then the counterclockwise distance between some two neighbors must be $\leq\frac{2\pi r}{6}=\frac{1}{3}\pi r$. But this contradicts the fact that the distance between any two neighbors must be strictly greater than $\frac{1}{3}\pi r$. Hence there are no satisfying arrangements of $6$ points.
Finally, noting that an arrangement of a regular pentagon of sidelength $r$ fits inside our circle of radius $r$, we can conclude that the maximum number of points we can place in accordance with the given rule is $5$.


text:
Q: A model for the framed little disks operad $f{\cal D}_n$ with arity one *equal* to $SO(n)$? The framed little disks operad $f{\cal D}_n$ can be described as the semidirect product ${\cal D}_n \rtimes SO(n)$, where ${\cal D}_n$ is the little disks operad and $SO(n)$ is the special orthogonal group, or rotation group.
As a topological space, forgetting the operad structure, this simply means that, in each arity $k$, we have
$$
f{\cal D}_n (k) = ({\cal D}_n \rtimes SO(n))(k) = {\cal D}_n (k) \times SO(n)^k \ .
$$
See for instance, Salvatore-Wahl.
So, in arity one, we get
$$
f{\cal D}_n(1) = {\cal D}_n(1) \times SO(n) \ ,
$$
which is easily seen to be homotopically equivalent to $SO(n)$, since ${\cal D}_n(1)$ is contractible:
$$
f{\cal D}_n(1) \simeq SO(n) \ .
$$
This is pretty exciting, because it's an example of a non-connected topological operad; that is, $P(1) \neq *$, and Fresse had to do a nice effort to adapt his Sullivan rational homotopy theory for topological operads Homotopy of operads to encompass it: see Extended
Now my question is the following: is there any other topological model $P$ of $f{\cal D}_n$ for which $P(1)$ is actually $P(1) = SO(n)$---not just homotopically equivalent?
By "topological model" I mean, any topological operad $P$ that can be joined with $f{\cal D}_n$ through a chain of quasi-isomorphisms (topological operad morphisms inducing isomorphisms in homology) like
$$
P \stackrel{\sim}{\longleftarrow} \cdot \stackrel{\sim}{\longrightarrow} \cdot \dots \stackrel{\sim}{\longleftarrow}\cdot \stackrel{\sim}{\longrightarrow} f{\cal D}_n  \ .
$$
And when I say "homology", I mean homology with coefficients in a zero characteristic field: over the real numbers, for instance, would be fine.
EDIT Idrissi kindly warns me that, in the presence of a non-simply connected $SO(n)$, this is the wrong notion of a topological model: I should have said weak homotopy equivalences instead of quasi-isomorphisms. (See the comments.)
I guess a brute-force approach---just delete ${\cal D}_n(1)$ from the definition, leave $SO(n)$ and compose with the homotopy equivalence---can not work because you would destroy the operad structure.

A: Let me summarize the comments. You have several possibilities:

*

*[Ryan's comment] You can consider the sub-operad $fD'_n \subset fD_n$ such that $fD'_n(r) = fD_n(r)$ for $r \ge 2$, and $fD'_n(1) = SO(n) \subset fD_n(1)$ is the subspace where the only little disk fills the whole ambient disk (i.e. is of radius $1$). Note that this only works if you consider the non-unital version of the framed little disk operad, i.e. with nothing in arity $0$; otherwise, this isn't a sub-operad.

*[Adrien's comment] For $n = 2$, you can consider $\mathcal{M}^{fr}_{0,\bullet+1}$, the moduli spaces of genus $0$ punctured Riemann surfaces with tangent vectors at the punctures.

*[my comment] Consider the Fulton–MacPherson compactification operad $\mathsf{FM}_n$. References include the original paper of Axelrod–Singer, the book of Lambrechts–Volić, or Sinha's paper Manifold-theoretic compactifications of configuration spaces. This operad admits a natural action of $SO(n)$, so you can take the semidirect product $\mathsf{FM}_n^fr = \mathsf{FM}_n \rtimes SO(n)$. Since $\mathsf{FM}_n(1)$ is a singleton, it follows that $\mathsf{FM}_n^{fr}(1) = SO(n)$.


text:
Q: Pyjamas + Django => CSRF confusion, 403 errors I've got Pyjamas and Django running via Apache2 with mod_wsgi on Windows 7. I do not believe I'm getting issues from the setups of these things, though: the only thing that is not working is trying to POST information from Pyjamas-generated forms. Trying to use Pyjamas-generated forms in my application produces 403s (the "CSRF verification failed" error page).
I have spent hours on this and read all of the answers I could find on here related to CSRF and Pyjamas, and done a lot of external research just on CSRF and Django, Django and Ajax, etc. If this question isn't reaching anyone who has knows just what to do in this situation, I think I've whittled down the essence of the question.
How would one get the {% csrf_token %} into the Pyjamas-generated form? It seems like it might be impossible, because from what I understand CSRF tokens are not persistent, which a Pyjamas-generated page is ... My Pyjamas page is generated from a Pyjamas .py file, resulting in a folder full of hard-coded stuff. How is it that I would integrate the current CSRF token into that already-coded form?
Please don't hesitate to ask for more details, this issue has been incredibly hard to navigate. None of the published information on integrating Pyjamas & Django regards this; and the only solutions I've found that seem aware of CSRF in Django say you should probably just disable CSRF protection (which I could do, but what protection could I put in place of it? My own cookie system? Is it a terrible idea to disable CSRF protection in any case?).
Thank you!

A: You'll need to write some JavaScript to get the CSRF token from the cookie (part of the HTTP request), then add it to the form on submit.
Look at this answer for a starting point: Django CSRF check failing with an Ajax POST request
The key here is that the JavaScript can be as persistent as your Pyjamas-generated files, because they defer handling the token until the form is submitted.


text:
Q: Load 3d object dynamic in Cocos 3d I am developer of iOS but new bee in Cocos, i am building an Augmented Reality App in which i want to load 3d object on run time and show them when specific marker detected. But my following Questions are about Cocoas and related to my own task, forgive me if i asked something silly .

*

*Can i load 3d objects on run time in Cocos 3d?

*Is this possible that i can get those 3d objects from my server via calling web-service, because these objects can b in .fbx format so is cocoas understand this type or should i use something else.

*Is cocoas support objective-c because i only have knowledge in objective-c.

*Will integration will be easy with my first part of app which i being developed in iOS, because i was thinking to do this task in Unity but Integration is so hectic so i decided to move any other and i got suggestion to go with Cocos 3d.
Please help me on this. Thanks in Advance.

A: *

*Yes

*Download from server: yes. You could use NSData (dataFromURL) to download a file. But last time I checked (4 months ago or so) cocos3d only supported the POD file format.

*Yes, Cocos3d is written in Objective-C (haven't you downloaded the code yet?).

*Easy is relative. Might be super-easy for a pro and next to impossible for a beginner. Hard to say without knowing you, your project, your requirements, your goals.


text:
Q: Does SQL Server support statistics on geometry column? I have a query on spatial data. In execution plan I see warnings, that geo-column does not have statistics.

I have index on this column, but I can't create statistics.

*

*Does SQL Server support statistics on geometry column?

*How can I avoid this warning?

A: In turn:

*

*It doesn't appear that SQL Server supports statistics on geometry/geography columns. Here's a simple demonstration:
create table #foo (g geometry);
create statistics foo_g on #foo (g);
When I run this, I get the following error:

Msg 1978, Level 16, State 1, Line 3 Column 'g' in table '#foo' is of a
  type that is invalid for use as a key column in an index or
  statistics.

*I don't think you do. I wish the optimizer was smart enough to say "that column will never have statistics (as a natural consequence of the above) and not gripe about it. But alas, it is the optimizer that Gotham has, not the optimizer Gotham deserves.

A: It supports bounding boxes and grid levels instead of statistics.
If you tilt your head a little, you will realize a bounding box is effectively a custom statistics histogram that controls what tiny box your geometric points (object) fits into.  The grid levels then control the depth of the search into that bounding box.


text:
Q: Getting an error when when the program tries to write to file? The problem is the part where I write to the file. Everytime that I am done giving the values to the strings in the console, it will give me an error as follows:
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
at java,util,Scanner,ensureOpen(Unknown Source)
at java,util,Scanner,findWithinHorizon(Unknown Source)
at java,util,Scanner,hasNextLine(Unknown Source)
at mainPackage,MainClass,main(MainClass.java:71)

This is my code:
package mainPackage;

import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
import java.util.ArrayList;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedWriter;

public class MainClass {

   private static FileWriter fw;
   private static BufferedWriter out;
   private static Scanner input;
   private static Scanner file;
   private static FileWriter fw2;
   private static BufferedWriter out2;
   private static Scanner file2;
   private static ArrayList<String> questList;
   private static ArrayList<String> ansList;

   public static void main(String[] args) throws IOException  , IllegalStateException{

      fw = new FileWriter("C:/Users/ALAN_BARE/Desktop/Dictionary.txt" , true );
      input = new Scanner(System.in);
      file = new Scanner(new File("C:/Users/ALAN_BARE/Desktop/Dictionary.txt"));
      out = new BufferedWriter(fw);
      fw2 = new FileWriter("C:/Users/ALAN_BARE/Desktop/Dictionary2.txt" , true);
      out2 = new BufferedWriter(fw2);
      file2 = new Scanner(new File("C:/Users/ALAN_BARE/Desktop/Dictionary2.txt"));
      questList = new ArrayList<String>();
      ansList = new ArrayList<String>();

      String engword;
      String gerword;
      String response;
      int counter = 0;

      //Loading the file data to the arraylist
      while (file.hasNextLine()) {
         questList.add(file.nextLine());
         ansList.add(file2.nextLine());
      }

      file.close();
      file2.close();

      System.out.println("What do you want to do, register words or Play the game?");
      response = input.nextLine();

      //Getting the values of the strings via user input
      if (response.contains("register")) {

         System.out.println("Type yor english word:");
         engword = input.nextLine();
         System.out.println("Type the translation in German:");
         gerword = input.nextLine();

         //writing it to a file
         if (file.hasNextLine()) {
             out.newLine();
             out.write(engword);
         }
         else {
             out.write(engword);
         }

         if (file2.hasNextLine()) {
             out2.newLine();
             out2.write(gerword);
         }
         else {
             out2.write(gerword);
         }
      }

      //The same, just for a different response
      else if (response.contains("Register")) {
         System.out.println("Type yor english word:");
         engword = input.next();
         System.out.println("Type the translation in German:");
         gerword = input.next();

         if (file.hasNextLine()) {
            out.newLine();
            out.write(engword);
         }
         else {
            out.write(engword);
         }

         if (file2.hasNextLine()) {
             out2.newLine();
             out2.write(gerword);
         }
         else {
             out2.write(gerword);
         }
      }

      out.close();
      out2.close();

      //Running the quiz game
      if (response.contains("play")) {

          while (counter <= 10 ) {
              counter++;
              int sel = ThreadLocalRandom.current().nextInt(0, questList.size() + 1);

              System.out.println("The english word is :" + questList.get(sel));
              System.out.println("Please type the translation in German:");
              String answer = input.nextLine();

              if (answer.contains(ansList.get(sel))) {
                  System.out.println("Correct!");
              }
              else {
                  System.out.println("Wrong! You Lose! If you want to play again, restart the app.");
                  break;
              }
          }
      }

      while (counter == 10) {
          System.out.println("You Win The Game! If you want to play again, restart the app.");
          counter++;
      }
   }
}

What could be the problem?

A: It is normal that you get the error after you close the Scanner object named as file at line 56

file.close()

The error you get address the problem clearly.

Scanner closed


text:
Q: Getting the Folder size for only subfolders, whist ignoring any other content? I've created the script below, which manages and maintains allocated storage within a RootFolder, into which are stored daily backups each within its sown individual folder, and should the RootFolder content exceed a preset limit, then the oldest backup folder is then deleted.
So far so good . . . the problem I have is that largeish files may also be added to the RootFolder [strHomeFolder] and as such are also included in the total accumulated 'size'.  As a consequence the backup folders may be prematurely deleted, and in the worst case scenario all may be deleted altogether, which unfortunately may somewhat defeat the purpose of having backups !
I am therefore seeking advice in makeing the objFSO.GetFolder check only the contents of all of the backup Folders located within the RootFolder whilst ignoring any of the files at that level.
strOldestFolder = ""
dtmOldestDate = Now

Set oShell = CreateObject("WScript.Shell")
strHomeFolder = oShell.ExpandEnvironmentStrings("%USERPROFILE%\HDBackups")

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strHomeFolder)

intFolderSize = Int((objFolder.Size / 1024) / 1024)

If intFolderSize >= 50 Then ' change as appropriate value in MBytes
    Set objSubFolders = objFolder.SubFolders
    For Each objFolder in objSubFolders
        strFolder = objFolder.Path
        dtmFolderDate = objFolder.DateCreated
        If dtmFolderDate < dtmOldestDate Then
            dtmOldestDate = dtmFolderDate
            strOldestFolder = strFolder
        End If
    Next
    objFSO.DeleteFolder(strOldestFolder)
End If

A: Just loop through the Root folder's SubFolders and sum up intFolderSize:
strOldestFolder = ""
dtmOldestDate = Now

Set objShell = CreateObject("WScript.Shell")
strHomeFolder = objShell.ExpandEnvironmentStrings("%USERPROFILE%\HDBackups")

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strHomeFolder)

Dim objSubFolder
intFolderSize = 0
For Each objSubFolder In objFolder.SubFolders
    intFolderSize = intFolderSize + objSubFolder.Size
Next

intFolderSize = Int((intFolderSize / 1024) / 1024)

If intFolderSize >= 50 Then ' change as appropriate value in MBytes
    Set objSubFolders = objFolder.SubFolders
    For Each objFolder In objSubFolders
        strFolder = objFolder.Path
        dtmFolderDate = objFolder.DateCreated
        If dtmFolderDate < dtmOldestDate Then
            dtmOldestDate = dtmFolderDate
            strOldestFolder = strFolder
        End If
    Next
    objFSO.DeleteFolder (strOldestFolder)
End If


text:
Q: Need help in creating an appropriate model to predict semantic similarity between two sentences I am new to ML field and trying my hands on creating a model which will predict semantic similarity between two sentences.
I am using following approach:
1.Using word2vec model in gensim package vectorise each word present in the sentences in question
2.Calculate the average vector for all words in every sentence/document
import numpy as np
from scipy import spatial

index2word_set = set(model.wv.index2word)

def avg_feature_vector(sentence, model, num_features, index2word_set):
    words = sentence.split()
    feature_vec = np.zeros((num_features, ), dtype='float32')
    n_words = 0
    for word in words:
        if word in index2word_set:
            n_words += 1
            feature_vec = np.add(feature_vec, model[word])
    if (n_words > 0):
        feature_vec = np.divide(feature_vec, n_words)
    return feature_vec

3.Next calculate cosine similarity between these two average vectors
s1_afv = avg_feature_vector('this is a sentence', model=model,
num_features=300, index2word_set=index2word_set)
s2_afv = avg_feature_vector('this is also sentence', model=model,
num_features=300, index2word_set=index2word_set)
sim = 1 - spatial.distance.cosine(s1_afv, s2_afv)
print(sim)

Reference stackoverflow question:
How to calculate the sentence similarity using word2vec model of gensim with python
Help needed for the following challenge:
As I want to create a model which would predict semantic similarity between two sentences, I am not quite sure about:
1.Which model would be best suited for this problem
2.Next more importantly how to train that model?
Should I create a matrix where each row will contain two sentences:
sen1 and sen2 and I would vectorise them and calculate cosine similarity(as per the above mentioned approach)
Then for training data:
X_Train: avg vectors for sen1 and sen2 and their cosine similarity value
y_Train(prediction) : a set of binary values(1 or similar if cosine similarity > 0.7 and 0 otherwise)
I am quite confused whether my approach is correct and how to put a proper approach in the form of a working codebase.
Internet and materials available online are my only teachers to learn ML; thus requesting your guidance in help clearing my gap in understanding and help in coming up with a good working model for my problem.

A: Your general approach is reasonable. An average of the word-vectors in a sentence often works OK as a rough summary vector of the sentence. (There are many other possible techniques which might do better, but that's a good easy start.)
You can use someone else's pre-trained word-vectors, but if you have a good large training set of text from your domain, those word-vectors may work better. You should look for a tutorial on how to train your own word-vectors with gensim. For example, there'a a demo Jupyter notebook word2vec.ipynb included with it, in its docs/notebooks directory, which you can also view online at:
https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/word2vec.ipynb
Your current avg_feature_vector() function has a number of problems. In particular:

*

*if you pass in the model, it already includes within it the fixed index2word list, and an already-determined number-of-dimensions – so no need to pass those in redundantly

*you're looping over all words in the model, rather than just the ones in your sentence, so not calculating just based on your sentence

*there are better, more pythonic ways to do the various array math operations you're attempting - including in the numpy library a simple mean() function that will spare you the adding/dividing of creating the average
You may want to fix those problems, as an exercise, but you could also use utility methods on the word-vectors model instead. In particular, look at n_similarity() - it specifically takes two sets-of-words, automatically averages each set, then reports the similarity-value (closer to 1.0 for more-similar, closer to -1.0 for least-similar) between the two sets. See:
https://radimrehurek.com/gensim/models/keyedvectors.html#gensim.models.keyedvectors.Word2VecKeyedVectors.n_similarity
So if you had two sentences (as strings) in sent1 and sent2, and a set of word-vectors (either just-trained by you, or loaded from elsewhere) in kv_model, you could get the sentence's similarity via:
kv_model.n_similarity(sent1.split(), sent2.split())

(You might still get errors if any of the word-tokens aren't known by the model.)
Whether you actually create average vectors for different sentences and store them in some list/dict/dataframe/etc, or simply remember the pairwise-similarities somewhere, will depend on what you want to do next.
And, after you have the basics working on this simple measure of text-similarity, you could look into other techniques. For example, another way to compare two texts using word-vectors – but not via the simple average – is called "Word Mover's Distance". (It's quite a bit slower to calculate, though.)
Another technique for collapsing texts into a single vector, for the purposes of comparison, is available in gensim as Doc2Vec – it works a lot like Word2Vec but also creates vectors-per-longer-text, instead of just vectors-per-individual-word.

A: First of all thank you for asking this question, I am dabbling with same problem, first and foremost it is not a simple problem to solve because it deals with a nuance of a language and how to make a machine understand human language.
Since the time this question was asked to this time there have been a lot of changes that has happened in the ML/AI world so I thought updating this answer might help someone.
The problem with your approach is getting the average of all words in a sentence and averaging it out to get a derived vector for your sentence, given the tool of that time it might be okay but you should have gone with something more sophisticated like Doc2Vec from gensim.
For todays time I feel there exist way more sophisticated and effective word embedding rather sentence embedding that you can use.
List of few of them have been very cleverly curated at this github repo from HuggingFace.
There is also an amazing discussion which I would love to point out to people reading this:
https://github.com/huggingface/transformers/issues/876
People often try to use a combination of ElasticSearch BM25 + Embeddings, but practical accuracy is still lower.
I am still in search of a semantic search technique which can help me do a semantic search over my domain data.
The closes thing is Transfer Learning where you can use a pre-trained model and add your domain data over it to finetune that model.
You can have a look at the example:
https://github.com/UKPLab/sentence-transformers/blob/master/examples/application_semantic_search.py
But this way also we are not able to consider ontology and various scenarios where the word-overlap should come into picture.


text:
Q: Why does 'bundle install' fail and force me to 'gem install' myself? I have executed the command
bundle install

In my Ruby on Rails projects, and I get the following error message
An error occurred while installing bcrypt (3.1.10), and Bundler cannot continue.
Make sure that `gem install bcrypt -v '3.1.10'` succeeds before bundling.

After executing
gem install bcrypt -v '3.1.10'

the problem disappears. My question is why it's necessary sometimes to install some gems in a direct way?


text:
Q: Google Auth credentials not retrieved properly on Heroku staging account Rather than storing a credentials file on the server, we opted to use env vars to store the required info:
GOOGLE_CLIENT_ID
GOOGLE_CLIENT_EMAIL
GOOGLE_ACCOUNT_TYPE
GOOGLE_PRIVATE_KEY

And we're obtaining authorization for a CalendarService as follows:
scopes = ["https://www.googleapis.com/auth/calendar"]
auth = ::Google::Auth.new_application_credentials(scopes)
service = ::Google::Apis::CalendarV3::CalendarService.new
service.authorization = auth
service.authorization.fetch_access_token!

Every part of the process works locally - authorizing, fetching an access token, interacting with API, etc. When we deploy to our staging environment on Heroku, we can't get past the following error:
Unable to read the credential file specified by GOOGLE_APPLICATION_CREDENTIALS: Neither PUB key nor PRIV key: nested asn1 error
I had seen this error in testing so I know it can be related either to a missing credentials file (like the error indicates) OR to an invalid id, private key, or email combination (because I was accidentally replacing the private key with an invalid value). In that situation, the error message was identical.
We have verified that all vars match the credentials used locally - what am I missing?

A: Make sure you are setting properly the GOOGLE_PRIVATE_KEY variable.
On Heroku to set a multi-line config variable you need to run:
heroku config:add GOOGLE_PRIVATE_KEY="$(cat private_key_file)"

A: An alternative to storing the key in a new file and using cat would be to use printf instead.
heroku config:add GOOGLE_PRIVATE_KEY="$(printf "-----BEGIN PRIVATE KEY.....")"


text:
Q: wglMakeCurrent with hdc parameter NULL According to the registered here (khronos site):

If the OpenGL context version of <hglrc> is 3.0 or above, and if
      either the <hdc> parameter of wglMakeCurrent is NULL, or both of the
      <hDrawDC> and <hReadDC> parameters of wglMakeContextCurrentARB are
      NULL, then the context is made current, but with no default
      framebuffer defined. The effects of having no default framebuffer on
      the GL are defined in Chapter 4 of the OpenGL 3.0 Specification.

Trusting this information I created a device context "off screen" with:
HDC m_hDC = CreateCompatibleDC(NULL);

I configured the Pixels and added to DC with the SetPixelFormat function:
SetPixelFormat(m_hDC, iPixelFormat, &chosenPFD);

Then I created a rendering context:
m_hGLRC = ::wglCreateContextAttribsARB(m_hDC, NULL, &(iAttributes[0]));

So far so good, it works.
Now it's time to make the context current.
First I delete the DC (I will not need it anymore) and call the wglMakeCurrent with a NULL dc parameter:
DeleteDC(m_hDC);
bool ret = wglMakeCurrent(NULL, m_hGLRC);

That did not work. The ret is false and I get this error:

Win32 Error# (6): ERROR_INVALID_HANDLE


text:
Q: Running UrlFetchApp call repeatedly on error I use UrlFetchApp to update a webshop via Woocommerce API. It works like a charm, but some of the IPs what Google use to run UrlFetchApp calls banned by a security app on the server.
I am trying to rerun UrlFetchApp maximumthree times if the respons is not 200, by using a for loop. Unfortunatally it doesn't work. As I can see execution stop if error happen.
var url = "https://valami.hu/wp-json/wc/v3/products/...";
var options = {
    'contentType': 'application/json',
    'method' : 'put',
    'muteHttpExceptions': true,
    'payload' : APIPayloadObject
  };

for(n = 0; n < 3; n++){
    var response = UrlFetchApp.fetch(url, options);
    if (response.getResponseCode() == 200){
      break;
    }
}

Do you have any idea how to achieve this repeted UrlFetchApp execution. Should I use try, catch blocs or something? Thank you,


text:
Q: How can I port PHP preg_split to Java for the special case of unserializing a value in ADODB? I need to port this function for unserializing a value in ADODB to Java.
        $variables = array( );
        $a = preg_split( "/(\w+)\|/", $serialized_string, -1, PREG_SPLIT_NO_EMPTY |   PREG_SPLIT_DELIM_CAPTURE );
        for( $i = 0; $i < count( $a ); $i = $i+2 ) {
            $variables[$a[$i]] = unserialize( $a[$i+1] );
        }

I have a library to unserialize the values the php way, but I need help on porting over the preg_split. What would this regex look like in Java?

A: Equivalent java code :

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

// Test
String serialized_string = "foo|bar|coco123||cool|||";

// Split the test
String[] raw_results=serialized_string.split("\\|");// Trailing empty strings are removed but not internal ones

// Cleansing of the results
List<String> php_like_results = new ArrayList<String>();
for(String tmp : raw_results) {
    if (tmp.length()>0) {
       php_like_results.add(tmp);
    }
}

// Output results
System.out.println(php_like_results);

This will produce :
[foo, bar, coco123, cool]


text:
Q: EntityType 'IdentityUserRole' no tiene ninguna clave definida Tengo un problema con un proyecto ASP MVC con identity, al modificar el ID a int todo es correcto me genera la columna tipo int, pero al intentar cambiar los nombres de las columnas de las tablas me genera un error al ejecutar el proyecto.
He intentado varias soluciones que he encontrado pero sigo sin poder solucionarlo, alguna idea?
El error es:

PortalPrueba1.Models.IdentityUserLogin: : EntityType
  'IdentityUserLogin' no tiene ninguna clave definida. Defina la clave
  para este EntityType.
PortalPrueba1.Models.IdentityUserRole: : EntityType 'IdentityUserRole'
  no tiene ninguna clave definida. Defina la clave para este EntityType.
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' se basa
  en el tipo 'IdentityUserLogin' que no tiene claves definidas.
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' se basa
  en el tipo 'IdentityUserRole' que no tiene claves definidas.

Mi codigo en identityModels es el siguiente:
namespace PortalPrueba1.Models
{

    public class CustomUserRole : IdentityUserRole<int> { }
    public class CustomUserClaim : IdentityUserClaim<int> { }
    public class CustomUserLogin : IdentityUserLogin<int> { }

    public class CustomRole : IdentityRole<int, CustomUserRole>
    {
        public CustomRole() { }
        public CustomRole(string name) { Name = name; }
    }

    public class CustomUserStore : UserStore<ApplicationUser, CustomRole, int,
        CustomUserLogin, CustomUserRole, CustomUserClaim>
    {
        public CustomUserStore(ApplicationDbContext context)
            : base(context)
        {
        }
    }

    public class CustomRoleStore : RoleStore<CustomRole, int, CustomUserRole>
    {
        public CustomRoleStore(ApplicationDbContext context)
            : base(context)
        {
        }
    }

    // Para agregar datos de perfil del usuario, agregue más propiedades a su clase ApplicationUser. Visite https://go.microsoft.com/fwlink/?LinkID=317594 para obtener más información.
    public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole,
    CustomUserClaim>
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(
    UserManager<ApplicationUser, int> manager)
        {
            // Note the authenticationType must match the one defined in
            // CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(
                this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

        public class ApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole,
         int, CustomUserLogin, CustomUserRole, CustomUserClaim>
        {
            public ApplicationDbContext()
            : base("DefaultConnection")
            {
            }

            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                //throw new UnintentionalCodeFirstException();
                base.OnModelCreating(modelBuilder);

                modelBuilder.Entity<IdentityUser>().ToTable("Po_Users");
                modelBuilder.Entity<ApplicationUser>().ToTable("Po_Users");
                modelBuilder.Entity<IdentityRole>().ToTable("Po_Roles");
                modelBuilder.Entity<IdentityUserRole>().ToTable("Po_UserRoles");
                modelBuilder.Entity<IdentityUserClaim>().ToTable("Po_UserClaims");
                modelBuilder.Entity<IdentityUserLogin>().ToTable("Po_UserLogins");

            }

            public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }

        }

    }
}

Agradezco su ayuda.

A: Hola ya encontré la solución y es que estaba mandando a llamar el modelo de identity y las cambie por las clases "Custom..." que yo había declarado de manera que quedara así:
 protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);

                modelBuilder.Entity<ApplicationUser>().ToTable("Po_Users");
                modelBuilder.Entity<CustomRole>().ToTable("Po_Roles");
                modelBuilder.Entity<CustomUserRole>().ToTable("Po_UserRoles");
                modelBuilder.Entity<CustomUserClaim>().ToTable("Po_UserClaims");
                modelBuilder.Entity<CustomUserLogin>().ToTable("Po_UserLogins");
}


text:
Q: Dynamic Title in angularjs - using ng-attr-title How can i get a dynamic title in angularJS.I know to use ng-attr-title as given below

Hover me

and the controller is
var app = angular.module('myApp', []);
function ctrl($scope){
$scope.title = "I 'm a tooltip!";
}

Here is the JSfiddle and its working.  What i am trying is to have two different titles one while enabled and another while disabled so i want to decide the variable that goes in to ng-attr-title at runtime as given below.

Hover me

and the controller is
var app = angular.module('myApp', []);
function ctrl($scope){
$scope.Enabledtitle = "U can click me";
$scope.Disabledtitle = "U cannot click me";
 $scope.message="Enabledtitle";
}

So when i hover i should get the tooltip saying  "U can click me". SO that i get the flexibility to switch between the tooltip messages just by updating the scope variable message
Here is the JSfiddle where i tried the dynamic title and am getting "Enabledtitle" as tooltip instead of "U can click me".
How can i tell angular to parse {{Enabledtitle}} and gimme its value.

A: In the controller:
$scope.getMessage() {
    return isEnabled ? "You can click me" : "You can't click me";
}

in the view:

...

Or, every time the code changes the value of the isEnabled flag, also change the message.

A: do
$scope.message=$scope.Enabledtitle;

instead of
$scope.message="Enabledtitle";

A: You will need to use bracket notation to access property with the variable name. So the title attribute becomes ng-attr-title="{{this[message]}}:

var app = angular.module('myApp', []);

function ctrl($scope) {
    $scope.Enabledtitle = "U can click me";
    $scope.Disabledtitle = "U cannot click me";
    $scope.message = "Enabledtitle";
}

Hover me

In your case, this points to current scope object $scope and you are reading it's property by dynamic key message.
Demo: http://jsfiddle.net/oetd3bvy/2/


text:
Q: How does wc -l `ls` give the actual number of lines? Can anyone explain to me how does this command work.
wc -l `ls`

while this command gives the total number of java lines or txt lines.

A: ls outputs a list of file/directory names in the current directory.
`ls` will be replaced by the output of ls.  So you're actually running something like:
wc -l file1 file2 file3 ... fileN

And of course wc will open each file named in the command line in turn, to count the lines.
The same effect could be had by running:
wc -l *

Note that this only holds if none of the file names in the current directory contain any "weird" character (whitespace or \[?*).


text:
Q: Panda3D doesn't take in latest model i've been really frustrated with Panda3d so far with the importation of models. Panda3d will only import a model once and will never update ever again (even after changing the name of the .egg file)
I first imported a model (let's call it version 1), into VS2010 panda3d. Then i revised the model in 3dsMax and exported it into egg again (version 2). However, no matter how many times i import, panda3d will stubbornly use version 1. Renaming the .egg doesn't help either. Im suspecting that panda3d caching system is caching my previous model and there's something important linking all the versions together, defaulting the panda3d engine to go back to version 1.
The main question is, how do i solve this problem of panda3d not taking in the latest model? Thank you.

A: I think you will get answers to your questions about Panda3D more quickly if you ask them over on the Panda3D forums.
But to answer your specific question, Panda does indeed incorporate a model cache, which by default reads a particular filename once (during a session) but does not read the disk again during the same session, even if the file changes (but you can explicitly ask it to read the disk again if you need this).  Panda also has a persistent disk cache, which by default caches the loading of a model between sessions as well, though in this case it does always check the timestamp of the file before blindly returning the previous model, and if the file is updated, it will always re-read it and return the new version instead.
In neither case will it return a cached version if you completely rename the file, so something else must be going on in that case.
The precise way you disable caching depends on the particular calls you are using to load the model.  You reference VS2010, so I infer that you are writing in C++ (but using VS2010 instead of VS2008 isn't officially supported, so you might have other problems as well unless you have far out of your way to use VS2010 correctly).
To avoid the cache for a particular model, try passing a LoaderOptions object with the LF_no_cache bits set in the flags to ModelPool::load_model() (or whichever interface you are using to load models).


text:
Q: Collections.sort - I have created 2 user define objects [both are of different types] and then add into arraylist , then I have tried to sort it
Expected Result of code is ClassCastException but Actual Result :- [Person with pid- 1 - a1-name, Person with pid- 2 - c2-name, Sorting.Employee@cdfc9c, Sorting.Employee@1837697]

Person class:
package Sorting;

public class Person implements Comparable<Person> {
    private int pid;
    private String pname;

    public int getPid() {
        return pid;
    }

    public void setPid(int pid) {
        this.pid = pid;
    }

    public String getPname() {
        return pname;
    }

    public void setPname(String pname) {
        this.pname = pname;
    }

    @Override
    public String toString() {
        return "Person with pid- " + getPid() + " - " + getPname();
    }

    @Override
    public int compareTo(Person p) {
        return this.pid - p.pid;
    }
}

Employee class:
package Sorting;

public class Employee implements Comparable {
    @Override
    public int compareTo(Object o) {
        return 0;
    }
}

SortingofObjects class:
package Sorting;

import java.util.ArrayList;
import java.util.Collections;

public class SortingofObjects {

    public static void main(String[] args) {
        Person p1 = new Person();
        p1.setPid(1);
        p1.setPname("a1-name");

        Person p2 = new Person();
        p2.setPid(2);
        p2.setPname("c2-name");
        Employee e1 = new Employee();
        Employee e2 = new Employee();

        ArrayList a = new ArrayList();
        a.add(p1);
        a.add(p2);
        a.add(e1);
        a.add(e2);
        Collections.sort(a);
        System.out.println(a);
    }
}

A: Collections.sort does not call compareTo on every pair in the List, just enough pairs to sort the List. As an example, run this code:
public class Test implements Comparable<Test> {

    public static void main(String[] args) {
        List<Test> list = new ArrayList<Test>();
        list.add(new Test(1));
        list.add(new Test(2));
        list.add(new Test(3));
        list.add(new Test(4));
        Collections.sort(list);
    }

    private final int number;

    Test(int number) {
        this.number = number;
    }

    @Override
    public int compareTo(Test that) {
        System.out.println(this + ".compareTo(" + that + ")");
        return 0;
    }

    @Override
    public String toString() {
        return "" + number;
    }
}

The output is
2.compareTo(1)
3.compareTo(2)
4.compareTo(3)

Since your List is in the order Person, Person, Employee, Employee, the only combination that would throw a ClassCastException, namely
Person.compareTo(Employee)

never occurs. If your List contained an Employee before a Person it would throw an exception.

A: If it just so happens that the sorting algorithm used only compares Employees to Persons, and not the other way around, then it'll never throw, because Employee.compareTo accepts any Object.  You just got lucky, more or less.


text:
Q: Django - Display list of category belonging to each card I have a Giftcard model, and Category model which holds all category, rate and term for each card. It has a foreign key back to Giftcard.
I just want to be able to list category, rate and terms for each Giftcard. As the code is right now, it displays the displays same category, rate and terms for all Giftcard.
model
class Giftcard(models.Model):
name = models.CharField(max_length=100, unique=True)
card_image = models.ImageField(upload_to='Giftcard', blank=False)
date = models.DateTimeField(auto_now_add=True)
publish = models.BooleanField(default=False)

class Category(models.Model):
category = models.CharField(max_length=250)
name = models.ForeignKey(Giftcard, on_delete=models.CASCADE, related_name="specs")
rate = models.IntegerField()
terms = models.TextField()

Here is my views
def giftcard(request):
giftcards = Giftcard.objects.filter(publish=True)

context = {
    'giftcards': giftcards,
}

return render(request, 'dashboard/giftcard.html', context)

Here is my template
{% for giftcard in giftcards %}

Select the card category and the amount.

                          <form class="card-form">

                              Card category
                              <input list="category" class="form-control" name="category" id="card_category"
                                placeholder="Select card category">

                              {% for spec in giftcard.specs.all %}
                              <datalist id="category">
                                <option value="{{ spec.category }}">{{ spec.category }}</option>
                              </datalist>
                              {% endfor %}

                              Amount

                                <input type="text" class="form-control" id="amount"
                                  placeholder="Please enter amount">
                                #100,000

                              {% for spec in giftcard.specs.all %}
                              Current rate - {{ spec.rate }}
                              {% endfor %}

                              <button type="button" class="btn  process-card-btn">Proceed</button>

                          </form>

Trading terms

                        {% for spec in giftcard.specs.all %}

                          {{ spec.terms }}

                        {% endfor %}

                          <button type="button" class="btn process-card-btn">Proceed</button>

          {% endfor %}

A: From django-doc,you have to make ForeginKey field in your main Giftcard table which will do ManyToOne relation with Category table.
Try this:
models.py
from django.db import models

class Category(models.Model):
    category = models.CharField(max_length=250)
    rate = models.IntegerField()
    terms = models.TextField()

    def __str__(self):
        return self.category

class Giftcard(models.Model):
    name = models.CharField(max_length=100, unique=True)
    card_image = models.ImageField(upload_to='Giftcard/', blank=False)
    date = models.DateTimeField(auto_now_add=True)
    publish = models.BooleanField(default=False)
    gift_category = models.ForeignKey(Category, on_delete=models.CASCADE)

views.py
def giftcard(request):
    giftcards = Giftcard.objects.filter(publish=True)

    context = {
        'giftcards': giftcards
    }
    return render(request, 'dashboard/giftcard.html', context)

Now, you can access all the properties of Category table in Giftcard items in your template file, and a giftcard can have more than one category, it is called ManyToOne relation,

Note: you can also use choices, which is much better than making table, you can see that too here in django-doc.

 Edit
Do this in datalist
<datalist id="category">
    {% for spec in giftcard.specs.all %}

        <option value="{{ spec.category }}">{{ spec.category }}</option>
    {% endfor %}

</datalist>

A: If, as you say in one of your comments, "it won't work that way because a giftcard can have more than one category" and "No, Category cannot have more than one Giftcard", then your original models are correct, with ForeignKey in the Category class.  Second, I do not know what exactly is going on, perhaps add screenshots of what you are getting that is wrong, because I just tried your original code out, and it works, with the modifications to the datalist suggested by @Sunderam.  Test this out in your html template:
{% for giftcard in giftcards %}
    {% for spec in giftcard.specs.all %}
        {{ spec.terms }}

        {{ spec.category }}

        {{ spec.rate }}

    {% endfor %}
{% endfor %}

When I did this, I am seeing different terms, categories and rates for each.  Again, is this not what you want?
Edit
You must understand that the datalist will have all the spec values, and one shows up when you start typing in the input box.  for example, if you type c, then the list will pop up with all categories that begin with c.
Edit
Make sure the datalist has been changed to

  Card category
  <input list="category" class="form-control" name="category" id="card_category"
    placeholder="Select card category">

  {% for spec in giftcard.specs.all %}
  <datalist id="category">
    <option value="{{ spec.category }}">{{ spec.category }}</option>
  </datalist>
  {% endfor %}

After all, you want only one <datalist> element, and then many <option>s.


text:
Q: std::set::insert: duplicates using a user-defined class I am using C++ set container to remove duplicates, but am having a problem with a user-defined class. I defined the comparison operator as below and it works well:
bool operator < (const TLineSegment& other) const
{
    int cx1 = (int)((x1 + x2) / 2.0);
    int cy1 = (int)((y1 + y2) / 2.0);
    int cx2 = (int)((other.x1 + other.x2) / 2.0);
    int cy2 = (int)((other.y1 + other.y2) / 2.0);

    if (cx1 == cx2)
        return (cy1 < cy2);
    else
        return (cx1 < cx2);
}

However, the below code by adding more condition (no duplicate within a certain range) contains a very few duplicates. I found it working in most cases, but it sometimes doesn't work, really weird. One case I found was two TLineSegments are the same (but not the same instance) and both of them were inserted.
bool operator < (const TLineSegment& other) const
{
    const int epi = 5;
    int cx1 = (int)((x1 + x2) / 2.0);
    int cy1 = (int)((y1 + y2) / 2.0);
    int cx2 = (int)((other.x1 + other.x2) / 2.0);
    int cy2 = (int)((other.y1 + other.y2) / 2.0);

    if (abs(cx1 - cx2) < epi) {
        if (abs(cy1 - cy2) < epi) {
            return false;
        }
        else {
            return (cy1 < cy2);
        }
    }
    else {
        return (cx1 < cx2);
    }

A: Let's compare the line segment (-n,0):(n,0) to the line segment (-x,-y):(x,y). So (cx1,cy1) and (cx2,cy2) are both (0,0). For both implementations of operator<, the result will be false in either direction, which implies that the two line segments are equivalent. That is, any line segment centered at (0,0) is equivalent to every other such line segment?!
This is obviously incorrect.
The simplest thing is to take advantage of std::tuple having operator< defined and do:
std::tuple<int, int, int, int> tied() const {
    // can be just auto in C++14. typically I'd say use std::tie()
    // but we're dealing with ints right?
    return std::make_tuple(x1, y1, x2, y2);
}

bool operator < (const TLineSegment& other) const
{
    return tied() < other.tied();
}


text:
Q: A numerical evaluation of $\sum_{n=1}^{\infty}(-1)^{\frac{n(n+1)}{2}}\frac1{n!}\int_0^1x^{(n)} dx$ I would like to obtain a numerical evaluation of the series
$$S=\sum_{n=1}^{\infty}(-1)^{\frac{n(n+1)}{2}}\frac1{n!}\int_0^1x(x+1)\cdots(x+n-1)\: dx$$ to five significant digits.
I've used Mathematica, but some results puzzle me:
$$\text{NSum}\left[(-1)^{\frac{n*(n+1)}{2}}*\frac{\int_0^1 \text{Pochhammer}[x,n] \, dx}{n!},\{n,1,23\}\right]=-0.530724...$$
$$\text{NSum}\left[(-1)^{\frac{n*(n+1)}{2}}*\frac{\int_0^1 \text{Pochhammer}[x,n] \, dx}{n!},\{n,1,24\}\right]=-0.298186...$$
Any help is welcome.

A: Sum the Integrands
We can use the identity
$$
\frac{(1+i)i^n+(1-i)(-i)^n}2=(-1)^{\frac{n(n+1)}2}\tag{1}
$$
to get
$$
\begin{align}
&\sum_{n=0}^\infty(-1)^{\frac{n(n+1)}2}\frac{x(x+1)\cdots(x+n-1)}{n!}\\
&=\sum_{n=0}^\infty\frac{(1+i)i^n+(1-i)(-i)^n}2\binom{n+x-1}{n}\tag{2a}\\
&=\sum_{n=0}^\infty\frac{(1+i)(-i)^n+(1-i)i^n}2\binom{-x}{n}\tag{2b}\\
&=\frac{1+i}2(1-i)^{-x}+\frac{1-i}2(1+i)^{-x}\tag{2c}\\
&=\frac{1+i}22^{-x/2}e^{i\pi x/4}+\frac{1-i}22^{-x/2}e^{-i\pi x/4}\tag{2d}\\[4pt]
&=2^{-(x+1)/2}e^{i\pi(x+1)/4}+2^{-(x+1)/2}e^{-i\pi(x+1)/4}\tag{2e}\\[8pt]
&=2^{-(x-1)/2}\cos(\pi(x+1)/4)\tag{2f}\\[8pt]
&=2^{(1-x)/2}\sin(\pi(1-x)/4)\tag{2g}
\end{align}
$$
Explanation:
$\text{(2a)}$: apply $(1)$
$\text{(2b)}$: $\binom{-x}{n}=(-1)^n\binom{n+x-1}{n}$
$\text{(2c)}$: apply Binomial Theorem
$\text{(2d)}$: convert to polar form
$\text{(2e)}$: algebra
$\text{(2f)}$: convert to trig form
$\text{(2g)}$: $\cos(\pi(x+1)/4)=-\sin(\pi(x-1)/4)$

Integrate the Sum
Note that we included the $n=0$ term, which is $1$, in $(2)$. We simply need to integrate $(2)$ over $[0,1]$ and subtract the contribution from the $n=0$ term, which is $1$.
$$
\begin{align}
&\int_0^12^{(1-x)/2}\sin(\pi(1-x)/4)\,\mathrm{d}x-1\\
&=\int_0^12^{x/2}\sin(\pi x/4)\,\mathrm{d}x-1\\
&=\mathrm{Im}\!\left(\int_0^1e^{(\log(2)/2+i\pi/4)x}\,\mathrm{d}x\right)-1\\
&=\mathrm{Im}\!\left(\frac{i}{\log(2)/2+i\pi/4}\right)-1\\
&=\bbox[5px,border:2px solid #C00000]{\frac{8\log(2)}{4\log(2)^2+\pi^2}-1}\\[3pt]
&\doteq-0.52972762307114482514\tag{3}
\end{align}
$$
This agrees with Olivier Oloa's result.

Changing the Order
Using the log-convexity of $\Gamma(x)$ and the first few terms of the power series for $\Gamma(x)$ near $x=1$, it is shown in this answer that
$$
\frac1{n!}\int_0^1\frac{\Gamma(x+n)}{\Gamma(x)}\,\mathrm{d}x
\sim\frac1{\log(n)}-\frac\gamma{\log(n)^2}-\frac{\frac{\pi^2}6-\gamma^2}{\log(n)^3}+O\left(\frac1{\log(n)^4}\right)\tag{4}
$$
This means that the terms in
$$
\sum_{n=1}^\infty(-1)^{n(n+1)/2}\frac1{n!}\int_0^1\frac{\Gamma(x+n)}{\Gamma(x)}\mathrm{d}x\tag{5}
$$
converge very slowly. Given this, it is reasonable to question the change of order between integration and summation.
However, we are allowed to change the order of a finite sum and integration, and therefore, we can consider the sum grouped into fours.
Since $(-1)^{n(n+1)/2}$, starting at $n=1$, follows the pattern $-1,-1,+1,+1,\dots$, and the absolute values of the terms are monotonically decreasing, the sum of each group of four terms is negative. Since the sum converges, it converges absolutely. Now we can apply Fubini's Theorem to allow us to switch the order of summation (integration on a discrete space) and integration.

A: You can expect the error in $S_n$ to be of the order of $a_{n+1}$. The problem is that the sequence
$$
\frac1{n!}\int_0^1x(x+1)\cdots(x+n-1)\,dx
$$
decreases very slowly. In fact
$$
a_{2^{20}}=0.06865413726465990.
$$
I have done calculations that suggest that $a_n$ decreases like $C/\log n$ for some constant $C$. This implies that to get an error of order $10^{-5}$ you need to sum $e^{10^5}$ terms.

A: Since:
$$x(x+1)\cdot\ldots\cdot(x+n-1) = \frac{\Gamma(x+n)}{\Gamma(x)}=\frac{1}{\Gamma(x)}\int_{0}^{+\infty}t^{x+n-1}e^{-t}\,dt$$
we have:
$$ \sum_{\substack{n\geq 1\\n\equiv 1\!\!\pmod{\!\!4}}}\!\!\!\!\!\!\frac{x(x+1)\cdot\ldots\cdot(x+n-1)}{n!}=\frac{1}{\Gamma(x)}\int_{0}^{+\infty}t^x e^{-t}\sum_{k=0}^{+\infty}t^{4k}\,dt$$
so:
$$ \sum_{n\geq 1}(-1)^{\frac{n(n+1)}{2}}\frac{x(x+1)\cdot\ldots\cdot(x+n-1)}{n!}=\frac{1}{\Gamma(x)}\int_{0}^{+\infty}t^x e^{-t}\frac{-1-t+t^2+t^3}{1-t^4}\,dt$$
and the original sum equals:
$$ S=-\int_{0}^{1}\int_{0}^{+\infty}\frac{t^x}{\Gamma(x)}\frac{1+t}{1+t^2}e^{-t}\,dt\,dx\tag{1}$$
that can be approximated quite well by using the Weierstrass product for the $\Gamma$ function.
Using Mathematica, with the previous formula I got:
$$ S \approx \color{red}{-0.4018838\ldots}.\tag{2}$$

A: In fact this series admits a very nice closed form.
We have

$$\sum_{n=1}^{\infty}\frac{(-1)^{\frac{n(n+1)}{2}}}{n!}\int_0^1x(x+1)\cdots(x+n-1)\: dx=\color{blue}{\frac{8 \ln 2 }{\pi ^2+4 \ln^2 2}-1} \tag1$$

with the numerical evaluation
$$\begin{align}
\color{blue}{-0.529727623071144825135721...} .\tag2
\end{align}
$$
I've found the following result.
Theorem. Let $u$ be a complex number such that |u|<1. Then

$$\begin{align}
&\sum_{n=1}^{\infty}\frac{(-1)^{\frac{n(n+1)}{2}}}{n!}\left(\int_0^1x(x+1)\cdots(x+n-1)\: dx\right)u^n\\\\
&=-1+\frac{(1+i)u}{2 (1+iu)\log(1+iu)}+\frac{(1-i)u}{2 (1-iu)\log(1-iu)},
\end{align} \tag3
$$

where $i^2=-1$.
Proof. Recall that $$
x(x+1)\cdots(x+n-1)=\sum_{k=0}^n {n\brack k}x^k \tag4
$$ where $\displaystyle {n\brack k}$ are the unsigned Stirling numbers of the first kind counting the numbers of permutations of
$n$ letters that have exactly $k$ cycles,  giving
$$
\int_0^1 x(x+1)\cdots(x+n-1)\: dx =\sum_{k = 1 }^{n } \frac{\large {n \brack k}}{k+1}. \tag5
$$
Using $(5)$, we have proved that (see here, identity $(3)$) for $|u|<1$,
$$
\sum_{n=1}^{\infty}\frac{(-1)^n}{n!}\left(\int_0^1x(x+1)\cdots(x+n-1)\: dx\right)u^n=-1+ \frac{u}{(1+u) \log(1+u)} \tag6
$$ and that (see here)
$$
\frac{1}{n!} \int_0^1x(x+1)\cdots(x+n-1)\: dx = \mathcal{O} \left(\frac{1}{\ln n}\right), \quad \text{as} \quad n \rightarrow \infty.
$$ Consequently, setting $\displaystyle a_n:= \int_0^1x(x+1)\cdots(x+n-1)\: dx$ for notational convenience, with $|u|<1$, we are allowed to write
$$
\begin{align}
\sum_{n=1}^{\infty}(-1)^{\frac{n(n+1)}{2}}\frac{a_n}{n!} u^n&=\sum_{p=1}^{\infty}(-1)^{p}\frac{a_{2p}}{(2p)!} u^{2p}+\sum_{p=1}^{\infty}(-1)^{p}\frac{a_{2p-1}}{(2p-1)!} u^{2p-1}\tag7\\\\
&=\frac12 \left(g(iu)+g(-iu)\right)-\frac i2 \left(g(iu)-g(-iu)\right) \tag8
\end{align}
$$ where $g(\cdot)$ is the right hand side member of $(6)$. This gives $(3)$.
The series $$\sum_{n=1}^{\infty}(-1)^{\frac{n(n+1)}{2}}\frac{a_n}{n!} \tag9 $$ is convergent by the Dirichlet test, then we deduce $(1)$ from $(3)$ by Abel's theorem, using
$$
-1+\frac{1}{2 \log(1-i)}+\frac{1}{2 \log(1+i)}=-1+\frac{8 \ln 2 }{\pi ^2+4 \ln^2 2}.
$$


text:
Q: Windows 8.1 second monitor large with low resolution I am running Windows 8.1 on a Lenovo Y50. I am connecting to a Lenovo LS2023 20" Wide external monitor and I am having some trouble with getting the displays to scale properly.
The Y50 is a 15.6" screen with 1920x1080 resolution and the External Monitor is a 20" screen with 1600 x 900 resolution, making the resolution disproportionate to the actual monitor size. When I go into screen resolution and try to get the monitors scaled appropriately to each-other any adjustments I make are accompanied by a "input signal out of range" error on the large monitor, a "resolution too low" on the smaller monitor, or skewed graphics. If I give each monitor their recommended resolutions the 20" monitor appears smaller than the 15.6" monitor, making the applications on the external monitor huge and teeny tiny by comparison on the laptop monitor, not to mention the magic teleporting mouse pointer.
When I try to use the scaling options (control panel >> display) it changes the scale of both monitors and does not help when trying to make their virtual position line up with there physical position.
From what I can tell Windows is reading the monitor as a 1600 x 900 sized monitor with the same DPI as the Y50, which it isn't. Is there any way to tell Windows that the external monitor has a lower DPI and is a 20" monitor, not a 13" monitor, while keeping the high resolution on the laptop monitor?
Thank You

A: the problem is caused by a settings on Host (if it's Win 8.1). It is caused by DPI Scaling.
One of the possibile workaround can be:
On the Host, find the vmware.exe executable, right click, properties, compatibility, under Settings check "Disable display scaling on High DPI settings".
Close and re-open vmware workstaion.
Regards.


text:
Q: Overriding prestashop module translation missing I try to modify a module template in prestashop so I've copied the module to my theme folder "modules".
I've noticed that the theme is changing the only problem is that the translation is not. I got the original text on the final shop template. Is there some simple way of making this work?
I don't know how to make modules so this way was great except the translation part - the rest of the store is translated except those modules. I use prestashop 1.4.

A: In your Back Office, you need to edit the Module Translations under Tools > Translations > Modify Translations. They are translated separately from the Front Office and Back Office translations, just select "Modules" from the drop-down menu.

A: Make sure your module can be translated also :
    {l s='Login' mod='blockuserinfo'}
The name of the module has to be here,
also make sure to check the prestashop user guide :
http://doc.prestashop.com/display/PS15/Translations+in+PrestaShop+1.5


text:
Q: java.net.UnknownHostException when connecting to bitnami/kafka Docker Compose image I'm trying to run the bitnami/kafka Docker Compose multi-container application and create topics with bin/kafka_topics.sh as described in https://kafka.apache.org/quickstart. I'm running the following docker-compose.yml:
version: "2"

services:
  zookeeper:
    image: docker.io/bitnami/zookeeper:3.7
    ports:
      - "2181:2181"
    volumes:
      - "zookeeper_data:/bitnami"
    environment:
      - ALLOW_ANONYMOUS_LOGIN=yes
  kafka:
    image: docker.io/bitnami/kafka:3
    ports:
      - "9092:9092"
    volumes:
      - "kafka_data:/bitnami"
    environment:
      - KAFKA_CFG_ZOOKEEPER_CONNECT=zookeeper:2181
      - ALLOW_PLAINTEXT_LISTENER=yes
    depends_on:
      - zookeeper

volumes:
  zookeeper_data:
    driver: local
  kafka_data:
    driver: local

but when I try to create a topic, I get a java.net.UnknownHostException error:
~/D/kafka_2.13-3.0.0> bin/kafka-topics.sh --create --partitions 1 --replication-factor 1 --topic quickstart-events --bootstrap-server localhost:9092
[2022-01-03 07:05:15,990] WARN [AdminClient clientId=adminclient-1] Error connecting to node 3d6fe6f02854:9092 (id: 1001 rack: null) (org.apache.kafka.clients.NetworkClient)
java.net.UnknownHostException: 3d6fe6f02854: nodename nor servname provided, or not known
    at java.base/java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
    at java.base/java.net.InetAddress$PlatformNameService.lookupAllHostAddr(InetAddress.java:933)
    at java.base/java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1519)
    at java.base/java.net.InetAddress$NameServiceAddresses.get(InetAddress.java:852)
    at java.base/java.net.InetAddress.getAllByName0(InetAddress.java:1509)
    at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1367)
    at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1301)
    at org.apache.kafka.clients.DefaultHostResolver.resolve(DefaultHostResolver.java:27)
    at org.apache.kafka.clients.ClientUtils.resolve(ClientUtils.java:109)
    at org.apache.kafka.clients.ClusterConnectionStates$NodeConnectionState.currentAddress(ClusterConnectionStates.java:508)
    at org.apache.kafka.clients.ClusterConnectionStates$NodeConnectionState.access$200(ClusterConnectionStates.java:465)
    at org.apache.kafka.clients.ClusterConnectionStates.currentAddress(ClusterConnectionStates.java:170)
    at org.apache.kafka.clients.NetworkClient.initiateConnect(NetworkClient.java:975)
    at org.apache.kafka.clients.NetworkClient.ready(NetworkClient.java:301)
    at org.apache.kafka.clients.admin.KafkaAdminClient$AdminClientRunnable.sendEligibleCalls(KafkaAdminClient.java:1117)
    at org.apache.kafka.clients.admin.KafkaAdminClient$AdminClientRunnable.processRequests(KafkaAdminClient.java:1377)
    at org.apache.kafka.clients.admin.KafkaAdminClient$AdminClientRunnable.run(KafkaAdminClient.java:1320)
    at java.base/java.lang.Thread.run(Thread.java:833)

It seems that Kafka is not resolving the host name, which I don't yet understand because I'm specifying it as localhost:9092 in both applications. Any idea how to get this to work?

A: I worked around this problem by instead connecting to Kafka from another contain as described in the "Connecting to other containers" section of https://hub.docker.com/r/bitnami/kafka/. I ran the following docker-compose.yml:
version: '2'

networks:
  app-tier:
    driver: bridge

services:
  zookeeper:
    image: 'bitnami/zookeeper:latest'
    environment:
      - 'ALLOW_ANONYMOUS_LOGIN=yes'
    networks:
      - app-tier
  kafka:
    image: 'bitnami/kafka:latest'
    environment:
      - KAFKA_CFG_ZOOKEEPER_CONNECT=zookeeper:2181
      - ALLOW_PLAINTEXT_LISTENER=yes
    networks:
      - app-tier
  myapp:
    image: 'bitnami/kafka:latest'
    environment:
      - KAFKA_CFG_ZOOKEEPER_CONNECT=zookeeper:2181
      - ALLOW_PLAINTEXT_LISTENER=yes
    networks:
      - app-tier

in a directory named bitnami-docker-kafka. Then I exec'd into the container and ran kafka-topics.sh --create specifying the --bootstrap-server as kafka:9092:
> docker exec -it bitnami-docker-kafka-myapp-1 /bin/bash
I have no name!@af986a978cae:/$ kafka-topics.sh --create --partitions 1 --replication-factor 1 --topic quickstart-events --bootstrap-server kafka:9092
Created topic quickstart-events.


text:
Q: Parse an adaptive card json to C# object and dynamically build Action.Showcards based on my api data I have an adaptive card json with Action.ShowCard property and 1 submit button. I want to convert it to C# object and loop the Action.showcard to dynamically build multiple showcard buttons based on the count/data coming from an api call.
I was able to convert it to c# object using "AdaptiveCard.FromJson(json).Card", but not able to proceed further
Suppose i get 3 project codes, so i want to build 3 action.showcards and populate its fields from api data.
Below is the adaptive card with only 1 showcard, I need to consume this card and build multiple showcards.
{
"type": "AdaptiveCard",
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.3",
"body": [
    {
        "type": "TextBlock",
        "text": "**Timesheet Project Codes**",
        "wrap": true
    },
    {
        "type": "ActionSet",
        "actions": [
            {
                "type": "Action.ShowCard",
                "title": "123456",
                "card": {
                    "type": "AdaptiveCard",
                    "body": [
                        {
                            "type": "ColumnSet",
                            "columns": [
                                {
                                    "type": "Column",
                                    "width": "stretch",
                                    "items": [
                                        {
                                            "type": "TextBlock",
                                            "text": "Project Code:",
                                            "wrap": true
                                        }
                                    ]
                                },
                                {
                                    "type": "Column",
                                    "width": "stretch",
                                    "items": [
                                        {
                                            "type": "TextBlock",
                                            "text": "123456",
                                            "wrap": true
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            "type": "ColumnSet",
                            "columns": [
                                {
                                    "type": "Column",
                                    "width": "stretch",
                                    "items": [
                                        {
                                            "type": "TextBlock",
                                            "text": "Project Name:",
                                            "wrap": true
                                        }
                                    ]
                                },
                                {
                                    "type": "Column",
                                    "width": "stretch",
                                    "items": [
                                        {
                                            "type": "TextBlock",
                                            "text": "abc/def/ghi",
                                            "wrap": true
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            "type": "ColumnSet",
                            "columns": [
                                {
                                    "type": "Column",
                                    "width": "stretch",
                                    "items": [
                                        {
                                            "type": "TextBlock",
                                            "text": "Cost Code:",
                                            "wrap": true
                                        }
                                    ]
                                },
                                {
                                    "type": "Column",
                                    "width": "stretch",
                                    "items": [
                                        {
                                            "type": "TextBlock",
                                            "text": "ghi1234",
                                            "wrap": true
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            "type": "ColumnSet",
                            "columns": [
                                {
                                    "type": "Column",
                                    "width": "stretch",
                                    "items": [
                                        {
                                            "type": "TextBlock",
                                            "text": "Project Code Start Date:",
                                            "wrap": true
                                        }
                                    ]
                                },
                                {
                                    "type": "Column",
                                    "width": "stretch",
                                    "items": [
                                        {
                                            "type": "TextBlock",
                                            "text": "January 1, 2022",
                                            "wrap": true
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            "type": "ColumnSet",
                            "columns": [
                                {
                                    "type": "Column",
                                    "width": "stretch",
                                    "items": [
                                        {
                                            "type": "TextBlock",
                                            "text": "Project Code End Date: ",
                                            "wrap": true
                                        }
                                    ]
                                },
                                {
                                    "type": "Column",
                                    "width": "stretch",
                                    "items": [
                                        {
                                            "type": "TextBlock",
                                            "text": "December 31, 2025",
                                            "wrap": true
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            "type": "ColumnSet",
                            "columns": [
                                {
                                    "type": "Column",
                                    "width": "stretch",
                                    "items": [
                                        {
                                            "type": "TextBlock",
                                            "text": "Project Code Allocation Start Date:",
                                            "wrap": true
                                        }
                                    ]
                                },
                                {
                                    "type": "Column",
                                    "width": "stretch",
                                    "items": [
                                        {
                                            "type": "TextBlock",
                                            "text": "March 1, 2022",
                                            "wrap": true
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            "type": "ColumnSet",
                            "columns": [
                                {
                                    "type": "Column",
                                    "width": "stretch",
                                    "items": [
                                        {
                                            "type": "TextBlock",
                                            "text": "Project Code Allocation End Date:",
                                            "wrap": true
                                        }
                                    ]
                                },
                                {
                                    "type": "Column",
                                    "width": "stretch",
                                    "items": [
                                        {
                                            "type": "TextBlock",
                                            "text": "November 31, 2022",
                                            "wrap": true
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            }
        ]
    },
    {
        "type": "ActionSet",
        "actions": [
            {
                "type": "Action.Submit",
                "title": "Fill Timesheet",
                "data": "Fill Timesheet"
            }
        ]
    }
]

}

A: From your explanation, I understand that you're using AdaptiveCard.FromJson to deserialize the entire thing into onc card.
Instead, you could try deserializing the JSON and then parsing it to build multiple separate Adaptive Cards in code.
Once you have built C# objects from your parsed JSON, you can then manipulate them and add or remove components as desired.


text:
Q: How to calculate this limit with L'Hôpital's Rule I want to calculate the limit $\lim_{x\rightarrow0}x^2e^{1/x}$, but I have no idea how this limit is supposed to calculated.
EDIT: After writing it as $\lim_{x\rightarrow0}\frac{e^{\frac{1}{x}}}{x^{-2}}$, use L'Hôpital's Rule twice:
$\lim_{x\rightarrow0}\frac{(e^{\frac{1}{x}})'}{(x^{-2})'} = \lim_{x\rightarrow0}\frac{xe^{\frac{1}{x}}}{2}$
$\lim_{x\rightarrow0}\frac{(xe^{\frac{1}{x}})'}{(2)'} = \lim_{x\rightarrow0}\frac{e^{\frac{1}{x}}-\frac{e^{\frac{1}{x}}}{x}}{0}$
So, as my math level (low) tell me a thing $e^{\frac{1}{x}} > \frac{e^{\frac{1}{x}}}{x}$ and $e^{\frac{1}{x}} - \frac{e^{\frac{1}{x}}}{x} > 0$
Does this mean answer is $\inf$? Or I just failed?

A: The limit, as it has been proposed, does not exist.
However both side limits exist.
Indeed, if we make the change of variable $y = 1/x$ and approach $0$ from the right, it results that
\begin{align*}
\lim_{x\to 0;x\in(0,\infty)}x^{2}e^{1/x} = \lim_{y\to+\infty}\frac{e^{y}}{y^{2}} = +\infty
\end{align*}
On the other hand, if we make the same change of variable, but approach $0$ from the left, we get
\begin{align*}
\lim_{x\to 0;x\in(-\infty,0)}x^{2}e^{1/x} = \lim_{y\to-\infty}\frac{e^{y}}{y^{2}} = 0
\end{align*}
and we are done.
Hopefully this helps !


text:
Q: How to pass variable from form to ajax in ASP.NET CORE 2.2 I have page with an item list and I need to add them to shop cart. I need to add them with ajax, I did write ajax request, so how should I pass vars to ajax and then send to controller:
function AddToCart(id) {
    $.ajax({
        url: "/CartNancy/Add",
        type: "POST",
        data: {
            id : id
        },
        success: function () {
            prompt("Added to cart");
        }
    });
}

And this is form
<form method="post">
<input name="Id" value="@item.Id" class="btn btn-success" hidden>
<button onclick="AddToCart()" class="btn btn-success">Add to cart</button>
</form>

Controller
[HttpPost]
public JsonResult Delete(string id) {
    _bookService.Remove(id);
    return new JsonResult("Deleted");
}

A: To force Web API to read the simple id from the request body, add the [FromBody] attribute to the parameter:
[HttpPost]
public JsonResult Delete([FromBody]string id) {
    _bookService.Remove(id);
    return new JsonResult("Deleted");
}

You can check the full doc here:

A: Try adding [FromBody] to the parameter:
[HttpPost]
public JsonResult Delete([FromBody]string id) {
    _bookService.Remove(id);
    return new JsonResult("Deleted");
}

A: you defined the function with the id parameter but did not send it when calling. can't see add to cart function on controller.
if you want to add that hidden value to ajax request then..
function AddToCart() {
    var id = document.getElementsByName("id")[0].value;
    $.ajax({
        url: "/CartNancy/Add",
        type: "POST",
        data: {
            id : id
        },
        success: function () {
            prompt("Added to cart");
        }
    });
}


text:
Q: Deep copy entity with NHibernate I am currently starting a new ASP.NET MVC Project at work where we need to generate a project cost estimate.
We are using NHibernate, ASP.NET MVC 1.0 and StructureMap.
The client wants to be able to fill all the information about the project, the information is in different pages and we need to persist in between each post back.
The client does not want to have the option to Save it under a name when it is completed, but we want to persist it in the database even when he did not save it yet. So we had the idea to create a "Draft mode", so the user will start working on his project, will fill all the pages, and it will be persisted in the database with the "Draft mode" on.
But we need to manage the drafts, I mean, when the user will start editing an existing project, we will need to create a copy of it, set the object and all its childs to Draft mode and create a copy of it in our database. We will need to alter all the references from the childs.
So, I am trying to find the best way to deep copy the objects and alter all the references,
I would prefer to do not have to create a copying class for every entity that I will have to copy, maybe something more generic if this is possible.
Please let me know if you need more details or if something is unclear.
Thanks,
Charles

A: I would try to have my domain solve this issue and leave NHibernate to just saving the data instead of copying it. I would create an IDeepCopy interface that defines a DeepCopy() method. And then in each of these method you would create a new object and just copy the values yourself and control how you want to handle children or parent objects correctly.

A: This is probably bad idea and I'm not sure it would work, but what if you simply went through the object graph and set all required id's to the default unsaved values and then let cascading saves do the work of piecing all the references back together in the database.

A: I recommend to use SharpArchitecture for your project. It'll save you a lot of time and money.
There are no easy way to do a deep copy of data because it's very specific to a case. So you have to create all copies manually.
I also recommend to use different tables for draft entities and not draft ones. IMO in this case it'll be much more easier to implement and it doesn't violates with SRP. As it was said, divide and rule.

A: I use this function:
    public static T DeepClone<T>(T obj)
    {
        using (var ms = new MemoryStream())
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            ms.Position = 0;

            return (T)formatter.Deserialize(ms);
        }
    }