Q:

Ajax call on custom component: insufficient privileges

I wrote a VisualForce page that has two drop-down lists. When the user selects an item from the first list, it makes an Ajax call to populate the second list. Everything worked great.
I split the <apex:pageBlock> into its own component, and now the Ajax call shows an error after making a selection in the first list:
Insufficient Privileges
You do not have the level of access necessary to perform the operation you requested. Please contact the owner of the record or your administrator if access is necessary.
The thing is, I am an administrator. This worked fine all in one VisualForce page, but now that it is split into a separate component, it fails. The debug log shows no failures. It does not tell me the specific object with the permission error. Based on some debug logging that I added, it appears to be failing before it even enters any Apex code. I think the failure is somewhere in the Ajax call but unfortunately none of the logging or error reporting tells me anything useful.
Unfortunately I cannot share the actual code/VF that causes this because it is proprietary to the customer, but here is a SSCCE:
VisualForce:
<apex:page id="pageId" controller="MyController">
  <apex:form id="mainFormId">
    <apex:sectionHeader subtitle="Custom Lookup Demo" title="Custom Lookup"/>
    <c:MyComponent />
  </apex:form>
</apex:page>

VisualForce Component:
<apex:component controller="MyController">


Q:

RFID-Safe Wallet destroys mag stripe?

I'm getting a hang of paying with credit cards, and contactless payment especially, lately (which was quite uncommon where I live until like a few months ago). I'm now looking to buy one of these small credit card wallets because of the comfort and small profile, but also in order to get something with RFID safety.
I'm not really informed on how they actually work. However while searching for a good looking wallet online, I now read on multiple articles that people are complaining about the RFID system destroying their credit cards (the magnetic stripe).
I'm now concerned about whether really getting such a RFID safe wallet. Is it possible for systems like that to destroy your credit cards in such a way?

A:

Short answer: No.
Long answer: Nooooooo.
Longer answer: RFIDs typical work via magnetic coupling to both power and to transmit data. By modulating the load on the secondary coil of the magnetic couple (aka transformer), the RFID card is able to effect a back EMF on the primary coil.
RFID-proof wallets disrupt this by creating a Faraday cage (i.e. opaque box to RF) which prevents the magnetic coupling from occurring.
In order words, it is literally a tinfoil hat.
Seriously. You can build your own RFID-proof wallet by putting tinfoil in it.

A:

What can happen, and actually had happen, is that some card holder were badly designed and included a simple magnet for locking.
This will do nothing to the RFID part of the chip, but it can damage the magnetic strip that is used in some terminal (The ones where you slide the card and don't have to enter your pin code).
Note that this is not limited to "RFID safe" wallet, but can happen with any magnetic locking wallet if you get the strip to close to the magnet. This was also known to disable some bus ticket or other magnetic cards.


Q:

Can't send streamed data from client to server via WCF

I'm trying to send some data from client to server using streaming functionality in WCF. I can read stream returned from server with no issues. Other way around doesn't work however.
Tried wrapping stream in class decorated with MessageContract with no success.
Client config:
    <bindings>
      <netTcpBinding>
        <binding name="streamingBinding" transferMode="Streamed"
    maxReceivedMessageSize="5000000000">
          <security mode="None" />
        </binding>
      </netTcpBinding>
    </bindings>

Server config:
    <bindings>
      <netTcpBinding>
        <binding name="streamingBinding" transferMode="Streamed"
    maxReceivedMessageSize="5000000000">
          <security mode="None" />
        </binding>
      </netTcpBinding>
    </bindings>

...
    <service behaviorConfiguration="WcfSvc.WcfServiceBehavior"
    name="Shared.StreamingService">
        <endpoint address="" binding="netTcpBinding"
    bindingConfiguration="streamingBinding"
                  contract="Shared.IStreamingService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexTcpBinding"
    bindingConfiguration=""
                  contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:8733/StreamingTest/" />
          </baseAddresses>
        </host>
      </service>

Host app:

    private static IStreamingService _service;
    private static ServiceHost _serviceHost;

    static void Main()
        {
            _service = new StreamingService();
            _serviceHost = new ServiceHost(_service);
            _serviceHost.Open();

            Console.WriteLine("Press enter to read data");
            Console.ReadLine();

            var stream = _service.GetData();
            var file = File.Create(@"PATH TO NON EXISTING FILE");
            stream.CopyTo(file);
            file.Close();

            Console.WriteLine("Press enter to close host");
            Console.ReadLine();

            _serviceHost.Close();
        }

Client app:
    private const string EndpointAddress = "net.tcp://localhost:8733/StreamingTest/";
        private const string TcpBindingConfigName = "streamingBinding";

        private static WcfChannelFactory<IStreamingService> _factory = new WcfChannelFactory<IStreamingService>();
        private static IStreamingService _service;
        private static ICommunicationObject _communicationObject;

        static void Main()
        {
            Console.WriteLine("Press enter to connect");
            Console.ReadLine();

            (_service, _communicationObject) = _factory.OpenAsync(EndpointAddress, TcpBindingConfigName).Result;

            var s = File.OpenRead(@"PATH TO EXISTING FILE");
            _service.SetData(s);

            Console.WriteLine("Press enter to disconnect");
            Console.ReadLine();

            _communicationObject.Close();
        }

Service:
    [ServiceContract(SessionMode = SessionMode.NotAllowed)]
    public interface IStreamingService
    {
        [OperationContract]
        void SetData(Stream data);

        [OperationContract]
        Stream GetData();
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class StreamingService : IStreamingService
    {
        private Stream _data;

        public void SetData(Stream data)
        {
            _data = data;
        }

        public Stream GetData()
        {
            return _data;
        }
    }

Channel factory implementation:
    public class WcfChannelFactory<TService>
    {
        private ChannelFactory<TService> _channelFactory;

        public async Task<(TService, ICommunicationObject)> OpenAsync(string endpointAddress, string tcpBindingConfigName)
        {
            var tcpBinding = new NetTcpBinding(tcpBindingConfigName);
            _channelFactory = new ChannelFactory<TService>(tcpBinding);
            await Task.Factory.FromAsync(_channelFactory.BeginOpen, _channelFactory.EndOpen, null);
            var wcf = _channelFactory.CreateChannel(new EndpointAddress(endpointAddress));
            return (wcf, wcf as ICommunicationObject);
        }

        public void Close()
        {
            _channelFactory?.Close();
            _channelFactory = null;
        }
    }

Please fill file names at lines where file streams are created.
After running host and client, pressing enter in client window and then in host window exception is thrown:
System.ObjectDisposedException: Cannot access a closed Stream. (on line 'stream.CopyTo(file);' in host app)
Reverse scenario works just fine (sending file from server to client)

A:

I know what caused my problem. The problem is here:
public Stream GetData()
{
    return _data;
}

After returning from GetData method WCF automatically closes the stream. To propagate the stream outside of the service class I had to use an event:
public event Action<StreamMessage> DataSet;

public void SetData(StreamMessage data)
{
    _data = data;
    DataSet?.Invoke(data);
}

and then consume the stream in the event handler.


Q:

Binding an ASP.NET GridView Control to a string array

I am trying to bind an ASP.NET GridView control to an string array and I get the following item:

A field or property with the name
  'Item' was not found on the selected
  data source.

What is correct value I should use for DataField property of the asp:BoundField column in my GridView control.  Here is my source code:
ASPX page
<asp:GridView ID="MyGridView" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Item" />
        <asp:CommandField ButtonType="Link" ShowSelectButton="true" SelectText="Click Me!" />
    </Columns>
</asp:GridView>

Code Behind:
string[] MyArray = new string[1];
MyArray[0] = "My Value";
MyGridView.DataSource = MyArray;
MyGridView.DataBind();

UPDATE
I need to have the AutoGenerateColumns attribute set to false because I need to generate additional asp:CommandField columns.  I have updated my code sample to reflect this scenario

A:

After hours of search, I finally found that there is a special DataField for this case: "!"
<asp:GridView ID="MyGridView" runat="server" AutoGenerateColumns="false">
<Columns>
    <asp:BoundField DataField="!" />
</Columns>
</asp:GridView>

I hope it'll help someone one day :)

A:

Try replacing the BoundField with a TemplateField like so:
<asp:TemplateField HeaderText="String Value">
        <ItemTemplate>
            <%# Container.DataItem %>
        </ItemTemplate>
    </asp:TemplateField>

BTW I lifted this from another question

A:

One method is to pass it a class with a single, named field.  That way, you can give it a name.
public class GridRecord
{
    public string MyValue { get; set; }
}

Then convert your string array to a list of the class
string[] MyArray = new string[1];
MyArray[0] = "My Value";
List<GridRecord> MyList = (
    from ar in myArray
    select new GridRecord
    {
        MyValue = ar
    }).ToList();
MyGridView.DataSource = MyList;
MyGridView.DataBind();

Now you can name your DataField property
<asp:GridView ID="MyGridView" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="MyValue" />
    </Columns>
</asp:GridView>


Q:

Send data to a php script with AngularJS

I'm new in AngularJS and following some tutorials I was able to create a simple page and a simple form.
The problem is that every time I submit the form seems that the script is sending empty data.
This is my html:

Contatti

{{ message }}

        <form ng-submit="processForm()">

                Nome
                <input type="text" name="name" class="form-control" placeholder="chris" ng-model="formData.name">
                 {{ errorName }}

            <button type="submit" class="btn btn-large">
                Salva
            </button>
        </form>

    {{ formData }}

This is the js:
//Creo il modulo e includo ngRoute come dipendenza
var scotchApp = angular.module('scotchApp', ['ngRoute']);

//Configuro le routes
scotchApp.config(function($routeProvider){

    $routeProvider

        .when('/', {
            templateUrl: 'pages/home.html',
            controller: 'mainController'
        })

        .when('/chi-siamo', {
            templateUrl: 'pages/chi-siamo.html',
            controller: 'aboutController'
        })

        .when('/contatti', {
            templateUrl: 'pages/contatti.html',
            controller: 'contactController'
        });

});

//Creo il controller che gestisce la home
scotchApp.controller('mainController', function($scope){
    $scope.message = "Sono in home";
});

//Controller che gestisce la pagina chi-siamo
scotchApp.controller('aboutController', function($scope){
    $scope.message = "Sono in Chi siamo";
});

//Controller che gestisce la pagina contatti
scotchApp.controller('contactController', function($scope, $http){

    $scope.formData = {};

    $scope.processForm = function(){

        console.log($scope.formData);

        $http.post('process.php', $scope.formData)
             .success(
                function(data){

                    console.log(data);

                    if( data.success )
                    {
                        $scope.message = data.message;
                    }
                    else
                    {
                        $scope.errorName = data.errors.name;
                    }

                }
             );
    }
});

and this is a very simple php script:
<?php
// process.php

$errors = array();  // array to hold validation errors
$data = array();        // array to pass back data

// validate the variables ========
if (trim($_POST['name']) == '')
  $errors['name'] = 'Name is required.';

// return a response ==============

// response if there are errors
if ( count($errors) > 0 ) {

  // if there are items in our errors array, return those errors
  $data['success'] = false;
  $data['errors']  = $errors;
} else {

  // if there are no errors, return a message
  $data['success'] = true;
  $data['message'] = 'Success!';
}

// return all our data to an AJAX call
echo json_encode($data);

Even if I write some data in my input in the console I get:
Object {success: false, errors: Object}
errors: Object
name: "Name is required."
__proto__: Object
success: false
__proto__: Object

Am I missing something?

A:

you need to get the data in php as,
$data = json_decode(file_get_contents("php://input"));

$data->name  // to access name

OR
add the jquery and
change the headers,
$http({
    url: "process.php",
    method: "POST",
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data: $.param($scope.formData)
}).success(function(data, status, headers, config) {

}).error(function(data, status, headers, config) {

});

in php
$name= $_POST['name'];

if you need to change the headers of all ajax requests then do it in config block for EX,
app.config(['$httpProvider' , '$routeProvider', function ($httpProvider, $routeProvider) {
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
}])


Q:

Как полностью отключить программу c#?

Есть программа, при запуске которой начинает выполняться много разных функций, и курсор начинает передвигаться по всему экрану, если программу закрыть через крестик, то она все равно продолжает работать и таскать курсор по экрану, как можно полностью остановить выполнение программы?

A:

Application.exit()

Сообщает всем потребителям сообщений, что они должны завершиться, а затем закрывает все окна приложения после того, как сообщения будут обработаны.

MSDN


Q:

Event entries scheduling algorithm PHP

we have an entry portal system in which we accept entries for events.
For example Championship Event 2017 will be held on 30th Nov.
Event got about 150 entries in different classes. Junior Class, Senior Class, Pro Class etc.
Now event venue only has certain numbers of ground on which the competition can be held. For example Ground 1, Ground 2 and Ground 3. Its a solo performance event.
Now our system needs to generate a schedule in such a way that competitors who entered multiple classes or same classes multiple times should get maximum break between their performances.
The input data we have are registration under each class.
Starting time of each Ground. For example Ground A will start at 8:00 AM, Ground 2 at 8:00 and Ground 3 at 9:00.
We also know that which class will be held in which arena. For example Junior and senior Class will be held in Ground 1 and Pro Class will be held in Ground 2.
We know the performance time as well. Senior Class 1 performance is 5 minutes. Junior class performance is 7 minutes and Pro Performance is 9 minutes.
Now I have written following code to get the schedule so that competitors competing multiple times in one class or in multiple class get maximum break between their performance but it still puts same competitor performance one after another.
Let me know what is my mistake.
foreach ($totalPerformanceTimeSlot as $time => $performance) {
    # $totalPerformanceTimeSlot is array of timeslots starting from 8:00 am

    foreach ($performance as $classId) {
        #there could be 2 performance at the same time in different arena for different class.
        $totalPerformanceLeftThisClass = count($this->lassRegistrationLinks[$classId]); //Get the total performance for this class from array;

        # $accountRidesLeftArray has value of how many times each account is performing in this class
        arsort($accountRidesLeftArray);
        # for each person,  estimate what their start time threshold should be based on how many times they're performing
        $accountPerformanceTimeThreshold = array();

        foreach ($accountPerformanceLeftArray as $accountId => $accountPerformancesLeft) {

            $tempPerformanceThreshold = 20 * 60;
            # reduce this person's performance threshold by a performance at a time until the minimum performance threshold has been met
            while ((($totalPerformanceLeftThisClass * $this->classes[$classId]['performanceTime']) / $accountPerformanceLeft < $tempPerformanceThreshold) && ($tempPerformanceThreshold > $this->minRideThreshold))
                $tempPerformanceThreshold -= $this->classes[$classId]['performanceTime'];

            $accountPerformanceTimeThreshold[$accountId] = $tempPerformanceThreshold;
        }

        $performanceLeft = $totalPerformanceLeftThisClass - $count;

        # given the number of performance left in the class,
        # calculate how important it is per account that they get placed in the next slot
        $accountToPerformNextImportanceArray = array();
        $timeLeft = $performanceLeft * $this->classes[$classId]['performanceTime'];

        foreach ($accountPerformanceLeftArray as $accountId => $accountPerformancesLeft) {

            # work out the maximum number that can be used as entropy
            $entropyMax = (20 * 60 / ($timeLeft / 1)) * 0.5;
            $entropy = ((mt_rand (0, $entropyMax * 1000)) / 1000);

            # the absolute minimum amount of time required for this user to perform
            $minTimeRequiredForComfortableSpacing = ($accountRidesLeft - 1) * 20* 60;
            # add a bit of time around the absolute minimum amount of time required for this person to perform so that it doesn't instantly snap in when this person suddenly has the minimum amount of time left to perform
            $generalTimeRequiredForComfortableSpacing = $minTimeRequiredForComfortableSpacing * 1.7;

            $nearestPerformancePrior = $this->nearest_performance_prior($classDetails['date'], $currentTime, $accountId);
            $nearestRideAfter = $this->nearest_performance_after($classDetails['date'], $currentTime, $accountId);

           # work out how important it is for this rider to ride next based on how many rides they have left
           $importanceRating = 20 * 60 / ($timeLeft / $accountPerformanceLeft);

           # if there's more than enough time left then don't worry about giving this person any importance rating,  ie. it's not really important that they perform straight away
           if ($timeLeft > $generalTimeRequiredForComfortableSpacing)
                $importanceRating = 0;

           # add a little bit of random entropy to their importance rating
           $importanceRating += $entropy;

           # if this account has performed too recently to place them here in this slot,  then make them very undesirable for this slot
           if ((!is_null($nearestPerformancePrior)) && ($nearestPerformancePrior > $currentTime - $accountPerformanceTimeThreshold[$accountId]))
               $importanceRating = -1;

          # work out if this account will perform too soon afterwards to place them here in this slot,  then make them very undesirable for this slot
          if ((!is_null($nearestRideAfter)) && ($nearestRideAfter < $currentTime + $accountRideTimeThreshold[$accountId]))
               $importanceRating = -1;

           $accountToPerformNextImportanceArray[$accountId] = $importanceRating;

       }

       arsort($accountToPerformNextImportanceArray);
       //Then I take the first one from this array and allocate the time for that user.
       $this->set_performance_time($classDetails['date'], $accountId, $currentTime);
       $currentTime += $this->classes[$classId]['performanceTime'];
    }
}

Here is some explanation of the variables
$accountPerformancessLeft is total number of performance for each user.
For e.g. if user has entered into 2 classes that means $accountPerformancessLeft is 6 for that user.
threshold is something like break.
Rider and account is conceptually the same.

I know it is hard to think the output without the actual data but any help would be appreciated.
Thank you

A:

Well, first let's see what we have and simplify the problem:

There are different competitions(events) but since they are independent to each other we can consider only one
We have C different classes (senior, junior, ...)
We have G different grounds that each ground may hold some of C classes.
There are some persons(competitor) lets say P who registers to C classes.
Persons need to have maximum possible break.

So putting them all together the problem is:
The are some grounds G = {g1, g2, ..., gm} that each of them contains some persons P = {p1, p2, ..., pn}. We want to maximize the break time of each person in all of its competitions.
The trivial case:
First, let's assume that there is only one ground g1, and a group of person P = {p1, p2, ..., pn} who wants to compete on this ground. let's define a boolean method isItPossible(breaktime) showing that whether it is possible to schedule the competition that each person has at least breaktime to rest or not. we can simply prove that this method is monotonic i.e. if there exist a breaktime that isItPossible(breaktime) became true then:
isItPossible(t) = true       for every t <= breaktime

So we can use binary search to find the maximum value for breaktime. Here is the pseudo code (C++ syntax like):
double low = 0 , high = INF;
while(low < high){
    mid = (low + high) / 2;
    if(isItPossible(mid))
        low = mid;
    else
        high = mid;
}
breakTime = low;

Now the only thing remains is implementing isItPossible(breaktime) method. There are a lot of ways to implement it but I use greedy algorithm and a heap priority queue to solve it. We need a priority queue for maintaining some tuples. Each tuple contains a person, the number of time that person should compete and the earliest time we can schedule a competition for that person. We start from time t0 (the opening time of the ground e.g. it could be 8.00 a.m.) and each time we pick a person from the priority queue with the minimum earliest time. Here is the C++ like pseudo code:
bool isItPossible(double breaktime){
    //Tuple(personId, numberOfCompete, earliestTime)
    priority_queue<Tuple> pq;
    for p in Person_list
        pq.push(Tuple(p,countCompetition(p),t0));

    for(time = t0;time<end_of_ground_time;){
        person = pq.pop();
        add_person_to_scedule_list(person.personId, max(time, person.earliestTime));
        time = max(time, person.earliestTime) + competition_time;
        if(person.numberOfCompete > 1)
            pq.push(Tuple(person.Id,person.numberOfCompete - 1,time + breaktime)));
    }
    return pq.isEmpty();
}

The main problem:
After solving the trivial case we are ready to solve the original problem. In this case there are G = {g1, g2, ..., gm} grounds and we want to schedule P = {p1, p2, ..., pn} competitors. Like the trivial case we define a isItPossible(breaktime) function. Again we can prove that this function in monotonic, so we use binary search for finding the maximum value (like the above code). After that we only need to implement the isItPossible(breaktime) method. In this case implementing this method is little tricky.
For this method you can do some heuristic algorithms or some creative greedy ones (for example distribute each person start time base on breakTime over all grounds and check whether it is possible to do it for all persons or not). But again I suggest you to use Greedy algorithm and priority queue like the trivial case. Your tuple should also contains number of times that person compete in each ground, and when you want to increase time and sweep it, you should iterate over all grounds and schedule them simultaneously.
Hope it can help you. Of course there are some evolutionary algorithms like genetic or PSO to solve it (I can also explain them if you want) But using the above method is much simpler to implement and debug.


Q:

Different templates for UpdateView for the same model in Django

So I've got a template listing different products in user cart - I would like to give user a chance to update each product from this view. But depending on product type I would like to display different 'update_templates'.
What should be the best scenario for this situation?
Should I use few different UpdateViews for the same model? Like:
class ProductType1UpdateView(UpdateView):
    model = CartItem
    fields = '__all__'
    template_name_suffix = '_product1_update_form'

class ProductType2UpdateView(UpdateView):
    model = CartItem
    fields = '__all__'
    template_name_suffix = '_product2_update_form'

Or should I make it in one view, and add some if statements that will display proper template depending on product type? Like:
class ProductUpdateView(UpdateView):
    model = CartItem
    fields = '__all__'
    {here if statement checking product id}
         template_name_suffix = '_product1_update_form'
    {elif}
         template_name_suffix = '_product2_update_form'

The first option works, but it doesn't feel right to me. How would I formulate my if statement to make it with the second option. Or is there maye another, better way to do it?

A:

You can override get_template_names() function, like this:
class ProductUpdateView(UpdateView):
    model = CartItem
    fields = '__all__'

    def get_template_names(self):
         if self.kwargs.get('id') == 1:
             self.template_name_suffix = '_product1_update_form'
          else:
             self.template_name_suffix = '_product2_update_form'
          return super(ProductUpdateView, self).get_template_names()


Q:

Create an order for JSON to be loaded

I have multiple external JSON files that need to be loaded on my page. Is there a way to set an order for them to be loaded.
JavaScript
const func1 = () => {
    $.getJSON(json1, result => {});
    $.getJSON(json2, result => {});
}
...
    const func2 = () => {
    $.getJSON(json3, result => {});
    $.getJSON(json4, result => {});
}

Right now I have 4 different getJSON and now as I can see, this is the loading order = json1=>json3=>json4=>json2.
Is there a way to set an order on when to load the json files. I want to load it json1=>json2=>json3=>json4?

A:

The issue you're seeing is because the requests are all asynchronous. As such you are entirely at the mercy of the network between the client's machine and the receiving server, as well as the load the server is under at that given moment and how strenuous each task you're asking to be done is, as to which of those requests are received and responded to first.
There are ways to mitigate this in your client-side logic, such as request chaining or synchronous requests, however the former has a negative effect of UI performance and the latter is terrible practice as it locks the browser until all requests complete.
The best approach to take if you need to rely on the order of the response, is to instead aggregate all of these requests in to a single one and send that alone. Your client-side logic can then continue processing as it has access to all the data you require. This will also scale much better in terms of server performance. It may require some changes to your server side logic, however, but this is a small price for both better client-side logic and server-side performance.


Q:

JButton background images

I'm writign a POS system(point of sale) for fun.  A typical feature of a POS system is buttons that have different background colors for different products.  But I don't mean the background behind the button's image, i mean like in this random picture I got off google images:

Edit: Note I changed the look and feel to the system one
I need to do something like THAT with my buttons.  I know a few ways this COULD be possible:

Creating a look and feel for my buttons?
Completely overriding the paintComponenet method in my JButtons(But that's a pretty pathetic way to do it...  and the border + text isn't drawn when I override that... obviously a bad idea)
Using button.setContentAreaFilled(false);, and putting a JPanel of the same size as the button behind the button.

I don't really know how to create my own look and feel, and it sounds like a pain, especially just for 1 button, and I heard something about breaking the look and feel which scared me away from that idea.  The 3rd way sounds plausible, and not extremely difficult, but I what is the very best way to do what I am trying to do?
Right now my code for creating butons is this:
JButton b = new JButton(text);
    b.addActionListener(this);
    b.setFont(Main.f);
    b.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    buttons.add(b);
    return b;

I've messed around with this code(Mostly for fun, not practicality):
JButton b = new JButton(text){
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            Color bg = getBackground();
            int borderchange = -50;
            g.setColor(new Color(
                    Math.max(0,bg.getRed()+borderchange),
                    Math.max(bg.getGreen()+borderchange,0),
                    Math.max(bg.getBlue()+borderchange,0)));
            g.fillRect(0,0,getWidth(),getHeight());
            g.setColor(getBackground());
            int border = 4;
            g.fillRect(border,border,getWidth()-border,getHeight()-border);
            g.setColor(Color.BLACK);
            g.setFont(getFont());
            g.drawString(getText(),getWidth()/2,getHeight()/2);
        }
    };

A:

Creating a look and feel for my buttons?

Look and Feel is something like as theme,
by default this ColorScheme has a one, two, three Colors, this theme is applied for all Swing JComponents,
then all Swing JComponents have got the same Color, ColorScheme
not something that you looking for

Completely overriding the paintComponenet method in my JButtons(But
  that's a pretty pathetic way to do it...  and the border + text isn't
  drawn when I override that... obviously a bad idea)

JButton has array of Colors
you can to override paintComponent, fills whole area, Rectangle with one Color (not something that you looking for) or to use GradientPaint
you can to override BasicButtonUI
override proper key in UIManager and put there arrays of Colors

Using button.setContentAreaFilled(false);, and putting a JPanel of
  the same size as the button behind the button.

this could be easiest of ways, prepare Icons (or download set of Icons)
use proper methods, implemented  (Mouse & Key & KeyBindings) events

in the JButton API
override ButtonModel (by using ChangeListener)


Q:

How can we execute messages at a particular time daily in nodejs?

I want to execute the message daily at 10'o clock  5 minutes  25 seconds but I tried the program  I got an error:
ERROR OCCURED:
  throw patterns[5] + ' is a invalid expression for week day';
      ^
 is a invalid expression for week day

Code:
var cron = require('node-cron');
cron.schedule('25 05 10 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 January,February,March,April,May,June,July,August,September,October,November,December   Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday ', function(){
    console.log('Time for breakfast');
});

A:

The cron syntax is as described in the node-cron library page:
┌────────────── second (optional)
│ ┌──────────── minute
│ │ ┌────────── hour
│ │ │ ┌──────── day of month
│ │ │ │ ┌────── month
│ │ │ │ │ ┌──── day of week
│ │ │ │ │ │
│ │ │ │ │ │
* * * * * *

So, for executing the task every day at 10:05:25, try
25 5 10 * * *
cron.schedule('25 5 10 * * *', function() {
  console.log('Time for breakfast');
});


Q:

Filtering a numpy meshgrid

I would like to filter the values of a numpy meshgrid:
X,Y = np.mgrid[-10:10,-10:10]

in this case, I would like to remove all coordinates for which x**2 + y**2 <= 2.  However, when I try to filter the array directly, for example
filter(lambda x,y: x**2 + y**2 >= 2, np.meshgrid[-10:10,-10:10])

I get errors because I'm not properly dealing with the array's structure.
Any tips for doing this right would be appreciated!

A:

X,Y = np.mgrid[-10:10,-10:10]
idx = (X**2 + Y**2 > 2)
X, Y = X[idx], Y[idx]

The problem is that you no longer have 2D arrays, which may be an issue for things like matplotlib.

Seeing your own answer, and that you basically want to replace with 0 entries not fulfilling the condition, it is probably going to be cleaner and more efficient to do:
idx = X**2 + Y**2 > 2
X[~idx] = 0
Y[~idx] = 0


Q:

Run 3 threads and wait in Java

I'm trying to write a class that can only run X(Let's say 3)threads at one time. I have 8 threads that need to execute but I only want to allow 3 to run at once, then wait.  Once one of the currently running threads stops, then it will start another.  I'm not quite sure how to do this.  My code looks like this:
public class Main {
  public void start() {
    for(int i=0; i<=ALLTHREADS; i++) {
      MyThreadClass thread = new MyThreadClass(someParam, someParam);
      thread.run();

      // Continue until we have 3 running threads, wait until a new spot opens up.  This is what I'm having problems with
    }
  }
}

public class MyThreadClass implements Runnable {
  public MyThreadClass(int param1, int param2) {
    // Some logic unimportant to this post
  }

  public void run() {
    // Generic code here, the point of this is to download a large file
  }
}

As you can see above most of it is stubbed out pseudo-code.  I can post it if anyone would like but it's unimportant to the main question.

A:

you should use thread pooling mechanism here to run multiple threads.
to make it easy we can go for thread pool executor in java which is very easy
create a fixed pool of 3 threads using executors method.
write a for loop for 8 iteration and call execute on each thread and it will run only 3 threads at a time.
ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 8; i++) {
             Task task = new Task(someParam, someParam);
            executor.execute(task);
          }
        executor.shutdown();

A:

Unless this is homework, you can use Executors.newFixedThreadPool(3) which returns an ExecutorService with a max of 3 threads to perform Runnable tasks.


Q:

JS Draggable Viewport

I was wondering if it is at all possible to create a draggable viewport in JS. The idea is to have three DIVs layered on top of each other:

Top layer is a draggable viewport that reveals the bottom-most DIV (image)
Middle layer is a large image that covers the bottom DIV entirely
Bottom layer is a large image that is hidden by the middle layer (apart from the bit in the viewport)

I've found many helpful libraries to make a draggable DIV, but am not so sure that it is possible to make it see through the middle layer to reveal the bottom layer.
EDIT: I've uploaded a diagram of what I mean - The viewport looks "through" the middle layer, at the bottom layer - diagram

A:

With many thanks to charlietfl, I have solved my problem. I've used the JQuery UI Draggable plugin and dropped the number of layers down to two, simply adjusting the background position of the top DIV (#viewport) based on its own position.
HTML:

CSS:
#container {
    width: 1600px;
    height: 817px;
    background-image: url("assets/images/extras2/extras-top.jpg");
    position: relative;
}

#viewport {
    width: 338px;
    height: 235px;
    position: absolute;
    left: 300px;
    top: 20px;
    background-image: url("assets/images/extras2/extras-bottom.jpg");
    background-position: -300px -20px;
}

JS:
jQuery(function($){
    $("#viewport").draggable({containment: "#container", scroll: false});
    $("#viewport").on("drag", function(){
        $(this).css("background-position", "-" + $(this).position().left + "px -" + $(this).position().top + "px")
    });
});


Q:

Embedded Facebook Like-Box won't let me style it. Why?

I am trying put place a Facebook Like-Box on a page on my site, and then style it via my own CSS (chiefly to increase the height awarded to div#stream_content.  (The idea is to have the FB feed act as a news feed, but I don't want the user to have to scroll to see more the top two items or so as it does by default).
I have read and experimented with suggestions from these articles and more:
http://stackoverflow.com/questions/4064038/customizing-facebook-like-box,
http://www.daddydesign.com/wordpress/how-to-customize-your-facebook-fan-box/,
http://hitech-tips.blogspot.com/2010/05/facebook-like-button-xfbml-tutorial.html
I am going the FBML route (rather than using an iframe) as I gather is required for applying a cross-domain stylesheet.  I gather also that I need this doctype declaration for my webpage:
<!doctype html lang="en" xmlns:fb="http://www.facebook.com/2008/fbml" xml:lang="en">
So then I have this in the body of the page:

    <fb:like-box
            profile_id="***my ID here***"
            width="450"
            height="600"
            colorscheme="dark"
            show_faces="false"
            stream="true"
            header="false"
            logobar="0"
            css="http://***my domain here***/css/FBstyles.css?1"
            href="http://www.facebook.com/***my page name here***"
    ></fb:like-box>

But I still get these sorts of errors:
"(4) Unsafe JavaScript attempt to access frame with URL ...(my webpage)...from frame with URL http://www.facebook.com/plugins/likebox.php?channel=http%3A%2F%2Fstatic.ak.fbcdn.net%2Fconnect%2Fxd_proxy.php%3Fversion%3D2%23cb%3Dfd907a0e%26origin...blahblahblah. Domains, protocols and ports must match."
Where am I screwing up?

A:

I went this route too.  Although you are using FBML, the actual embedded code ends up being an iframe anyway.  (you can see it in the DOM with an HTML inspector after it loads).  About the only thing I was able to do was put it in a div with a colored background, since the iframe is transparent, and a border.
You are probably getting errors since the javascript on the Facebook server is trying to access the CSS on your server.  I didn't think you could do this.
EDIT:
In the StackOverflow link you provided, the posted answers clearly state that using your own CSS only works with a "Fan" box, not with a "Like" box.


Q:

How to find service record of Boston police detective (1945-1968)?

I have had no luck finding archives regarding Detective Frank (Franny, Francis) Murphy.
As a boy My Grandmother would show me a photo album with page after page of his exploits on and off duty! I was always amazed and have been unable to locate a thing now. The police department said, Do you know how many Francis Murphy's we have had?
I said he was a detective  and he said it did not matter, I recall he was in Roxbury and he was in the SS, secret services? My Father told me Franny was the kind of cop they wrote about, he lived on a boat in Boston and worked as security for a TV/Radio station in 1968 the year he retired and died.

My Mother showed me her album since then but I cannot find the paper I wrote down the names of his partner on.
I read he was very active in crime fighting, it was as if I was reading scripts for a detective TV show! My Father said Franny was well known as was his Mother and sister Mary, all the police knew them and Franny. Franny lived at home with his Sister and Mother when young and My Grandmother said they could go weeks without seeing him come or go, he was hiding his black eyes and stitches etc from his Mother. There was a story where he jumped off a fire escape and broke a guy's leg, another he was at a bar or restaurant and 2 robbers came in and he killed them off duty! There was one where he and his partner were the subject of an all night ride along, The reporter described Murphy as a squat large built person who could instantly move like lightning and was very good with his fists! It was as if his best buddies were reporters and they wrote about his many adventures to the point I assumed some body would recall him, but no.

A:

Create a biographical sketch and timeline, and a research plan.  To find his records in any archive, first you need to have enough specific information to be sure that you are asking about the right individual.
You read newspaper accounts in the scrapbook, so if you don't have access to the scrapbook, step one would be to find the newspaper accounts, and his obituary.  Newspaper sites like Genealogy Bank, Newspaper Archive, Google News Search, etc. might be available for search at your local public library if you can't afford a subscription.  When looking for an obituary, put in 1968, but search for a range around that year in case your father's memory of the date of death is not quite accurate. Use a keyword search to look for combinations of the keywords in your original question.  (SS = special services)
Assemble the information you find in chronological order to make a timeline.
The purpose of this is to make it easier to ask for and find any records which might exist.  The problem with genealogy these days is that advertising from big sites like Ancestry.com encourage us to start immediately searching by name when there are other things we need to consider first.  Find his date of death and work backwards from there. Use what you find as the basis for other research questions.  Which radio station was it?  How long did he work there?  When was his retirement from the BPD?  How long was his career?
There's a huge difference between asking someone "Do you have any material on Francis Murphy?" and "Where can I find records about members of the Boston Police Department who served in the period 1940-1970?  The detective I'm researching worked in special services and retired in 1965."
As you've seen, if you ask the question the first way, especially with a common name like Murphy, you'll get the answer that there are too many Murphys to answer your question; if you ask the second way, you may get the answer that BPD service records are not available to the public, or they might be able to direct you to someone who might know (e.g. at the City Archives).  After you find a collection of records that might be relevant, then you ask "is there anyone named Francis Murphy in this collection?" and "How can I tell if this Francis Murphy is the one I'm looking for, or someone else with the same name?"
After gathering more information, if I wanted to hunt down the service records, I might search at the Boston City Archives or seek help from the reference desk of the Boston Public Library.  I would expect much more information to be available locally and off-line than I could find myself using online services, but before I reached out to those organizations I would collect whatever I could find that might help identify the person I wanted to research.  I would also expect that some records would not be available due to privacy concerns.
If I could not research in person, after assembling a precise set of questions that I wanted to know the answers to, and establishing a budget, I would consider hiring a professional genealogist.  But no matter who does the search -- whether you do it yourself, or whether you hire someone to do it for you -- the search will be far more productive if you have a clear picture of what you want to know, and search for the answers to specific, focused questions.
Pay close attention to the specific information you find in any records or newspaper accounts you seek; when you search for more records, it helps to record and use the specific language that the records themselves will use.  Researching the general background of the city and the Police Department gives context for what you find -- if you find important events, add that background information to your timeline as well.
For example: according to the newspaper the Boston Record American, in February of 1964 the special service squad was broken up and the men were transferred to other units (Source: Genealogy Bank; published on Thursday, February 27, 1964, in the Boston Record American (Boston, MA). page 4, column 1).  This fact now gives you two things to search for -- before 1964, you search for references to the special service squad; after the reorganization, you search for the Criminal Investigative Division (CID).
In this particular case, it is especially helpful to study Murphy's associates.  Collect the names of other detectives and officers who are mentioned in the newspaper articles that you find him in. Searching for their names may help you find other newspaper articles in which Murphy also appears.  Newspapers are often transcribed or indexed by computers using a process called optical character recognition (OCR), which isn't perfect.  You can't depend on every instance of 'Murphy' being transcribed as 'Murphy' because the computer can make a mistake.  (One common mistake seen in Ancestry's City Directories:  the middle initial H is read as II.)
Displays of search results and articles displayed from the search may also be limited on how many hits they report per page.  If you search for 'funeral' on Genealogy Bank and choose the setting that highlights the word 'funeral' on the chosen newspaper page, it may only highlight the first several instances of the word, so if you have an entire page of funeral notices, look at the entire page to make sure the notice you seek isn't buried at the bottom without a highlight.

A brief death notice for retired police detective Francis J. Murphy was published in the newspaper Boston Record American (Boston, Massachusetts) in the Saturday, December 16, 1967 issue, page 21, column 1, and can be seen at Genealogy Bank (requires a subscription).  According to the article, he worked for the department for 20 years (many of them on special services) and for radio station WHDH for two years as their head of security.
Another brief article appeared in the Boston Herald (Boston, MA) the following day (Sunday, December 17, 1967, page 64, column 3).  The Herald says that he was appointed to the Boston police department Dec 18, 1946, and was assigned to District 19, Mattapan, before he got the assignment to the Special Service squad at headquarters.  "He subsequently was promoted to first grade detective and assigned to the headquarters detective bureau for city-wide investigative assignments."
Working backwards from this date, and varying the keywords, you can find other articles.
If you don't want to subscribe to Genealogy Bank, you may be able to access these articles at your local public library, if your library has NewsBank (both are owned by ProQuest).  WorldCat lists some holdings for the Boston Record American at the Library of Congress and at the State Library of Massachusetts (in Boston).  Wikipedia's list of online newspaper archives may also be useful.
When using any library or online subscription service, make a note of the coverage for the collection you have searched -- collections are often incomplete, and one repository may have issues of a newspaper that another one lacks.
His police service records may not be accessible to the public; if you want to hire a professional, be prepared to provide proof of your relationship.

Another thing to consider: Boston historical societies and/or genealogical societies might be able to help you.  For instance, the New England Historical and Genealogical Society (NEHGS), which is based in Boston, has both free events which are open to the public, and paid workshops for people who want to learn more about their family history.  (One such example:  "The New England Historic Genealogical Society is participating in the Free Fun Fridays program sponsored by the Highland Street Foundation. On Friday, July 11, 2014, NEHGS will open our doors at no cost to visitors all day long."  NEHGS also has free 15-minute consultations, but space is limited, and you have to sign up in advance.)
If you have a digital camera or scanner, you could take photos of the scrapbook.  That way the original scrapbook could stay safe at home, but you would have copies that you could take with you while you are doing research.  (NEVER take originals out on the road with you -- they might be damaged or lost.)
One other thing to consider:  your relative died in 1967.  Reading the scrapbook of his cases, which were written as they happened, will leave you with a feeling that not much time has passed.  But if you are talking about someone who served in the 1960s, fifty years have passed since then.  How long is the service career of detectives like your relative?  Speaking of career terms rather than lifetimes, two generations may have gone by.  I would ask at the City Archives or a historical society to find out if anyone specializes in the history of the BPD -- that would be one way to find out others who may know more about your relative, or other detectives in his unit.

A:

I have discovered more information and just located news archives with many Frances Murphy incidents of bravery and duty.
"Slattery's Raiders", a group of officers under the command of Captain John J. Slattery, Jr. that was formed to combat vice and street crime in Boston.
Members of the elite unit called Slatterys Raiders.
John J. Slattery, 86, deputy supt. of Boston Police
Joseph Michael "Joe" Jordan is a retired American law enforcement officer who served as Commissioner of the Boston Police Department from 1976 to 1985.
Emmett F. McNamara
Frances Murphy
John J. Slattery, 86, deputy supt. of Boston Police.(Obituary)
Article from: The Boston Herald | March 18, 1997
John Joseph Slattery of Braintree, formerly of Port Charlotte, Fla., a retired deputy superintendent of the Boston Police Department, died Feb. 16. He was 86.
Born in Boston, he lived in Florida for 30 years after his retirement.
He served in the Marine Corps in Nicaragua in the late 1920s. He was made a drill instructor on Parris Island at 19 years of age.
He served in the state police for two years before joining the Boston Police Department,
where he was placed in charge of a crime-fighting team of officers called "Slattery's Raiders." Joseph Jordan, a member of his team, was a past commissioner of the Boston Police. …

Joseph Michael "Joe" Jordan is a retired American law enforcement officer who served as Commissioner of the Boston Police Department from 1976 to 1985.
He was the first uniformed BPD officer to rise through the ranks to become commissioner.
Early life Jordan was born in South Boston. He was the youngest of six children. As a child, Jordan wanted to be a police officer.
Early career In 1946, Jordan joined the Boston Police Department as a traffic patrol officer. In 1950 he became a detective. During the 1950s and 60s he was a member of "Slattery's Raiders", a group of officers under the command of Captain John J. Slattery, Jr. that was formed to combat vice and street crime in Boston. In 1967 Jordan was chosen to command the department's narcotics unit. Two years later he was promoted to Deputy Superintendent and Chief of Detectives. In 1973 he was placed in command of Area C, which consisted of the Allston,
Brighton, Back Bay, and the South End. On July 17, 1974, Jordan was promoted to Superintendent and placed in charge of the Bureau of Field Services. He was later named Superintendent-in-
Chief, the second highest position in the BPD after Commissioner.
In 1946, Jordan joined the Boston Police Department as a traffic patrol officer. In 1950 he became a detective. During the 1950s and 60s he was a member of "Slattery's Raiders", a group of officers under the command of Captain John J. Slattery, Jr. that was formed to combat vice and street crime in Boston.
While serving as a police officer, Jordan took courses at Northeastern University as a way to study to promotion exams. He spent sixteen years as a student at Northeastern and earned his bachelor's degree in 1969. He later completed a master's program in public administration.
January 15, 1985, Jordan announced that he was retiring effective January 31.
After his retirement from the BDP, Jordan became an associate at Cass Associates, a Boston security consulting and investigating firm that developed security and drug programs for hospitals and technology companies.

Emmett F. McNamara
Emmett F. McNamara Obituary - 89 years old, of Braintree, retired Boston Police Detective of 35 years, He was born in Roxbury and formerly of Jamaica Plain and Hyde Park. Emmett was a World War II veteran of the U. S. Army and a proud member of the Greatest Generation and was chosen to be in the OSS office of Strategic Service during the war. Prior to the war, he was a member of the CCC (Civilian Conservation Corps). After the war, he was hired as a guard at the old Charlestown Prison, and then was appointed to the Boston Police Department in 1954. He was a member of an elite unit called Slatterys Raiders. He earned several citations and was promoted to Detective 3rd grade. In 1964, he single handily apprehended four suspects of an armed robbery of the Progressive Credit Union and was promoted to Detective 1st grade and continued to distinguish himself through the rest of his career until his retirement in 1988.

Frances Murphy
Franny's career paralelled the rest of the members in that he was appointed in 1946, distinguished himself as an officer and was made a detective and Slattery's Raider.
Franny died in 1967, retired in 1965 and was head of security for WHDH-TV, a CBS affiliate, owned by The Boston Herald-Traveler Corp.


Q:

How to make my front page display only the most recent sticky post, plus usual widgets?

WP 3.3.1, Suffusion 4.0.2
I am trying to figure out how to make my front page display only the most recent post marked sticky.  I can't find how to do this in the documentation.
What I'm trying to do is use a combination of future post publication dates and expirations (via the Atropos plugin) to control what shows up on my front page.
Any suggestions? Is there a plugin that has a shortcode that lets me insert the most recent stick post?

A:

If I'm understanding you correctly, you want to show only the most recent sticky post only on the front page. I had the same issue a month or two ago, and got some fantastic help from the community here at WordPress Answers. The solution is to run two loops in your index.php file. One to pull only the most recent sticky post, and the second to display all other type of posts.
Here's the link, but I will post my code for this problem as well.
<?php get_header(); ?>
<?php get_sidebar( 'left' ); ?>

<?php if ( is_home() && !is_paged() ) : ?>
<div id="post-wrapper">
    <?php
        // Get IDs of sticky posts
        $sticky = get_option( 'sticky_posts' );
        // first loop to display only my single,
        // MOST RECENT sticky post
        $most_recent_sticky_post = new WP_Query( array(
            // Only sticky posts
            'post__in'            => $sticky,
            // Treat them as sticky posts
            'ignore_sticky_posts' => 1,
            // Order by date to get the most recently published sticky post
            'orderby'             => date,
            // Get only the one most recent
            'posts_per_page'      => 1
        ) );
        ?>

    <?php while ( $most_recent_sticky_post->have_posts() ) :  $most_recent_sticky_post->the_post(); ?>
        <!-- your code to display most recent sticky -->
    <?php endwhile; wp_reset_query(); ?>

<?php endif; ?>

<?php
    $all_other_posts = array(
        'post__not_in'  => get_option( 'sticky_posts' )
    );

    global $wp_query;
    $merged_query_args = array_merge( $wp_query->query, $all_other_posts );
    query_posts( $merged_query_args );
?>

<?php if( have_posts() ) : ?>
    <?php while( have_posts() ) : the_post(); ?>
        <!-- your code to display all other posts -->
    <?php endwhile; ?>
<?php endif; ?>
</div> <!-- end #post-wrapper -->

Obviously this code isn't copy-and-paste for everyone. It worked for me in the code structure I had at the time. Also, forgive the nasty formatting :P


Q:

How to set properties referenced from dependencies in Maven

In my project I've got maven dependency.
by the way it's:
<dependency>
   <groupId>org.mule.modules</groupId>
   <artifactId>mule-module-activiti</artifactId>
   <version>3.2.0</version>
</dependency>

In this dependency POM there is property which is used but not defined - ${activiti.version}
The only way I found how to set this property is by specifying it on command line like mvn -Dactiviti.version=5.10
Is there some way how to specify this property in my projects POM?
<properties><activiti.version>5.10</activiti.version></properties> doesn't work.
I hope I made the problem clear enough.
Thanks for help.
EDIT:
Situation I'm trying to solve can be reproduced if you create new maven project with dependency:
<dependency>
   <groupId>org.mule.modules</groupId>
   <artifactId>mule-module-activiti</artifactId>
   <version>3.2.0</version>
</dependency>

and provide required repositories:
  <repositories>
        <repository>
            <id>muleforge-repo</id>
            <name>MuleForge Repository</name>
            <url>http://repository.muleforge.org/release</url>
            <layout>default</layout>
        </repository>

        <repository>
            <id>codehaus-repo</id>
            <name>Codehaus Repository</name>
            <url>http://dist.codehaus.org/mule/dependencies/maven2</url>
            <layout>default</layout>
        </repository>
        <repository>
            <id>activiti</id>
            <name>Activiti</name>
            <url>https://maven.alfresco.com/nexus/content/groups/public/</url>
        </repository>
    </repositories>

EDIT 2:
Here is a POM for org.mule.modules:mule-module-activiti:3.2.0, library my projects depends on. Inside of this pom they use expression ${activiti.version}. But they don't set value for this expression.  (there is nothing like <properties><activiti.version>5.10</activiti.version></properties>)
Question is how can I set value for this expression from my pom?

A:

OK, finnaly, after few days of searching and experimenting I found solution for my problem.
If you need to provide properties for maven on command line (talking about system properties, which are slightly different from maven properties), you can also use plugin to provide these properties in your pom or in separate properties file.
note:
System properties can be used for overriding of maven properties in your dependecies.
Like this:
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>properties-maven-plugin</artifactId>
    <version>1.0-alpha-2</version>
    <executions>
        <execution>
            <goals>
                <goal>set-system-properties</goal>
            </goals>
            <configuration>
                <properties>
                    <property>
                        <name>activiti.version</name>
                        <value>5.10</value>
                    </property>
                </properties>
            </configuration>
        </execution>
    </executions>
</plugin>

I hope it will be of some help for someone.
Also sorry for my clumsy question which was apparently hard to understand.

A:

You can use properties to define versions:
<properties>
  <module-version>3.2.0</module-version>
</properties>
..
<dependency>
   <groupId>org.mule.modules</groupId>
   <artifactId>mule-module-activiti</artifactId>
   <version>${module-version}</version>
</dependency>

Why shouldn't that work?
You should never define versions of artifacts via properties on command line, cause you can't reproduce this in the future and i doubt that this works.


Q:

24 hr countdown loop in angular js

Hello am just knew to angular, how can you translate this code into angularjs. My goal is to have it count down 24hrs and restarts again
 setInterval(function time(){
  var d = new Date();
  var hours = 24 - d.getHours();
  var min = 60 - d.getMinutes();
  if((min + '').length == 1){
    min = '0' + min;
  }
  var sec = 60 - d.getSeconds();
  if((sec + '').length == 1){
        sec = '0' + sec;
  }
  jQuery('#the-final-countdown p').html(hours+':'+min+':'+sec)
}, 1000);

This is the html

A:

Just wrap the funciton setInterval into $interval in your controller like this:
$interval(function time(){
  var d = new Date();
  var hours = 24 - d.getHours();
  var min = 60 - d.getMinutes();
  if((min + '').length == 1){
    min = '0' + min;
  }
  var sec = 60 - d.getSeconds();
  if((sec + '').length == 1){
        sec = '0' + sec;
  }
  $scope.data = hours+':'+min+':'+sec;
}, 1000);

and in your view just template with data like this

{{data}}


Q:

conflicts with home internet and VPN

Sorry for my English.
I have a usb modem through which I go out to the Internet.  I want to connect via VPN to the corporative network. The connection is successful. The corporation portal works okay, but I can't to connect to various servers via rdp (or other services). This is my routes without vpn(on Russian language, sorry):

This is routes with the vpn:

I think the problem is that the provider of the modem and the corporate network(gateway address:192.168.0.1) use the same netmask. How to solve it?
PS. When VPN is connected the Internet works okay.
PS2. I use the Kerio VPN Client.

A:

As far i can see, there is no direct problem with your local network and the VPN. Your local network uses the 192.168.0.x ip range and the VPN is using the 10.253.2.x range.
The netmask is OK to the the same, the base network address is the one that should not be the same (that aren't, as i said above)
I suspect the problem might be the DNS or some firewall (yours or theirs).
To debug, try to ping a internal server name on the corporative network (something like the file server. please be sure that it work on the corporative network, to ensure its valid) and will get 1 of this 3 output:
 C:\temp>ping file-server.company.com
 Ping request could not find host file-server.company.com . Please check the name and try again.

This will tell you that you aren't resolving the corporative DNS. It may be because it's not configured by the vpn or its blocked. Do a ipconfig /all to see if you have DNS setup in the vpn internet. If yes, then it's a firewall, if not, then it's the VPN that isn't configuring the DNS
another possible output is:
 C:\temp>ping file-server.company.com
 Pinging file-server.company.com [10.253.2.10] with 32 bytes of data:

This tell you that the DNS is working (you get one IP), but can't ping the server. It's most probably a firewall problem or a vpn routing problem on the corporative network. A tracert file-server.company.com might help seeing where the IP packages are being lost.
If the ping command also show this:
 Reply from 10.253.2.10: bytes=32 time<1ms TTL=255

then you are connected, have working DNS and routing. If you still can't use the remote servers, then it's for sure a firewall problem (or the service is blocked for the VPN ip
range)
If the DNS fail, try to repeat this tests, but with the IP address of the server. If the IP is outside the range 10.253.2.[1-254], then your VPN isn't setting up the route for those networks.
vpn usually are hard to debug, so take baby steps, testing each part of the vpn. i'm assuming that the vpn is really working as you have the VPN ip. For each problem found, you will need to talk to the IT team, showing then the test results, so help then debug the problem with you.


Q:

Getting error {"detail":"Method \"GET\" not allowed."}

I am new to vue.js and django also,
Need some help on below issue.
I have created an api in which I am trying to fetch the data from one DB table and send the same to vue.js page to have check on it.
I am getting error "{"detail":"Method \"GET\" not allowed."}"
I tried it in multiple ways like sending the data in JSON form or as a array but still getting the same issuse
Model.py  below are the models for deserializing and for the table I am using to fetch the data
def deserialize_Issue(issue):
    """Deserialize user instance to JSON."""
    return {id': issue.id, 'IName': issue.IName, 'IDesc': issue.IDesc, 'ITeam': issue.ITeam,'IStat': issue.IStat, 'IChat': issue.IChat, 'Iuri': issue.Iuri, 'Ibridge': issue.Ibridge, 'Ibridgedetails': issue.Ibridgedetails  }

class Issue(TrackableDateModel):
    IName=models.CharField(max_length=500)
    IDesc=models.CharField(max_length=1000)
    ITeam =models.CharField(max_length=500)
    IStat=models.CharField(max_length=250)
    IChat=models.CharField(max_length=2,default='NA')
    Iuri=models.URLField(default='NA')
    Ibridge=models.CharField(max_length=2,default='NA')
    Ibridgedetails=models.CharField(max_length=20,default='NA')

def __str__(self):
    return self.IName, self.IStat

IN my view.py file I have created the calls and the get method to fetch the data from the table.
class IssuesDetailsView(APIView):

    def get(self, request, *args, **kwargs):
        DETAILS='Issue.objects.all()'
        serializer=deserialize_Issue(DETAILS,many=True)

        return Response ({'Issues': serializer.data})

abc.vue in vue.js file trying to acees the get the data
fetchIssueDetails () {
  $.get(`http://127.0.0.1:8000/api/chats/`, (data) => {
    this.Issues = data.Issues
  })

    .fail((response) => {
      alert(response.responseText)
    })
}

I want to read the table data in the vue.js file in for loop

A:

Here's the urls.py you've provided me in the comments:
from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('chats/', views.ChatSessionView.as_view()),
    path('chats/<uri>/', views.ChatSessionView.as_view()),
    path('chats/<uri>/messages/', views.ChatSessionMessageView.as_view()),
]

Notice how the url /api/chats/ is tied to views.ChatSessionView, not IssuesDetailsView. Yet in your Javascript you are making the request to /api/chats/.
So one way to resolve your issue is
path('chats/', views.IssuesDetailsView.as_view()),


Q:

Baking with remote signer compatible with --require-authentication?

For client ops, using a remote signer with --require-authentication requires manually entering the client key's decryption password.
It's not documented anywhere -- is this incompatible with baking? There's no way that I'm aware of to decrypt the client key when setting up baking and I assume authentication isn't bypassed for baking.
Thanks

A:

On tezos mainnet, you cannot generate your key in unencrypted form. So you have to enter the password to decrypt the key.
Solution is to import an unencrypted key and then use is to authenticate any communication with remote-signer.
I used tezbox wallet to generate unencrypted keys and then copy the private key and imported to my server using below command.
./mainnet.sh client import secret key auth-alias unencrypted:edskxxxxxxxxxxxxxTnZR

A:

As touched on in comments, the most correct answer to this is:
No, you cannot use --require-authentication with a signer for baking. There's no TTY present and you cannot decrypt the authentication key when an endorsement / baking operation needs to run.
Best practice here is to use an encrypted tunnel between the signer and the baker and for the signer to not be directly accessible to the network.


Q:

Mysql menu to xml

I've got DB. I use Zend Navigation to generate the menu. But I want that my menu would be dynamically editable from panel. My menu has also sub-menus.
My db:
id title        parent
1  First        0
2  sub_first    1
3. sub_first_2  1
4. second       0
5. sub_second   4

I want to export it in XML in that way:
<first>

 <sub_first>
 </sub_first>

 <sub_first_2>
 </sub_first_2>

</first>

How to generate xml from DB which will looks like the one I wrote?

A:

I would encapsulate the iteration with a RecursiveIterator so you can easily create whatever output you desire.
class RecursiveMenuIterator implements RecursiveIterator {
    private $_data;
    private $_root;
    private $_position = 0;

    public function __construct(array $data, $root_id = 0) {
        $this->_data = $data;
        $this->_root = $root_id;
    }

    public function valid() {
        return isset($this->_data[$this->_root][$this->_position]);
    }

    public function hasChildren() {
        $subid = $this->_data[$this->_root][$this->_position]['id'];
        return isset($this->_data[$subid])
            && is_array($this->_data[$subid]);
    }

    public function next() {
        $this->_position++;
    }

    public function current() {
        return $this->_data[$this->_root][$this->_position];
    }

    public function getChildren() {
        return new self($this->_data,
            $this->_data[$this->_root][$this->_position]['id']);
    }

    public function rewind() {
        $this->_position = 0;
    }

    public function key() {
        return $this->_position;
    }

    public static function createFromSelect($select) {
        $menu_array = array();
        foreach($select->query()->fetchAll() as $row) {
            $menu_array[$row['parent_id']][] = $row;
        }

        return new self($menu_array);
    }
}

You can use it to create the XML:
function iterator_to_xml($iterator, $element) {
    foreach($iterator as $child) {
        $childElem = $element->addChild($child['title']);
        foreach($child as $key => $val) {
            $childElem->addAttribute($key, $val);
        }

        if($iterator->hasChildren()) {
            iterator_to_xml($iterator->getChildren(), $childElem);
        }
    }
}

Or the Zend_Navigation:
function iterator_to_navigation($iterator, $container) {
    foreach($iterator as $child) {
        $child['label'] = $child['title'];
        $page = new Zend_Navigation_Page_Uri($child);
        $container->addPage($page);

        if($iterator->hasChildren()) {
            iterator_to_navigation($iterator->getChildren(), $page);
        }
    }
}

Usage:
$select = $db->select()
    ->from("tblMenu");

$menuIterator = RecursiveMenuIterator::createFromSelect($select);

$navi = new Zend_Navigation();
iterator_to_navigation($menuIterator, $navi);

$xml = new SimpleXMLElement("<menu/>");

iterator_to_xml($menuIterator, $xml);


Q:

What about the sound change initial n -> initial l?

While learning (a little) Cantonese, I was annoyed by the fact that every initial [n] was converted to [l], so that the word "you", written

néih hóu

in guidebooks is universally pronounced

léih hóu

People would, if pressed, say that the pronunciation is "néih hóu", and that they were using "lazy pronunciation" (see Cantonese phonology). The sound-shift was common to words with initial [n]. It did not appear in the superficial list of cross-linguistically regularly observed sound changes that I saw on Wikipedia, which were b>p>f, d>t>th and g>c>ch. These sound changes are just voicing/unvoicing toggles and turning into a fricative, both of which are simple transformations. Initial n to l is just strange (and, possibly coincidentally, it relates the semitic and Indo-European words for "no").
I was wondering if [n] -> [l] is a sound change which is common cross-linguistically, whether it is directional (is it observed going the other way), if it is confined to the initial position, and more generally which transformations are known with what direction and probability.

A:

A sound change can only be "regular" with respect to a particular language. There are sound changes in languages which seem completely off the wall to me, but are "regular" in the sense that they are consistent with the diachronic evidence (i.e. the forms in a daughter language can be derived regularly from rules applied to a mother language). As such there is no list of "regular sound changes", where a sound change is somehow impossible if it is not in the list.
As for the body of your question, [n] and [l] are said to be in free variation in Cantonese, which means that they are used interchangeably by native speakers, who consider both pronunciations acceptable. There are also some socio-linguistic factors involved — the [l] pronunciation is associated with female speech.
[Incidentally, I personally say nei5 for 你 'you', but loeng4 instead of the "correct" noeng4 for the word 娘 'young girl'. This particular pair of pronunciations is very much in flux at the moment, and Cantonese may eventually shift largely to one pronunciation over time. Cantonese used to distinguish retroflex [ʂ] from apical [s] (e.g. 傷 shoeng1 'wound' vs 相 soeng1 'mutual'), but that distinction too has gradually been erased over the last 50-100 years.]
An example of a quirky sound change, and I really do enjoy these, is from Taishanese, a Chinese topolect which, like Cantonese, is also spoken in Guangdong:

t -> ∅ / #_
b -> ∅ / #_

A:

[n] and [l] are similar acoustically and aerodynamically, in that both are made with periodic vibration and no buildup of pressure, but have more complex formant structures than vowels due to the presence of antiformants. They are also similar articulatory, both being made with the front of the tongue raised towards the alveolar ridge. The only difference in tongue shape is that the tongue body is narrowed laterally in the production of [l] to allow air to flow over the edges of the tongue. Given their phonetic similarity, it is not surprising if they change into one another.
Interesting work on phonetic similarity can be found in Jeff Mielke's phonetic similarity database. A more technical treatment will be found in Stevens' (1998) Acoustic Phonetics.
Unfortunately I cannot find a good database of attested sound changes in the languages of the world. Maybe the closest thing that can be found is a database of phonological alternations, which are themselves "sound changes in progress." The sound change is however quite frequent cross-linguistically in my estimation. What is unusual about the Cantonese case is that the change has resulted in massive homophony, which typically doesn't happen to such an extent.
The most interesting part of the question concerns the transition probabilities of the change and its reverse. I have no idea about this but the question could be answered with a rich enough database.

A:

I'd actually been preparing the latter part of your question myself: what diachronic sound changes are common cross-linguistically, and are there databases documenting their occurrence? (I was prompted by remarks about identifying common changes from personal experience working with the comparative method). I haven't gotten around to posting the question, but I did stumble upon a database which is relevant:
The DiaDM Project: A web-based platform for Diachronic Data and Models, with one of the three sub-projects covering historical sound change: UniDia.

Although determining to the elaboration of models that are directly
  applicable to (real) case studies, there are no compendia that
  explicitly survey the types of sound changes, their directionality,
  their relative prevalence, their immutable tendencies and the
  dimensions structuring their specific behaviours. All this is
  admittedly of common knowledge, but for someone external to the field
  - mathematicians, biologists or physicists that could inspire new quantitative approaches to recurrent issues in historical linguistics
  - it is not. Moreover, accessing this knowledge can prove difficult and excessively time consuming as it is scattered in a multilingual
  literature and transcribed under various and diverging symbolisms.
UniDia targets this gap by associating the compilation of published
  sound change hypotheses from a large geographically and genetically
  diverse sample to distribution and tendency analysis methods. The
  symbolism is unified and all transcriptions are harmonized to the IPA
  – transcription conventions are presented on the left-hand menu bar.
  No prior typology is imposed on the data but rather, it is the aim of
  UniDia to explore the overall consistency of the sound change
  hypothesized across language areas and families and to distinguish the
  specific from the ‘universal’.

This of course doesn't (yet) cover all language families (and the interface isn't ideal), but it looks interesting.
P.S. meta - does this more general question merit a separate post or should it be answered here?


Q:

Thumbnail image do not display in asp.net

I have written a basic code that gets the image stored in the image folder creates a thumbnail for that image and saves in another folder called 'thumbnail' and then later this thumbnail image is displayed.
'image' gets the required image from folder whose thumbnail is required.
'imagename' is the string that saves the name of image.
'imgThumb' is the thumb image saved in thumbnails folder.
imagename = dt.Rows[0]["image"].ToString();
                System.Drawing.Image imgThumb = null;
                System.Drawing.Image image = null;
                image = System.Drawing.Image.FromFile(Server.MapPath("images/catalog/" + imagename ));

                if (image != null)
                {
                    imgThumb = image.GetThumbnailImage(50, 50, null, new IntPtr());
                    imgThumb.Save(MapPath("~/images/thumbnails/") + imagename );
                    Image.ImageUrl = "~/images/thumbnails/" + lnkimgnm;

                }

This code works fine locally. I can view the thumbnail image as required.
But same code when i uploaded on the server its not working.I mean i cant see the thumbnail of the image.May be that its not getting the image itself to generate the thumbnail. What could be the difference?
I tried assigning the url of an existing thumbnail image than it was displaying.It means that either its not getting the image from images/catalog folder or it cannot save the thumbnail at the specified path.
Please need help. Note: this code is working fine locally.

A:

see, if you can save and view thumbnails offline perfectly and if it is not workin online only then you can try few things online

check your folder/vertual directory properties. give that folder read and write permission.
check folder spelling.


Q:

GeneralSharePoint HowTo

I have a general SharePoint question for the community. I would like to utilize our underutilized SharePoint intranet site by having building visitors log in and log out by filling out a form on a SharePoint web-page for which I would create using SharePoint Designer, In doing so I would eliminate the paper method at the security desk and I would be able to view the visitors in the building in real time and hopefully be able to extract data to Excel.
Please tell me if I am on the right path here

A:

This could work in the way PirateEric hints to above.
Create a custom list with at least three fields: Visitor name, sign in time, sign out time. Other fields may include the visitor's company, who they are meeting on these premises and their mobile number.
Let the security guard add a new item to the list for every visitor. They enter the name and the sign in time (which can be a calculated default value).
The security guard saves the item and it will receive a SharePoint list ID. You could then have the security guard write that ID number on a visitor badge.
The visitor wears the badge while they are in the building and upon leaving check back with the security guard and hand in their visitor badge. The security guard brings up the visitor's log book item, either by name or by ID and enters the check-out time.
In busy rush-hour scenarios, visitors can just drop their numbered badges at the security desk into an "unattended exits" bucket and leave the building. Dropped badges can be processed whenever the staff find the time. The actual exit time may not be known (or the visitor may be asked to write the exit time on the badge before dropping it at the desk).
In an emergency situation, the SharePoint list shows all visitors that don't have an exit time and a quick check of the unattended exit bucket will show the badges that have been dropped but not yet been processed.
This is a very easy technical effort, a little bit of education for the security front desk, and a little bit of change management for check-in/check-out policy and procedure.
All in all a good example to go (almost) paperless (there's still the visitor badge) and have the data available not just for the front desk who keep the paper sign-in book, but also for the Health and Safety / Fire Wardens who need to tick off their lists in an evacuation scenario. No need to call the front desk for a copy of the paper book. Just pull the SharePoint view of visitors that have not yet exited.


Q:

using Google Guice GraphViz extension and private modules

I have simple private module:
public class SomePrivateModule extends PrivateModule {
    @Override
    protected void configure() {
        bind(SomeInterface.class).
        annotatedWith(SomeAnotation.class).
        to(SomeClass.class);

        expose(SomeInterface.class).annotatedWith(SomeAnotation.class);

        bind(String.class).annotatedWith(Names.named("some_name")).toInstance("foofoo");
    }
}

I using this module in another module using install(new SomePrivateModule). unfortunately on dependencies graph I get "k_26662236" in circle instead of @SomeAnotation SomeInterface in rectangle  and dependencies for SomeClass.
When I changing SomePrivateModule to extend AbstractModule instead of PrivateModule everything works fine.
Is it bug in Guice or I'm doing something wrong?

A:

Unfortunately graphing private modules isn't yet implemented.


Q:

Why do links on my transparent div become unclickable in IE?

Links on my website: http://rnmtest.co.uk/oddfellows/
If you hit 'Dine' you should see a 'Book Now' button.  This element is not clickable in IE.  The area below it has a semi-transparent png as the background.  The content is loaded via jQuery.
I have put the anchor within a container div as recommended by other websites, but this has had no effect.  If I resize the window in IE8 I can sometime click a small portion of the button.
This effect occurs on all anchors, not just the images.

A:

I had to make the link position:relative; explicitly.


Q:

Set RTL direction for "Tablecell" or "Table" in OpenXml

I want to set a RTL direction for some cell of a table that I create with OpenXml.
row.Append(
    new TableCell(
        new Paragraph(
            new Run(
                new Text("FullName")))){
                    TableCellProperties = new TableCellProperties()
                    {
                        TableCellWidth = new TableCellWidth(){
                            Type = TableWidthUnitValues.Dxa,
                            Width = "3400"  },
                        TextDirection = new TextDirection(){
                            Val = new   EnumValue<TextDirectionValues>(TextDirectionValues.TopToBottomRightToLeft)}
}
});

I wrote this code, but TextDirectionValues Enum dosen't have a RTL value.

A:

If your tables are like this:
TableRow > TableCell > Paragraph > Run > Text.
This code may help you:
//Justification
aRow.Descendants<TableCell>().ElementAt(indx).Descendants<Paragraph>()
    .ElementAt(0).ParagraphProperties = new ParagraphProperties()
    {
        Justification = new Justification()
        {
            Val = new EnumValue<JustificationValues>(JustificationValues.Right)
        }
    };

//RightToLeftText
foreach (var r in aRow.Descendants<TableCell>().ElementAt(indx).Descendants<Run>())
{
    r.RunProperties = new RunProperties()
    {
        RightToLeftText = new RightToLeftText()
        {
            Val = new OnOffValue(true)
        }
    };
}


Q:

Quick but detailed way to see that $i^\#:\mathcal{O}(\mathbb{A}^2)\to \mathcal{O}(U)$ is an isomorphism?

Consider the affine scheme $\mathbb{A}^2=(Spec \mathbb{C}[x,y],\mathcal{O})$ and the open subscheme $U=(U,\mathcal{O}|_U)$ where $U=Spec \mathbb{C}[x,y]\setminus\{(x,y)\}$. We have a natural inclusion $i:U\hookrightarrow \mathbb{A}^2$ where $i:U\to Spec\mathbb{C}[x,y]$ is just the inclusion and for all open $V\subset Spec\mathbb{C}[x,y]$ we have the map
$$i^\#_V:\mathcal{O}(V)\to (i^*\mathcal{O}\mid_U)(V)=\mathcal{O}\mid_U(i^{-1}(V))=\mathcal{O}(V\cap U)$$
given by the restriction $res_{V,V\cap U}:\mathcal{O}(V)\to \mathcal{O}(V\cap U)$. I want to determine $i^\#(Spec\mathbb{C}[x,y])$, i.e. the map
$$res_{Spec\mathbb{C}[x,y],U}:\mathcal{O}(Spec\mathbb{C}[x,y])\to \mathcal{O}(U)$$
Here is my approach: I know that $\mathcal{O}(U)\cong\mathbb{C}[x,y]$. This isomorphism is realised by noting that by definition of a sheaf $\mathcal{O}(U)$ can be identified with pairs of sections $(a,b)\in \mathcal{O}(D(x))\times \mathcal{O}(D(y))$ such that $a|_{D(xy)}=b|_{D(xy)}$ and this given an isomorphism $\mathcal{O}(U)\cong \mathbb{C}[x,y]\subset \mathcal{O}(D(xy))=\mathbb{C}[x,y,1/x,1/y]$.
In other words, the image of an element $s\in\mathcal{O}(U)$ under this isomorphism $\mathcal{O}(U)\cong\mathbb{C}[x,y]$ is $s|_{D(xy)}$.
So to see that $res_{Spec\mathbb{C}[x,y],U}$ is an isomorphism, we note that $x|_{D(xy)}=x\in \mathbb{C}[x,y]\subset \mathcal{O}(D(xy))$ and similarly for $y$, which proves the claim.
Now I feel like I'm doing way to much work for this. I would appreciate a quicker way of seeing this, that is still precise and uses just the definitions of an affine scheme (so no argument like "a polynomial function on $\mathbb{C}^2\setminus 0$ can be extend to a polynomial function on $\mathbb{C}^2$ or something like that).

A:

I don't know if this is what you are looking for, but this presentation made the proof clearer for me. In particular, it gives a good justification as to why the isomorphism $\mathcal{O}(U) \simeq k[x,y]$ you wrote down is actually the restriction map.
Let $U = \mathbf{A}^2 \smallsetminus \{0\}$, which we can cover by $V_1 = \mathbf{A}^2 \smallsetminus \{x=0\}$ and $V_2 = \mathbf{A}^2 \smallsetminus \{x=0\}$. Let $V_{12} = V_1 \cap V_2$ be their intersection. By the sheaf property, the sequence
$$
  0 \longrightarrow \mathcal{O}(U) \longrightarrow \mathcal{O}(V_1) \times \mathcal{O}(V_2) \longrightarrow \mathcal{O}(V_{12})
$$
is an exact sequence (of abelian groups), where the maps are respectively given by
$$
  f \longmapsto (f\rvert_{V_1},f\rvert_{V_2}) \quad \text{and} \quad (g_1,g_2) \mapsto g_1\rvert_{V_{12}} - g_2\rvert_{V_{12}}.
$$
Since $\mathcal{O}(V_1) = k[x^{\pm1},y]$, $\mathcal{O}(V_2) = k[x,y^{\pm1}]$, and $\mathcal{O}(V_{12}) = k[x^{\pm1},y^{\pm1}]$, we have the commuative diagram
$$\require{AMScd}\begin{CD}
  0 @>>> k[x,y] @= k[x,y] @>>> 0\\
  @. @VV\rho_{\mathbf{A}^2,U}V @VV(\rho_{\mathbf{A}^2,V_1},\rho_{\mathbf{A}^2,V_2})V @VVV\\
  0 @>>> \mathcal{O}(U) @>>> k[x^{\pm1},y] \times k[x,y^{\pm1}] @>\varphi>> k[x^{\pm1},y^{\pm1}]
\end{CD}$$
where $\rho_{W,Z}$ denotes the restriction of a section from an open set $W$ to an open set $Z$. To show that $\rho_{\mathbf{A}^2,U}$ is an isomorphism, we use the snake lemma. Injectivity follows by injectivity of $(\rho_{\mathbf{A}^2,V_1},\rho_{\mathbf{A}^2,V_2})$. Surjectivity follows by noting that the map $\varphi$ induces an injection of the cokernel of $(\rho_{\mathbf{A}^2,V_1},\rho_{\mathbf{A}^2,V_2})$ into $k[x^{\pm1},y^{\pm1}]$, which follows by the exactness of
$$
  0 \longrightarrow k[x,y] \longrightarrow k[x^{\pm1},y] \times k[x,y^{\pm1}] \longrightarrow k[x^{\pm1},y^{\pm1}],
$$
which you already know. $\blacksquare$


Q:

Verilog Arithmetic and Logic Unit (ALU) Compilation Error

I am getting a compilation error as such:

Error (10663): Verilog HDL Port Connection error at jdb_Blogic_v.v(7):
output or inout port "f" must be connected to a structural net
expression

I commented the line with the error. How do I fix it?
I also included the mux2to1 function code.
module jdb_Blogic_v (FS2_in, FS1_in, B_in, Y_out);

input FS2_in, FS1_in;
input [3:0] B_in;
output reg [3:0] Y_out;

jdb_mux2to1_v stage0 (B_in[0], FS1_in, FS2_in, Y_out[0]); //ERROR IS HERE ACCORDING TO COMPILER
jdb_mux2to1_v stage1 (B_in[1], FS1_in, FS2_in, Y_out[1]);
jdb_mux2to1_v stage2 (B_in[2], FS1_in, FS2_in, Y_out[2]);
jdb_mux2to1_v stage3 (B_in[3], FS1_in, FS2_in, Y_out[3]);

endmodule

module jdb_mux2to1_v (s, x1, x2, f);

input x1, x2, s;
output f;
wire    k, g, h;

not (k, s);
and (g, k, x1);
and (h, s, x2);
or (f, g, h);

endmodule

A:

Change the declaration of Y_out from output reg [3:0] to just output [3:0]. This will change it from being a reg to a wire.
A reg can only be assigned to from within a procedural statement, such as an always block.


Q:

mysql post from html table

I am trying to get my sql to post information from a html form into my database however keep getting:
( ! ) SCREAM: Error suppression ignored for
( ! ) Notice: Undefined index: firstname in C:\wamp\www\insert.php on line 29
Call Stack
#   Time    Memory  Function    Location
1   0.0005  247624  {main}( )   ..\insert.php:0

The code i am using is:
<form action="insert.php" method="post">
   Name: <input type="text" name="firstname">
   <input type="submit" value="Submit">
</form>

<?php
// This is the connection to my database
$con = mysql_connect('127.0.0.1', 'shane', 'diamond89');
if (!$con){
   die('Could not Connect: ' . mysql_error());
}

// This selects which database i want to connect to
$selected = mysql_select_db("shane",$con);
if (!$con){
   die("Could not select data");
}

// This inserts new information to the Database
$name = $_POST['name'];

$query = "INSERT INTO test1 VALUES('id', '$name')";
mysql_query($query) or die('Error' . mysql_error());

// This closes my connection
mysql_close($con)
?>

A:

Your form has an input named firstname not name, so $_POST['name'] should be $_POST['firstname']
change
    // This inserts new information to the Database
    $name = $_POST['name'];

to
   // This inserts new information to the Database
   $name = $_POST['firstname'];


Q:

Python typeerror int object not iterable, sum function issue (I think)

The object of the program is to ask the user how many articles of clothing they collected on each day of a 3 day (weekend) clothes drive, average them, do it again for the second weekend, then average the two weekends (clothes per day).
Here is my code:
import math

num_clothes = int()
weekend_total = int()
weekend_avg = float()
total_clothes = int()
total_avg = float()
index = int()

index = 1
while index <= 2:
    index = 1
    while index <= 3:
        num_clothes = int(input("How many articles of clothing did you collect today? "))
        index = index + 1

    weekend_total = sum(num_clothes)
    weekend_avg = weekend_total / 3
    print("Total Collected:\t", weekend_total)
    print("Weekend Average:\t", weekend_avg)
    index = index + 1`1

total_clothes = sum(weekend_total)
total_avg = total_clothes / 6
print("Total Number of Clothing Collected:\t", total_clothes)
print("Average Collected:\t", total_avg)

And here is the error i keep getting:
Traceback (most recent call last):
  File "G:\ITCS 1140\labs\python\lab 9.py", line 17, in <module>
    weekend_total = sum(num_clothes)
TypeError: 'int' object is not iterable

I am trying to make num_clothes into a list and add all the values of it with sum(num_clothes).

A:

Your num_clothes is an variable of type int and you are passing this variable as parameter to the sum function
weekend_total = sum(num_clothes)

You can see by the documentation that, if you want to sum properly, you need an iterator passed as parameters.
If you want to read a list from the user, try to change your input to this:
    a = [int(x) for x in input().split()]

Example
-------

    >>> a = [int(x) for x in input().split()]
    3 4 5
    >>> a
    [3, 4, 5]
    >>> sum(a)
    12
    >>>

Source
Alternatively, you can leave your code as it is and change num_clothes to list(). Then, after read the input, append the result to the list:
num_clothes = list()

...

num_clothes.append(int(input(...))

...

weekend_total = sum(num_clothes)


Q:

Using a button to toggle an LED ON/OFF

I'm fairly new to Arduino and am trying to use a push button to toggle an LED on and off using a momentary press of the button. This code is lifted straight off the tutorial on the Arduino website but is not working for me. It seems to send the LED on a loop - switching between on and off by itself, and pressing the button pauses the cycle.
Any ideas as to why it is doing that?
int buttonPin = 2;         // the number of the input pin
int ledPin = 13;       // the number of the output pin

int state = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

void setup()
{
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);

}

void loop()
{

  reading = digitalRead(buttonPin);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
if (reading == HIGH  && previous == LOW && millis() - time > debounce) {
  if (state == HIGH)
    state = LOW;
  else
    state = HIGH;
time = millis();
}

else
  if (state == LOW)
    state = LOW;
  else
    state = HIGH;
  digitalWrite(ledPin, state);
 //Serial.println(buttonPin);
  //
 Serial.println(reading);
previous = reading;
}

A:

I tested your sketch and it works. I simplified it; it's the same logic, but in a more concise way:
void loop()
{
    reading = digitalRead(buttonPin);

    // if the input just went from LOW and HIGH and we've waited long enough
    // to ignore any noise on the circuit, toggle the output pin and remember
    // the time
    if(reading == HIGH  && previous == LOW && millis() - time > debounce) {
        state = !state;
        time = millis();
    }

    digitalWrite(ledPin, state);
    Serial.println(reading);
    previous = reading;
}

setup is still the same.


Q:

Limit with arctan: $\lim_{x\rightarrow 0} \frac{x\sin 3x}{\arctan x^2}$

$$\lim_{x\rightarrow 0} \frac{x\sin 3x}{\arctan x^2}$$
NB! I haven't learnt about L'Hôpital's rule yet, so I'm still solving limits using common limits.
What I've done so far
$$\lim_{x\rightarrow0}\left[\frac{x}{\arctan x^2}\cdot 3x\cdot \frac{\sin 3x}{3x}\right] = 0\cdot1\cdot\lim_{x\rightarrow0}\left[\frac{x}{\arctan x^2}\right] = 0??$$
Obviously I'm wrong, but I thought I'd show what I tried.

A:

Starting as you did, we want to find the limit of
$$\frac{3x^2}{\arctan(x^2)}\cdot\frac{\sin(3x)}{3x}.$$
Only the first term gives any trouble. Let $x$ be not too large, and let $x^2=\tan w$, You want to find
$$\lim_{w\to 0} \frac{3\tan w}{w},$$
which is not difficult. Replace $\tan w$ by $\frac{\sin w}{cos w}$.

A:

You should put in
$$
\frac{x^2}{\arctan x^2}
$$
that has limit $1$:
$$
\lim_{x\to0}\frac{x\sin3x}{\arctan x^2}=
\lim_{x\to0}3\frac{\sin3x}{3x}\frac{x^2}{\arctan x^2}=\dots
$$
If you don't know the limit above, just substitute $t=\arctan x^2$, so $x^2=\tan t$ and the limit is
$$
\lim_{x\to0}\frac{x^2}{\arctan x^2}=\lim_{t\to0}\frac{\tan t}{t}
$$
that you should be able to manage.


Q:

Execute DB2 iSeries Stored Procedure from a SQL 2005 Linked Server

I am trying to execute a stored procedured from a linked database in MS SQL 2005.  The linked database is a db2 database on a iseries server.  I am using the iSeries IBMDASQL service provider.  I am able to query the stored procedure without problems using a simple vbscript and ado.  When I try to execute the same stored procedure in query analyzer on the SQL Server, I never see any results.  Query analyzer always show 'command executed' and when I execute the select * on the temp table, no values appear.  What am I doing wrong?????
Thanks!
--code from query analyzer below--
DECLARE @emailToAddress         char(50)
DECLARE @emailFromAddress       char(50)

set @emailToAddress = 'customer.service@company.com'
set @emailFromAddress = 'customer@gmail.com'

If Object_ID('tempdb..#tmpResultTbl') Is Not Null
    Drop Table #tmpResultTbl

Create Table #tmpResultTbl
(
OUTPGMID Char(150))

--SET FMTONLY Off
Set NoCount On
Insert Into #tmpResultTbl
EXEC ('CALL abicqual.VP_GETCCEPGMID(?, ?) ', @emailToAddress, @emailFromAddress) AT MAM400

Select * From #tmpResultTbl

UPDATED:
Here is the updated code to use openquery... still no luck :(
DECLARE @TSQL varchar(8000)
DECLARE @emailToAddress         varchar(50)
DECLARE @emailFromAddress       varchar(50)
SET @emailToAddress = 'customer.service@company.com'
SET @emailFromAddress = 'customer@gmail.com'
SET @TSQL = 'SELECT * FROM OPENQUERY(MAM400,''CALL abicqual.VP_GETCCEPGMID(''''' + @emailToAddress + ''''', ''''' + @emailFromAddress + '''''' + ')''' + ')'
Print @TSQL
EXEC (@TSQL)
--output below--
SELECT * FROM OPENQUERY(MAM400,'CALL abicqual.VP_GETCCEPGMID(''customer.service@company.com'', ''customer@gmail.com'')')
Msg 7357, Level 16, State 2, Line 1
Cannot process the object "CALL abicqual.VP_GETCCEPGMID('customer.service@company.com', 'customer@gmail.com')". The OLE DB provider "IBMDASQL" for linked server "MAM400" indicates that either the object has no columns or the current user does not have permissions on that object.

A:

Turns out that there are a number of issues with the IBMDASQL provider that I was using.  Believe it or not it is faster and more reliable to use the Microsoft OLE DB Provider for ODBC Drivers.  After creating a new linked server with this provider, all of my earlier sql attempts worked properly.
Cheers!


Q:

Como crear una capa de virtualización de Servicios

Alguien me podría ayudar a crear una capa de virtualización de servicios, esta capa de virtualización deberá servir para que los clientes no consumirán directamente los servicios expuestos por los proveedores, proporcionando agilidad para poder realizar transformaciones, orquestaciones, cambio en interfaces y desacoplamiento entre los servicios expuestos y/o los servicios consumidores.
Saludos.

A:

Lo que planteas suena a BizTalk service
con este podrias crear servicio que mapeen con servicios o librerias de terceros, entonces el cliente consume los servicios que BizTalk exponga abstrayendo de la libreria de lso proveedores. Por supuesto la idea es que no tengas que desarrollar los servicios intermedio entre el cliente y el proveedor, sino que los configuras
Esto tambien se podria implementar en Azure