text:
Q: Can not connect to MySql server remotely I can not connect to MySQL server from a remote computer. When I try to connect it gives me the error

Host '' is not allowed to connect to this MySQL server

I've edited the MySQL server my.ini file by changing the bind line from #bind = "127.0.0.1"  to bind = *. I've turned off the firewall of the client machine trying to access the server. I also gave full privilege to the user of MySQL database through which I am  trying to connect to the server by using the MySQL grant command, but nothing seems to be working.
Please help me.
Thanks

A: A MySQL user has a "from host" field. This is probably set to some IP and those mismatch, giving you that error.
This field allows for extra security and can be set to any IP/hostname.
If this field is set for the user then you can only login to the MySQL server with that user from the IP/hostname specified.
If you want to test your connection you can just use a wildcard for the "from host" field % so that any IP can connect using that user, I wouldn't recommend this in a product environment though.

A: First check if you can connect to port 3306. You can use telnet for this, from your client system execute
telnet <server ip> 3306
You should get connected or asked for a password.
Also you can see if the port is open for outside connection by executing
netstat -an to get the list of open ports and the listening ip.
If that works then try to use a mysql client to connect using mysql -h <hosst> -u <user> -p <database>

A: Sounds like you may need to grant privileges to connect to the database, to the user/host that is trying to connect.  See http://dev.mysql.com/doc/refman/5.1/en/grant.html.


text:
Q: Using Pyomo Kernel to solve Disjunctive models I am trying to recreate a problem in the "Pyomo - Optimization Modeling in Python" book using the pyomo kernel instead of the environ. The problem is on page 163 and called "9.4 A mixing problem with semi-continuous variables." For those without the book, here it is:
The following model illustrates a simple mixing problem with three semi-continuous
variables (x1, x2, x3) which represent quantities that are mixed to meet a volumetric
constraint. In this simple example, the number of sources is minimized:
from pyomo.environ import *
from pyomo.gdp import *
L = [1,2,3]
U = [2,4,6]

index = [0,1,2]
model = ConcreteModel()
model.x = Var(index, within=Reals, bounds=(0,20))
# Each disjunct is a semi-continuous variable
# x[k] == 0 or L[k] <= x[k] <= U[k]
def d_rule(block, k, i):
    m = block.model()
    if i == 0:
        block.c = Constraint(expr=m.x[k] == 0)
    else:
        block.c = Constraint(expr=L[k] <= m.x[k] <= U[k])
model.d = Disjunct(index, [0,1], rule=d_rule)
# There are three disjunctions
def D_rule(block, k):
    model = block.model()
    return [model.d[k,0], model.d[k,1]]
model.D = Disjunction(index, rule=D_rule)
# Minimize the number of x variables that are nonzero
model.o = Objective(expr=sum(model.d[k,1].indicator_var for k in index))
# Satisfy a demand that is met by these variables
model.c = Constraint(expr=sum(model.x[k] for k in index) >= 7)

I need to refactor this problem to work in the pyomo kernel, but the kernel is not yet compatible with the pyomo gdp used to transform disjunctive models to linear ones. Has anyone ran into this problem, and if so did you find a good method to solve disjunctive models in the pyomo kernel?

A: I have a partial rewrite of pyomo.gdp that I could make available on a public github branch (probably working, but lacks testing). However, I am weary of investing more time in rewrites like this, as the better approach would be to re-implement the standard pyomo.environ api on top of kernel, which would make all of the extensions compatible.
With that being said, If there are collaborators willing to share in some of the development and testing, I would be happy help complete the kernel-gdp version I've started. If you want to discuss this further, it would probably be best to open an issue on the Pyomo Github page.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Delphi 2010 - Why can't I declare an abstract method with a generic type parameter? I am trying to do the following in Delphi 2010:
TDataConverter = class abstract
public
    function Convert<T>(const AData: T): string; virtual; abstract;
end;

However, I keep getting the following compiler error:
E2533 Virtual, dynamic and message methods cannot have type parameters
I don't quite understand the reason why I can't do this. I can do this in C# e.g.
public abstract class DataConverter
{
    public abstract string Convert<T>(T data);
}

Anyone know the reasoning behind this?

A: You can do it in .NET because Delphi and .NET handle generics differently.  I don't know enough to go into detail.  I do know why you can't do it in Delphi, though.
Every virtual method has to have a slot in the virtual method table for the class.  This has to be set up when the unit is compiled so its information can be put into the DCU.  (And likewise, every dynamic method has to have an entry in the dynamic method table, at the time when the unit is compiled.)
But if you create generic methods, each time you invoke it in code, a different copy of the code gets created, specific to that type parameter.  This is necessary for handling different types in different ways.  (If you pass in an interface or a string, for example, it has to take care of the reference count.)  But you can't create new virtual methods and new VMT slots for them, since the DCU has already been created and can't be changed now.


text:
Q: Break one line python code to multiple lines How to break one line code into multiple descriptive line because i am unable to understand this one line code.
data = formatted_data + "|" + '|'.join(["{}".format(a) for b, a in sorted(values.items()) if a and b not in ['SecureHash']])

Is this correct or not any one help me:
for b, a in sorted(values.items()):
    if a and b not in ['SecureHash']:
        c = ["{}".format(a)]
        data = formatted_data + "|" + "|".join(c)

A: This code is collecting a string representation of a, and then building another string with it.
You need to define an external list, to account for the list comprehension expression.
c = ["{}".format(a) for b, a in sorted(values.items()) if a and b not in ['SecureHash']]

Further, to break down how c is being assembled, you can expand the list comprehension:
c = []
for b, a in sorted(values.items()):
    if a and b not in ['SecureHash']:
        c.append('{}'.format(a))

Finally, just combine the three parts:
data = formatted_data + "|" + "|".join(c)

A: Well, generally you can see any opening bracket and the plus operators in the string as a "breaking point". Working with your example:
data = formatted_data
data += "|"
data += '|'.join(["{}".format(a) for b, a in sorted(values.items()) if a and b
not in ['SecureHash']])

OK so now we need to unpack what's happening in that join:
data = formatted_data
data += "|"
jointmp = ["{}".format(a) for b, a in sorted(values.items()) if a and b not in ['SecureHash']]
data += '|'.join(jointmp)

OK so we've got some string formatting and a bunch of list comprehensions:
data = formatted_data
data += "|"

jointmp = []
for b, a in sorted(values.items()):
  if a and b not in ['SecureHash']:
      jointmp += ["{}".format(a)] # Equivalent to str(a) ?

data += '|'.join(jointmp)

To do the last stage there was a lot of going back and for as things were expanded. Those list comprehensions are quite terse...
There are some questions here though:

*

*Where did values come from?

*What's the "{}".format(a) for?

etc.
Your "expanded" code is not quite equivalent because you don't handle the case where there are no matches / values is empty and you are replacing data each time rather than growing it.

A: You might want to read up on list comprehensions.
basically it's making a list of things like this:
[item for item in iterable_thing]
so this one is making a list of strings ("{}".format(a)). I assume a is a hash, but let's pretend it's a number in a range:
["{}".format(a) for a in range(5)]
will make:
>>>['0', '1', '2', '3', '4']
Comprehensions can become quite complicated with the addition of if statements, and whoever wrote this code is one of those a in b in i in j kind of people, it seems, so their code is hard to follow. Good variable names are SO important.


text:
Q: How to set High DPI scaling override to System (Enhanced) for WinForms app I have an old-school ordinary WinForms app in VS2019, for which the tabs on a tab control are vertically squished on a high-DPI monitor.  In fact, if the app is opened on a high-DPI monitor and dragged to a regular monitor, the tabs remain squished.  I want the app to automatically scale the controls properly.  As a user, I can make that happen post-installation by adjusting Compatibility Settings on the executable:  [Properties->Compatibility->Change high DPI settings->High DPI scaling Override->Override high DPI scaling behavior. Scaling performed by System (Enhanced)].  I don't want the user to have to do that -- I'd rather fix it in the source code.
I've read dozens and dozens of articles on this subject and it seems they are all outdated, as the 'recommended method' has changed several times over the past few years (and none of them seem to work).  The bottom line is that it seems likeI need to do the opposite of what most of them advise -- specifying that the app is DPI-aware (i.e. turning 'DPI-awareness' 'on').  It is NOT DPI-aware, but the 'System (Enhanced)' scaling (seemingly intended precisely for non-DPI-aware apps) works great.  But maybe I misunderstand what 'DPI-awareness' means.
What is currently the best practice for specifying programmatically (or via the manifest) that 'this app does not have any provisions for scaling itself or being aware of how many pixels per inch your monitor has, but allowing "System (Enhanced)" scaling from Windows 10 works great.  Please do that.'?


text:
Q: Problem with Authorization and variations in Sharepoint? Hello i have a website in Sharepoint that is using variations. I have for sites with variation: ES, CA, EU, EN.  I use authorization with roles and i put restrictions in the location tag in web.config. This is not working. Everybody can enter es/admin.
<location path="es/admin">
    <system.web>
      <authorization>
        <allow roles="administrators" />
        <deny users="*" />
      </authorization>
    </system.web>
  </location>

But, if I use one site that is not a variation, for example, like this:
<location path="prueba">
    <system.web>
      <authorization>
        <allow roles="administrators" />
        <deny users="*" />
      </authorization>
    </system.web>
  </location>

it works, there is a redirection.
If this is not possible, please give alternatives, i use a custom membership provider and role provider, so how can i restrict this site in a variation to only a group?

A: This is because variations aren't actual locations and so the web.config option won't work - they are a little url trick which defines what is read from the database.


text:
Q: please enable billing in your cloud project при запуске gradle получаю такое сообщение:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden { "code" : 403, "errors" : [ { "domain" : "global", "location" : "Authorization", "locationType" : "header", "message" : "The account for the specified project has been disabled.", "reason" : "accountDisabled" } ], "message" : "The account for the specified project has been disabled." }

просьба помочь разобраться, что оно от меня хочет

A: Это заголовок ошибки, только что разобрался в чем дело. Я пробовал подключить вчера онлайн тестирование, но что-то пошло не так. И успешно забыл об этом. А сейчас вот оно начало требовать подключить эту штуку и я без малейшего понятия, что оно от меня хочет так как я же никаких покупок не делал в моем приложении. В итоге удалил эту настройку и все стало норм.


text:
Q: how to declare a byte[] in C# so that ironpython interprets it as byte[] and not as a tuple In a C++/CLI we have a function that returns this:
array<Byte>^ OutBuffer = gcnew array<Byte>(BufferSize);

IronPython treats it as a byte[].
In C#, we have a function that returns this:
OutBuffer = new Byte[InBuffer.Length];

While a C# client treats Outbuffer as a byte[], IronPython treats it as a tuple containing multiple arrays.
How do we make IronPython relate to OutBuffer as a byte[] and not as a tuple?
Why the discrepancy between the C# and C++/CLI?
EDIT: This question is posed and apparently solved, but no answer supplied. Can this be corrected?


text:
Q: Flutter Navigator pops the SimpleDialog after pressing the darkened area The GIF
The Navigator pops the SimpleDialog after pressing the darkened area as shown above in the gif.
How not to pop the SimpleDialog after pressing the darkened area?
Thank you!

A: You can use the barrierDismissible attribute
    showDialog(

     barrierDismissible: false,
     //...

See the doc here.


text:
Q: jquery mobile disable button after submit I have a jquery mobile site in which a user uploads a file.  It works fine but the file may take a few seconds and i do not want the user to click the cubmit button again or think the upload is not working.  I need to disable a button after the user submits, I also want to change the button text to "Processing..."  Keep in mind this is jquery mobile because most of the jquery ways of doing this will not work with jquery mobile.  The below code does not work properly.  Any ideas?
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css"/>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>

<script>
$( '#button1' ).click( function() {
    $('#button1' ).attr('disabled', 'disabled').button('disable');
    $('#button1').prev('span').find('span.ui-btn-text').text("Processing...");
});
</script>

<form name="myform" action="gohere.cfm" method="post" enctype="multipart/form-data" data-ajax="false">
    <input type="file" name="fileName" id="fileName">

    <button type="submit" id="button1" name="button1" >Upload</button>
</form>


text:
Q: Get first record of each entity order by a column I have a query in linq that fetch students assessments data something like
new {x.StudentId, x.StudentAssessmentId, x.AssessmentName, x.SubmittedDate}

then I perform some operations on this list to get only last added student assessment per student, I get last studentassessment by finding the max id of studentassessment,
so I finally get last studentassessments data of all the students.
Is there a way to do this directly in the initial list?
I thought about the way to group the results by student Id and select max of studentassessmentid, like
group x.StudentAssessmentId by x.StudentId
select new {x.Key, x.Max()}

in this way I will get student with there last studentassessmentid which is what I want but this will only give me studentassessment ids while I want other data also like AssessmentName, SubmittedDate etc.

A: Try something like this:
group x.StudentAssessmentId
by new {
        x.StudentId,
        x.AssessmentName,
        x.SubmittedDate }
into g
select new
{
  g.Key.StudentId,
  g.Key.AssessmentName,
  g.Key.SubmittedDate,
  g.Max(),
}


text:
Q: Detecting that a button's function is completed I placed an actionListener on some JButtons I created. It is such that if the user clicks a button, another class is called-up. I want to detect if that class has finished its function... for more clarity, here is my code:
Quest.addActionListener(new ActionListener(){
  public void actionPerformed(ActionEvent iq) {

        JButton source = (JButton) iq.getSource();

             if (point.equals(points.get(0))){

         q1 = new Quest1();  //class called up
         source.setEnabled(false);

         //This is where my problem lies.... I want to be able to detect when the button's action is finished...than some other action takes place!
}
});

please help me.....

A: You already wrote the code to that!
You see, unless you put in extra effort, a method that calls another method (like in this case: using new to construct another object) does things in sequence!
Meaning: your last line with the comment in your listener is reached after all other things in your method happened!
The only thing to be aware of: if the constructor of Quest would be creating and starting another Thread, then of course, things would be different. Then you would need hand-crafted communication between the threads involved. But I am somehow guessing that this is not the case here.

A: Change a boolean completed to true then check for that.

A: Why don't you just call a method there?
Quest.addActionListener(new ActionListener(){
  public void actionPerformed(ActionEvent iq) {
    JButton source = (JButton) iq.getSource();
    if (point.equals(points.get(0))){
      q1 = new Quest1();  //class called up
      source.setEnabled(false);
    }
    onButtonActionDone()
});

private void onButtonActionDone() {
  ...
}


text:
Q: Change the background color to black I want to change this background into the original black. This background is not pure black. Its values contain 1, 2 or 3. After using the following code I got the background value very near to black but not black. Although the background looks black
img = cv2.imread("images.bmp")

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(gray, 0, 255, cv2. THRESH_BINARY)

img[thresh == 5] = 0

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
erosion = cv2.erode(img, kernel, iterations = 1)

cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.imshow("image", erosion)
cv2.waitKey(0)
cv2.destroyAllWindows()

A: Try replacing this:
ret, thresh = cv2.threshold(gray, 0, 255, cv2. THRESH_BINARY)

img[thresh == 5] = 0

with this:
# threshold to 10% of the maximum
threshold = 0.10 * np.max(img)
img[gray <= threshold] = 0

The issue is that cv2.threshold() does not compute a threshold for you, but applies one and, for example, thresh in your code is already the thresholded image.
(EDITED)

A: This should fix your problem, to the best of my understanding.
import cv2

gray = cv2.imread(r"brain.png", cv2.IMREAD_GRAYSCALE)

thresh_val = 5
gray[gray < thresh_val] = 0

Besides that, watch out that
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)

is basically going to set the whole image to 255, since the second argument is the threshold and every pixel above threshold is set to the third value, which is 255.


text:
Q: Obtain the biggest circle which has all inner points close to given regions In $\mathbb{R}^2$, I've got various spots, which may either be points, lines or polygons (there will always be one point in $(0,0)$):
Illustration of the spots
How can I find the biggest circle/disk (center always in $(0,0)$), whose inner points do not exceed a given distance $d_{max}>0$ to at least one of the spots?

Edit
A smallest circle with radius $r=Max\left(\overline{P,(0,0)}\right)+d_{max}$ does not fit the needs, as there may be regions inside the circle, where the next "spot" may be further away than $d_{max}$:
Illustration: Problem with smallest circle-approach


text:
Q: mediaMatch not working when resizing window I am trying to add a javascript to check the width of the window and produce a different styling depending on if above or below a specific media breakpoint. All seems to work as expected however when I transition between the two breakpoints it breaks and I can see in the dev tools that the styling doesn't update. If I then refresh all looks right again.
Sample Code:
if (window.matchMedia("(min-width: 768px)").matches) {
  this.$obj.show().delay(200).animate({'bottom': '0'}, 1000);
} else {
  this.$obj.show().delay(200).animate({'top': '0'}, 1000);
}

How can I make this work when expanding and contracting the window as opposed to just on initial page load?


text:
Q: Generate random locations within a triangular domain I want to generate x and y having a uniform distribution and limited by [xmin,xmax] and [ymin,ymax]
The points (x,y) should be inside a triangle.
How can I solve such a problem?

A: Ok, time to add another version, I guess. There is known algorithm to sample uniformly in triangle, see paper, chapter 4.2 for details.
Python code:
import math
import random

import matplotlib.pyplot as plt

def trisample(A, B, C):
    """
    Given three vertices A, B, C,
    sample point uniformly in the triangle
    """
    r1 = random.random()
    r2 = random.random()

    s1 = math.sqrt(r1)

    x = A[0] * (1.0 - s1) + B[0] * (1.0 - r2) * s1 + C[0] * r2 * s1
    y = A[1] * (1.0 - s1) + B[1] * (1.0 - r2) * s1 + C[1] * r2 * s1

    return (x, y)

random.seed(312345)
A = (1, 1)
B = (2, 4)
C = (5, 2)
points = [trisample(A, B, C) for _ in range(10000)]

xx, yy = zip(*points)
plt.scatter(xx, yy, s=0.2)
plt.show()

And result looks like

A: Uniform on the triangle?
import numpy as np

N = 10 # number of points to create in one go

rvs = np.random.random((N, 2)) # uniform on the unit square
# Now use the fact that the unit square is tiled by the two triangles
# 0 <= y <= x <= 1 and 0 <= x < y <= 1
# which are mapped onto each other (except for the diagonal which has
# probability 0) by swapping x and y.
# We use this map to send all points of the square to the same of the
# two triangles. Because the map preserves areas this will yield
# uniformly distributed points.
rvs = np.where(rvs[:, 0, None]>rvs[:, 1, None], rvs, rvs[:, ::-1])

Finally, transform the coordinates
xmin, ymin, xmax, ymax = -0.1, 1.1, 2.0, 3.3
rvs = np.array((ymin, xmin)) + rvs*(ymax-ymin, xmax-xmin)

Uniform marginals? The simplest solution would be to uniformly concentrate the mass on the line (ymin, xmin) - (ymax, xmax)
rvs = np.random.random((N,))
rvs = np.c_[ymin + (ymax-ymin)*rvs, xmin + (xmax-xmin)*rvs]

but that is not very interesting, is it?

A: Here's some code that generates points uniformly on an arbitrary triangle in the plane.
import random

def point_on_triangle(pt1, pt2, pt3):
    """
    Random point on the triangle with vertices pt1, pt2 and pt3.
    """
    x, y = sorted([random.random(), random.random()])
    s, t, u = x, y - x, 1 - y
    return (s * pt1[0] + t * pt2[0] + u * pt3[0],
            s * pt1[1] + t * pt2[1] + u * pt3[1])

The idea is to compute a weighted average of the three vertices, with the weights given by a random break of the unit interval [0, 1] into three pieces (uniformly over all such breaks). Here x and y represent the places at which we break the unit interval, and s, t and u are the length of the pieces following that break. We then use s, t and u as the barycentric coordinates of the point in the triangle.
Here's a variant of the above that avoids the need to sort, instead making use of an absolute value call:
def point_on_triangle2(pt1, pt2, pt3):
    """
    Random point on the triangle with vertices pt1, pt2 and pt3.
    """
    x, y = random.random(), random.random()
    q = abs(x - y)
    s, t, u = q, 0.5 * (x + y - q), 1 - 0.5 * (q + x + y)
    return (
        s * pt1[0] + t * pt2[0] + u * pt3[0],
        s * pt1[1] + t * pt2[1] + u * pt3[1],
    )

Here's an example usage that generates 10000 points in a triangle:
pt1 = (1, 1)
pt2 = (2, 4)
pt3 = (5, 2)
points = [point_on_triangle(pt1, pt2, pt3) for _ in range(10000)]

And a plot obtained from the above, demonstrating the uniformity. The plot was generated by this code:
import matplotlib.pyplot as plt
x, y = zip(*points)
plt.scatter(x, y, s=0.1)
plt.show()

Here's the image:

And since you tagged the question with the "numpy" tag, here's a NumPy version that generates multiple samples at once. Note that it uses the matrix multiplication operator @, introduced in Python 3.5 and supported in NumPy >= 1.10. You'll need to replace that with a call to np.dot on older Python or NumPy versions.
import numpy as np

def points_on_triangle(v, n):
    """
    Give n random points uniformly on a triangle.

    The vertices of the triangle are given by the shape
    (2, 3) array *v*: one vertex per row.
    """
    x = np.sort(np.random.rand(2, n), axis=0)
    return np.column_stack([x[0], x[1]-x[0], 1.0-x[1]]) @ v

# Example usage
v = np.array([(1, 1), (2, 4), (5, 2)])
points = points_on_triangle(v, 10000)


text:
Q: c# regex captures I am matching a repeating group that contains a mixture of optional and non-optional groups.  When I iterate over the captures, the capture collections are always collapsed, i.e. they do not insert a null element for the non matched items.
Is there a way to preserve the order of matches in capture collections, such that any omitted optional item is inserted as null, thereby ensuring capture collection elements correspond across groups?
To clarify, let's say my repeating (parent) group is matched three times, and in one of the three matches an optional child group was omitted but was present in the other two groups, I end up with a capture collection for the child group which is one element less than the other capture collections.  How do I know which of the parent groups omitted the optional item?
I suppose it would be possible to use the Index property of the capture collection item and check whether it falls within the bounds of the parent group, but it would be easier if non-matches returned a null item in the capture collection.  Is there a way to achieve this?

A: Instead of (pattern)? use (pattern|) and you should get what you want...


text:
Q: Setting Up These Types While Keeping It Properly Structured I'm completely stuck in a situation and I have no idea on where to go from here. I'm creating a very large project, so my goal is to keep the code itself as clean as possible and keeping as many hacks as possible out of the mix.
Here is the situation.
I have a class called Woo_Type, it is the parent of my many derived classes.
Public MustInherit Class Woo_Type

    Private Shared TypeList As New Dictionary(Of String, Woo_Type)

    Public MustOverride Sub SetValue(ByVal val As Object)
    Public MustOverride Function GetValue() As Object

    Public Shared Function GetTypeFromName(ByVal name As String) As Woo_Type
        Return TypeList(name)
    End Function

    Public Shared Sub AddType(ByVal name As String, ByVal def As Woo_Type)
        TypeList.Add(name, def)
    End Sub

End Class

I have many classes that Inherit from Woo_Type that have similar structures to this:
Public Class Woo_tpInt
    Inherits Woo_Type

    Private value As Integer = 0

    Public Overrides Function GetValue() As Object
        Return value
    End Function

    Public Overrides Sub SetValue(val As Object)
        value = val
    End Sub

End Class

I want to be able to do things like:
Woo_Type.GetTypeFromName("int")
And have it return something like the class or something...
At this point I'm really confused as to what I want and I didn't know if anybody had any suggestions. To make sure that GetTypeFromName worked correctly, I had in an Initializer sub the following:
Public Sub InitializeTypes()
    Woo_Type.AddType("int", Woo_tpInt)
    Woo_Type.AddType("String", Woo_tpInt)
End Sub

But I quickly realized that-that obviously doesn't work either.
So this may seem confusing but I'm basically wondering how to better structure this so that everything works...

A: If what you want to do is get the type itself (as opposed to an object), I would recommend using reflection rather than trying to reinvent the wheel.  For instance, to get the Woo_tpInt type, you could do this:
Dim a As Assembly = Assembly.GetExecutingAssembly()
Dim t As Type = a.GetType("WindowsApplication1.Woo_tpInt") ' Change WindowsApplication1 to whatever your namespace is

If you want to use a shorter name like "int" to mean "WindowsApplication1.Woo_tpInt", you could create a dictionary to store the translation table, for instance:
Dim typeNames As New Dictionary(Of String, String)
typeNames.Add("int", GetType(Woo_tpInt).FullName)

Dim a As Assembly = Assembly.GetExecutingAssembly()
Dim t As Type = a.GetType(typeNames("int"))

A: What do you want to do with the result? Are you sure you don't simply need generics?
Public Class WooType(Of T)
    Public Property Value As T
End Class

Public Class Test
    Public Sub Foo()
        Dim int As New WooType(Of Integer)
        int.Value = 42
        Dim str As New WooType(Of String)
        str.Value = "Forty-Two"
    End Sub
End Class


text:
Q: php mail is never received under gmail I am new to php and I am trying to send a confirmation email:
public static function sendAuthenticationEmail($username, $email, $uuid) {
    $subject = "Register email address";
    $headers = 'MIME-Version: 1.0' . PHP_EOL .
               'Content-type: text/html; charset=iso-8859-1' . PHP_EOL .
               'To: ' . $username . ' <' . $email . '>' . PHP_EOL .
               'From: whereisthemonkey <noreply@whereisthemonkey.me>' . PHP_EOL .
               'X-Mailer: PHP/' . phpversion();
    $link = 'http://localhost/Whereisthemonkey/FileSystem/EmailSystem.php?email=' .
            $email . '&uuid=' . substr($uuid, 0, 14);
    $message = '

                <title>Email authentication</title>

Do not reply to the email!

Hey ' . $username . ', this email has recently been used as authentication on Whereisthemonkey!

                If that was you, please click
                here

If that was not you, please just ignore this email!

Have a nice day, the whereisthemonkey team!
            ';
    return mail($email, $subject, $message, $headers);
}

The mail is sent, but never arrives on the server (in this case gmail).
What am I doing wrong?
Thank you very much,
Lucas!

A: Maybe Gmail blacklist your server IP address OR the email is going to your spam folder.
Try to put the same code in a different server or use SMTP connection.


text:
Q: Efficient way to delete multiple rows in HBase Is there an efficient way to delete multiple rows in HBase or does my use case smell like not suitable for HBase?
There is a table say 'chart', which contains items that are in charts. Row keys are in the following format:
chart|date_reversed|ranked_attribute_value_reversed|content_id
Sometimes I want to regenerate chart for a given date, so I want to delete all rows starting from 'chart|date_reversed_1' till 'chart|date_reversed_2'. Is there a better way than to issue a Delete for each row found by a Scan? All the rows to be deleted are going to be close to each other.
I need to delete the rows, because I don't want one item (one content_id) to have multiple entries which it will have if its ranked_attribute_value had been changed (its change is the reason why chart needs to be regenerated).
Being a HBase beginner, so perhaps I might be misusing rows for something that columns would be better -- if you have a design suggestions, cool! Or, maybe the charts are better generated in a file (e.g. no HBase for output)? I'm using MapReduce.

A: Firstly, coming to the point of range delete there is no range delete yet in HBase, AFAIK. But there is a way to delete more than one rows at a time in the HTableInterface API. For this simply form a Delete object with row keys from scan and put them in a List and use the API, done! To make scan faster do not include any column family in the scan result as all you need is the row key for deleting whole rows.
Secondly, about the design. First my understanding of the requirement is, there are contents with content id and each content has charts generated against them and those data are stored; there can be multiple charts per content via dates and depends on the rank. In addition we want the last generated content's chart to show at the top of the table.
For my assumption of the requirement I would suggest using three tables - auto_id, content_charts and generated_order. The row key for content_charts would be its content id and the row key for generated_order would be a long, which would auto-decremented using HTableInterface API. For decrementing use '-1' as the amount to offset and initialize the value Long.MAX_VALUE in the auto_id table at the first start up of the app or manually. So now if you want to delete the chart data simply clean the column family using delete and then put back the new data and then make put in the generated_order table. This way the latest insertion will also be at the top in the latest insertion table which will hold the content id as a cell value. If you want to ensure generated_order has only one entry per content save the generated_order id first and take the value and save it into content_charts when putting and before deleting the column family first delete the row from generated_order. This way you could lookup and charts for a content using 2 gets at max and no scan required for the charts.
I hope this is helpful.

A: You can use the BulkDeleteProtocol which uses a Scan that defines the relevant range (start row, end row, filters).
See here

A: I ran into your situation and this is my code to implement what you want
Scan scan = new Scan();
    scan.addFamily("Family");
    scan.setStartRow(structuredKeyMaker.key(starDate));
    scan.setStopRow(structuredKeyMaker.key(endDate + 1));
try {
    ResultScanner scanner = table.getScanner(scan);

    Iterator<Entity> cdrIterator = new EntityIteratorWrapper(scanner.iterator(), EntityMapper.create(); // this is a simple iterator that maps rows to exact entity of mine, not so important !

    List<Delete> deletes = new ArrayList<Delete>();
    int bufferSize = 10000000; // this is needed so I don't run out of memory as I have a huge amount of data ! so this is a simple in memory buffer
    int counter = 0;
    while (entityIterator.hasNext()) {
        if (counter < bufferSize) {
                            // key maker is used to extract key as byte[] from my entity
            deletes.add(new Delete(KeyMaker.key(entityIterator.next())));
            counter++;

        } else {
            table.delete(deletes);
            deletes.clear();
            counter = 0;
        }
    }

    if (deletes.size() > 0) {
        table.delete(deletes);
        deletes.clear();
    }

} catch (IOException e) {
    e.printStackTrace();
}


text:
Q: check visibility of IE save dialog box using Selenium Web Driver Currently, in my web application, I want to automatically save the generated excel reports on button click.
Issue:-  I am not able to identify the visibility of IE save dialog box using Robot Class
Logic used to save IE file  which is working successfully to save  when alert is prompted
Robot robot = new Robot();
robot.setAutoDelay(5000);
Thread.sleep(3000);
robot.keyPress(KeyEvent.VK_ALT);
Thread.sleep(1000);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_ALT);

How to check the visibility of save dialog box in IE 11 browser also in Firefox?
I checked this post for the solution but it's not working.

A: Robot class does not provide possibility to detect if dialog is visible or not. Just put appropriate delays and clicks on buttons.


text:
Q: Creating index for WHERE OR I have a MySQL Table with 114843213 rows.
It is read-only for me and I want to read it 10000 rows at a time.
I could read it with OFFSET and LIMIT, but then I would read it in the wrong order (It takes less than a second).
This is my query:
SELECT *
FROM `AUDIT`
WHERE `AD_TIMESTAMP` > '1970-1-1 10:10:10.0'
   OR (`AD_TIMESTAMP` = '1970-1-1 10:10:10.0' AND `AD_SQLIDENTITY` > 1)
ORDER BY `AD_TIMESTAMP` ASC, `AD_SQLIDENTITY` ASC
LIMIT 10000 OFFSET 0;

So, I do need to read it by timestamp ascending, and If the timestamp for two or more entries is equal, then read it by its ID (AD_SQLIDENTITY).
This takes about 4 minutes per request.
I have created an Index like so:
create index AUDIT_AD_SQLIDENTITY_AD_TIMESTAMP_index
    on AUDIT (AD_SQLIDENTITY ASC , AD_TIMESTAMP ASC)

But when I use explain on the SELECT above I can see that it doesn't get used - so my index is not good enough. I also tried a view, but it takes 5 minutes to render.
How can I increase the performance of my SELECT?
Edit: more info
This is the explain:
[
  {
    "id": 1,
    "select_type": "SIMPLE",
    "table": "IdisAuditEntity",
    "partitions": null,
    "type": "ALL",
    "possible_keys": "AUDIT_AD_SQLIDENTITY_AD_TIMESTAMP_index",
    "key": null,
    "key_len": null,
    "ref": null,
    "rows": 103361870,
    "filtered": 35.55,
    "Extra": "Using where; Using filesort"
  }
]

Schema:
CREATE TABLE `AUDIT` (
  `AD_ID` char(32) COLLATE latin1_german1_ci DEFAULT NULL,
  `AD_SQLIDENTITY` int(11) DEFAULT NULL,
  `AD_USER` varchar(120) COLLATE latin1_german1_ci DEFAULT NULL,
  `AD_TIMESTAMP` datetime(3) DEFAULT NULL,
  `AD_FIELD` varchar(60) COLLATE latin1_german1_ci DEFAULT NULL,
  `AD_HOSTNAME` varchar(80) COLLATE latin1_german1_ci DEFAULT NULL,
  `AD_APPLICATIONNAME` varchar(120) COLLATE latin1_german1_ci DEFAULT NULL,
  `AD_OLDVAL` varchar(250) COLLATE latin1_german1_ci DEFAULT NULL,
  `AD_NEWVAL` varchar(250) COLLATE latin1_german1_ci DEFAULT NULL,
  `AD_TABLE` varchar(60) COLLATE latin1_german1_ci DEFAULT NULL,
  `AD_DS_ID` varchar(60) COLLATE latin1_german1_ci DEFAULT NULL,
  `AD_TABLE_SQL_IDENTITY` int(11) DEFAULT NULL,
  `AD_COLUMNS_UPDATED` longtext COLLATE latin1_german1_ci,
  `AD_TYPE` varchar(60) COLLATE latin1_german1_ci DEFAULT NULL,
  `AD_DS_ID2` varchar(60) COLLATE latin1_german1_ci DEFAULT NULL,
  `AD_TS1` datetime(3) DEFAULT NULL,
  `AD_TS2` datetime(3) DEFAULT NULL,
  `AD_TS3` datetime(3) DEFAULT NULL,
  `AD_L1` tinyint(4) DEFAULT NULL,
  `AD_L2` tinyint(4) DEFAULT NULL,
  `AD_C1` varchar(200) COLLATE latin1_german1_ci DEFAULT NULL,
  `AD_C2` varchar(200) COLLATE latin1_german1_ci DEFAULT NULL,
  `AD_NA_ID` varchar(30) COLLATE latin1_german1_ci DEFAULT NULL,
  KEY `AUDIT_AD_SQLIDENTITY_AD_TIMESTAMP_index` (`AD_SQLIDENTITY`,`AD_TIMESTAMP`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_german1_ci

A: I recognize that WHERE as one of two ways to walk through a 2-column index, remembering where you left off.  Contrary to the usual advice against OR, this one should be well optimized.
Every table should have a PRIMARY KEY.
For the query in question, you need the two columns in the opposite order in an index.
If you are guaranteeing that AD_SQLIDENTITY is unique, then have
PRIMARY KEY(AD_SQLIDENTITY),
INDEX(AD_TIMESTAMP, AD_SQLIDENTITY)

(and get rid of the current KEY)
If it is not unique, then add
ID BIGINT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(AD_TIMESTAMP, AD_SQLIDENTITY, ID),
INDEX(ID)

(and keep the current KEY if it is useful for any other query).
Other things to check:  How much RAM?  How big is the table?  What is the value of innodb_buffer_pool_size?


text:
Q: Java 6 RegEx to match all characters NOT in Unicode's Letters and Marks categories I need to remove all non Letter and Mark (Unicode categories) characters from a string. Currently I'm splitting and subsequently joining a string like so:
text.split("[\\p{P} \\t\\n\\r]")

My RegEx is however... acutely inadequate. Please help.
EDIT
I think this will work:
text.split("[\\P{M}\\P{L}]")

A: Try this:
text = text.replaceAll("[^\\p{L}\\p{M}]", "");

See more in http://www.regular-expressions.info/unicode.html


text:
Q: Select2 - Pass back additional data via ajax call Ok, I feel like I'm going crazy here.  I'm using the select2 jquery plugin (version 4), and retrieving data via ajax.  So you can type in a name, and it will return that contact information. But I also want to return what organization that contact is a part of.
Here is my select2 initialization:
$('#contact_id').select2({
    ajax: {
        url: 'example.com/contacts/select',
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                q: params.term,
                page: params.page
            };
        },
        processResults: function (data) {
            return {
                results: data
            };
        },
        cache: true
    },
    minimumInputLength: 3,
    maximumSelectionLength: 1
});

And here is the data I'm returning (laravel framework):
foreach($contacts as $con) {
    $results[] = [
        'id'    => $con->contact_id,
        'text'  => $con->full_name,
        'org'   => [
            'org_id'        => $con->organization_id,
            'org_name'      => $con->org_name
        ]
    ];
}

return response()->json($results);

So isn't 'org' supposed to be attached to either the created option or select element by select2? So I could do something like $('#contact_id').select2().find(':selected').data('data').org or $('#contact_id').select2().data('data').org or something like that?
Idealistically, this would look like:
<select>
    <option value="43" data-org="{org_id:377, org_name:'Galactic Empire'}">Darth Vader</option>
</select>

I swear I confirmed this worked last week, but now it's completely ignoring that org property.  I have confirmed that the json data being returned does include org with the proper org_id and org_name. I haven't been able to dig anything up online, only this snippet of documentation:

The id and text properties are required on each object, and these are the properties that Select2 uses for the internal data objects. Any additional paramters passed in with data objects will be included on the data objects that Select2 exposes.

So can anyone help me with this? I've already wasted a couple hours on this.
EDIT: Since I haven't gotten any responses, my current plan is to use the processResults callback to spawn hidden input fields or JSON blocks that I will reference later in my code.  I feel like this is a hacky solution given the situation, but if there's no other way, that's what I'll do. I'd rather that than do another ajax call to get the organization. When I get around to implementing it, I'll post my solution.

A: Can't remember what I was doing wrong, but with processResults(data), data contains the full response. In my implementation below, I access this info when an item is selected:
$('#select2-box').select2({
    placeholder: 'Search Existing Contacts',
    ajax: {
        url: '/contacts/typeahead',
        dataType: 'json',
        delay: 250,
        data: function(params){
            return {
                q: params.term,
                type: '',
                suggestions: 1
            };
        },
        processResults: function(data, params){
            //Send the data back
            return {
                results: data
            };
        }
    },
    minimumInputLength: 2
}).on('select2:select', function(event) {
    // This is how I got ahold of the data
    var contact = event.params.data;

    // contact.suggestions ...
    // contact.organization_id ...
});

// Data I was returning
[
    {
        "id":36167, // ID USED IN SELECT2
        "avatar":null,
        "organization_id":28037,
        "text":"John Cena - WWE", // TEXT SHOWN IN SELECT2
        "suggestions":[
            {
                "id":28037,
                "text":"WWE",
                "avatar":null
            },
            {
                "id":21509,
                "text":"Kurt Angle",
                "avatar":null
            },
            {
                "id":126,
                "text":"Mark Calaway",
                "avatar":null
            },
            {
                "id":129,
                "text":"Ricky Steamboat",
                "avatar":null
            },
            {
                "id":131,
                "text":"Brock Lesnar",
                "avatar":null
            }
        ]
    }
]

A: Can't comment for now (low reputation).. so... answering to slick:
Including additional data (v4.0):
processResults: function (data) {
    data = data.map(function (item) {
        return {
            id: item.id_field,
            text: item.text_field,
            otherfield: item.otherfield
        };
    });
    return { results: data };
}

Reading the data:
var data=$('#contact_id').select2('data')[0];
console.log(data.otherfield);


text:
Q: Elegant min/max absolute values in java I need to get the minimum and maximum values in a collection of floating point values, after applying an absolute value conversion. In python I would do this
min(map(abs, [-5, -7, 10, 2]))

how can I perform the same operation in java in the most elegant way?

A: You might be able to do something crazy, but the most straightforward solution is this:
List<Integer> x = new ArrayList<Integer>(Arrays.asList( {-5,-7,10,2} } );
for( int i = 0; i < x.size(); i++ ){
   x.set( i, Math.abs(x.get(i)) );
}

return Collections.max( x );

Collections and Arrays are infinitely useful.

A: Here is another way to do it. This approach does not require creating a second copy of the array, since Arrays.asList merely produces an array-backed view of the given array. Another potential advantage is the fact that the signs of the minimum and maximum are preserved. In the example below, the minimum is displayed as 1.333 and the maximum as -9.43.
It is more complex than Stefan's solution, but depending on the situation, it might be right for you.
    Float numbers[] = {-9.43f, 2.3f, -8.2f, 1.333f};

    // Calculate the minimum
    Float min = Collections.min(Arrays.asList(numbers),
            new Comparator<Float>() {
                public int compare(Float o1, Float o2) {
                    Float result = Math.abs(o1) - Math.abs(o2);
                    return result > 0 ? 1 : result < 0 ? -1 : 0;
                }
            }
    );

    // Calculate the maximum
    Float max = Collections.min(Arrays.asList(numbers),
            new Comparator<Float>() {
                public int compare(Float o1, Float o2) {
                    Float result = Math.abs(o2) - Math.abs(o1);
                    return result > 0 ? 1 : result < 0 ? -1 : 0;
                }
            }
    );

    System.out.println("Min = " + min);
    System.out.println("Max = " + max);

Output:
Min = 1.333
Max = -9.43

Edit: In response to "hatchetman82" in the comments, I decided to run a simple benchmark to see how my solution performs compared to Stefan Kendall's. For small arrays of less than ten thousand elements, the two solutions perform almost identically. However, for larger arrays, my solution will usually perform better.
Stefan's approach is perfectly valid, but it uses about twice as much memory as mine, because it must create a copy of the original array in order to store each element's absolute value. As for time complexity, I found that my approach performed anywhere between 4X and 7X faster, mostly due to the time Stefan's approach requires to copy the array. Keep in mind that these benchmarks were performed on a single machine (a MacBook Pro, 4GB, Core2 Duo @ 2.53) and results will vary depending on your computer's and JVM's configurations.
Stefan's approach is certainly more straight forward, and mine can perform better under certain situations. So basically each solution is valid, though one or the other might be preferable depending on the situation.

A: In the category of "something crazy":
import java.util.*;
import org.apache.commons.collections.iterators.IteratorEnumeration;
import org.apache.commons.functor.core.collection.TransformedIterator;
import org.apache.commons.functor.UnaryFunction;
//...
int commonsMin = Collections.min(
                 Collections.list((Enumeration<Integer>)
                 new IteratorEnumeration(
                 new TransformedIterator<Integer, Integer>(
                 Arrays.asList(3, -5, -7, 10, -2, 4).iterator(), new UnaryFunction<Integer, Integer>(){
                   public Integer evaluate(Integer a)
                   {
                     return Math.abs(a);
                   }
                 }))));
//...

This really wouldn't be that crazy if one of the Collections.min overloads took a Iterator, or there was an easy way to convert an Iterator to a Collection.  It may be even more sane with Java 7 closures.
EDIT:  This is cleaner with Guava/Google Collections.  I use HashSet because we really don't care about order:
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;

// ...
int guavaMin = Collections.min(
               Sets.newHashSet(
               Iterables.transform(
               Sets.newHashSet(3, -5, -7, 10, -2, 4), new Function<Integer, Integer>(){
                 public Integer apply(Integer a)
                 {
                   return Math.abs(a);
                 }
               })));
// ...

A: Creating another (more pragmatic) answer, to separate two approaches (see Kevin Day's comment):
This can be done in one array pass (sort is O(log n)), without creating any new list.  Just don't use Collections.max.  Instead, just calculate the absolute value as you go and have a running minimum/maximum:
List<Integer> l = Arrays.asList(3, -5, -7, 10, -2, 4);
int iterMin = Integer.MAX_VALUE;
for(Integer i : l)
  if(Math.abs(i) < iterMin)
    iterMin = Math.abs(i);

If you want to preserve the original value, you can easily do that:
int iterMinOrig = Integer.MAX_VALUE;
for(Integer i : l)
  if(Math.abs(i) < Math.abs(iterMinOrig))
    iterMinOrig = i;

A: I would suggest using a Comparator. For instance, if your list is doubles, then you have the following options:
Get the maximum absolute value:
double maxAbs = Collections.max( myList, new Comparator<Double>() {
        @Override
        public int compare(Double x, Double y) {
            return Math.abs(x) < Math.abs(y) ? -1 : 1;
        }

    });

Get the minimum absolute value:
double minAbs = Collections.max( myList, new Comparator<Double>() {
        @Override
        public int compare(Double x, Double y) {
            return Math.abs(x) > Math.abs(y) ? -1 : 1;
        }

    });

Sort your list in ascending order (with respect to the absolute value):
Collections.sort( myList, new Comparator<Double>() {
            @Override
            public int compare(Double x, Double y) {
                return Math.abs(x) < Math.abs(y) ? -1 : 1;
            }

        });

Sort your list in descending order (with respect to the absolute value):
Collections.sort( myList, new Comparator<Double>() {
            @Override
            public int compare(Double x, Double y) {
                return Math.abs(x) > Math.abs(y) ? -1 : 1;
            }

        });

If you have some other type like integers, just replace Double with Integer

A: Short (elegant?):
int min = Arrays.stream(array).map(Math::abs).min().getAsInt();
int max = Arrays.stream(array).map(Math::abs).max().getAsInt();

Or, to avoid traversing twice (more effective but maybe slightly less elegant):
IntSummaryStatistics d = Arrays.stream(array).map(Math::abs).summaryStatistics();
int min = d.getMin();
int max = d.getMax();

(Both adapted from https://stackoverflow.com/a/30692454)


text:
Q: GitLab 500 Error when visiting Project Page I am setting up GitLab Enterprise Edition for my organisation. We are using AWS EFS for storing repo data and two instances to serve SSH and HTTP/HTTPS traffic via AWS ELB. EFS volume is shared between both instances. But when I visit project home page after service restart we see 500 error page. We tried running gitlab-ctl reconfigure && gitlab-ctl restart but did not help.

*

*GitLab EE Version - 8.12.1-ee

*2 * Centos 7 (AWS EC2 Instance - m4.xlarge)

*AWS ELB to load balance ssh and http/https traffic

Error in logs
     ==> /var/log/gitlab/gitlab-rails/production.log <==
Started GET "/itops/docker" for 10.0.4.246 at 2016-09-26 07:58:58 +0000
Processing by ProjectsController#show as HTML
  Parameters: {"namespace_id"=>"itops", "id"=>"docker"}
Completed 500 Internal Server Error in 145ms (ActiveRecord: 14.2ms)

OpenSSL::Cipher::CipherError (bad decrypt):
  app/models/project.rb:531:in `import_url'
  app/models/project.rb:567:in `external_import?'
  app/models/project.rb:559:in `import?'
  app/models/project.rb:575:in `import_in_progress?'
  app/controllers/projects_controller.rb:95:in `show'
  lib/gitlab/request_profiler/middleware.rb:15:in `call'
  lib/gitlab/middleware/go.rb:16:in `call'
  lib/gitlab/middleware/readonly_geo.rb:29:in `call'

  ==> /var/log/gitlab/gitlab-rails/production.log <==
Started GET "/itops/docker/refs/master/logs_tree/?offset=50&_=1474877373459" for 10.0.9.106 at 2016-09-26 08:09:40 +0000
Processing by Projects::RefsController#logs_tree as JS
  Parameters: {"offset"=>"50", "_"=>"1474877373459", "namespace_id"=>"itops", "project_id"=>"docker", "id"=>"master"}
Started GET "/itops/docker/commits/master" for 10.0.4.246 at 2016-09-26 08:09:40 +0000
Processing by Projects::CommitsController#show as HTML
  Parameters: {"namespace_id"=>"itops", "project_id"=>"docker", "id"=>"master"}
Completed 500 Internal Server Error in 176ms (ActiveRecord: 16.8ms)

ActionView::Template::Error (bad decrypt):
    1: - if @project.mirror?
    2:   .prepend-top-default.gray-content-block.second-block.clearfix
    3:     - import_url = @project.safe_import_url
    4:     .oneline.project-mirror-text
    5:       This project is mirrored from #{link_to import_url, import_url}.
    6:
  app/models/project.rb:531:in `import_url'
  app/models/project.rb:587:in `safe_import_url'
  app/views/projects/commits/_mirror_status.html.haml:3:in `_app_views_projects_commits__mirror_status_html_haml___2300853211630423479_63495260'
  app/views/projects/commits/show.html.haml:35:in `_app_views_projects_commits_show_html_haml___2695203885719227520_58528080'
  app/controllers/projects/commits_controller.rb:27:in `show'
  lib/gitlab/request_profiler/middleware.rb:15:in `call'
  lib/gitlab/middleware/go.rb:16:in `call'
  lib/gitlab/middleware/readonly_geo.rb:29:in `call'

I imported Docker project from GitHub. All other pages are working fine (tree/master , activity, Graph, Pipeline, issues) only project home page and docker/commits/master is showing error.

A: Did you migrate from another server?
If so, it's possible your previous /etc/gitlab/gitlab-secrets.json file contains encryption keys that your new installation doesn't.
Copying over the old gitlab-secrets.json to /etc/gitlab on your new server (after making a backup of your new version, of course, in case you need to roll back) should fix it.

A: I my case the same exception was rised when i create repository by importing from another. After shutting down the donor project server I catch 500 error. The exception must be import_url unavailable , not ssl error.
My resolution was to clear broken link from database:
update projects set import_url=NULL where id = MY-PROJECT_ID;

A: We contacted both AWS and gitlab support team for this issue and find out that AWS EFS(Elastic File System - fancy NFS service) is not compatible with Gitlab. For more info please visit below link.
https://docs.gitlab.com/ee/administration/high_availability/nfs.html#aws-elastic-file-system

*

*The distributed architecture of EFS results in a higher latency per file operation

*Gitlab process very small files in a serialised manner (Examples of serialized commands: ls, cp, tar, rsync, git)

*EFS bases allowed IOPS on volume size. The larger the volume, the more IOPS are allocated. For smaller volumes, users may experience decent performance for a period of time due to 'Burst Credits'. Over a period of weeks to months credits may run out and performance will bottom out.

*For larger volumes, allocated IOPS may not be the problem. Workloads where many small files are written in a serialized manner are not well-suited for EFS. EBS with an NFS server on top will perform much better.


text:
Q: Database connection using dplyr with date field in database Is there some magic to using dplyr to access a database when it has a date field?
A dplyr tbl_df converts mysql datetime fields to chr.  That wouldn't be so bad if I could as.Date() them back.  But if I do that before collect()'ing the table, I get an error that as.Date() is an invalid sql function.  I can sort-of workaround this by calling collect(), but then I'm copying all of the data out of the database, which is what I was trying to avoid.  In addition, once I've collect()'ed, its a data.frame, so if I want to join it with another tbl I have to set copy=TRUE and copy that one into memory as well.


text:
Q: How to get consistent deep copy of MTLTexture contents?
I am receiving YUV 420 CMSampleBuffers of the screen in my System Broadcast Extension, however when I attempt to access the underlying bytes, I get inconsistent results: artefacts that are a mixture of (it seems) past and future frames. I am accessing the bytes in order to rotate portrait frames a quarter turn to landscape, but the problem reduces to not being able to correctly copy the texture.
The pattern of artefacts can change quite a lot. They can be all over the place and seem to have a fundamental "brush shape" that is square tile, sometimes small, sometimes large, which seems to depend on the failing work around at hand. They can occur in both the luminance and chroma channels, which results in interesting effects. The "grain" of the artefacts sometimes appears to be horizontal, which I guess is vertical in the original frame.
I do have two functioning work arounds:

*

*rotate the buffers using Metal

*rotate the buffers using CoreImage (even a "software" CIContext works)

The reason that I can't yet ship these workarounds is that System Broadcast Extensions have a very low memory limit of 50MB and memory usage can spike with these two solutions, and there seem to be interactions with other parts of the system (e.g. the AVAssetWriter or the daemon that dumps frames into my address space). I'm still working to understand memory usage here.
The artefacts seem like a synchronisation problem. However I have a feeling that this is not so much a new frame being written into the buffer that I'm looking at, but rather some sort of stale cache. CPU or GPU? Do GPUs have caches? The tiled nature of the artefacts reminds me of iOS GPUs, but that with a grain of salt (not a hardware person).
This brings me around to the question title. If this is a caching problem, and Metal / CoreImage has a consistent view of the pixels, maybe I can get Metal to flush the data I want for me, because an BGRA screen capture being converted to YUV IOSurface has Metal shader written all over it.
So I took the incoming CMSampleBuffer's CVPixelBuffer's IOSurface and created an MTLTexture from it (with all sorts of cacheModes and storageModes, haven't tried hazardTrackingModes yet) and then copied the bytes out with MTLTexture.getBytes(bytesPerRow:from:mipmapLevel:).
Yet the problem persists. I would really like to make the CPU deep copy approach work, for memory reasons.
To head off some questions:

*

*it's not a bytes-per-row issue, that would slant the images

*in the cpu case I do lock the CVPixelBuffer's base address

*I even lock the the underlying IOSurface

*I have tried discarding IOSurfaces whose lock seed changes under lock

*I do discard frames when necessary

*I have tried putting random memory fences and mutexes all over the place (not a hardware person)

*I have not disassembled CoreImage yet

This question is the continuation of one a posted on the Apple Developer Forums

Art by https://twitter.com/artofzara


text:
Q: Retrieving item text from Win32 ListView using JNA, C# is fine, but java can't get text I want to retrieve item information (text would be enough) from a Win32 ListView control (SysListView32). I'm using JNA's sendMessage() to send LVM_GETITEMTEXT. SendMessage() takes a pointer to a LVITEM structure which looks like this: LVITEM structure:
In c#, I successfully get the text from ListItem,
    int hwnd;   //窗口句柄
    int process;//进程句柄
    int pointer;
    int pointer2;
    private const uint LVM_FIRST = 0x1000;
    private const uint LVM_GETITEMCOUNT = LVM_FIRST + 4;//获取列表行数
    private const uint LVM_GETHEADER = LVM_FIRST + 31;
    private const uint LVM_GETITEMTEXT = LVM_FIRST + 45;//获取列表内的内容
    private const uint LVM_GETITEMW = LVM_FIRST + 75;

    private const uint HDM_GETITEMCOUNT = 0x1200;//获取列表列数

    private const uint PROCESS_VM_OPERATION = 0x0008;//允许函数VirtualProtectEx使用此句柄修改进程的虚拟内存
    private const uint PROCESS_VM_READ = 0x0010;//允许函数访问权限
    private const uint PROCESS_VM_WRITE = 0x0020;//允许函数写入权限

    private const uint MEM_COMMIT = 0x1000;//为特定的页面区域分配内存中或磁盘的页面文件中的物理存储
    private const uint MEM_RELEASE = 0x8000;
    private const uint MEM_RESERVE = 0x2000;//保留进程的虚拟地址空间,而不分配任何物理存储

    private const uint PAGE_READWRITE = 4;

    private int LVIF_TEXT = 0x0001;

    [DllImport("user32.dll")]//查找窗口
    private static extern int FindWindow(
                                        string strClassName,    //窗口类名
                                        string strWindowName    //窗口标题
    );

    [DllImport("user32.dll")]//在窗口列表中寻找与指定条件相符的第一个子窗口
    private static extern int FindWindowEx(
                                          int hwndParent, // handle to parent window
                                        int hwndChildAfter, // handle to child window
                                          string className, //窗口类名
                                          string windowName // 窗口标题
    );
    [DllImport("user32.DLL")]
    private static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);
    [DllImport("user32.dll")]//找出某个窗口的创建者(线程或进程),返回创建者的标志符
    private static extern int GetWindowThreadProcessId(int hwnd, out int processId);
    [DllImport("kernel32.dll")]//打开一个已存在的进程对象,并返回进程的句柄
    private static extern int OpenProcess(uint dwDesiredAccess, bool bInheritHandle, int processId);
    [DllImport("kernel32.dll")]//为指定的进程分配内存地址:成功则返回分配内存的首地址
    private static extern int VirtualAllocEx(int hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
    [DllImport("kernel32.dll")]//从指定内存中读取字节集数据
    private static extern bool ReadProcessMemory(
                                        int hProcess, //被读取者的进程句柄
                                        int lpBaseAddress,//开始读取的内存地址
                                        IntPtr lpBuffer, //数据存储变量
                                        int nSize, //要写入多少字节
                                        ref uint vNumberOfBytesRead//读取长度
    );
    [DllImport("kernel32.dll")]//将数据写入内存中
    private static extern bool WriteProcessMemory(
                                        int hProcess,//由OpenProcess返回的进程句柄
                                        int lpBaseAddress, //要写的内存首地址,再写入之前,此函数将先检查目标地址是否可用,并能容纳待写入的数据
                                        IntPtr lpBuffer, //指向要写的数据的指针
                                        int nSize, //要写入的字节数
                                        ref uint vNumberOfBytesRead
    );
    [DllImport("kernel32.dll")]
    private static extern bool CloseHandle(int handle);
    [DllImport("kernel32.dll")]//在其它进程中释放申请的虚拟内存空间
    private static extern bool VirtualFreeEx(
                                int hProcess,//目标进程的句柄,该句柄必须拥有PROCESS_VM_OPERATION的权限
                                int lpAddress,//指向要释放的虚拟内存空间首地址的指针
                                uint dwSize,
                                uint dwFreeType//释放类型
    );
    /// <summary>
    /// LVITEM结构体,是列表视图控件的一个重要的数据结构
    /// 占空间:4(int)x7=28个byte
    /// </summary>
    private struct LVITEM  //结构体
    {
        //public int a;
        public int mask;//说明此结构中哪些成员是有效的
        public int iItem;//项目的索引值(可以视为行号)从0开始
        public int iSubItem; //子项的索引值(可以视为列号)从0开始
        public int state;//子项的状态
        public int stateMask; //状态有效的屏蔽位
        public IntPtr pszText;  //主项或子项的名称
        public int cchTextMax;//pszText所指向的缓冲区大小
    }
    public Form1()
    {
        InitializeComponent();
    }

    /// <summary>
    /// LV列表总行数
    /// </summary>
    private int ListView_GetItemRows(int handle)
    {
        return SendMessage(handle, LVM_GETITEMCOUNT, 0, 0);
    }
    /// <summary>
    /// LV列表总列数
    /// </summary>
    private int ListView_GetItemCols(int handle)
    {
        return SendMessage(handle, HDM_GETITEMCOUNT, 0, 0);
    }

    private void button1_Click_1(object sender, EventArgs e)
    {
        int headerhwnd; //listview控件的列头句柄
        int rows, cols;  //listview控件中的行列数
        int processId; //进程pid

        hwnd = FindWindow("#32770", "Windows 任务管理器");
        hwnd = FindWindowEx(hwnd, 0, "#32770", null);
        hwnd = FindWindowEx(hwnd, 0, "SysListView32", null);//进程界面窗口的句柄,通过SPY获取
        headerhwnd = SendMessage(hwnd, LVM_GETHEADER, 0, 0);//listview的列头句柄

        rows = ListView_GetItemRows(hwnd);//总行数,即进程的数量
        cols = ListView_GetItemCols(headerhwnd);//列表列数
        GetWindowThreadProcessId(hwnd, out processId);

        //打开并插入进程
        process = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, false, processId);
        //申请代码的内存区,返回申请到的虚拟内存首地址
        pointer = VirtualAllocEx(process, IntPtr.Zero, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
        pointer2 = VirtualAllocEx(process, IntPtr.Zero, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
        string[,] tempStr;//二维数组
        string[] temp = new string[cols];

        tempStr = GetListViewItmeValue(rows, cols);//将要读取的其他程序中的ListView控件中的文本内容保存到二维数组中

        listView1.Items.Clear();//清空LV控件信息
        //输出数组中保存的其他程序的LV控件信息
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                temp[j] = tempStr[i, j];
            }
            ListViewItem lvi = new ListViewItem(temp);
            listView1.Items.Add(lvi);
        }
    }

    /// <summary>
    /// 从内存中读取指定的LV控件的文本内容
    /// </summary>
    /// <param name="rows">要读取的LV控件的行数</param>
    /// <param name="cols">要读取的LV控件的列数</param>
    /// <returns>取得的LV控件信息</returns>
    private string[,] GetListViewItmeValue(int rows, int cols)
    {
        string[,] tempStr = new string[rows, cols];//二维数组:保存LV控件的文本信息
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                int size = 40;// Marshal.SizeOf(typeof(LVITEM));
                byte[] vBuffer = new byte[256];//定义一个临时缓冲区
                LVITEM[] vItem = new LVITEM[1];
                vItem[0].mask = LVIF_TEXT;//说明pszText是有效的
               // vItem[0].iItem = i;     //行号
               // vItem[0].iSubItem = j;  //列号
                vItem[0].cchTextMax = vBuffer.Length;//所能存储的最大的文本为256字节
                vItem[0].pszText = (IntPtr)pointer2;// ((int)pointer + size);
                uint vNumberOfBytesRead = 0;

                //把数据写到vItem中
                //pointer为申请到的内存的首地址
                //UnsafeAddrOfPinnedArrayElement:获取指定数组中指定索引处的元素的地址

                IntPtr intPtr = Marshal.UnsafeAddrOfPinnedArrayElement(vItem, 0);
                WriteProcessMemory(process, pointer, intPtr, size, ref vNumberOfBytesRead);

                //发送LVM_GETITEMW消息给hwnd,将返回的结果写入pointer指向的内存空间
                SendMessage(hwnd, LVM_GETITEMW, i, pointer);

                //从pointer指向的内存地址开始读取数据,写入缓冲区vBuffer中
               // ReadProcessMemory(process, ((int)pointer + size), Marshal.UnsafeAddrOfPinnedArrayElement(vBuffer, 0), vBuffer.Length, ref vNumberOfBytesRead);
                ReadProcessMemory(process, pointer2, Marshal.UnsafeAddrOfPinnedArrayElement(vBuffer, 0), vBuffer.Length, ref vNumberOfBytesRead);

                string vText = Encoding.Unicode.GetString(vBuffer, 0, (int)vNumberOfBytesRead); ;
                tempStr[i, j] = vText;
            }
        }
        VirtualFreeEx(process, pointer, 0, MEM_RELEASE);//在其它进程中释放申请的虚拟内存空间,MEM_RELEASE方式很彻底,完全回收
        CloseHandle(process);//关闭打开的进程对象
        return tempStr;
    }

I use jna to rewrite in Java, but i can't get the text, vText always is '', if someone can tell me what's wrong in my java code?
The editor can't submit full java code, so , I submit the java code into the github, the code is here.
 public static void main(String[] args) {
    HWND hwnd = User32Ex.instance.FindWindow("#32770", "Windows 任务管理器");
    hwnd = User32Ex.instance.FindWindowEx(hwnd, 0, "#32770", null);
    hwnd = User32Ex.instance.FindWindowEx(hwnd, 0, "SysListView32", null);HWND listViewHwnd = hwnd;
    System.out.println(listViewHwnd);

    PointerByReference pointer = new PointerByReference();
    User32Ex.instance.GetWindowThreadProcessId(listViewHwnd, pointer);
    int pid = pointer.getPointer().getInt(0);
    Pointer process = Kernel32Ex.instance.OpenProcess(Api.PROCESS_VM_WRITE | Api.PROCESS_VM_OPERATION, false, new Pointer(pid));
    IntByReference addr = new IntByReference(0);
    SIZE_T size = new SIZE_T(4096);
    IntByReference epLvi = Kernel32Ex.instance.VirtualAllocEx(new HANDLE(process), addr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);

    LVITEM_VISTA lvitem = new LVITEM_VISTA();
    lvitem.mask = 1;
    lvitem.cchTextMax = 256;
    lvitem.pszText = new Memory(256);

    IntByReference bytesWritten = new IntByReference();
    Api.Kernel32Ex.instance.WriteProcessMemory(new HANDLE(process), epLvi, lvitem.getPointer(), lvitem.size(),bytesWritten);
    LRESULT isSuccess = Api.User32Ex.instance.SendMessage(listViewHwnd, 4171, new WPARAM(0), lvitem);
    System.out.println("isSuccess:" + isSuccess);

    byte[] result = new byte[256];
    ByteBuffer bufDest = ByteBuffer.allocateDirect(256);

    Pointer ptrSrc = Native.getDirectBufferPointer(bufDest);

    Api.Kernel32Ex.instance.ReadProcessMemory(new HANDLE(process), lvitem.pszText, ptrSrc, 256,bytesWritten);
    System.out.println(Arrays.toString(bufDest.array()));
    Api.Kernel32Ex.instance.VirtualFreeEx(new HANDLE(process), epLvi, new SIZE_T(4096), new DWORD(MEM_DECOMMIT | MEM_RELEASE));
    Api.Kernel32Ex.instance.CloseHandle(new HANDLE(process));
}

LVITEM_VISTA define
public static class LVITEM_VISTA extends Structure {
        public int mask;
        public int iItem;
        public int iSubItem;
        public int state;
        public int stateMask;
        public Pointer pszText;
        public int cchTextMax;
        public int iImage;
        public LPARAM lParam;
        public int iIndent;
        public int iGoupId;
        public int cColumns;
        public Pointer puColumns;
        //NTDDI_VERSION >= NTDDI_VISTA
        public Pointer piColFmt;
        public int iGroup;
        @Override
        protected List<?> getFieldOrder() {
            return Arrays.asList(new String[] {
"mask",  "iItem",  "iSubItem",  "state", "stateMask", "pszText", "cchTextMax",  "iImage", "lParam",  "iIndent", "iGoupId",  "cColumns", "puColumns", "piColFmt", "iGroup" });
        }
    }


text:
Q: Is there any way to realize if a number is truncated due to conversion? In a big code in C++ there are many calculations and castings (to different data types) to get in the end a float number, this number is being truncated or rounded somewhere in these big calculations and castings.
For example instead of getting the right and precise number 0.2500992 I get rounded number 0.2501.

*

*Is there any compiler warnings if the number will be truncated due to conversion ?

*Is there any known software that may go over the code and tells me what number may be truncated?

*In which situation truncation of float number will happen (when converting to which data type)?

*Does compiler round up float number? Can I tell compiler not to round up?

Thanks

A: I have found that there is a small error happened when subtracting two floating point numbers, I did the calculation using another method which is ceil() and 1 floating point manipulation instead of three floating point manipulations (first method).
It gives different result but the two results are constant either 0.2500992 or 0.2501.
In my opinion the solution is the method with ceil since it has less floating point manipulations small errors.
here is my code to explain clearly the issue I am facing.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define PARTS_PER_MILLION 1000000
#define FLOATING_POINT_ERROR 0.00001

int main()
{
  float ppm_f free_hd_ports;
  float totalAllocatedVideoParties = 1.749899983406066894531250000000;
  float num_hd720_vid_ports= 1.749899983406066894531250000000;
  unsigned short min_video_parties = 30,numVidHD720Parties = 28,numVidCifParties = 84,numVidHDParties;
  char buffer[25];
  unsigned long ppm1,ppm2;

//method 1
  numVidHD720Parties = floor(min_video_parties - totalAllocatedVideoParties);
  free_hd_ports = (float)min_video_parties - totalAllocatedVideoParties;

  ppm_f = (free_hd_ports - numVidHD720Parties);

  printf("ppm_f calculated by method with floating point subsctraction: %.20f\n",ppm_f);

//method 2
  numVidHDParties  = (unsigned short)ceil(num_hd720_vid_ports);
  ppm_f = ((float)numVidHDParties) - num_hd720_vid_ports;

  printf("ppm_f calculated by ceil method: %.20f\n",ppm_f);
}

Screen:
ppm_f calculated by method with floating point subsctraction: 0.25009918212890625000
ppm_f calculated by ceil method: 0.25010001659393310547

This example shows the the floating point calculation error described in the below link as mentioned before:
http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html


text:
Q: Symfony2 CMF Routing Auto Bundle - can't install I am trying to setup the Symfony2 CMF but experiencing trouble installing symfony-cmf/routing-auto-bundle. The tutorials I have followed appear to indicate this should be simple with composer, but I See the following error.
Problem 1
    - Installation request for symfony-cmf/routing-auto-bundle dev-master -> satisfiable by symfony-cmf/routing-auto-bundle[dev-master].
    - symfony-cmf/routing-auto-bundle dev-master requires symfony-cmf/routing-auto 1.0.* -> no matching package found.

My composer.json is below.
{
    "name": "symfony/framework-standard-edition",
    "license": "MIT",
    "type": "project",
    "description": "The \"Symfony Standard Edition\" distribution",
    "autoload": {
        "psr-0": { "": "src/", "SymfonyStandard": "app/" }
    },
    "repositories": [
        {
            "type": "package",
            "package": {
                "name": "jquery/jquery",
                "version": "1.11.1",
                "dist": {
                    "url": "http://code.jquery.com/jquery-1.11.1.js",
                    "type": "file"
                }
            }
        }
    ],
    "require": {
        "php": ">=5.3.3",
        "symfony/symfony": "2.5.*",
        "doctrine/orm": "~2.2,>=2.2.3",
        "doctrine/doctrine-bundle": "~1.2",
        "doctrine/data-fixtures": "1.0.*",
        "twig/extensions": "~1.0",
        "symfony/assetic-bundle": "~2.3",
        "symfony/swiftmailer-bundle": "~2.3",
        "symfony/monolog-bundle": "~2.4",
        "sensio/distribution-bundle": "~3.0",
        "sensio/framework-extra-bundle": "~3.0",
        "incenteev/composer-parameter-handler": "~2.0",
        "mailgun/mailgun-php": "~1.7.1",
        "symfony/monolog-bundle": "~2.4",
        "braincrafted/bootstrap-bundle": "~2.0",
        "twbs/bootstrap": "3.0.*",
        "twbs/bootstrap-sass": "3.1.*",
        "jquery/jquery":  "1.11.*",
        "friendsofsymfony/user-bundle": "~2.0@dev",
        "jackalope/jackalope-doctrine-dbal": "1.1.*",
        "doctrine/phpcr-odm": "1.1.*",
        "doctrine/phpcr-bundle": "1.1.*",
        "symfony-cmf/symfony-cmf": "1.1.*",
        "symfony-cmf/routing-auto-bundle": "dev-master",
        "sonata-project/doctrine-phpcr-admin-bundle": "1.2.*@dev",
        "doctrine/data-fixtures": "1.0.*@dev"

    },
    "require-dev": {
        "sensio/generator-bundle": "~2.3"
    },
    "scripts": {
        "post-root-package-install": [
            "SymfonyStandard\\Composer::hookRootPackageInstall"
        ],
        "post-install-cmd": [
            "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
                     "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
                "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::removeSymfonyStandardFiles",
            "Braincrafted\\Bundle\\BootstrapBundle\\Composer\\ScriptHandler::install"
        ],
        "post-update-cmd": [
            "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::removeSymfonyStandardFiles",
            "Braincrafted\\Bundle\\BootstrapBundle\\Composer\\ScriptHandler::install"
        ]
    },
    "config": {
        "bin-dir": "bin"
    },
    "extra": {
        "symfony-app-dir": "app",
        "symfony-web-dir": "web",
        "incenteev-parameters": {
            "file": "app/config/parameters.yml"
        },
        "branch-alias": {
            "dev-master": "2.5-dev"
        }
    }
}

Any help much appreciated!

A: there is no stable release of RoutingAutoBundle yet, so its correct that you specify "dev-master", however the bundle also uses a RoutingAuto component that is also not yet released as stable. you have 2 options now:
1) add a dependency on "symfony-cmf/routing-auto": "dev-master"
2) set "minimum-stability": "dev"


text:
Q: Process image pixels in parallel I am looking for an efficient way to parallelize the computations in the two loops, since it take too much time to get the result
import numpy as np
import cv2
from utils import distort_point

img = cv2.imread('test.png')
height, width, channel = img.shape

n_width = int(width/2)
n_height = int(height/2)

dist_image = np.zeros((n_height,n_width,channel))

for i in range(height):
    for j in range(width):
        point = distort_point((j,i))

        x,y = point[0],point[1]

        if x <0:
            x = 0
        if y <0:
            y = 0
        if x>n_width-1:
            x = n_width-1
        if y>n_height-1:
            y = n_height-1
        dist_image[y,x,:] = img[i,j,:]

cv2.imwrite('out_test.jpg',dist_image)

basically, the distort_point function takes a pixel coordinates and map it to another coordinates using some math computations. set the output to the image boundaries if it's outside the limits, then move the pixel value to the new position (in another image)

A: You can use Numba to speed up your computation.
Numba provides JIT compilation of your code. Because your code is quite simple you just need to wrap it in a function and use the njit decorator (equivalent to @jit(nopython=True)
So for example:
from numba import njit

@njit
def process(img):
    ...
    # your code here below 'img = cv2.imread('test.png')'
    return dist_image

dist_image = process(img)

cv2.imwrite('out_test.jpg',dist_image)

You also need to apply the same decorator to distort_point definition


text:
Q: implement a semaphore It appears that glib provides mutexes and conditions as thread synchronization primitives, but what about generic semaphores (in the sense that they support the original P and V operations?)  Am I correct in understanding a GCond as equivalent to a binary semaphore, with g_cond_signal being equivalent to P, and g_cond_wait being equivalent to V?  But what about semaphores not restricted to a maximum value of 1?
I thought of something like this:
struct semaphore {
  int n;
  GMutex sem_lock;
  GCond sem_cond;
}

Where the P operation would now look something like this:
void semaphore_P (struct semaphore *sem)
{
   g_mutex_lock(sem->sem_lock);
   while (sem->n == 0)
     g_cond_wait(sem->sem_cond, sem->sem_lock);
   --sem->n;
   g_mutex_unlock(sem->sem_lock);
}

Is there a simpler way to get at the functionality of pthreads' sem_wait and sem_post from within glib?

A: An asynchronous queue can be used as a semaphore:

*

*initialization: GAsyncQueue *queue = g_async_queue_new();

*the V operation: g_async_queue_push(queue, GINT_TO_POINTER(1));

*the P operation: g_async_queue_pop(queue);
The size of the queue serves as the counter of the semaphore.
The second parameter to g_async_queue_push may be any pointer except for NULL.
However, if you want to use the semaphore for some consumer/producer task, then sending in a pointer to some data will be useful.
In some cases, a thread pool may fit even better.


text:
Q: Maven - use different java classes during 'test' and 'war' phase I'm using maven war plugin to build war package.
Before package is build test are executed. To preinitialize my database with sample data I use spring bean. I would like to have different data in my db for tests and different when application starts.
I was thinking that maybe it is possible to use two different spring initializer classes in 'test' and 'war' phases but I don't know how to achieve this.

A: You have to put the different classes you need into src/main/java or src/test/java or may be supplemental application.xml into src/main/resources or src/test/resources. The test initializer can be done by a Test class which initializes first before all tests are running (take a look at testng which has this kind of feature).

A: Your tests should not be using the production Spring context (xml) files.
Instead, if you need to access an ApplicationContext in your tests (or if you are using a base testcase class like AbstractTransactionalJUnit4SpringContextTests), set up a test-context.xml context which points to the test database configuration and the test data scripts.


text:
Q: whmcs upgrading 6.2.1 to 7.1.1 Error (enable query buffering ) I can't upgrade my whmcs
server information:

*

*cloudlinux

*mysql

*cpanel

whmcs 6.2.1
new version : 7.1.1
Error:

Unable to complete incremental updates: Unable to import the 6.3.0
  Alpha1 database file. Unable to import
  /home/domain/public_html/whmcs/client/resources/sql/upgrade630alpha1.sql:
  SQLSTATE[HY000]: General error: 2014 Cannot execute queries while
  other unbuffered queries are active. Consider using
  PDOStatement::fetchAll(). Alternatively, if your code is only ever
  going to run against mysql, you may enable query buffering by setting
  the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

Why?


text:
Q: Unclear variable syntax in example I got this code from a nice book but I don't understand why the variables in the main function are different from the variables in go_south_east function and they get treated as the same variables.
include <stdio.h>

void go_south_east (int *lat, int *lon)
{
    *lat = *lat - 1;
    *lon = *lon + 1;
}

main()
{
    int latitude = 32;
    int longitude = -64;
    go_south_east (&latitude, &longitude);
    printf("Avast! Now at: [%i, %i]\n", latitude, longitude);
    return 0;
}

To my opinion latitude and lat are different variables. And the same is for longitude and lon. Then how can C know that *lon, *lat are the references of &longitude, &latitude. To me it should be lon in one function and the same lon in the second function. Isn't it so?

A: It's because you pass an address to lon and lat to the function. The first parameter in the signature is int *lat. That corresponds with the first address you passed, in your case, latitiude.

A: You are mistaking the "formal parameters" for the actual values passed in. When a function is defined, you specify the variable type and the local name that you will use within that function. This variable name is completely local to the function and does not have anything to do with what is outside.
include <stdio.h>

void go_south_east (int *lat, int *lon)
{
  *lat = *lat - 1;
  *lon = *lon + 1;
}

The first variable is pulled off the stack and put in a local variable called lat which is a pointer to an address. It then pulls the second input variable from the stack and puts it into a local variable called lat which is also an integer pointer. The changes are not made to the variables, but to the location in the computer that they point to - a variable location within main.
main()
{
  int latitude = 32;
  int longitude = -64;
  go_south_east (&latitude, &longitude);
  printf("Avast! Now at: [%i, %i]\n", latitude, longitude);
  return 0;

}
longitude and latitude are local variables within main and those names are not seen outside the brackets that enclose them. When you call go_south_east, the compiler takes the address of latitude and the address of longitude (which are integer pointers) and puts them on the stack. It then calls go_south_east.  The function does not change the variables it has been given, but gets the address (which is to the variable within main) and changes the contents of that address. That is why the values have been changed when you return.


text:
Q: Selenium unexpectedly having issues I have been using selenium now for a while on a number of projects.
With code that was running I am now receiving the following error:
    C:\Users\%USER%\Miniconda\python.exe C:/Users/%USER%/PycharmProjects/c_r/quick_debug.py
    Traceback (most recent call last):
      File "C:/Users/%USER%/PycharmProjects/c_r/quick_debug.py", line 17, in <module>
        c.setUp()
      File "C:\Users\%USER%\PycharmProjects\c_r\c.py", line 40, in setUp
        self.driver = webdriver.Chrome()
      File "C:\Users\%USER%\Miniconda\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 67, in __init__
        desired_capabilities=desired_capabilities)
      File "C:\Users\%USER%\Miniconda\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 87, in __init__
        self.start_session(desired_capabilities, browser_profile)
      File "C:\Users\%USER%\Miniconda\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 141, in start_session
        'desiredCapabilities': desired_capabilities,
      File "C:\Users\%USER%\Miniconda\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 201, in execute
        self.error_handler.check_response(response)
      File "C:\Users\%USER%\Miniconda\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 181, in check_response
        raise exception_class(message, screen, stacktrace)
    selenium.common.exceptions.WebDriverException: Message: unknown error: unrecognized Blink revision: 3b3c00f2d95c45cca18ab944acced413fb759311
      (Driver info: chromedriver=2.10.267521,platform=Windows NT 6.3 x86_64)

    Process finished with exit code 1

where c.setUp() is:
def setUp(self):
   self.driver = webdriver.Chrome()

Again -  this is code that WAS running and I am unsure how to this "Unrecognized blink revision" error.
Nothing has consciously changed.
Thank you for any pointers

A: After having a quick look at the source code, I think this is a compatibility issue between ChromeDriver and Chrome itself - I suspect your Chrome auto-updated and now is too new for ChromeDriver 2.10.
In other words: update ChromeDriver, latest is currently 2.19.


text:
Q: Shell script: Simple parameter comparison doesn't work I have the following shell script:
#!/bin/sh
# Musikscript für Android-App
#sudo killall -9 mplayer
#sudo  mplayer -ao alsa:device=hw=0.0 -playlist /home/pi/media/radio/ANTENNE-BAYERN.m3u   &
echo $1
echo $2

if [ "$1" = "playlist" ]
then
    sudo mplayer -ao alsa:device=hw=0.0 -playlist $2 &
fi

if [ "$1" = "playfile" ]
then
    sudo mplayer -ao alsa:device=hw=0.0 $2 &
fi

if [ "&1" = "stop" ]
then
    sudo killall -9 mplayer
fi

if [ "$1" = "volume" ]
then
    sudo amixer set PCM $2
fi

When I try to run a file with:
sudo sh /home/pi/scripts/mplayerscript.sh "playlist" "/home/pi/media/radio/ANTENNE-BAYERN.m3u"

It works without a problem, but
sudo sh /home/pi/scripts/mplayerscript.sh "stop"

only executes the 2 echo lines.

A: "&1" = "stop".. I think you meant "$1" = "stop" :)

A: Yep, I think you meant $1 instead of &1.
But when you have a script like that, conditions based on only one parameter, like $1 in your script, it's way easier to use "case".
case "$1" in
"playlist")
  sudo mplayer -ao alsa:device=hw=0.0 -playlist $2 &
 ;;

"playfile")
 sudo mplay -ao alsa:device=hw=0.0 $2 &
 ;;

"stop")
 sudo killall -9 mplayer
 ;;

"volume")
 sudo amixer set PCM $2
 ;;

esac


text:
Q: Make data frame with ratios of every column against every other This is similar to but not exactly the same as: calculate ratios for every 2 columns in a data frame
I have a data frame where I want to make a ratio of every column versus every other (in one direction is okay, I don't need both.)
df <- bind_cols(x = c(1, 2, 3), y = c(2, 3, 4), z = c(3, 4, 5))

ratios_df <- df %>%
  mutate(x_y = x/y,
         x_z = x/z,
         y_z = y/z) %>%
  select(-c(x:z))

How can I make a more automated approach to generating ratios_df?

A: You can use combn to combine the columns together and then divide the first with the second:
combn(df, 2, function(x) x[[1]] / x[[2]])
          [,1]      [,2]      [,3]
[1,] 0.5000000 0.3333333 0.6666667
[2,] 0.6666667 0.5000000 0.7500000
[3,] 0.7500000 0.6000000 0.8000000

You can add the names too:
nam = combn(names(df),2,paste,collapse="_")
`colnames<-`(combn(df,2,function(x)x[[1]]/x[[2]]),nam)
           x_y       x_z       y_z
[1,] 0.5000000 0.3333333 0.6666667
[2,] 0.6666667 0.5000000 0.7500000
[3,] 0.7500000 0.6000000 0.8000000

A: library(dplyr)

df <- bind_cols(x = c(1, 2, 3), y = c(2, 3, 4), z = c(3, 4, 5))

df_ratios <- as.data.frame(lapply(df, function(x) x/df))
df_ratios
# x.x       x.y       x.z      y.x y.y       y.z      z.x      z.y z.z
# 1   1 0.5000000 0.3333333 2.000000   1 0.6666667 3.000000 1.500000   1
# 2   1 0.6666667 0.5000000 1.500000   1 0.7500000 2.000000 1.333333   1
# 3   1 0.7500000 0.6000000 1.333333   1 0.8000000 1.666667 1.250000   1

df_ratios <- df_ratios[, sapply(strsplit(colnames(df_ratios), "\\."), function(x) x[1] > x[2])]
# y.x      z.x      z.y
# 1 2.000000 3.000000 1.500000
# 2 1.500000 2.000000 1.333333
# 3 1.333333 1.666667 1.250000

A: Another approach is to use combn to create the combination first and then do the calculations:
combos <- combn(names(df), 2, simplify = FALSE)

l2 <- lapply(combos, function(x) df[[ x[1] ]] / df[[ x[2] ]])

ratios_df <- setNames(as.data.frame(l2), sapply(l, paste, collapse = '_'))

which gives:

> ratios_df
        x_y       x_z       y_z
1 0.5000000 0.3333333 0.6666667
2 0.6666667 0.5000000 0.7500000
3 0.7500000 0.6000000 0.8000000


text:
Q: How to speak to a computer I am a self-taught, novice programmer. The language I chose was Objective-C, so that I can write Apple applications and software. I have learned the hard way that Objective-C has a steep learning curve, but I have forced myself to look at it over and over until I get it right.
I feel I am completing one major step, and that is becoming very comfortable with the syntax. Now as I enter the next big step - finding out what is possible with a computer programming language - I am thinking that all software is just developed within the confines of:

*

*classes

*loops

*booleans

*IF/OR statements

*variables

*etc.

Is that a true assessment? When thinking of software in my head do I just need to learn to convert it all to the above? Right?
Sorry if this question sounds funny, but I am just learning how to take the language in and talk (what I think is) the language of a computer. Is there a good book or tutorial that helps illustrate how to "speak as a computer would"?

A: Fundamentally, computers can only do a few basic things:

*

*They can perform simple arithmetic

*They can execute instructions sequentially

*They can branch to another instruction, based on a condition

*They can loop (a variation of branching)

*They can move data from one place to another

*They can store data and retrieve it for later use.

That's about it.  Everything you see a computer do is just an elaborate abstraction over these simple operations.
Programming languages are one of those abstractions.  They allow us to speak the computer's language (technically, machine code), using a symbolic language that is closer to the language we humans use to communicate.  Programs called compilers translate programming languages into machine code, so that the machine can execute our instructions, just as we specified them.
There are many different computer languages, each optimized for a particular way of thinking or problem solving.  These ways of thinking are called paradigms; many programming languages support more than one paradigm.  Objective C is just one such language.
The way each computer programmer gets started is as individual as your fingerprints.  If you really want to "get" the idea of computers, my advice is to learn more than one language.  Study other languages; see how they differ.  See how they all have certain things in common; although they might solve a problem differently, at their core they still resolve down to the same fundamental operations.

A: First-Class Functions
Another useful feature that a programming language can have is first-class functions.  A first-class function is a function that can be used as data.
In a language in which you can treat functions as data, you can create variables that refer to them, pass them around as arguments to functions, and return them from functions.  Once case where you might use this is the famous map function.
Say that I just got some string from a file or something and that the string contains a series of integers separated by spaces.  Say I use a string-splitting function to get an array of strings containing each of the integers (still as strings).  I have access to a library function to parse an integer from a string, and I want to use it to convert each of these strings containing integers to actual integer values.  I create the new array and write a loop to convert each string and store the resulting integer in the new array.
Now say I want to take a different array of integers and find the absolute value of each and store the results in a new array.  I can use another loop to do this.  However, I have this pattern showing up in my code: start with an array, perform some transformation of each value in the array, and store all of the results in a new array.  I could just write out the code to do this each time, but there is a way to abstract out the process of creating the new array, looping, transforming, and storing.
I can write a function that takes as arguments

*

*an array of type x

*a function for somehow transforming objects of type x into objects of type y (possibly the same type as x)

and have it create an array of elements of type y of the correct length, loop over the values in the original array, call the function argument to do the transformation, store the results in the new array, and return the new array.
After I've written this function, map, I don't have to write this code out by hand any more.
Objective-C should have function pointers because C has them.
The way I described map also took advantage of some sort of generic typing.
Closures
Another feature is closures.  A closure is a function object that captures some of the variables that existed in the scope in which it was created.  What does that mean?
Some languages let you write function literals, functions that don't (necessarily) have names and just appear in you code without a special separate declaration.  When you write a function literal in another function, there might be variables in the same scope as the function literal.  There are situations where you might find it useful to use those variables inside of the function literal and have those variables stay with the function object.  Such a function object would be a closure.
Here's an example of code that I wrote that creates a closure (written in Common Lisp):
(defun exponential-change (function constant)
  (lambda (time)
    (* (expt constant time) (funcall function time))))

(Don't ((let (the) parentheses) scare you)).  Think of it as being written like this:
function exponential_change (function, constant) {
    return function (time) {
        return exponent(constant, time) * function(time);
    };
}

I wrote this for synthesizing sound.  I represent a sound as a function of time that returns amplitude samples (-1 to 1).  This function, exponential-change, transforms a sound by making the amplitude increase or decrease (depending on the constant) in an exponential fashion.  exponential-change creates returns a function of time based on another function of time.  The fact that the new function keeps track of what function it needs to modify prevents other code from having to keep track of that detail.
Closures not only keep track of the values of the variables they capture but also the variables themselves.  This means that you could create a function that modifies those variables.


text:
Q: Class Instance in YAML file I have a test.yaml file in /opt directory in Ubuntu in which I have my db settings and I get that file in environment.rb  as shown
require File.expand_path('../application', __FILE__)
class Settings
raw_config = File.read("/opt/test.yml")
erb_config = ERB.new(raw_config).result
settings = YAML.load(erb_config)[::Rails.env]
 if settings
  settings.each  do |name, value|
  puts "checking array" , name, value
  instance_variable_set("@#{name}", value)
  self.class.class_eval { attr_reader name.intern }
 end
 end
end

Now in mongoid.yml file i want to use that class as shown in code
development:
 sessions:
  default:
   hosts:
    -Settings.sessions["default"]["hosts"]
  username: ve
  password: "123456"
  database: weather

but getting error like this
Moped::Errors::ConnectionFailure (Could not connect to any secondary or primary nodes for replica set ]>):
I am a new guy and stuck there.Any help will be much appreciated.
Thanks

A: Theory:
They key is to delete mongod.lock file and start mongodb service again. The lock file in Ubuntu is located at /var/lib/mongod.lock.
Details:
I was getting the same error under Ubuntu, this is what I did:

vagrant@lucid32:~$ sudo service mongodb restart

restart: Unknown instance:
vagrant@lucid32:~$ sudo rm /var/lib/mongod.lock
vagrant@lucid32:~$ sudo service mongodb start

mongodb start/running, process 2340
vagrant@lucid32:~$ sudo service mongodb restart

mongodb start/running, process 2368