text:
Q: Razor web pages: How do I create variable that is available to all pages? I have a lot of pages that is using the same variables. I would like to create these in a single page so I dont have to type them over and over again. How do I do this?
I tried both _appStart.cshtml and _PageStart.cshtml, but when i run my content page i get error "the name selectedData does not exist in the current context"
Here is my _PageStart.cshtml: (tried _appstart.cshtml too)
@{
var db = Database.Open("razortest");
var selectQueryString  = "SELECT * FROM tbl_stasjon ORDER BY nr";
var selectedData = db.Query(selectQueryString);
}

And all of my pages includes this:
@foreach(var row in (selectedData)) {

html here...

}

A: For a fairly straight-forward solution you could create a static class/method within App_Code that returns your query object and then call that method wherever you need it:
using System;
using System.Collections.Generic;
using System.Web;
using WebMatrix.Data;

public static class MyClass
{
    public static IEnumerable<dynamic> GetData()
    {
        var db = Database.Open("razortest");
        var selectQueryString  = "SELECT * FROM tbl_stasjon ORDER BY nr";
        return db.Query(selectQueryString);
    }
}

Then in your scripts you can do:
@foreach(var row in MyClass.GetData()) {
    html here...
}

There will likely be more elegant and performant ways to achieve this but they depend on what exactly you're doing. For the purposes of following a tutorial this should serve your purposes.

A: You could get use of the session and try to use a controller.
See

*

*Adding a Controller

*Adding a View

*Adding a Model
Override OnActionExecuting within your controller (wihtin the constructor the Session is not available)
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    base.OnActionExecuting(filterContext);
    if (Session != null)
        Session["selectedData"] = "Hello World";
}

And within the Action
Public ActionResult View1(){
     return View(Session["selectedData"];
}

Within your view you can handle this data
@{
ViewBag.Title = Model;
}

That's a simple solution with a string. You can create strongly typed views and get a very comfotable way to handle this data within your views.


text:
Q: IF logic in jekyll markdown On my jekyll blog there is already a page that lists all the categories and all their respective posts, here is the code:
{% for category in site.categories %}

{{ category | first }}

    {% for posts in category %}
      {% for post in posts %}

{{ post.title }}

          {{ post.date | date: "%B %-d, %Y" }}

      {% endfor %}
    {% endfor %}

{% endfor %}

My question is, how can I show only the posts on categoryX for example?
I realize this is probably something simple but couldnt find anywhere how to, I tried changing for posts in category to for posts in categoryX but it didnt work

A: To list a specific category you can specify it using site.categories.CATEGORY so it list all Posts in category CATEGORY.
For example, if you have a category called "diet" the you can filter its posts with {% assign posts = site.categories.diet %}{% for post in posts %}.. or {% assign posts = site.category['diet'] %}
Look at some of the Jekyll variables here: https://jekyllrb.com/docs/variables/

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to rename a local APT repository? I follow the steps in this post to create a custom repository, but I want to rename it. I can't find any way to do it. Can you please help me?

A: Sounds like you want to know how to rename a package.  There are two ways to do this.   In this example, I'm going to change the name of cowsay to mysay
From source
Download the debian  (or ubuntu) source package, rename the files as appropriate, replace the old name with the new name in the debian/* directory (that's what the sed lines are doing, then build it with dpkg-buildpackage.
Be a little careful, because some packages may have build rules which depend on the package name and may not be as trivial as cowsay.  This is probably the toughest option.
apt source cowsay
mv cowsay-3.03+dfsg2 mysay-3.03+dfsg2
mv cowsay_3.03+dfsg2-8.dsc mysay_3.03+dfsg2-8.dsc
mv cowsay_3.03+dfsg2.orig.tar.gz mysay_3.03+dfsg2.orig.tar.gz
cd mysay-3.03+dfsg2/
sed -i 's/\bcowsay\b/mysay/g' debian/changelog debian/control
sed -i 's./debian/cowsay./debian/mysay.g' debian/rules
dpkg-buildpackage -uc -us

From binary
Get the *.deb you want to manually split the archive up, edit the control file and then put it back togeather.
apt download cowsay
mkdir mysay && cd mysay

# Split everything up
ar -x ../cowsay_3.03+dfsg2-8_all.deb
mkdir control
tar -xf control.tar.xz -C control

# CHange the package name
sed -i 's/cowsay/mysay/' control/control

# Put the control file back togeather
cd control
tar -cf control.tar.xz *
mv control.tar.xz ../
cd ..
rm -r control

# Put the rest back togeather
ar r ../mysay_3.03+dfsg2-8_all.deb debian-binary control.tar.xz data.tar.xz

From binary (method 2)
This one simplifies the re-combining process. This is probably the easiest method.
apt download cowsay
ar x cowsay_3.03+dfsg2-8_all.deb
mkdir -p mysay/DEBIAN
tar -xf control.tar.xz -C mysay/DEBIAN
tar -xf data.tar.xz -C mysay/
sed -i 's/cowsay/mysay/' mysay/DEBIAN/control
dpkg-deb -b mysay

A few final notes:

*

*If you try to install cowsay and mysay on the same machine, one of the packages will fail.  That's because they both supply the same files, so it's impossible for your system to know which owns it.  A way to make this foolproof is to add a Conflicts: cowsay to the control file of mysay.

*Renaming packages is a little strange.  It is sure to cause the conflicts mentioned above.  I not sure I can picture a case where this is necessary.


text:
Q: Build Failed from Dev to Staging using TFS Release management I am trying to build a project from dev to staging environment, what all i did was just to merge the changes in dev to staging and trigger a build. but the build got failed even tried multiple times.
Below is the log file shared in google drive. there are no errors mentioned in the log file. Can anyone help me solve this problem.
https://drive.google.com/open?id=0B85ZmWDiKYHRVmN4MlMxc0ZEd28

A: I found a error in the log file in the release management, which says that "access denied for appsettings.config" file. I did remove the read only on the folder in the server and it worked. I am not sure of this fix properly, but it did work for me.
Thanks.


text:
Q: Django rest api problem: should either include a `querylist` attribute, or override the `get_querylist()` method This is my serializer class:
class JlistSerializers(serializers.ModelSerializer):
    class Meta:
        model = Jlist
        fields = ('id', 'name', 'news_channel', 'wiki', 'image', 'total_star', 'total_user')

This is my views
class JlistView(ObjectMultipleModelAPIView):
    queryset = Jlist.objects.all()

    def get_queryset(self, *args, **kwargs):
        userId = self.kwargs.get('pk')
        queryset = [
            {'queryset': Jlist.objects.all(),
             'serializer_class': JlistSerializers},
            {'queryset': JStarList.objects.filter(userId=userId),
             'serializer_class': JStarList}
        ]
        return queryset

I am getting followiing error
AssertionError at /api/jlist
JlistView should either include a `querylist` attribute, or override the `get_querylist()` method.

I have used the same code to create api for other serializer class but getting error in creating this api.Please help me figure out what is problem here?

A: You defined get_queryset, but it should be get_querylist. And remove queryset member too.
class JlistView(ObjectMultipleModelAPIView):

    def get_querylist(self, *args, **kwargs):
        userId = self.kwargs.get('pk')
        queryset = [
            {'queryset': Jlist.objects.all(),
             'serializer_class': JlistSerializers},
            {'queryset': JStarList.objects.filter(userId=userId),
             'serializer_class': JStarList}
        ]
        return queryset


text:
Q: String Matching from List of items Updating my question asked, I have an object search_string that stores the string.
> search_string

[1] "Bud Light - Mother EUR"
I have an another object of list that stores the Brand Names and Zone Names. Now using the search_string, i search it in the filter_values and returns what was year and what was Brand Name. I use the below command to achieve that.
> lapply(filter_values, function(x) {
    +       x[sapply(paste0('\\b',x,'\\b'), grepl,input$param$query, ignore.case=T)]
    +
    +     })
$Brand
[1] "Bud Light"          "Bud Light - Mother"

$Zone
[1] "EUR"

Now, issue i am facing is that if u notice in the output returned, searching for Bud Light - Mother
in the list also returns Bud Light which is not required.
How can i restrict it to return only what is entered/asked and not the closest matches also like returned right now.

A: An idea is to strip the search_string from the Year and match the Brand and vice versa, i.e.
Map(function(x, y) grep(x, y, value = TRUE),
         c(trimws(gsub('[0-9]{4}', '', search_string)), gsub('\\D+', '', search_string)),
         filter_values)

#$`Bud Light - Mother`
#[1] "Bud Light - Mother"

#$`2014`
#[1] "2014"

Same result can be achieved by using strsplit as per @Cath's comment,
Map(function(x, y) grep(x, y, value = TRUE),
    strsplit(search_string, "\\s(?=\\d{4})", perl=TRUE)[[1]],
    filter_values)


text:
Q: Default values for mandatory columns in SQLite (We're using SQLite Manager for Firefox). Are they necessary and if so, what should they be? My teammate made an SQLite database for our android app using SQLite Manager for Firefox but I noticed that most of the columns marked with an asterisk in the ERD do not have the constraint not null in the database he made. I asked him about it and he said he wasn't sure what to put for the default value. I've tried adding a column with a constraint myself. If I select not null but leave the default value blank I get this
SQLiteManager: ALTER TABLE "main"."productorder" ADD COLUMN "cart_id" INTEGER NOT NULL  [ Cannot add a NOT NULL column with default value NULL ]

I prefer that there isn't a default value for most of the columns but that the programmer is just prevented from making a row without giving a value.
We can give all mandatory columns default values if we have to. I found this question and it said that '' is acceptable as the default value for VARCHAR columns
Laravel migration with sqllite 'Cannot add a NOT NULL column with default value NULL'
However I don't know what the default value should be for foreign keys (like cart_id), dates, zipcodes, etc.


text:
Q: Is there a simple method to algebraically take a value outside of a trigonometric function argument Lets say I have a function $\sin(\frac{11\omega}{2})$ and I want to make the argument $\sin(\frac{\omega}{2})$,
I know that I cannot simply do this: $11*\sin(\frac{\omega}{2})$
So how would I go about removing the a constant from inside of a trig function?

A: Using DeMoivre's Theorem:
$$\left(\cos \theta +i\sin \theta \right)^n=\cos n\theta +i\sin n\theta $$
We observe that the imaginary parts must be equal.
Case 1:n is odd.
$$\sin \left(n\theta \right)=\sum _{k=0}^{\frac{\left(n-1\right)}{2}}\binom{n}{2k+1}\sin ^{2k+1}\left(\theta \right)\cos ^{\left(n-\left(2k+1\right)\right)}\left(\theta \right)$$
Case 2: n is even
$$\sin \left(n\theta \right)=\sum _{k=1}^{\frac{\left(n\right)}{2}}\binom{n}{2k-1}\sin ^{2k-1}\left(\theta \right)\cos ^{\left(n-\left(2k-1\right)\right)}\left(\theta \right)$$

A: You can trade $\cos nx$ and $\sin nx$ for polynomials in $\cos x,\sin x$. Similarly, you can trade the powers $\cos^n x,\sin^n x$ for linear combinations of $\cos kx,\sin kx$.
I am not sure that this will help you.

A: Building on @YvesDaoust 's answer, and from a section of Wikipedia's trigonometric identities page, we have:
$$\sin{(a \pm b)} = \sin{(a)}\cos{(b)} \pm \cos{(a)}\sin{(b)} \tag{1}$$
$$\cos{(a \pm b)} = \cos{(a)}\cos{(b)} \mp \sin{(a)}\sin{(b)} \tag{2}$$
so that you could split the trig that way.  These, especially (1), can be used to derive the double angle formula
$$\sin{(2a)} = 2\sin{(a)}\cos{(a)} \tag{3}$$
You can also consider the multiple angle formula found on the same page here.  It's basically an extension of (3).


text:
Q: Difficulty getting data from Sqlite database between two days I was doing an Android app that generates sales report for dates between the current date and seven days in the past. It worked fine, here's the code:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR,-7);

String currentDate = new SimpleDateFormat("dd-MM-yyyy").format(new Date());

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

String sevenDayAgo = sdf.format(calendar.getTime());

Cursor weeklyIncome = db.getResult("select sum(price) as total_income from sales where date between '"+sevenDayAgo+"' and '"+currentDate+"'");
Cursor weeklyCost = db.getResult("select sum(purchase_price * quantity) as total_cost from sales where date between '"+sevenDayAgo+"' and '"+currentDate+"'");

Say for example currentDate = 31-08-2018 and sevenDayAgo = 24-08-2018 this all worked fine but when I change my system date to the next day which is the next month and currentDate becomes 01-09-2018 the query doesn't return anything from the database, it should have returned records between 25-08-2018 and 01-09-2018 which has seven days in between. Somehow the query doesn't work when the 7 days are in two different months. I don't know what's going on and how to fix it.
p.s. The date column in sales table is of type TEXT.

A: The problem is the format you're using for dates (dd-mm-yyyy) isn't in lexicographic order. The string '25-08-2018' compares greater than '01-09-2018' . x BETWEEN y AND z is equivalent to x >= y AND x <= z. That condition won't be true for dates in that range using your format (Remember, they're just strings. sqlite does not have a date type.
You should be using ISO-8601 formats, like yyyy-mm-dd. These will sort properly ('2018-08-25' < '2018-09-01') and will allow you to use the sqlite3 date and time functions on them.

A: Suppose user has entered the birth date in 31/08/2018 this format :
Parse it like :
String[] parts = BirthField.getText().toString().trim().split("/");
int CAL_DAY, CAL_MONTH, CAL_YEAR;
if(parts.length == 3)
{
    CAL_DAY = Integer.parseInt(parts[0]);
    CAL_MONTH = Integer.parseInt(parts[1]);
    CAL_YEAR = Integer.parseInt(parts[2]);
}

You can check if user has entered a good date or not with :
if( CAL_DAY > 0 && CAL_DAY < 32 && CAL_MONTH > 0 && CAL_MONTH < 13 && CAL_YEAR > 1900 )

While storing in database table take below care :
Calendar CalendarEvent = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
CalendarEvent.set(Calendar.DATE, CAL_DAY);
CalendarEvent.set(Calendar.MONTH, CAL_MONTH - 1);
CalendarEvent.set(Calendar.HOUR_OF_DAY, Integer.parseInt(ScheduleTime) );
CalendarEvent.set(Calendar.MINUTE, 00);
CalendarEvent.set(Calendar.SECOND, 00);
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.getDefault());
String DayConsidered = format.format(CalendarEvent.getTime());

Please note CAL_MONTH - 1 as system starts months from 0 to 11
While storing store in database in SystemTime like :
SYSTIME = CalendarEvent.getTimeInMillis();

While using it again retrieve it from database and initialise calendar event with it like :
Calendar CalendarEvent = Calendar.getInstance();
CalendarEvent.setTimeInMillis( Long.parseLong(SYSTIME) );

int CAL_DAY = CalendarEvent.get(Calendar.DAY);
CalendarEvent.set(Calendar.DATE, CAL_DAY - 7);

And it will start working for even if days / months / even you change years from any date; it will always show the date which is less than 7 days
Hope it helps and let me know how it works as i am answering it quick...

Edit : 2

Better and most efficient way which i am using in my project and working perfectly is :
Log.d("ADDING A MONTH :", "ADDING 1 MONTH....\n");
CalendarEvent.add(Calendar.MONTH, 1);

Log.d("NEGATING 7 DAYS :", "NEGATING 7 DAYS....\n");
CalendarEvent.add(Calendar.DATE, -7);


text:
Q: How to grab a href from a specific URL by class? I need Excel VBA code which triggers when a username is entered into a specific cell within a spreadsheet. This then navigates to the Web page which in this instance is a work directory. It then finds the div class "panel bg-brick-red managed-by"> and returns the href associated with that class as a string.
I then wish to extract from that string a specific part of the href  and paste it into a cell within the spreadsheet.
So you type a username into a specific cell in your spreadsheet to trigger the sub, it navigates to the url of our internal directory to find the person and then grabs from that page their line manager's pay number from the href by stripping that pay number from the href and then pastes the result into a nominated result cell within Excel.

A: A flexible way to extract something from a string is with a Regular Expression pattern match. Add a reference to Microsoft Internet Controls.
Option Explicit

Sub ExtractFromURL()

    Dim IE As Object, URL As String
    Dim links As Object, link As Object
    Dim href As String, PayNo As String

    Set IE = New InternetExplorerMedium
    IE.Visible = True

    URL = "http://some/web/page"
    IE.navigate URL

    Do Until IE.readyState >= 4
        DoEvents
    Loop

    ' find element
    Set links = IE.document.getElementsByClassName("panel bg-brick-red managed-by")
    Set link = links(0).getElementsByTagName("a")
    href = link(0).href

    ' build regex to pattern match PayNp
    Dim regex As Object, m As Object 'match
    Set regex = CreateObject("vbscript.regexp")
    With regex
       .Global = False
       .MultiLine = False
       .IgnoreCase = True
       .Pattern = "(\d{5,6})" 'a number with 5 to 6 digits
    End With

    ' extract number
    If regex.test(href) Then
         Set m = regex.Execute(href) ' match
         PayNo = m(0)
         MsgBox PayNo & " extracted from " & href
    Else
         MsgBox "No number in " & href
    End If
    IE.Quit

End Sub


text:
Q: Problem about Func class Program
{
    static void Main()
    {
        int i = 0;
        whatever x = new whatever(i);
        Console.WriteLine(x);
        i = 1;
        Console.WriteLine(x);
        Console.ReadKey();
    }

    class whatever
    {
       public whatever(object variable)
       {
           this.variable = () => variable.ToString();
       }

       private Func<string> variable;
       public string data;

       public override string ToString()
       {
           data = variable();
           return data;
       }
}

Output:
0
0

what I want to do is get updated i's value.

A: If you want to capture the local variable then you've put the lambda in the wrong place. The lambda has to go where it can be closed over the outer variable you want to capture.
class Program
{
    static void Main()
    {
        int i = 0;
        var x = new Whatever<int>(()=>i);
        Console.WriteLine(x);
        i = 1;
        Console.WriteLine(x);
        Console.ReadKey();
    }
}

class Whatever<T>
{
   private Func<T> variable;
   public Whatever(Func<T> func)
   {
       this.variable= func;
   }
   public override string ToString()
   {
       return this.variable().ToString();
   }
}

Does that make sense? See, the lambda has to be where the "i" is declared, so that "i" is an outer variable of the lambda and therefore the lambda sees changes to it.

A: i is an integer (value type), which is passed by value - a copy of the value is passed to the whatever constructor. When you change its value on the Main method, it doesn't change what has been already passed to the class. So you can't get the updated value on whatever.
If you have an object which holds a field of an integer value, and then pass that object to whatever, then changes to that field will be reflected on the class.

A: Maybe the problem is that delegate is bound to boxed integer data. This is why you change your int and delegate evaluates to old boxed data.
Try it with constructor that takes an int.
But, yes it's true that ints are pased by value, so this will not work.
Pass delegate to ctor.
class Program
{
        static void Main()
        {
            int i = 0;
        whatever x = new whatever(() => i.ToString());
        Console.WriteLine(x);
        i = 1;
        Console.WriteLine(x);
        Console.ReadKey();
    }

    class whatever
    {
        public whatever(Func<string> someFunc)
        {
            this.variable = someFunc;
        }

        private Func<string> variable;
        public string data;

        public override string ToString()
        {
            data = variable();
            return data;
        }
    }
 }

Output:
0
1
Or as other have indicated:
class Program
{
    static void Main()
    {
        var myRefType = new MyRefType();
        myRefType.MyInt = 0;

        var x = new whatever(myRefType);
        Console.WriteLine(x);
        myRefType.MyInt = 1;

        Console.WriteLine(x);
        Console.ReadKey();
    }

    class whatever
    {
        public whatever(MyRefType myRefType)
        {
            this.variable = () => myRefType.MyInt.ToString();
        }

        private Func<string> variable;

        public override string ToString()
        {
            return variable();
        }
    }

    class MyRefType
    {
        public int MyInt { get; set; }
    }
}

Outputs:
0
1

A: Integers are of value type, not reference type.

A: int is value type, meaning its value is copied each time you use it and not its reference. The best way to make this work is make reference type around int:
class IntRef
{
    public int Val;
}

You will need to always use IntRef.Val and passing the IntVal itself around will retain the reference.


text:
Q: Magento 2.2.1: Attribute values sort by name I write here for an help.
Magento 2.2.1: For a few days I'm using Magento 2, after I used it for a couple of years Magento 1. I am aware of the presence of an important discomfort: attribute values are not sorted alphabetically, but only by order of insertion.
It's a serious problem, especially if the variables are so many. How can I fix it?
I tried to follow the other solutions in this forum, but I could not solve it.
Thank you in advance

A: The fixes works in Magento 2.1.x but in 2.2.x the classes has been refactored and previous workaround stop working.
Info about the issue here:
https://github.com/magento/magento2/issues/7441


text:
Q: Android: Refreshing listView of neighboring tab inside Viewpager not working I have a viewpager with many tabs in my app. From one of the tabs (say A) I want to change the listView in the neighboring tab (say B). The tab B has an adapter that extends ArrayAdapter. This is what I am doing.
In Tab A
ParentFragment parentFragment = (ParentFragment)getParentFragment();
List<Fragment> fragmentList = parentFragment.getChildFragmentManager().getFragments();
for (Fragment fragment : fragmentList) {
    if (fragment instanceof TabB) {
        ((TabB) fragment).adapterB.add(name);
        ((TabB) fragment).adapterB.notifyDataSetChanged();
        break;
     }
}

I am not sure if this is the ideal way but I think it should work. However the list in Tab B remains the same when I navigate to B. What is the problem with my approach. Any help would be appreciated. Thanks !!


text:
Q: How can I deserialize xml with 2 different types of the same xml element and property name? In the database, we have an xml field that contains 2 validation schemas; the old one does not have a namespace, the new one does. The reason for this is that we had to version one of the properties. Here is an example of the differences:
Version 1
<PropertyA>
  <PropertyA1>false</PropertyA1>
  <PropertyA2>3.23</PropertyA2>
</PropertyA>

Version 2
<ts:PropertyA xmlns:ts="http://www.example.com/v2">
  <ts:PropertyA1>false</ts:PropertyA2>
  <ts:PropertyA2>
    <ts:PropertyA2a>
        <ts:PropertyA2a1>City 1</ts:PropertyA2a1>
        <ts:PropertyA2a2>3.23</ts:PropertyA2a2>
    </ts:PropertyA2a>
    <ts:PropertyA2b>
        <ts:PropertyA2b1>City 2</ts:PropertyA2b1>
        <ts:PropertyA2b2>1.21</ts:PropertyA2b2>
    </ts:PropertyA2b>
  </ts:PropertyA2>
</ts:PropertyA>

Basically, we just create multiple options for PropertyA2...
So now the isue is deserialization. This object needs to be deserialized into the same data object in the app code and the problem is that the element name is the same so the serializer is obviously having trouble figuring out which object to deserialize into since sometimes the database will return Version 1 and sometimes it will return Version 2.
Here is an example of the data class being used for serialization and my current approach that isn't quite working:
[Serializable]
public class MyDataClass
{
    // ... other stuff

    [XmlElement(Name = "PropertyA", typeof(V1.PropertyA), Namespace = "")]
    public V1.PropertyA PropertyAV1 { get ;set; }

    [XmlElement(Name = "PropertyA", typeof(V2.PropertyA), Namespace = "http://www.example.com/v2")]
    public V2.PropertyA PropertyAV2 { get; set; }
}

[Serializable]
public class V1.PropertyA
{
    public bool PropertyA1 { get; set; }

    public decimal PropertyA2 { get; set; }
}

[Serializable]
public class V2.PropertyA
{
    public bool PropertyA1 { get; set; }

    public List<SomeOtherThing> PropertyA2 { get; set; }
}

When I go to deserialize V1, it works fine. When I go to deserialize V2, i get an error Did not expect <ts:PropertyA xmlns:ts="http://www.example.com/v2"> so I'm thinking there's a parameter I'm missing in the deserialize method:
public MyDataClass Deserialize(string xml)
{
    var s = new XmlSerializer(typeof (MyDataClass));
    MyDataClass info = null;
    using (var r = new StringReader(xml))
    {
        info = (MyDataClass) s.Deserialize(r);
    }
    return info;
}

I believe you can set the expected namespace in the serializer, but since I don't know what the namespace is going to be until I actually inspect the xml document, I'm not sure how to proceed.
So my question is this: Is what I'm trying to do even possible? Am I on the right track? Is there a better solution that is maybe less contrived? How can I have the serializer deal with the new namespace and deserialize to the correct properties?

A: You can't.
The problem here is that you have to hardcode MyDataClass according to a single XMLSchema. If the XMLSchema alters, MyDataClass is no longer a valid target for the XMLSerializer's deserialize method, which is why you're getting the 'Did not expect ...' error message. In this case, when reading the V2 xml data stream, the deserialize method tries to fill MyDataClass#PropertyAV1 with the content of <ts:PropertyA2> and there is no way of telling it to instead fill MyDataClass#PropertyAV2. Even if there was a way to achieve this, you'd be stuck with an undefined value for MyDataClass#PropertyAV1 in the object of type MyDataClass.
So there are two solutions to the problem at hand :
a) Stick with XMLSerializer and define class MyDataClass like so
    public class MyDataClass
    {
        // only one Property here, as there's only one root element in the xml
        // and this single Property is not bound to a specific XML element
        [XmlAnyElement]
        public PropertyA PropertyA { get ;set; }
    }

You then have to analyze the contents of PropertyA yourself and build some logic around it, see here for more details :
http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlanyelementattribute.aspx
b) Dispense the XMLSerializer, read the XML data stream with XMLReader and do the all the parsing of the xml yourself, also add logic to create the according C# objects, depending on the the type of xml you've read.
Obviously, both solutions require more coding on the C# side, but with solution b) you'll have the chance of gaining a performance benefit, as XMLSerializer#deserialize most probably builds a DOM tree to create the C# object from, which the XMLReader doesn't do.

A: It seems that what I was trying to do was either unachievable  or no one with the right level of xml fu saw this thread :(.
So anyway, what I ended up doing was adding an extra column to the database with the version number of the xml contract. Since everything in there was the same, I just called it V1.
I then read that info out into app code and used the version number to drive a factory. Basically, if v1, then deserialize to this, if v2, deserialize to this other thing.
And of course, to support that, I simply created a new data object that had the appropriate structure to support v2. I'm not happy with it, but it works and is flexible enough :/


text:
Q: Update another field on slug creation using DoctrineExtensios I'm using DoctrineExtensions in my Symfony 2 project, i have a simple Entity class where i'm using Sluggable on a property, then i would like to set the value to another property based on the slug, but, even when using Lifecycle Callbacks @ORM\PrePersist, @ORM\PreFlush, at this time the slug property still empty, meaning no slug is generated yet, here is my class, to keep this short, i'm not going to put here the get and set function of each property, just the part of the class that are important for this example(please, read the comments)
<?php

namespace My\LearnBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * Banner
 *
 * @ORM\Table(name="banner")
 * @ORM\HasLifecycleCallbacks()
 */
class Banner {

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="bigint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=128, nullable=false)
     * @Assert\NotBlank()
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="slug", type="string", length=256, nullable=false)
     * @Gedmo\Slug(fields={"name"})
     */
    private $slug;

    /**
     * @var string
     *
     * @ORM\Column(name="tracking_url", type="string", length=256, nullable=false)
     */
    private $trackingUrl;

    /**
     * Set slug
     *
     * @param string $slug
     * @return Banner
     */
    public function setSlug($slug) {
        $this->slug = $slug;
        $this->trackingUrl = $slug."/tracking"; //Doesn't work
        return $this;
    }

    /**
     * Set trackingUrl value
     *
     * @ORM\PreUpdate
     */
    public function setTrackingUrlValue() {
        //the slug is empty. Doesn't work
        $this->trackingUrl = $this->slug."/tracking";
        return $this;
    }

    /**
     * Set trackingUrl value
     *
     * @ORM\PreFlush
     */
    public function setTrackingUrlValueOnFlush() {
        //the slug is empty. Doesn't work
        return $this->setTrackingUrlValue();
    }

}

What i've tried? well, using the setSlug function but it doesn't work(note comments on example above), seems it is not called. Using Lifecycle Callbacks @ORM\PrePersist, @ORM\PreFlush and @ORM\PreUpdate, doesn't work neither.
Now i solved this in the controller, after calling flush on the EntityManager, setting the property value based on the slug and calling flush again, so, making 2 database query in a single request, one for insert, one for update. I don't want to use an Event Listener because this behavior is just for this particular entity, or exist a way to attach an event listener to a single entity?.
But right now, i would like to know:
why what i was trying to do using Lifecycle Callbacks didn' work?
Why using the setSlug function didn't work?
A cleaner way to accomplish what i want?
thanks

A: What's probably happening is that the annotated listeners have a higher priority than the one creating the slug (or they have an equal priority in which case the annotated ones get probably added before).
I'm afraid you have to ditch annotations, create an actual listener and tag it for the event registration compiler pass to pick it up. What's nasty with this one is that the bundle seems to use onFlush for creating the slug (code).
Listener
namespace Acme\DemoBundle\Listener;

use Acme\DemoBundle\Model\TrackingUrlUpdateable;
use Doctrine\ORM\Event\OnFlushEventArgs;

class TrackingUrlUpdater
{
    public function onFlush(OnFlushEventArgs $eventArgs)
    {
        $em  = $eventArgs->getEntityManager();
        $uof = $em->getUnitOfWork();

        // Let's process both types of entities in a single loop.
        $entities = array_merge(
            $uof->getScheduledEntityInsertions(),
            $uof->getScheduledEntityUpdates()
        );

        foreach ($entities as $entity) {
            // Using a fictional interface (e.g. for making testing easier).
            if (!($entity instanceof TrackingUrlUpdateable)) {
                 continue;
            }

            // `Banner::updateTrackingUrl()` would internally change the
            // tracking url to the correct one.
            $entity->updateTrackingUrl();

            // The change-set must be recomputed as its fields were modified
            // in the previous step.
            $uof->recomputeSingleEntityChangeSet(
                $em->getClassMetadata(get_class($entity)),
                $entity
            );
        }
    }
}

Registration
What's left now is to register the listener with a lower priority than the Sluggable listener.
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:doctrine="http://symfony.com/schema/dic/doctrine">

    <services>
        <service id="acme.listener.tracking_url" class="Acme\DemoBundle\Listener\TrackingUrlUpdater">
            <tag name="doctrine.event_listener" event="onFlush" priority="-1" />
        </service>
    </services>
</container>

Oh, and don't forget to test!

A: Assuming you're using StofDoctrineExtensionsBundle to integrate the library, the alternative would be to increase the priority of the sluggable listener so that your annotated callbacks would get invoked after the sluggable listener.
A compiler pass would probably do the trick.
namespace Acme\DemoBundle\DependencyInjection\CompilerPass;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class SluggableListenerPriorityChangingPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $id  = 'stof_doctrine_extensions.listener.sluggable';
        $tag = 'doctrine.event_subscriber';

        $definition = $container->getDefintion($id);
        $attributes = $definition->getTag($tag);

        if (!$attributes) {
            throw new \LogicException("The listener (`$id`) must have a `$tag` tag.");
        }

        $attributes['priority'] = 10;

        $definition
            ->clearTag($tag);
            ->addTag($tag, $attributes)
        ;
    }
}

The sluggable listener service itself is registered here, if its enabled from the configuration.


text:
Q: Java Scheduler Quartz Cron Trigger Time Setting I am using Quartz for Scheduling my job in java. I have used "CronTrigger" for setting my time.
I want to fire my Job each day at 11:55 Pm in night. What should i write in the setCronExpression(" ") for having my Job Done. .??
What i thought of the Code is:---
CronTrigger trigger = new CronTrigger();
trigger.setName("runMeJob");
trigger.setCronExpression("0 55 23 * * ?");

Is the above code correct or should i do some modifications in it????

A: It would be: 0 55 23 1/1 * ? *
There is a nice website exactly for your case: CronMaker

CronMaker is a utility which helps you to build cron expressions.
  CronMaker uses Quartz open source scheduler. Generated expressions are
  based on Quartz cron format.


text:
Q: Finding closest combination to current ongoing one I'm currently building a tic tac toe in vanilla javascript. However the game is 'sort of' done but I'm trying to add levels of difficulty. So basically the thing I want to do is , on every player move , to get the the closest possible winning combination based on his moves and place computer's mark into the missing winning's combinations place.
Let's say I have multidimensional array with the winning combinations
winningCombinations: [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 4, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 4, 6],
        [2, 5, 8]
    ]

And the player X starts his moves. So his first move is 0, so saving player's current combination in array. So in first move the current comb is
currentPlayerCombintation: [0]

so I want to return [0,1,2], [0,4,8] and [0,3,6] from the winning combination's array.
However the player makes his second move , so he target's 4 so
currentPlayerCombination: [0,4]

and now I want to return the closest possible winning combination which is [0,4,8].
I've tried a lot of things including every() , some() , filter() but could not achieve the thing I want.
I've tried sort of
    for(let i = 0; i < this.currentPlayerCombination.length ; i++) {
            this.winningCombinations.some((arr) => {
                if(arr.includes(this.currentPlayerCombination[i])) {
                    console.log(arr);
                }
            });
        }

But this didnt work as expected :(

A: You could take a Set and map the count of the matching items, get the max count and filter the array.

function getWinningPositions(pos) {
    var posS = new Set(pos),
        temp = winningCombinations.map(a => [a, a.reduce((c, v) => c + posS.has(v), 0)]),
        max = Math.max(...temp.map(({ 1: c }) => c))
    return temp
        .filter(({ 1: c }) => c === max)
        .map(([a]) => a);
}

var winningCombinations = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 4, 8], [0, 3, 6], [1, 4, 7], [2, 4, 6], [2, 5, 8]];

console.log(getWinningPositions([0]).map(a => a.join(' ')));
console.log(getWinningPositions([0, 4]).map(a => a.join(' ')));
console.log(getWinningPositions([0, 4, 5]).map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: First map the winningCombinations to an array of arrays whose numbers are only the numbers that have not been picked yet. Then, find the lowest length of those arrays, and you can identify the original winningCombinations which are closest to the currentPlayerCombination:

const winningCombinations = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 4, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 4, 6],
  [2, 5, 8]
];
const currentPlayerCombination = [0, 4];

// eg: get [[1, 2], [3, 5,], [6, 7, 8], [8], ...]
const winningCombsWithoutCurrent = winningCombinations.map(arr => (
  arr.filter(num => !currentPlayerCombination.includes(num))
));
// eg: here, lowestLength should be 1, because [8] has a length of 1
const lowestLength = winningCombsWithoutCurrent.reduce((a, { length }) => Math.min(a, length), 3);

const combosWithLowestLength = winningCombsWithoutCurrent
  .reduce((a, { length }, i) => {
    if (length === lowestLength) {
      a.push(winningCombinations[i]);
    }
    return a;
  }, []);
console.log(combosWithLowestLength);


text:
Q: Convert x, y coordinates into px Imagine there is a post in Instagram and someone tagged in the picture and the coordinates of the tagged-person-icon in the picture is something like :
position: [
      x = 0.5162392854690552,
      y = 0.44017091393470764
  ]

So my goal is to convert this position into px format( by px I mean the px in the css) so I'll be able to use it the way I want it .
I believe that there is some formula to do that , but I didn't find it.

A: Multiply x by width and y by height.
$position = [
    'x' => 0.5162392854690552,
    'y' => 0.44017091393470764
];

$width = 800;
$height = 800;

$x = round($position['x'] * $width);
$y = round($position['y'] * $height);

$css = "position: absolute; top: {$y}px; left: {$x}px;";
echo $css;

gives you
position: absolute; top: 352px; left: 413px;

Update
If the image is responsive use percentage as @schmauch mentioned in the comment.
$x = round($position['x'] * 100);
$y = round($position['y'] * 100);

$css = "position: absolute; top: {$y}%; left: {$x}%;";
echo $css;

gives you
position: absolute; top: 44%; left: 52%;


text:
Q: Raise Event on another Form subject is declare event on Form1 , and run that event on Form2
here is the code , but event doesnt work on Form2 !! what is missing here??
many thanks
Form1:
Public Class Form1

    Private Sub btnOpenForm2_Click(sender As Object, e As EventArgs) Handles btnOpenForm2.Click
        Form2.Show()
    End Sub

    Public Event show_My_Message()
    Private Sub btnShowMessageOnForm2_Click(sender As Object, e As EventArgs) Handles btnShowMessageOnForm2.Click
        RaiseEvent show_My_Message()
    End Sub

End Class

Form2:
Public Class Form2

    Public WithEvents My_Form1 As Form1 = New Form1
    Private Sub Show_My_Message_On_Form2() Handles My_Form1.show_My_Message
        MsgBox("Hello")
    End Sub

End Class

A: Try it without cross form event handling,
Form1
Public MyForm2 As Form2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If MyForm2 Is Nothing Then
        MyForm2 = New Form2
    End If
    MyForm2.Show()
    MyForm2.Show_My_Message_On_Form2("Hello")
End Sub

Form2
Public Class Form2

    Public Sub Show_My_Message_On_Form2(theMess As String)
        MessageBox.Show(theMess)
    End Sub

End Class

A: Here's an example of what Jimi was talking about, using the .Owner property.
Form1:
Public Class Form1

    Private Sub btnOpenForm2_Click(sender As Object, e As EventArgs) Handles btnOpenForm2.Click
        Form2.Show(Me) ' <-- Pass Form1 into Form2 via Show()
    End Sub

    Public Event show_My_Message()
    Private Sub btnShowMessageOnForm2_Click(sender As Object, e As EventArgs) Handles btnShowMessageOnForm2.Click
        RaiseEvent show_My_Message()
    End Sub

End Class

Form2:
Public Class Form2

    Private WithEvents My_Form1 As Form1

    Private Sub Form2_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        If Not IsNothing(Me.Owner) AndAlso Me.Owner Is Form1 Then
            My_Form1 = DirectCast(Me.Owner, Form1)
        End If
    End Sub

    Private Sub F1_show_My_Message() Handles My_Form1.show_My_Message
        MessageBox.Show("Hello")
    End Sub

End Class


text:
Q: Creating jasmine unit test for angular directive The below directive checks/loads the template with value "pass, fail, required".
The conditions are
if(parent value == required){
1. if the value is true --> $scope.msg = "fail" --> loads the template with {{msg}} value
2. if the value is false --> $scope.msg = "pass" --> loads the template with {{msg}} value
}

In detail,
loading Template: [showerror.html]

{{msg}}

Directive Call:

(obj contains as obj.error and obj.required )
Directive:
angular.module("dsf").directive('showError', [

    function () {
        'use strict';

        return {
            scope: {
                obj: '=showError'
            },
            link: function ($scope) {

                $scope.showError =  {};
                $scope.msg = "";

                function setTemplate(filename) {
                    $scope.showError.template = 'app/path/' + filename + '.html';
                }

                $scope.$watch(function () {

                    if ($scope.obj.required === true) {
                        if ($scope.obj.error === false) {
                            $scope.msg = "Pass";
                        } else if ($scope.obj.error === "required") {
                            $scope.msg = "Required";
                        } else if ($scope.obj.error === true) {
                            $scope.msg = "fail";
                        }

                    } else {

                        if ($scope.obj.error === true) {
                            $scope.msg = "fail";
                        } else if ($scope.obj.error === false) {
                            $scope.msg = "Pass";
                        }

                    }

                    setTemplate("showerror");
                });

            },
            template: '

'
        };
    }
]);

As i am new to jasmine test, how can i write the test for this directive? any suggestions?
Ok. I have written the unit test for this directive. What is the wrong now?
describe('showError', function () {
    'use strict';
    var compile, $scope, element;
    beforeEach(module('dsf'));

    beforeEach(inject(function ($compile, $rootScope) {
        element = angular.element('

');
        $scope = $rootScope.$new();
        compile = function (obj) {
            $scope.obj = obj;
            $compile(element)($scope);
            $scope.$digest();
        };
    }));
    it('updates the element when obj validation changes', function () {
        var obj;
        obj = {};
        $scope = compile(obj);
        $scope.apply(function () {
            obj.required = true;
            obj.error = true;
        });
        expect($scope.obj.msg).toContain('fail');
        $scope.apply(function () {
            obj.required = true;
            obj.error = false;
        });
        expect($scope.obj.msg).toContain('Pass');
        $scope.apply(function () {
            obj.required = true;
            obj.error = "required";
        });
        expect($scope.obj.msg).toContain('Required');
        $scope.apply(function () {
            obj.required = false;
            obj.error = true;
        });
        expect($scope.obj.msg).toContain('Pass');
        $scope.apply(function () {
            obj.required = false;
            obj.error = false;
        });
        expect($scope.obj.msg).toContain('fail');
    });
});

I am getting error:
undefined is not an object (evaluating $scopr.apply) error

A: The command you're looking for is $scope.$apply() not $scope.apply().


text:
Q: Free software similar to ET GeoTools? ers,
At my prior position, we "often" had to capture Geology data from geo-referenced images.  Yes ... sometimes a necessary evil, but it has been a while since my hardcore digitizing days.  Regardless, we used this handy add-on for ArcMap called ET GeoTools.  We were able to simply digitize the polylines for the adjacent Geological categories, then run an analysis of over/undershoots.  Once we had that issue fixed, you could simply convert the polylines to polygons and build your polygon attribution in to the Database from there.  It was a beautiful thing!!!!  I didn't have to concern myself with snapping to every node on adjacent polygons, and this little add-on had a number of other neat little capabilities as well.
Now, I looked in to it, and it turns out they want $195.00 for the software.  I don't have any knowledge of programming languages - I should make that clear too before I move on.  Anyway,  I wondered 2 things, and perhaps a few of you may have a suggestion or two.  Does ArcMap 10 have this functionality (I am in 9.3 but soon to be using 10).  OR .... is there a free add-on that can do this?  Even if there's something out there that will export to .shp format, that will suffice.  I'll just take care of the rest of the work in good ol' ESRI following the conversion.
Anyone?  Thanks in advance

A: I've not been too up on ET GeoTools lately but if you can't bring yourself (just saying) to pay $200 for an extension to a very expensive piece of GIS software (ArcGIS Desktop), it might be time to move to a different platform.
I'd recommend gvSIG and SEXTANTE.
If English is your first language, take a look at the OADigital Branch.

A: I believe ET Geowizard have a toolset that you can download for free to use it in ArcGIS 10. If you are only looking to convert polylines to polygon, ET Geowizard is just a right free tool that can be used with ArcGIS 10. There are so many other tools available on ET Geowizard for which you have to pay license fee. However, you can use this for free. Make sure you read the readme file before installing it.

A: As far as "free" add-ons that will accomplish polyline to polygon coversion are concerned, I never did end up going this route or finding any such add-on. I ended up resolving my own issue in AutoCAD Civil 3D 2011.  This in no way negates the fact that ET GeoTools has some other great functionalities beyond this.  Many of you had some really great suggestions too.
Granted, the process was a tad more involved with my Civil 3D, I still did manage to cut considerable time off the overall process.  My workflow was as follows:

*

*I georeferenced the data capture image, and brought it in to CAD with the "mapconnect" command;

*I made a rectangle around my interest area, and drew lines which either ended at another polyline segment, or at the rectangle I created around my interest area;

The beauty of doing this in CAD, is that there are no under/overshoots due to the snapping capabilities.  Additionally (unlike ArcMap), CAD allows you to zoom in & out with the roller on your mouse in a very controlled/dynamic fashion (very similar to Paint Shop Pro).  You can also customise your snap settings (to node, nearest, endpoint, etc), and turn the snapping on & off by simply hitting the F3 button (very efficient once you get used to the interface!!!).

*

*Once I completed the digitizing, I typed "bpoly" in my command line, and clicked inside each area, then hit enter.  Hitting enter again re-activates the same command, and I repeated this process until all areas were converted to polygons;

*I saved the .dwg file, projected it to the correct datum and zone in ArcCatalog;

*I dropped the drawing file in ArcMap, and queried the appropriate polygon layer out of the drawing file, then exported it to a shapefile format;

*With the image underneath, I started an edit session, and populated my "soil category number" colum with numbers (1s would = Sand & Gravel; 2s would = Silt ......).
It's FAR more efficient to assign a number to your classifications, especially if the category names are lengthy or difficult to spell - ie-ethyl flouranthene.  You can always redefine them with a shortcut (my next step) as opposed to manually typing EACH  category name in to the attribute table during the edit session.  This also alleviates the possibility of putting accidental spacing in some of your fields.  A former co-worker taught me this handy shortcut.  Since that day, I've never bothered to type the same category names over-and-over in an editing session (HUGE waste of time!!).

*

*Next. I queried each "number" from the "SOIL_NUM" column and populated a new column I created (SOIL_CL) with the appropriate classification in field calculator (choose "selected" ---- > right mouse on the column header and select field calculator ----- > type the soil classification in qoutes.

I have generalised this explaination somewhat (rather than explaining "every step" in great detail).  Most of you are far more advanced users than myself anyway.  For the benefit of Junior GIS professionals, it's the ability to "think out" shortcuts/solutions to augment efficiency and accuracy that differentiates the strong from the weak in our field!!!  Use what you learn every day to solve issues/problems tomorrow!!
The key point here .... I cut my digitizing time by at least 80%.  Thank you all very much for the feedback.  I am very pleased with myself, as I was able to figure this one out on my own (thus avoiding DAYS of digitizing -- woow hoo!!).
Cheers everyone & thanks again!!

A:
Does ArcMap 10 have this functionality
  (I am in 9.3 but soon to be using 10).

If you're licensed for ArcEditor or ArcInfo, I think you could use the topology tools to do this.

A: EDIT: I understand your plight with getting approval to purchase software. In that light, my suggestion probably doesn't offer anything to help you out at the moment.
NeuraMap is not free by any means, so I apologize straight away if this isn't something you're interested in. However, I just finished digitizing more than 30 map plates from a couple of old USGS reports. The maps consisted of line features like structural contours as well as polygonal features such as rock outcrop areas. It doesn't do anything with regards to topology, but what it does do is it uses neural-network algorithms to auto-trace the maps you feed it. It takes some tweaking depending on the quality and color scheme of the map; you need good solid, outlines of contrasting-color to get good results. Feature attribution and exporting to .shp is very easy.


text:
Q: Mysql query for the attendance register I am planning the export of data for the attendance register, the data comes from these two db :
Users:
+----+--------+---------+
| id | name   | surname |
+----+--------+---------+
| 1  | george | shish   |
| 2  | frank  | matano  |
| 3  | test   | test    |
+----+--------+---------+

reportdipendente:
+-----------+---------------+------------+
| id_report | id_employee   | date       |
+-----------+---------------+------------+
| 1         | 1             | 07-09-2020 |
| 2         | 2             | 07-09-2020 |
| 3         | 2             | 06-09-2020 |
| 4         | 1             | 06-09-2020 |
+-----------+---------------+------------+

With that query:
SELECT id,id_employee,name,surname,GROUP_CONCAT(date)
FROM users as u
JOIN reportdipendente as r
    ON u.id=r.id_employee
WHERE r.date LIKE ?
GROUP BY id

Mysql return:
+----+-------------+--------+---------+-----------------------+
| id | id_employee | name   | surname | date                  |
+----+-------------+--------+---------+-----------------------+
| 1  | 1           | george | shish   | 06-09-2020,07-09-2020 |
| 2  | 2           | frank  | matano  | 06-09-2020,07-09-2020 |
+----+-------------+--------+---------+-----------------------+

Is all ok, but how i can print users nr 3 too? because he don't have any record in second db
Another details:

*

*i use like with param ex. '%09-2020%'

*date is varchar

A: SELECT u.id,
       COALESCE(ANY_VALUE(r.id_employee), '') id_employee,
       u.name,
       u.surname,
       COALESCE(GROUP_CONCAT(r.date), '') date
FROM users as u
LEFT JOIN reportdipendente as r
     ON u.id=r.id_employee
    AND r.date LIKE ?
GROUP BY u.id,
         u.name,
         u.surname


text:
Q: Target first level
*s and not the nested
*s I have the following HTML:

A

subsection

B

subsection

C

subsection

With jQuery, how do I target the FIRST level of
s?
For example, I need to make the font bold on hover to the
s with the letters A, B and C, but NOT have that font style applied to the nested
s (with the name subsections).
Here's an initial jsfiddle DEMO if you'd like to use it.
Thanks.
EDIT--
Solution:
CHILD SELECTORS, that's the answer.
No need for jQuery, this can be done using CSS.
Here's the updated DEMO
EDIT-- Here's a more clear demo
Thanks,

A: I would set one rule to target all li elements and then another to override this that targets nested li elements.
li{font-weight:bold;}
ul ul li{font-weight:normal;}

Nested li elements would be normal weight and top level would be bold.

A: You could do this:
$('ul > li:not(:has(ul))');

But it would be better to give your top level
 an ID so you can target it with a valid CSS selector:
$('#topUL > li')

A: Have a container
 with a class, and use the > selector. Lets say your container div's class is "myclass":
.myclass ul li {
   ...this will affect both levels of li.
}

.myclass > ul > li {
   ...this will only affect the first level.
}

.myclass > ul > li > ul > li {
   ...this will only affect the second level.
}

Note: the > selector does not work in IE6 and below when used as a CSS selector. It does work in all other browsers though, including IE7 and IE8, and when used in JQuery, it works in all browsers supported by jQuery, including IE6.

A: CHILD SELECTORS, that's the answer.
No need for jQuery, this can be done using CSS. Target the first-level li elements with a selector:
ul > li {
    font-weight: bold;
}

And then undo the styling for deeper li elements:
ul > li li {
    font-weight: normal;
}

Here's the updated DEMO.

A: I don't think your problem has been completely addressed (although there has been some good attempts).  Your example problem deals with applying a style to a parent and preventing the child from inheriting the style -- which is a CSS problem.
You could target the list items by knowing the parent element (as some have noted). Then add a class on hover.
$('div > ul > li').hover(function(){
    $(this).addClass('myHover');
},
function(){
    $(this).removeClass('myHover');
});

And your CSS would have the class for the parent, and a negating style for the children:
.myHover { font-weight: bold; }
.myHover li { font-weight: normal; }

A: Here is an extended version of user @Spudley's answer - with a snippet.
Might save some people some time.

/* this will affect all levels of li */
.myclass ul li {
  color: red;
}

/* this will only affect level 1 */
.myclass>ul>li {
  color: green;
}

/* this will only affect level 2 */
.myclass>ul>li>ul>li {
  color: blue;
}

/* this will only affect level 3 */
.myclass>ul>li>ul>li>ul>li {
  color: aqua;
}

* {
  font-family: arial;
}

Level 1

Level 2

Level 3

Level 3

Level 2

Level 2

Level 3

Level 3

Level 3

Level 4

Level 4

Level 1


text:
Q: MySQL GROUP BY on SELECT If Statement I'm am trying to join a table that has a boolean column, and in my results I'm trying to get two columns from the join, one where the boolean is 0 and a separate on where it is 1.
Since there is a one to many relationship, I need to do a GROUP BY.
The following query returns the correct non GROUP BY results.
For each profile ID there is at least one row for both genre and influence.
SELECT p.profileID, IF( gpro.isInfluence =0, g.genreName, NULL ) AS genre, IF( gpro.isInfluence =1, g.genreName, NULL ) AS influence, g.genreName
FROM profiles p
LEFT JOIN genre_profiles gpro ON gpro.profileID = p.profileID
LEFT JOIN genres g ON g.genreID = gpro.genreID
WHERE g.genreName IS NOT NULL

However, when I do the corresponding GROUP BY/GROUP_CONCAT the output does not make sense.
SELECT p.profileID, IF( gpro.isInfluence =0, GROUP_CONCAT( g.genreName ) , NULL ) AS genre, IF( gpro.isInfluence =1, GROUP_CONCAT( g.genreName ) , NULL ) AS influence, g.genreName
FROM profiles p
LEFT OUTER JOIN genre_profiles gpro ON gpro.profileID = p.profileID
LEFT OUTER JOIN genres g ON g.genreID = gpro.genreID
WHERE g.genreName IS NOT NULL
GROUP BY p.profileID

The above groups all the g.genreName rows in either of the columns, instead of them being split based on the gpro.isInfluence value. The column the result falls under I believe corresponds to the first result that is grouped.
1000001052  Latin American,Rock,Hip Hop NULL
1000001637  NULL    Electronic,Easy listening,Asian,popgun
1000001666  NULL    Electronic,Bacon,Emo,Modern folk,Hip Hop,R...

What I don't understand is why are the genre values are grouped together and not in their respective columns like the first query.

A: SELECT p.profileID, GROUP_CONCAT( IF( gpro.isInfluence =0, g.genreName, NULL ) ) AS genre, GROUP_CONCAT( IF( gpro.isInfluence =1, g.genreName, NULL ) ) AS influence, g.genreName
FROM profiles p
LEFT OUTER JOIN genre_profiles gpro ON gpro.profileID = p.profileID
LEFT OUTER JOIN genres g ON g.genreID = gpro.genreID
WHERE g.genreName IS NOT NULL
GROUP BY p.profileID

Putting the GROUP_CONCAT outside the IF statement gives the correct output, thanks to Ertunc for helping my brain make the pivot on that one.

A: Here is a very basic statement to apply IF condition in Select statement with GROUP BY clause.
GROUP_CONCAT( IF (condition, 1, 0)) col

As GROUP_CONCAT return multiple , separated values. With the below line of statement we can avoid duplicate values
GROUP_CONCAT(DISTINCT IF (condition, 1, 0)) col


text:
Q: Поисковый запрос в JIRA на Python3 Доброго времени суток. Я в процессе обучения Python (кнопаю сразу Python3) и поставили передо мной такую задачу:
Написать скриптик на Python, работающий по принципу "ввёл JQL-запрос, получил список тикетов, вывел его на экран"
Я только в процессе изучения языка (и это мой первый язык), так что работа с HTML для меня лес тёмный.
Собственно на данный момент я разобрался, что:
import urllib.request

url = '/ссылка на поиск issue в JIRA/'
response = urllib.request.urlopen(url)
reading_link = response.read()

Вот этот участок кода откроет мне указанную линку, прочтёт её. Но вот как сделать так, чтобы JIRA съела мой JQL-запрос для advanced-поиска и выдала мне результат по моему запросу?
Т.е. мне понятно, что нужно добавить input, который будет принимтаь этот самый запрос, в стиле:
jql_input = input('Enter a JQL request: ')

Но вот как мне эту переменную послать куда надо - для меня загадка.
Может, тут кто поможет?)


text:
Q: component one c1upload does fire in callback event so does not support text box ,label values protected void C1Upload2_ValidatingFile(object sender, C1.Web.Wijmo.Controls.C1Upload.ValidateFileEventArgs e)
{
    try
    {
        var s = e.UploadedFile.GetStream();
        byte[] imgbyte = new byte[s.Length];
        s.Read(imgbyte, 0, Convert.ToInt32(s.Length));
        string type = e.UploadedFile.Extension;
        if (e.IsValid)
        {
            cmd = new SqlCommand("sp_pdm_shopping_upload", con);
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            cmd.Parameters.Add(new SqlParameter("@sample", SqlDbType.Char, 10));
            SqlParameter contentparameter = null;
            contentparameter = (new SqlParameter("@image", SqlDbType.Image));
            contentparameter.Direction = ParameterDirection.Input;
            cmd.Parameters.Add(contentparameter);
            cmd.Parameters.Add(new SqlParameter("@type", SqlDbType.Char, 10));
            cmd.Parameters["@sample"].Value = txt_code.Text;
            cmd.Parameters["@image"].Value = imgbyte;
            cmd.Parameters["@type"].Value = "INV";
            cmd.ExecuteNonQuery();
            con.Close();
            e.IsValid = false;
            s.Close();
            e.UploadedFile.Delete();
        }
        else
        {
            ErrorMsg.Visible = true;
            this.ErrorMsg.Text = e.UploadedFile.FileName + Environment.NewLine;
        }

    }
    catch
    {

    }
}


text:
Q: breqn doesn't manage to fully break my equation I'm trying to use the breqn package to add automatic line breaks to a particular equation. It gives me three line breaks in the example below, then gives up and lets the equation trail off the page. Is there any way to fix this, short of manually breaking the lines?
\documentclass{article}
\usepackage{breqn}
\begin{document}

\begin{dmath*}
F(T_1, T_2) = T_1 + T_2 + u_0^{-2} (x_1 u_0 + 2 u_1) C_2(T_1, T_2)
+ u_0^{-4} (x_1 u_0 u_1 - 2 u_1^2)C_3(T_1, T_2)
+ ((4 x_2 u_0^3 - 2 x_1 u_0 u_1^2 + 4 u_1^3 + 4 u_0^2 u_2)/u_0^6) T_1^3 T_2
+ ((x_1^2 u_0^2 u_1 + 6 x_2 u_0^3 - 3 x_1 u_0 u_1^2 + 2 u_1^3
+ 6 u_0^2 u_2)/u_0^6) T_1^2 T_2^2 + ((4 x_2 u_0^3 - 2 x_1 u_0 u_1^2 + 4 u_1^3
+ 4 u_0^2 u_2)/u_0^6) T_1 T_2^3 + ((-4 x_2 u_0^3 u_1 + 5 x_1 u_0 u_1^3
+ 3 x_1 u_0^3 u_2 - 10 u_1^4 - 14 u_0^2 u_1 u_2)/u_0^8) T_1^4 T_2 + \cdots
\end{dmath*}

\end{document}

I'm not concerned for now with the typographic quality of the output; I just want to be able to see the whole equation. And I want to avoid manually setting the breaks, because the equation I'm trying to set is really long--about ten times the length of the equation above.


text:
Q: Getting error in google api client with id 0 when used in alertdialog I am using google's auto location to fetch the location which i have given in the alert dialog box when i opened the dialog for the first time everything works fine but when i close the dialog box and open the dialog box again it shows me an error stating Already managing a GoogleApiClient with id 0 even i have tried changing enableautomanage and added the onstart and onpause method but nothing works .
Can anyone tell me why it occurs and how can i overcome this error when using it in alertdialog box.
code:
 final LayoutInflater layoutInflater = LayoutInflater.from(Activity_AddFastEntryDaybook.this);
    final View promptView = layoutInflater.inflate(R.layout.dialog_add_newfarmer, null);
    final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Activity_AddFastEntryDaybook.this);
    alertDialogBuilder.setView(promptView);
    alertDialogBuilder.setCancelable(true);
    mlayout = promptView.findViewById(R.id.relative_view_layout);
    final TextInputLayout ti_farmername = (TextInputLayout) promptView.findViewById(R.id.inputfarname);
    final TextInputLayout ti_farmermobno = (TextInputLayout) promptView.findViewById(R.id.inputfarmobno);
    final TextInputLayout ti_farmerlocation = (TextInputLayout) promptView.findViewById(R.id.inputfarmlocation);
    edt_farmername = (EditText) promptView.findViewById(R.id.farmername);
    edt_farmermobno = (EditText) promptView.findViewById(R.id.farmermobileno);
    final ImageView importcontacts = (ImageView) promptView.findViewById(R.id.img_importcontacts);
    final ImageView btnsave = (ImageView) promptView.findViewById(R.id.img_save);
    final AutoCompleteTextView actv_farmerlocation = (AutoCompleteTextView) promptView.findViewById(R.id.farmerlocation);
    // checkconnection();
    mGoogleApiClient = new GoogleApiClient.Builder(Activity_AddFastEntryDaybook.this)
            .addApi(Places.GEO_DATA_API)
            .enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
            .addConnectionCallbacks(this)
            .build();
    actv_farmerlocation.setThreshold(1);
    actv_farmerlocation.setOnItemClickListener(mAutocompleteClickListener);
    mPlaceArrayAdapter = new PlaceArrayAdapter(this, android.R.layout.simple_list_item_1,
            BOUNDS_MOUNTAIN_VIEW, null);
    actv_farmerlocation.setDropDownWidth(-1);
    actv_farmerlocation.setAdapter(mPlaceArrayAdapter);

    importcontacts.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            farmercontacts();
        }
    });
    btnsave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String farmer_name = edt_farmername.getText().toString();
            String farmer_mobno = edt_farmermobno.getText().toString();
            String farmer_location = actv_farmerlocation.getText().toString();
            if (farmer_name.length() == 0) {
                edt_farmername.setError("Enter Name");
            } else if (farmer_mobno.length() == 0) {
                edt_farmermobno.setError("MobileNo");
            } else if ((farmer_mobno.length() > 10) && (farmer_mobno.startsWith("6") || farmer_mobno.startsWith("5") || farmer_mobno.startsWith("4") || farmer_mobno.startsWith("3")
                    || farmer_mobno.startsWith("2") || farmer_mobno.startsWith("1") || farmer_mobno.startsWith("0") || farmer_mobno.startsWith("*") || farmer_mobno.startsWith("#") || farmer_mobno.endsWith("*") || farmer_mobno.endsWith("#"))) {
                edt_farmermobno.setError("enter a valid mobile no");
            } else if ((farmer_mobno.length() == 10) && (farmer_mobno.startsWith("6") || farmer_mobno.startsWith("5") || farmer_mobno.startsWith("4") || farmer_mobno.startsWith("3") || farmer_mobno.startsWith("2") || farmer_mobno.startsWith("1") || farmer_mobno.startsWith("0") || farmer_mobno.startsWith("*") || farmer_mobno.startsWith("#") || farmer_mobno.endsWith("*") || farmer_mobno.endsWith("#"))) {
                edt_farmermobno.setError("Invalid mobile no");
            } else if ((farmer_mobno.length() < 10) && farmer_mobno.startsWith("6") || farmer_mobno.startsWith("5") || farmer_mobno.startsWith("4") || farmer_mobno.startsWith("3")
                    || farmer_mobno.startsWith("2") || farmer_mobno.startsWith("1") || farmer_mobno.startsWith("0") || farmer_mobno.startsWith("*") || farmer_mobno.startsWith("#") || farmer_mobno.endsWith("*") || farmer_mobno.endsWith("#")) {
                edt_farmermobno.setError("enter a valid mobile no");

            } else if (farmer_location.length() == 0) {
                actv_farmerlocation.setError("Location");
            } else {
                edt_farmername.setError(null);
                edt_farmermobno.setError(null);
                actv_farmerlocation.setError(null);
                databasehandler.insertFarmer(farmer_name, farmer_mobno, farmer_location);
                alert.dismiss();
                myAdapterfarmer.notifyDataSetChanged();
            }
        }
    });
    alert = alertDialogBuilder.create();
    alert.show();

Error:
java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0
                                                                    at com.google.android.gms.common.internal.zzab.zza(Unknown Source)
                                                                    at com.google.android.gms.internal.zzpk.zza(Unknown Source)
                                                                    at com.google.android.gms.common.api.GoogleApiClient$Builder.zzf(Unknown Source)
                                                                    at com.google.android.gms.common.api.GoogleApiClient$Builder.build(Unknown Source)
                                                                    at codingtown.coconut.daybook.activity.Activity_AddFastEntryDaybook.addnewfarmer(Activity_AddFastEntryDaybook.java:325)
                                                                    at codingtown.coconut.daybook.activity.Activity_AddFastEntryDaybook.access$000(Activity_AddFastEntryDaybook.java:74)
                                                                    at codingtown.coconut.daybook.activity.Activity_AddFastEntryDaybook$5.onClick(Activity_AddFastEntryDaybook.java:265)

A: Issue is not from alertdialog ,You may try this by adding code
` mGoogleApiClient .enableAutoManage(this, 0 /* clientId */, this)


text: Q: How a trained DRL model run with smaller number of state? I trained a DRL model with a large number of states, for example, my state dimension includes 1 hunter and 20 prey. But if I want to run my trained DRL model with less state dimension, let say, 1 hunter and 2 prey. How could my DRL model handle with variable state dimension?


text:
Q: Simplify list of tuples based on contiguous points I have a list of tuples where the first item in each tuple is the start distance along a route and the second item is the ending distance along that route.
>>> MyTuples=[(0,100),(100,150),(150,180),(180,190),(400,450),(450,700)]
>>> MyTuples
[(0, 100), (100, 150), (150, 180), (180, 190), (400, 450), (450, 700)]
>>>

The first item in the list goes from point 0 to point 100, the second goes from point 100 to 150 and so on.
However, I want to simplify this list by aggregating on those items that are continuous. That would reduce the list to: [(0,190),(400,700)]
What is the best way to do this?

A: With a generator, you could do this with something like:
def aggregate(tuples):
    current = None
    for (x, y) in tuples:
        if current == None:
            current = (x, y)
        else:
            (a, b) = current
            if b == x:  # should this be b >= x?
                current = (a, y)
            else:
                yield current
                current = (x, y)
    if current != None:
        yield current

In terms of functional programming this has a structural idiom which can be factored out called foldl which is common to all streams. You would write in Haskell,
aggregate (x:xs) = reverse $ foldl chomper [x] xs where
    chomper output@((a, b) : rest) element@(x, y)
        | x == b     = (a, y) : rest
        | otherwise  = element : output

In other words you could also make this concrete to lists in Python and write instead:
def foldl(fn, a, bs):
    """Fold a list from the left with `fn`.

    This is a left fold, it takes an (A, B) -> A function and an A and a
    list of Bs and produces an A."""
    z = a
    for b in bs:
        z = fn(z, b)
    return z

def chomper(output, element):
    (a, b) = output.pop()
    (x, y) = element
    if x == b:
        output.append((a, y))
    else:
        output.append((a, b))
        output.append(element)
    return output

A: Here is a short and neat way of doing it:
>>> l = [(0, 100), (100, 150), (150, 180), (180, 190), (400, 450), (450, 700)]
>>> l1, l2 = zip(*l)
>>> zip((i for i in l1 if not i in set(l2)), (i for i in l2 if i not in set(l1)))
[(0, 190), (400, 700)]

It's also easy with a little recursion, but cycles are going to cause infinite recursion:
def follow(d):
    # this finds the correct "ending" given a start point in the mapping
    follow_inner = lambda x: d[x] if d[x] not in d else follow_inner(d[x])
    for start in d:
        if start in d.values():
            # skip "linking" items
            continue
        yield start, follow_inner(start)

Use it like this:
lst = [(0,100),(100,150),(150,180),(180,190),(400,450),(450,700)]
filtered = list(follow(dict(lst)))
print filtered
# [(0, 190), (400, 700)]

There are obvious improvements this is just a POC. You can also use only generators (more fitting I suppose) - but I did this for fun :-)

A: MyTuples = [(0, 100), (100, 150), (150, 180), (180, 190), (400, 450), (450, 700)]

def con(l):
    it = iter(l)
    # pull first tuple
    tmp,  prev = next(it,((),()))
    for a, b in it:
        # compare prev b to current  a if they are != the sequence is broken
        if prev != a:
            yield tmp, prev
            tmp = a
        # update prev
        prev = b
    yield tmp, prev
print(list(con(MyTuples)))

Output:
[(0, 190), (400, 700)]


text:
Q: Win32 File IO works but fopen et. al. fails. What is going on here? Never had that before. If I use the fopen() etc. functions for reading a file from disk, fopen succeeds, but the FILE * content looks a bit NULL-ish. Then I try fseek(SEEK_END) and it reports that the file is of size 0 bytes.
If I do the same with CreateFile(), GetFileSize(), ReadFile(), it works. Same function, same path...
VS2013 Community Edition, Win7 x64, 64bit compile.
Files I tested with were small (never more than 400 bytes). They are located on E: drive (E:\temp), which is a local partition.
Any ideas where I need to solder my computer to fix that? :)
static void LoadFile(const std::string &path, std::string& target)
{
#if 1
    HANDLE hFile = ::CreateFileA(path.c_str(), FILE_READ_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
    finally finallyClose([&hFile](){ ::CloseHandle(hFile); });
    if (INVALID_HANDLE_VALUE != hFile)
    {
        DWORD fileSize = ::GetFileSize(hFile, NULL);
        target.resize(fileSize);
        DWORD bytesRead = 0UL;
        BOOL success = ::ReadFile(hFile, &target[0], fileSize, &bytesRead, NULL);
    }
    else
    {
        std::cout << "Could not load file: " << path << std::endl;
    }

#else
    FILE * inFile = NULL;
    errno_t err = fopen_s(&inFile, path.c_str(), "rb");

    if (NULL != inFile)
    {
        finally finallyClose([&inFile](){ fclose(inFile); });

        int fileSize = fseek(inFile, 0, SEEK_END);
        fseek(inFile, 0, SEEK_SET);
        target.resize(fileSize);
        fread(&target[0], sizeof(char), fileSize, inFile);
    }
    else
    {
        std::cout << "Could not load file: " << path << std::endl;
    }
#endif
}

A: The fseek function returns 0 on success.  It does not return the number of bytes the file pointer has moved.
http://en.cppreference.com/w/c/io/fseek
You need to call ftell to get back the file size.
http://en.cppreference.com/w/c/io/ftell
fseek(inFile, 0, SEEK_END);
int filesize = ftell(inFile);
target.resize(filesize);


text:
Q: Iterate over 2 dataframes and match columns for N% of similarity I am trying to find similar strings in 2 different pandas dataframes using fuzzywuzzy.
So far all I can think of is to iterate over each frame and then use fuzz.ratio(v1, v2) to return a % of similarity.
Logic like this:
for v1_df1, v2_df1 in df1[['given_name', 'surname']].itertuples(index=False):
    for v1_df2, v2_df2 in df2[['given_name', 'surname']].itertuples(index=False):

        ratio_v1 = fuzz.ratio(v1_df1, v1_df2)

This is not suitable, but hopefully, it demonstrates what I'm trying to do. I would like an effective way to match string on two separate pandas data frames and conditionally deem them similar given a configurable %

A: Say
df1:
    Name    First_Name
0   Lara    Owlen
1   Heiberg Lanzer
2   Willy   Jones
3   Rosy    Lily
4   Stuart  Littlt

df2:
    Name        First_Name
0   Braund      Owen
1   Heikkinen   Laina
2   Allen       William
3   Moran       James
4   McCarthy    Timothy

import itertools
from fuzzywuzzy import fuzz
p1 = list(itertools.product(*[df1['Name'].values, df2['Name'].values]))
p2 = list(itertools.product(*[df1['First_Name'].values, df2['First_Name'].values]))
for N1, N2 in zip(p1,p2):
    Name_ratio = fuzz.ratio(N1[0], N1[1])
    First_Name_ratio = fuzz.ratio(N2[0], N2[1])

You can like this way.


text:
Q: File not found after I just successfully loaded assembly I am loading two assemblies using reflection and then using a few types from them.  After I load the assembly, load a type and then instantiate a type with Activator, I get a FileNotFound exception on the assembly when trying to invoke a "LoadFromXml" method.  This was previously working and I cannot figure out what changed.  Also, I can get a property from the created instance without a problem.  It's only throwing exceptions when invoking the method "LoadFromXml."
 private static object CheckForVersion(int version, string constructFilePath, string utilityFilePath)
    {
        if (!System.IO.File.Exists(constructFilePath) || !System.IO.File.Exists(utilityFilePath) || version < 7) return null;

        var utilAssembly = System.Reflection.Assembly.LoadFile(utilityFilePath);
        var constructAssembly = System.Reflection.Assembly.LoadFile(constructFilePath);

        var InfoManager = utilAssembly.GetType(String.Format("{0}.InfoManager", utilAssembly.FullName.Split(',')[0]));
        var ExecutionServerPropertiesConstructType = constructAssembly.GetType(String.Format("{0}.ExecutionServerPropertiesConstruct", constructAssembly.FullName.Split(',')[0]));

        string dbFolder = (string)(InfoManager.GetProperty("ServerDatabaseFolder").GetValue(null, null));

        if (Directory.Exists(dbFolder) == true)
        {
            string FilePath = Path.Combine(dbFolder, @"ExecutionServer.config.xml");                    //DONT LOCALIZE

            dynamic theServerProperties = Activator.CreateInstance(ExecutionServerPropertiesConstructType);

            theServerProperties.LoadFromXml(FilePath);

            var retVal = new
            {
                InstalledProductVersion = version,
                ServerGuid = (string)InfoManager.GetField("SERVER_GUID").GetValue(null),
                WorkflowRootnodeGuid = (string)InfoManager.GetField("WORKFLOW_ROOTNODE_GUID").GetValue(null),
                TaskRootnodeGuid = (string)InfoManager.GetField("TASK_ROOTNODE_GUID").GetValue(null),
                TriggerRootnodeGuid = (string)InfoManager.GetField("TRIGGER_ROOTNODE_GUID").GetValue(null),
                ProcessRootnodeGuid = (string)InfoManager.GetField("PROCESS_ROOTNODE_GUID").GetValue(null),
                ConnectionString = theServerProperties.ConnectionString
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(retVal);
        }

        return null;
    }

A: After some more investigation, it seems like the file was already loaded by another process/assembly perhaps.  Changing from Reflection.LoadFile() to Reflection.LoadFrom() resolves the issue.


text:
Q: What is a reasonable way to convert a complicated Ant script to a set of Eclipse projects? I inherited an existing Ant build script. It invokes javac three times on three different source directories: shared, client, and server. It then produces two JAR files: client.jar (shared + client) and server.jar (shared + server).
When I translated this to Eclipse, I ended up making three projects with appropriate dependencies. This works, but I'm not a fan of the Eclipse project explosion (this was an easy case; I have about a dozen such ant scripts, and some would turn into 6 or 7 Eclipse projects).
My question: is there a better way?
I should also mention that I don't want to simply create one Eclipse project with three source directories. That's not the way that Ant compiles the code, and it would make it harder to find cases where people were using classes from an inaccessible source tree (using server classes from the client code). (I also happen to have classes with the same name in client and server, so I actually can't just dump all the source together.)

A: We have a similar project set up: 13 eclipse projects each with their own ant scripts. 7 of them are shared and produce JARs the other 6 are webapps that get packaged in to WARs. The ant script for each of the WAR-producing projects invokes the build in its dependencies and sucks the generated jars in to the lib. So, no, we don't have a better way, but I have a fuzzy vision for how things could be better if we switched from ant to maven:
The 7 shared projects change much less frequently than the webapps. I would like to publish those shared project JARs to our own repo and then for each of the webapps specify which version of the dependency they need and let maven handle getting it for us. That way we wouldn't need to have all of the JAR projects open in Eclipse unless we were making changes to them.


text:
Q: 5 red and 10 black balls in a bowl, with replacement Problem A bowl contains $5$ red and $10$ black balls. A ball is picked randomly and the colour is noted. After every pick the ball is placed back, and an extra ball of the same color is added to the bowl. Determine the following:
(i) Given that the first $n$ balls are all black, what is the probability (say $\alpha_n$) that the ($n+1$)-st ball is also black? What is $\lim_{n \to \infty} \alpha_n$ ?
(ii) Given that the second until the $(n+1)$-st ball are all black, what is the probability (say $\beta_n$) that the first drawn ball is black. What is $\lim_{n \to \infty} \beta_n$?
My Attempt:
(i) Let $A_i$ be the event that on the $i$th pick the ball is black. Then $$P(A_1) = \frac{10}{15}, P(A_2) = \frac{11}{16}, P(A_3) = \frac{12}{17}, \ldots $$ Let $B_n$ be the event that the first $n$-balls were all black. Then I computed $$P(B) = P(A_1) P(A_2) \ldots P(A_n) $$ and so $$P(B_{n+1}) = \alpha_n = \big( \frac{10}{15} \big) \big( \frac{11}{16} \big) \ldots \big( \frac{10 + n-1}{15+n-1} \big) \big( \frac{10+n}{15+n} \big). $$
I think that $\lim_{n\to \infty} \alpha_n = 1$, though not sure how to show this.
Is my reasoning correct, and how to solve problem (ii)? Help is appreciated.

A: $\alpha_n$ is the probability that the $(n+1)$-th draw is black, given that the first $n$ are.   So it is simply $$\alpha_n =\frac{10+n}{15+n}$$

Let $F$ be the event that the first extraction is black.  $\quad \mathsf P(F)=\frac{10}{15}\\\quad \mathsf P(F^\complement)=\frac 5{15}\\\therefore \mathsf P(F)=2~\mathsf P(F^\complement)$
Let $S_n$ be the event that the next $n$ extractions are all black. (The second to $(n+1)$-th)
$$\begin{align}\beta_n = \mathsf P(F \mid S_n) =&~ \dfrac{\mathsf P(S_n\mid F)~\mathsf P(F)}{\mathsf P(S_n\mid F)~\mathsf P(F)+\mathsf P(S_n\mid F^\complement)~\mathsf P(F^\complement)}
\\[1ex] =&~ \dfrac{2~\mathsf P(S_n\mid F)}{2~\mathsf P(S_n\mid F)+\mathsf P(S_n\mid F^\complement)}
\end{align}$$
Evaluate the two conditionals and simplify.


text:
Q: Simple Form Radio Buttons - Display inline I'm trying to use Simple Form in my Rails 4 app (with twitter bootstrap).
I have this line in my form. It is a question with a Yes or No answer. I'd like the button to be inline with the label. At the moment, the button appears above the label (so 4 rows, for button, Yes, button, No).
 <%= f.collection_radio_buttons :project_image, [[true, '  Yes'] ,[false, '  No']], :first, :last, :inline,  {:class => "create-project", :style=> 'width: 650px' }  %>

I should also say that I have tried the solutions posted here:
    simple_form_for rails radio button inline and have tried this line:
<%= f.collection_radio_buttons :project_image, [[true, '  Yes'] ,[false, '  No']], :first, :last, {:inline_label=> true}, {:class => "create-project", :style=> 'width: 650px' }  %>

Inspecting that in google shows that there are separate  and  tags.
I have not been able to get this to render inline. Please can you help me understand how to render radio buttons inline the above line.
In response to the suggestion below about adding bootstrap styling to simple form. I tried:
     <label class="checkbox-inline">
      <%= f.collection_radio_buttons :project_image, [[true, '  Yes'] ,[false, '  No']], :first, :last,  {:item_wrapper_class => 'inline'}, {:class => "create-project", :style=> 'width: 650px' }  %>
  </label>

The result of the above was to slightly indent the segment but still not rendering inline.
Thank you

A: Add radio-inline class to your radio buttons.
Refer: http://getbootstrap.com/css/#forms

A: If the above doesn't work for you, try:
<%= f.collection_radio_buttons :project_image, [[true, 'Yes'] ,[false, 'No']], :first, :last) do |b| b.label { b.radio_button + b.text } %>


text:
Q: SQLCMD Incorrect syntax near '.' When executing a stored procedure using SQLCMD with the following parameters:
. sqlcmd -S $sql_server -U $sql_usr -P $sql_pwd -d $sql_db -Q "EXEC $storedProc $dateVariable, $regionType, ALM.10.2.33.1" -V 1 -b

The following message is received:
Incorrect syntax near '.'.
If I pass ALM_10_2_33_1 instead of ALM.10.2.33.1, the stored procedure is executed perfectly.
Thanks,

A: Delimit the parameter correctly with single quotes
"EXEC $storedProc $dateVariable, $regionType, 'ALM.10.2.33.1'"

SQL Server has quirk that allows (var)char parameters to be specified without delimiters if they don't contain certain characters like ..
You can see it in MSDN
EXEC sp_addserver <'new_name\instancename'>, local

But if you check sp_addserver, @local is varchar(10), and 'LOCAL' is mentioned as the value required.

A: Try wrapping ALM.10.2.33.1 in square brackets:
[ALM.10.2.33.1]


text:
Q: DIfference between Bigquery and GA in sessions per Landing content grouping I want to use Bigquery to report on the number of sessions per landing content group per source / medium. Basically I want to reproduce the GA report: Behaviour - Site content - Landing Pages - Select content group - Select custom dimension Source / Medium.
Bigquery reports more sessions (around 1% - 2%) as GA. Is there something wrong with this query? (No sampling in GA)
SELECT
  date,
  Landing_Content_Group,
  Source_Medium,
  COUNT(1) AS Sessions
FROM (
  SELECT
    date,
    CONCAT(fullVisitorId,STRING(visitId)) AS sessionId,
    hits.contentGroup.contentGroup1 AS Landing_Content_Group,
    trafficSource.source +'/'+ trafficSource.medium AS Source_Medium
  FROM (TABLE_DATE_RANGE([TABLE], DATE_ADD(CURRENT_TIMESTAMP(), -3, 'DAY'), DATE_ADD(CURRENT_TIMESTAMP(), -3, 'DAY')))
  WHERE
    hits.hitnumber = 1
  GROUP BY
    date,
    sessionId,
    Landing_Content_Group,
    Source_Medium )
GROUP BY
  date,
  Landing_Content_Group,
  Source_Medium
ORDER BY Sessions DESC

A: CONCAT(fullVisitorId,STRING(visitId)) AS sessionId is good to count sessions without midnight split. visitId stays the same over the split.
Use CONCAT(fullVisitorId,STRING(visitStartTime)) AS sessionId and totals.visits=1 (=sessions with any interaction) to be consistent with GA.


text:
Q: C — warning: control reaches end of non-void function [-Wreturn-type] I am a newbie in C programming.
Can anyone help me to explain about the error that I'm getting.
I don't understand why I'm getting this error.
test4.c: In function 'main':
test4.c:65:3: warning: control reaches end of non-void function [-Wreturn-type]

Below is my code :
#include <webots/robot.h>
#include <webots/distance_sensor.h>
#include <webots/differential_wheels.h>

#define TIME_STEP 64

int main()
{
   wb_robot_init();
   int i;
   WbDeviceTag ps[8];
   char ps_names[8][4] = {"ps0","ps1","ps2","ps3",
      "ps4","ps5","ps6","ps7"};

   for(i=0;i<8;i++)
   {
      ps[i]=wb_robot_get_device(ps_names[i]);
      wb_distance_sensor_enable(ps[i], TIME_STEP);
   }

   while(1)
   {
      int delay=wb_robot_step(TIME_STEP);
      if(delay==-1)
         break;

      double ps_values[8];
      for(i=0;i<8;i++)
         ps_values[i]=wb_distance_sensor_get_value(ps[i]);
      //printf("ps0=%d\t", ps_values[0]);

      double left_speed=500;
      double right_speed=500;

      for(;;)
      {

         if(ps_values[0]>80 || ps_values[1]>80 || ps_values[2]>80)
         {
            left_speed =-500;
            right_speed =500;
         }
         else if(ps_values[5]>80 || ps_values[7]>80 || ps_values[2]>80)
         {
            left_speed =500;
            right_speed =-500;
         }
         else
         {
            left_speed =500;
            right_speed =500;
         }

      }
      wb_differential_wheels_set_speed(left_speed, right_speed);
      wb_robot_cleanup();
      return 0;
   }
}

A: You have a non-void function that is not returning a value. Your compiler has analyzed that the end of the function can be be reached.
if(delay==-1)
    break;

So your omission of a return statement is suspect or wrong.
Add a return 0; or anything sensible value at the end of the function.
The main function is special. It is valid C to return no value. But even if it's legal to skip the return the compiler can give you a diagnostic message (a.k.a. warning).
You can try to convince your compiler that this is okay with some kind of pragmas or command line arguments. Or you give up and return a value, even if you don't think it's necessary. This will suppress this warning. (One statement is not that expensive.)

A: It seems to me that the return statement you have at the end of your while loop was placed there by mistake. Otherwise, the function will return after one round of execution of the code inside the loop. What's the point of the loop then?
Instead of
   while(1)
   {
      int delay=wb_robot_step(TIME_STEP);
      if(delay==-1)
         break;

      ....
      ....

      wb_differential_wheels_set_speed(left_speed, right_speed);
      wb_robot_cleanup();
      return 0;
   }

Perhaps you meant to use:
   while(1)
   {
      int delay=wb_robot_step(TIME_STEP);
      if(delay==-1)
         break;

      ....
      ....

      wb_differential_wheels_set_speed(left_speed, right_speed);
      wb_robot_cleanup();
   }

   // The return statement outside the while loop.
   return 0;

This will fix the compiler warning too.


text:
Q: Change height of jspDrag? I'm using jspScrollpane on a div with a ton of text (a full movie script). Due to the huge amount of content and the limited height of the container div (600px) the vertical scrollbar handle (jspDrag) becomes tiny.
I tried changing the height in the css file but it doesn't work so I'm assuming it is controlled in the js file(?)
How can I set the height of jspDrag regardless of the amount of content?
Thanks

A: This can be frustrating for sure. Since its controlled by the javascript you can override the priority by adding !important after that specific line and it will work. See example below. Hope that helps out.
.jspDrag {
    height:77px !important;
    top:1px;
    background:url(images/exammpleimage.png) top left no-repeat;
}

A: you can use auto autoresize: auto to reinitialize it self when needed. If  the vertical scroll doesn't have the right height, make sure that your content width is not bigger than width of the container. (ex image that is too big, some div with width 100 + margins) etc.
$('#content-wrapper').jScrollPane({
    showArrows: true,
    autoReinitialise: true
});


text:
Q: foreachRDD in Spark Stream will not write file This is my Spark Streaming job:
object StreamingTest {
    def main(args: Array[String]) = {
        val sparkConf = new SparkConf().setAppName("StreamingTest")
        val ssc = new StreamingContext(sparkConf, Seconds(10))
        ssc.checkpoint("checkpoint")
        val lines = KafkaUtils.createStream(
                        ssc,
                        "localhost:2181/kafka",
                        "streaming-group",
                        Map("streaming-topic" -> 1),
                        StorageLevel.MEMORY_AND_DISK
        ).map(_.2)
        lines.flatMap(_.split(" ")).map(token => s"${token} => ${token.hashCode}")
            .foreachRDD(rdd => {
                rdd.saveAsTextFile(s"/results/raw-${System.currentTimeInMillis()}.txt")
            })
        lines.flatMap(_.split(" ")).map(token => s"${token} => ${token.hashCode}")
            .saveAsTextFiles("/results/raw", "test")
        ssc.start
        ssc.awaitTermination
    }
}

The last save operation works. It writes files to /results/raw. The one inside the foreach loop does not. Can someone explain why?


text:
Q: Atmega32 can't verify after setting correct fuses for external crystal. HELP I am having trouble with some Atmega32A's purchased off from eBay. The MCU's does not seem to be fake as they are functioning properly. I am experiencig the following problem: I want to use external crystal of 14.7456MHz. With default fuse settings (
0xE1 / 0b11100001 low fuse;
0x99 / 0b10011001 high fuse;

) I am able to program the MCU and it verifies, everything is OK when it works with internal clock speed at 1MHz. When I change high fuse to 0b11001001 to disable JTAG and program CKOPT, it works again. But when I change low fuse to make the MCU to use external clock, it writes the hex, but cannot verify the MCU, and it's not working. Here's the output:
> "make.exe" program
avrdude -p atmega32 -P usb -c usbasp    -U flash:w:main.hex

avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9502
avrdude: NOTE: FLASH memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: reading input file "main.hex"
avrdude: input file main.hex auto detected as Intel Hex
avrdude: writing flash (15896 bytes):

Writing | ################################################## | 100% 6.73s

avrdude: 15896 bytes of flash written
avrdude: verifying flash memory against main.hex:
avrdude: load data flash data from input file main.hex:
avrdude: input file main.hex auto detected as Intel Hex
avrdude: input file main.hex contains 15896 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 4.87s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0x0c != 0x00
avrdude: verification error; content mismatch

avrdude done.  Thank you.

make.exe: *** [program] Error 1

> Process Exit Code: 2
> Time Taken: 00:12

The programmer is working fine, I can confirm the circuit is working because it's working with Atmega32 when setting to use external clock (I am using 2x22pF ceramic capacitors right next to the crystal). The issue is with these Atmega32A's. What can be the reason? I found this, but I think 1111 is the correct one for the crystal.
Device clocking options             CKSEL 3..0
External crystal/ceramic resonator  1111-1010
External low frequency crystal      1001
External RC oscillator              1000-0101
Calibrated Internal RC oscillator   0100-0001
External clock                      0000

Thanks in advance.


text:
Q: Poor FPS in game while streaming I have been recently streaming and I have set my stream onto all the best settings for my internet speed and the right resolution etc.
Here is my speed test results (speedtest.net):

While I stream people say that the stream is really smooth and gameplay looks fine however in game for me I get a terrible FPS! Usually on Medium settings (In Minecraft) I get around 20-70 FPS however I see a MASSIVE drop when streaming which is around 10-30 FPS!?!? Can someone please help me and try and see what I can do to solve this?
P.S I use OBS to stream to Twitch.tv

A: I'm going to make this an answer so I can give a more complete and better formatted reply.
First off, keep in mind that most popular streamers usually have a separate computer dedicated toward streaming. This requires a significant investment!
In order to immediately improve your performance you should put minecraft at the lowest possible settings as well as look to reduce the compression ratio of OBS. Higher ratio = more work for your CPU = FPS lag/drops. I'm at work at the moment, but when I get home I could look into it further. Don't worry about burning out your CPU either. The only way that would happen is if youre trying to overclock it or if its just faulty. Feel free to adjust the priority,  just understand that it can negatively impact the performance of other programs including OBS. If you prioritize Minecraft you run the risk of taking processing power from OBS which will cause your stream to lag.
Having a good rig doesn't always guarantee the ability to stream either. I can hit about 200 fps in league on my computer, but if I try streaming I get a considerable performance drop along with a nearly imperceptible delay.
I'll add onto this if anything else comes to mind as my caffeine kicks in.