text:
Q: Symfony2 Form issue, adding a dynamic field I have a symfony 2 form that describes a package:
class PackageType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->setMethod('POST')
            ->add('deliveryNote')
            ->add('receiver', new ReceiverType());

        // field stockitem exists, added dynamically NOT good

    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'IREnterprise\AppBundle\Entity\Package',
            'csrf_protection'   => false,
            'allow_extra_fields' => true
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'IREnterprise_AppBundle_package';
    }
}

Each package has 1 receiver, and a dynamic amount of package lines that are associated with the package, each package line contains one stockitem.
The idea is that the user is able to add existing StockItems, as package lines.
I have achieved that, and it looks like this:

every time the user clicks addPackageLine a package line is added to the form, and he can pick a stockItem and the amount of that stockItem.
Anyway, i had to do something hackish to get around the formBuilder.
So the controller ends up looking like this:
public function newPackageAction(Request $request)
{
    $package = new Package();
    $form = $this->createForm(new PackageType(), $package);
    $form->handleRequest($request);

    // Test if stock item belongs to user, and add to package
    $formStockItems = $request->request->get('IREnterprise_AppBundle_package[stockItems]', null, true);

    // This is bad ... very bad, should be a doctrine validation
    if (empty($formStockItems)) {
        $form->add('packageLines')->addError(new FormError('Package Lines cannot be null'));
    }

    if ($form->isValid()) {

        $em = $this->getDoctrine()->getManager();

        $package->setUser($this->getUser());

        foreach ($formStockItems as $formStockItem) {
            $stockItem = $em->getRepository('IREnterpriseAppBundle:StockItem')
                ->findByUserAndId($this->getUser(), $formStockItem['item']);

            if (!empty($stockItem)) {

                // Create a package line for the stock item, and add it the line to the package
                $packageLine = new PackageLine();
                $packageLine->setStockItem($stockItem);
                $packageLine->setAmount($formStockItem['quantity']);
                $packageLine->setPackage($package);

                $package->addPackageLine($packageLine);
            }
        }

        $em->persist($package);
        $em->flush();

        $response = View::create($package);
        return $response;
    }

    return View::create($form, Response::HTTP_BAD_REQUEST);

}

I would like to do this in a less hackish way, so that form->isValid() also validates all the packageLiens sent along, because my form errors become messed up with this approach, any suggestions?

A: Use the "collection" form type in symphony. See the How to Embed a Collection of Forms document for complete details, but the basics are that the collection type takes an option "type", which specifies the form type for each element of the collection.
You can also specify "allow_add" and "allow_delete" options to allow it to be dynamically sized.
using "allow_add" also enables a way to create a "prototype" form field that can be used by your javascript to render the form for new items in this collection


text:
Q: Parsing hyperlinks from Access VBA to Word template I'm using VBA in Access 2010 form to populate a Word template with data from my tables.
What I can't achieve so far is inserting a hyperlink in the text.
To make things easier for me I'm inserting all the data into table in the template like this:
Private Sub button_Click()

On Error GoTo myError
Dim objWRD As Object 'Word.Application
Dim objDoc As Object 'Word.Document
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strRecords As String

'open a query and prepare the data'
Set db = CurrentDb()
Set qfd = db.QueryDefs("my_query")
Set rs = qfd.OpenRecordset()

'open a Word template'
Set objWRD = CreateObject("Word.Application")
objWRD.Visible = True
Set objDoc = objWRD.Documents.Add("path_to_my_document_template", , , True)
objWRD.ScreenUpdating = False

'insert records into template'
Dim i As Integer
i = 1
While Not rs.EOF
    objDoc.Tables(i).Cell(2, 1).Range.Text = "" & rs("hyperlink")
    objDoc.Tables(i).Cell(2, 2).Range.Text = "" & rs("description")
    rs.MoveNext
    i = i + 1
Wend

rs.Close
Set rs = Nothing

leave:
    Exit Sub
myError:
    MsgBox Error$
    Resume Next
End Sub

Can anyone please help me to insert a working hyperlink to the template into     rs("hyperlink") place?

A: Where you reference the table cell to hold the hyperlink, try this:
objDoc.Hyperlinks.add Anchor:=objDoc.tables(i).Cell(2, 1).Range, _
    Address:=rs("hyperlink")

And to add additional text to the same cell (In this case I'm inserting "Text to Insert" prior to the hyperlink.
With objDoc.Tables(i).Cell(2, 1).Range
    .Collapse Direction:=wdCollapseStart
    .Text = "Text to Insert" & Chr(11)
End With

so your While Loop would look something like this:
 Dim i As Integer
    i = 1
    While Not rs.EOF

    objDoc.Hyperlinks.add Anchor:=objDoc.Tables(i).Cell(2, 1).Range, _
        Address:=rs("hyperlink")
    With objDoc.Tables(i).Cell(2, 1).Range
        .Collapse Direction:=wdCollapseStart
        .Text = "Text to Insert" & Chr(11)
    End With
   objDoc.Tables(i).Cell(2, 2).Range.Text = "" & rs("description")
        rs.MoveNext
        i = i + 1
    Wend

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I set an initial value for ListWheelScrollView?
I made time picker in my app like the above. Each number is a different ListWheelScrollView and I would like to set an initial value for them. How can I do this?
List<Widget> createNumbers(context, maxNum) {
  List<Widget> widgets = [];
  for (int i = 0; i <= maxNum; i++) {
    widgets.add(
      Text(
        i.toString(),
        style: Theme.of(context).textTheme.headline6,
      ),
    );
  }
  return widgets;
}

double itemExtent = 20;

//^^These parts are for decoration and generating the numbers)^^

int initialNumber = 11; // I want this to be the initial number

return ListWheelScrollView(
  itemExtent: itemExtent,
  physics: FixedExtentScrollPhysics(),
  children: createNumbers(context, 59),
);

A: You can use FixedExtentScrollController() along with FixedExtentScrollPhysics()
ListWheelScrollView(
  physics: const FixedExtentScrollPhysics(),
  controller: FixedExtentScrollController(initialItem:_yourInitialItemIndex),
),

A: you can't set default value for ListWheelScrollView, but what if you jump to that value after build:
  initListData(_) async {
    _controller.jumpToItem(/* index of your default value */);
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback(initListData);
  }


text:
Q: Efficient model traversal (joins) in Rails I have a rails app with a set of relations. Users read and rank books, and organizations are collections of users, who collectively have a list of books they've read/rated:
class Organization
  has_many :users, through: memberships
end

class Membership
  belongs_to :organization
  belongs_to :user
end

class User
  has_many :books, through: :readings
  has_many :organizations, through: :memberships
end

class Readings
  belongs_to :user
  belongs_to :book
end

class Book
  has_many :readings
end

I would like to, in one query, find all the books that an organization has read and rated. Something like:
organization.members.books

I would ideally like to use this with will_paginate and sort by the ratings on the Readings class. Any idea how to do this without custom SQL?

A: Try the following relations:
class Organization < ActiveRecord::Base
  has_many :memberships
  has_many :users, through: :memberships
  has_many :books, -> { uniq }, through: :users
end

class Membership < ActiveRecord::Base
  belongs_to :organization
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :memberships
  has_many :readings
  has_many :organizations, through: :memberships
  has_many :books, through: :readings
end

class Reading < ActiveRecord::Base
  belongs_to :user
  belongs_to :book
end

class Book < ActiveRecord::Base
  has_many :readings
  has_many :users, through: :readings
  has_many :organizations, -> { uniq }, through: :users
end

Now you can call @organization.books to get all books for a specific organization.
I don't know exactly how you handle ratings, but you could add a scope called rated to your Book model and then call @organization.books.rated to get all rated books for a specific organization. Here is an example of what that scope might look like:
class Book < ActiveRecord::Base
  has_many :readings
  has_many :users, through: :readings
  has_many :organizations, through: :users

  scope :rated, -> { where.not(rating: nil) }
  scope :rated_above, ->(rating) { where('rating >= ?', rating) }
  scope :rated_below, ->(rating) { where('rating <= ?', rating) }
end

That is just an example assuming you use some integer based rating system where a nil rating means it is unrated. I also threw in the rated_above and rated_below scopes, which you may or may not find useful. You could use them like @organization.books.rated_above(6) to only get the books with a rating greater than or equal to 6. Again, these are just examples, you might need to change them to work with your rating implementation.

Update
In the case where your ratings are stored on the Reading model, you can change your Book model to the following:
class Book < ActiveRecord::Base
  has_many :readings
  has_many :users, through: :readings
  has_many :organizations, -> { uniq }, through: :users

  scope :rated, -> { with_ratings.having('COUNT(readings.rating) > 0') }
  scope :rated_above, ->(rating) { with_ratings.having('average_rating >= ?', rating) }
  scope :rated_below, ->(rating) { with_ratings.having('average_rating <= ?', rating) }

  private

  def self.with_readings
    includes(:readings).group('books.id')
  end

  def self.with_ratings
    with_readings.select('*, AVG(readings.rating) AS average_rating')
  end
end

I am not sure if there is a simpler approach, but it gets the job done. Now the scopes should work as expected. Additionally, you can sort by rating like this: @organization.books.rated.order('average_rating DESC')

A: This should give you all the books that an organization has read in one query. Not sure how your ratings are implemented.
Book.joins(:readings => {:user => :memberships})
  .where(:readings => {:users => {:memberships => {:organization_id => @organization.id}}})


text:
Q: Call a DoubleClick Bid Manager API I am writing my first Google APIs Winforms application and I'm unable to figure out how to make an API call.
The example in this google "get started" documentation is not helping a lot.
I have a Client ID and secret and have authorized my app using these.
ClientSecrets cs = new ClientSecrets { ClientId = "<...>.apps.googleusercontent.com", ClientSecret = "<...>" };

var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(cs, new[] { @"https://www.googleapis.com/auth/doubleclickbidmanager" }, "user",
            System.Threading.CancellationToken.None, new Google.Apis.Util.Store.FileDataStore(@"C:\temp", true));

I now want to call this API and see its results.
Can someone give me pointers on how do I go about it?

A: Install the nugget package Install-Package Google.Apis.Doubleclickbidmanager.v1
The following code should work for Oauth2
string clientId = "ddd";
string clientSecret = "ddd";

var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                , scopes
                                                                                , "test"
                                                                                , CancellationToken.None
                                                                                , new FileDataStore(".",true)).Result;

   var service = new DoubleClickBidManagerService(new BaseClientService.Initializer()
       {
       HttpClientInitializer = credential,
       ApplicationName = "xyz",
       });

All your calls should go though the service
service.Lineitems.Downloadlineitems(body).Execute();


text:
Q: Java thottling mechanism Update: I'm on Java 1.6.34 with no chance of upgrading to Java 7.
I have a scenario where I am only allowed to call a method 80 times per minute. It's actually a service API written by a 3rd party, and it "shuts down" (ignores calls) its API if you call it too many times:
public class WidgetService {
    // Can only call this method 80x/min, otherwise it
    // it just doesn't do anything
    public void doSomething(Fizz fizz);
}

I'd like to write an ApiThrottler class that has a boolean canRun() method that will tell my Java client whether the doSomething(Fizz) method can be called or not. (Of course it can always be called, but there's no sense of calling it if we've exceeded our rate.)
So something that would allow me to write code like so:
// 80x/min
ApiThrottler throttler = new ApiThrottler(80);

WidgetService widgetService = new DefaultWidgetService();

// Massive list of Fizzes
List<Fizz> fizzes = getFizzes();

for(Fizz fizz : fizzes)
    if(throttler.canRun())
        widgetService.doSomething(fizz);

This doesn't necessarily have to be the API (ApiThrottler#canRun), but nevertheless I need a solid/reliable mechanism that will pause/sleep until WidgetService#doSomething(Fizz) can be called.
This makes me feel like we're heading into the realm of using multiple threads, which makes me feel like we could use some sort of locking mechanism and the Java notification (wait()/notify()) model. But having no experience in this realm, I can't seem to wrap my head around the most elegant solution. Thanks in advance.

A: Probably one of the best of options would be to use Semaphore http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html class and give it 80 permits every minute. This can be accomplished for example by using timer class http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html.
The caller thread will consume permits every time it performs the call to the service by calling acquire() on the semaphore, which will block if all permits have been drained already.
It would of course be possible to code this up using wait/notify and integer counter with timer or separate thread, as you mention, but that would be more complex compared to the usage of more modern java.util.concurrent API that I have outlined above.
It can look close to the following:
class Throttler implements TimerTask {
  final Semaphore s = new Semaphore(80);
  final Timer timer = new Timer(true);

  Throttler() {
    timer.schedule(this, 0, 60*1000);   //schedule this for 1 min execution
  }

  run() {  //called by timer
    s.release(80 - s.availablePermits());
  }

  makeCall() {
    s.acquire();
    doMakeCall();
  }

}

This should work starting from Java 5.
Also even nicer solution would be to use com.google.common.util.concurrent.RateLimiter from Guava. It can look like this:
class Throttler {
  final RateLimiter rateLimiter = RateLimiter.create(80.0/60.0);

  makeCall() {
    rateLimiter.acquire();
    doMakeCall();
  }
}

Semantics is slightly different compared to Semaphore solution, with RateLimiter being most probably better fit in your situation.

A: I have written something like this recently. The only change is that my code expects a callback when the function is done running. So if it cant run, I directly call the callback.
One additional change is that, since this call is probably async, it is possible the call is in progress when you call it the second time. In such cases, I just ignored the call.
And my throttler has a helper function called call which takes the function to be called and the callback. This was in C++, so for you that would be in the form of Action and listener interfaces.
This has the advantage over Semaphore based solutions that it serializes requests so that you dont call it too often either.
interface Callback{
    public void OnFunctionCalled();
}

class APIThrottler
   //ctor etc
   boolean CanCall();

   public boolean IsInProgress();

   public void SetInProgress(boolean inProgress = true);

   public void Mark(){/*increment counter*/; SetInProgress(false);} // couldnt think of a better name..

   public void Call(Callable event, Callback callback){
        If(IsInProgress())
            return;
        else if(CanCall())
        {
            SetInProgress();
            event.Call();
        }
        else
            callback.OnFunctionCalled();

    }
}

Once the function callsback (or within the function itself if it is synchronous) you would need to Mark() once it is done.
This is for the most part my implementation, only difference is that I was dealing with once in x seconds (or minutes).

A: This can be achieved by using a simple counter. Let's call it "permit" counter initialized at 80. Before you call "the function" first attempt to acquire a permit. When you're done, release it. Then setup a repetitive timer that reset the counter to 80 every second.
class Permit extends TimerTask
{
    private Integer permit = 80;

    private synchronized void resetPermit() { this.permit = 80; }

    public synchronized boolean acquire() {
        if(this.permit == 0) return false;
        this.permit--;
        return true;
    }

    public synchronized void release() { this.permit++; }

    @Override public void run() { resetPermit(); }
}

Setup the timer to reset permit every second like this. The first parameter of schedule method is an instance of TimerTask (pass the Permit class object above). The run() method will be invoked for every period specified on the second argument (here 1000 miliseconds / 1 sec). The 'true' argument indicates this is a daemon timer which will keep repeating.
Timer timer = new Timer(true);
timer.schedule(permit, 1000);

Then everytime you need to call your function, first check if you can acquire any permit. Don't forget to release it when you're done
void myFunction() {
  if(!permit.acquire()) {
      System.out.println("Nah.. been calling this 80x in the past 1 sec");
      return;
  }

  // do stuff here

  permit.release();
}

Note the usage of synchronized keyword on Permit class methods above -- this should avoid more than 1 thread executing any of the method of the same object instance simultaneously

A: You can keep records of times, and make sure no more than 80 records in the last minute.
// first=newest, last=oldest
final LinkedList<Long> records = new LinkedList<>();

synchronized public void canRun() throws InterruptedException
{
    while(true)
    {
        long now = System.currentTimeMillis();
        long oneMinuteAgo = now - 60000;

        // remove records older than one minute
        while(records.getLast() < oneMinuteAgo)
            records.removeLast();

        if(records.size()<80) // less than 80 records in the last minute
        {
            records.addFirst(now);
            return;   // can run
        }

        // wait for the oldest record to expire, then check again
        wait( 1 + records.getLast() - oneMinuteAgo);
    }
}

It is possible that at 0th second, we issue 80 calls, wait a minute, then at the 60th second, we issue another 80 calls. The other end may happen to measure a 160 calls within a minute, due to clock imprecision on both ends, or network random delays. To be safe, enlarge the time window, say do throttle at 80 calls per 70 seconds instead.


text:
Q: wxpython: adding panel to wx.Frame disables/conflicts with wx.Frame's OnPaint? I just encountered this strange situation: I found an example, where wx.Frame's OnPaint is overridden, and a circle is drawn. Funnily, as soon as I add even a single panel to the frame, the circle is not drawn anymore - in fact, OnPaint is not called at all anymore ! (Btw, I tried the example out on Ubuntu Lucid)
Can anyone explain me if this is the expected behavior, and how to correctly handle a wx.Frame's OnPaint, if the wx.Frame has child panels ? Small code example is below..
Thanks in advance for any answers,
Cheers!
The code:
#!/usr/bin/env python

# http://www.linuxquestions.org/questions/programming-9/wxwidgets-wxpython-drawing-problems-with-onpaint-event-703946/

import wx

class MainWindow(wx.Frame):
    def __init__(self, parent, title, size=wx.DefaultSize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, title, wx.DefaultPosition, size)

        self.circles = list()
        self.displaceX = 30
        self.displaceY = 30

        circlePos = (self.displaceX, self.displaceY)
        self.circles.append(circlePos)

        ## uncommenting either only first, or both of
        ## the commands below, causes OnPaint *not* to be called anymore!
        #~ self.panel = wx.Panel(self, wx.ID_ANY)
        #~ self.mpanelA = wx.Panel(self.panel, -1, size=(200,50))

        self.Bind(wx.EVT_PAINT, self.OnPaint)

    def OnPaint(self, e):
        print "OnPaint called"
        dc = wx.PaintDC(self)
        dc.SetPen(wx.Pen(wx.BLUE))
        dc.SetBrush(wx.Brush(wx.BLUE))

        # Go through the list of circles to draw all of them
        for circle in self.circles:
            dc.DrawCircle(circle[0], circle[1], 10)

def main():
    app = wx.App()
    win = MainWindow(None, "Draw delayed circles", size=(620,460))
    win.Show()
    app.MainLoop()

if __name__ == "__main__":
    main()

A: OK, this isn't really trivial, I guess... But I found the thread "wxPython - drawing without paint event - Python answers", where it is mentioned:

One nice strategy from an example in "wxPython in Action" is the
  following:

*

*the frame has Draw methods that draw into a BufferedDC, which is
  chained to a bitmap member,

*inside the paint method, the bitmap member is drawn to screen

... however, that is actually slightly misleading - if we look at one of those examples, such as Chapter-06/example1.py, it is noticeable that the app spawns a wx.Frame (as in my example); but the wx.Frame here is simply initialized by instantiating a wx.Window - and it is here where all this DC onPaint stuff happens.
With that in mind, my code above can be modified, so it finally works again (i.e. blue circle rendered), as below:
#!/usr/bin/env python

# http://www.linuxquestions.org/questions/programming-9/wxwidgets-wxpython-drawing-problems-with-onpaint-event-703946/

import wx

class MainWindowWindow(wx.Window):
    def __init__(self, parent):
        wx.Window.__init__(self, parent)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.circles = list()
        self.displaceX = 30
        self.displaceY = 30

        circlePos = (self.displaceX, self.displaceY)
        self.circles.append(circlePos)

        ## uncommenting either only first, or both of
        ## the commands below, now calls onPaint
        ## (without these panels, OnPaint called once - with them, twice)
        self.panel = wx.Panel(self, wx.ID_ANY)
        self.mpanelA = wx.Panel(self.panel, -1, size=(200,50))

    def OnPaint(self, e):
        print "OnPaint called"
        dc = wx.PaintDC(self)
        dc.SetPen(wx.Pen(wx.BLUE))
        dc.SetBrush(wx.Brush(wx.BLUE))

        # Go through the list of circles to draw all of them
        for circle in self.circles:
            dc.DrawCircle(circle[0], circle[1], 10)

class MainWindow(wx.Frame):
    def __init__(self, parent, title, size=wx.DefaultSize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, title, wx.DefaultPosition, size)
        MainWindowWindow(self)

def main():
    app = wx.App()
    win = MainWindow(None, "Draw delayed circles", size=(620,460))
    win.Show()
    app.MainLoop()

if __name__ == "__main__":
    main()

Well, hope this helps someone,
Cheers!


text:
Q: Which distro support more packages? Arch or Debain based? Since there is no apt in arch Linux I m hesitant to use it. Because most package is in  either rpm or Deb extension. Is packages of arch Linux lot more than of Debian based distro like Ubuntu?

A: According to https://repology.org Arch Linux has the largest number of packages among all Linux distros. Debian leads by the number of non-unique packaged projects.


text:
Q: Remove everything without Digits With Notepad ++ I wish to remove everything except Digits in my notepad ++ with regular expression.
can anyone help me with the String to use. that would help me get results like
from
416385-creativelive-photo-week-2014-hd-full-day-5.html
416668-creativelive-photo-week-2014-hd-full-day-4.html
421733-creativelive-photo-week-2014-day-2.html

to
416385
416668
421733

A: According to this sentence:

I wish to remove everything except Digits in my notepad ++ with regular expression.

do:
Find what: \D+
Replace with: :Nothing
It'll give : 416385201454166682014442173320142, but I'm pretty that's not what you want.

Another proposal is to keep also line break:
Find what: [^\d\r\n]+
Replace with: :Nothing
It'll give:
41638520145
41666820144
42173320142

Finally, according to your example, I guess you want:
Find what: ^(\d+).*$
Replace with: $1
NB.: Don't check dot matches new line.
It'll give:
416385
416668
421733


text:
Q: Coefficients of $\prod_{i=1;i \neq j}^{n} (x-i)$ $1 \leq j \leq n$. Is there a formula that exists to find coefficients for this function? This is as far as i have got it using Sterling numbers of the first kind.. I was wondering if there was a more explicit formula?
$$
\prod_{i=1;i \neq j}^{n} (x-i) = \frac{1}{x}\sum_{k=1;k \neq j}^{n+1} \sum_{2 \leq i_1 \leq ... \leq i_{k-1} \leq n+1} \frac{n!}{i_1 ... i_{k-1}}(-1)^{n-k+1}x^k
$$


text:
Q: Why is my processor "TurboBoosting" Below is a screenshot of my computer screen five minutes after I log on.

As you can see, my processor is turbocharging, and its the only process using the CPU.
Whats going on here?  Why is this happening?

A: I am not really sure what the issue is. Turbo-boosting happens automatically when your processor decides that it can increase the clock cycle count, that such increasing is "needed" and that it does not violate some power constraints (if you are on a laptop that is not plugged int, you can set it so that it will never turbo-boost for example).
If your program "needs" the extra speed, and your processor is giving it, everything is working as it should.


text:
Q: Adding to the End of a Cell Array I have a 12X1 cell array that holds character strings in each cell. I have also defined four string variables and I wish to add these to the end of the cell array so that it becomes a 16X1 array. I have posted below my code on how I append the four variables; but I am trying to learn this language as best as I can and I am curious if there is a more "elegant" way of appending those variables than what I have written.
        elseif (ext == '.s3p')
            %Read in file to be analyzed; convert to string format so
            %that the strsplit function can be used
            inFile = textread(thisFile, '%s', 'delimiter', '\n'); %#ok<DTXTRD>
            strForm = string(inFile);
            cellOut = arrayfun(@(x) strsplit(x, ' '), strForm, 'UniformOutput', false);

            %Find the end of the meta data and where the Option line of
            %the .s3p file begins (denoted by a '#'). Convert Option
            %line to string for parsing.
            metaDataEndLine = find(~cellfun(@isempty, strfind(inFile, 'Measurements'))) - 1; %#ok<STRCLFH>
            opLine = find(~cellfun(@isempty, strfind(inFile, '#'))); %#ok<STRCLFH>
            opStr = cellstr(cellOut{opLine});

            %Generate meta-data character strings to be printed to the
            %output file. File format can be generalized such that each
            %column corresponds to spefied data unit (i.e. frequency is
            %always the second col).
            metaFreq   = opStr(1,2);
            metaParam  = opStr(1,3);
            metaFormat = opStr(1,4);
            metaResist = opStr(1,6);

            %Genereate a cell array that houses the up-front data
            %provided by the file. Remove unnecessary chars.
            metaDataPrintFile = strForm(1:metaDataEndLine);
            metaDataPrintFile = cellfun(@(x)erase (x, '!'), metaDataPrintFile, 'UniformOutput', false);
            metaDataPrintFile = cellfun(@(x)erase (x, 'Correction: '), metaDataPrintFile, 'UniformOutput', false);

            %Add data to the class array metaPrint. Append string
            %variables generated above.
            this.metaPrint = metaDataPrintFile;
            this.metaPrint{length(this.metaPrint) + 1}      = strcat('Freq = ', metaFreq);
            this.metaPrint{length(this.metaPrint) + 2} = strcat('Parameter = ', metaParam);
            this.metaPrint{length(this.metaPrint) + 3} = strcat('Format = ', metaFormat);
            this.metaPrint{length(this.metaPrint) + 4} = strcat('Input Resistance = ', metaResist);
        end %if

Also, if you see anything else that I could do to make my code more effecient I am all ears!
Thank you in advance and please let me know if there is any other additional information that I can provide.

A: This is your code, simplified:
c = cell(12,1);
c{length(c) + 1} = 'a';
c{length(c) + 2} = 'b';
c{length(c) + 3} = 'c';
c{length(c) + 4} = 'd';

Let's look at what it does:
length(c)
% ans =  22

Oops! The first line adds one element; the second line adds an element 2 past the end, adding an empty element then the string; the third line adds an element 3 past the end, adding two empty elements and then the string; etc. -- Note that length(c) is evaluated on the extended array every time!
What you want to do is this:
c = cell(12,1);
c{length(c) + 1} = 'a';
c{length(c) + 1} = 'b';
c{length(c) + 1} = 'c';
c{length(c) + 1} = 'd';

Or more simply
c = cell(12,1);
c{end + 1} = 'a';
c{end + 1} = 'b';
c{end + 1} = 'c';
c{end + 1} = 'd';

Here we're appending one element each time. To prevent increasing the array size 4 times, you can assign those in reverse order:
c = cell(12,1);
c{end + 4} = 'd';
c{end - 1} = 'c';
c{end - 2} = 'b';
c{end - 3} = 'a';

This time we're appending 4 elements in the first statement, and filling them in afterwards.
Yet another alternative is
c = cell(12,1);
c(end + (1:4)) = {'a','b','c','d'};

(note the round brackets for indexing here). We're now appending 4 elements in one go.


text:
Q: How can i use ng-hide if like.length === 0? I have an angular application. I can succefully output true or false by writing {{liked.length === 0}} . It alterates between true and false as desired.
If  i use it in ng-show/hide however:
  <any ng-show="liked.length === 0"  />

It always shows the tag ng-show, never the ng-hide. Why?

A: With ng-show, the element will get display: none; style if the expression evaluates to false. With ng-hide, the element will get display: none; style if the expression evaluates to true.


text:
Q: JS - Redirect and return to home page I have an issue, I want to create a script in Page1 and after X seconds redirect to Page2, and inside Page2 return to Page1, and make it is not difficult, and here is my issue, after return from Page 2, I want to redirect to Page3, and return to Page1, and when I reurn from Page3 I want to redirect to Page4, every redirect with X seconds.
I know I can redirect with meta tag
<meta http-equiv="refresh" content="X;
URL=Page2.com">

and the same tag for Page2 to return to Page1, but I need to do is something like this in Page1
<!-- First Redirect -->
<meta http-equiv="refresh" content="x; URL=Page2.com">
<!-- Second Redirect -->
<meta http-equiv="refresh" content="x+x; URL=Page3.com">
<!-- Third Redirect -->
<meta http-equiv="refresh" content="x+x+x; URL=Page4.com">
<!-- Fouth Redirect -->
<meta http-equiv="refresh" content="x+x+x+x; URL=Page5.com">

There is someway to that in script? because it didn't work, always redirect me to Page1.com.
Thanks for helping me!

A: You need a stateful solution. Here's a possible solution:
// PAGEX content where X = 2, 3, 4, 5...
<meta http-equiv="refresh" content="X; URL=page1.com">

and
// PAGE1 content:

<script>
let urls = JSON.parse(localStorage.getItem('urls') || '[-1]')
let urlList = ['page2.com', 'page3.com', 'page4.com']

if(urls[0] == -1) { // fresh start
  localStorage.setItem('urls', JSON.stringify(urlList))
  startRedirection(urlList[0])
} else if(urls.length == 0) { // all redirects done
  console.log("Exhausted")
  localStorage.removeItem('urls') // removes the key "urls" for a fresh start
} else {
  const url = urls.shift() // get the first url in "urls" array and remove it from the array
  localStorage.setItem('urls', JSON.stringify(urls)) // update the state
  startRedirection(url) // redirect
}

function startRedirection(url) {
  setTimeout(() => location.href = url, 2000)
}

</script>

A: page1.html : OnLoad check the url parameter for next page
function onLoad(){
   var url_string = window.location.href;
   var url = new URL(url_string);

   //Set pageName and time from url or some default value.
   var pageName = url.searchParams.get("pageName") !== null ?
url.searchParams.get("pageName") : 'page2.html';
   var time = url.searchParams.get("time") !== null ? url.searchParams.get("time") : 1000;

   setTimeout(function(){
     window.location = pageName;
   }, parseInt(time));
}

page2.html : Pass next redirect page as parameter
function onLoad(){
    window.location = 'page1.html?pageName=page3.html&time=2000'
}

A: I resolved this way:
<script>
let urls = JSON.parse(localStorage.getItem('urls') || '[-1]')
let urlList = ['page2.com', 'page3.com', 'page4.com']

if(urls[0] == -1) { // fresh start
localStorage.setItem('urls', JSON.stringify(urlList))
startRedirection('page1.com')
} else if(urls.length == 0) { // all redirects done
console.log("Exhausted")
localStorage.removeItem('urls') // removes the key "urls" for a fresh start
location.reload();
} else {
const url = urls.shift() // get the first url in "urls" array and remove it
from the array
localStorage.setItem('urls', JSON.stringify(urls)) // update the state
startRedirection(url) // redirect
}

function startRedirection(url) {
setTimeout(() => location.href = url, 2000)
}
</script>


text:
Q: Add subscriber to mailchimp with python What is the simplest way - or library - to add a subscriber to mailchimp with python 2.5 on google app engine?

A: mailsnake and PostMonkey both require Requests library, which dropped python 2.5 support with 0.10.1.
The simplest path seems to be chimpy.
Code Sample:
from chimpy import chimpy

chimp = chimpy.Connection('MAILCHIMP_APIKEY')
chimp.list_subscribe('your_list_id', self.request.get('email'), {'FIRST': '', 'LAST': ''}, double_optin=False)

A: The MailChimp API has all the details for the functionality that you want.

*

*API Documentation : http://apidocs.mailchimp.com

*Python libraries: http://apidocs.mailchimp.com/api/downloads/ and go to Python section

*Subscribe an email to a list : http://apidocs.mailchimp.com/api/1.3/listsubscribe.func.php
Hope this helps.


text:
Q: Cannot break Shrek loop in Rstudio I have created a "while" loop that looks like this:
x <- 2
while (x < 8) {
    print("Shrek")
}

Now, I have tried breaking the loop by inserting break in to the while loop, like this:
while (x < 8) {
    print("Shrek")
    break
}

but this doesn't break the loop, the console just keeps printing "Shrek".
How can i make it stop? Have I put break in the wrong place?
Side question: Can there arise any problems from exiting Rstudio while it's in an on-going while() loop like this?
Thanks!
Edit:
Pressing escape stopped the loop. Is there any line of code in the console that also stops it?

A: Based on the code you have given I can't reproduce this. When I run everything, break works just fine. Have you potentially defined a variable called 'break' that would have overridden the default function? If not try resetting R and running this again.


text:
Q: Animation working fine in 4.2 but with an error in 2.3 This might be a bit long, but I will be so clear while explaining.
I'm developing an app which basically consists of a layout, with two relative layouts. When you click any of the two layouts, the second layout, expands or shrinks deppending of its actual visibility.
This is the layout:

This is the code that listens for any click on "main" or on "child" to expand/shrink:
    public void toggleAmagar(View v){
        View parent = (View) v.getParent();
        View child = parent.findViewById(R.id.child);
        Log.d("debugging","toggle amagar. Child visibility is :"+child.getVisibility()+". Clickable? Child: "+child.isClickable()+". Parent: "+v.isClickable());
        ExpandAnimation expandAni = new ExpandAnimation(child, 500);
        child.startAnimation(expandAni);
    }

And this is the animation class:
public class ExpandAnimation extends Animation {
private View mAnimatedView;
private LayoutParams mViewLayoutParams;
private int mMarginStart, mMarginEnd;
private boolean mIsVisibleAfter = false;
private boolean mWasEndedAlready = false;

public ExpandAnimation(View view, int duration) {
    setDuration(duration);
    mAnimatedView = view;
    mViewLayoutParams = (LayoutParams) view.getLayoutParams();
    // decide to show or hide the view
    mIsVisibleAfter = (view.getVisibility() == View.VISIBLE);

    mMarginStart = mViewLayoutParams.bottomMargin;
    mMarginEnd = (mMarginStart == 0 ? (0- view.getHeight()) : 0);
    view.setVisibility(View.VISIBLE);
}

@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
    super.applyTransformation(interpolatedTime, t);
    Log.d("debugging","aplicant. Visible = "+this.mAnimatedView.getVisibility());
    mAnimatedView.setClickable(false);
    if (this.hasEnded()){
        mAnimatedView.setClickable(true);
        View pare = (View) mAnimatedView.getParent();
        View germa = (View) pare.findViewById(R.id.main);
        germa.setClickable(true);
    } else {
        mAnimatedView.setClickable(false);
        View pare = (View) mAnimatedView.getParent();
        View germa = (View) pare.findViewById(R.id.main);
        germa.setClickable(false);
    }
    if (interpolatedTime < 1.0f) {

        // Calculating the new bottom margin, and setting it
        mViewLayoutParams.bottomMargin = mMarginStart
                + (int) ((mMarginEnd - mMarginStart) * interpolatedTime);

        // Invalidating the layout, making us seeing the changes we made
        mAnimatedView.requestLayout();

    // Making sure we didn't run the ending before (it happens!)
    } else if (!mWasEndedAlready) {
        mViewLayoutParams.bottomMargin = mMarginEnd;
        mAnimatedView.requestLayout();

        if (mIsVisibleAfter) {
            mAnimatedView.setVisibility(View.GONE);

        }
        mWasEndedAlready = true;
    }
}

This is what happens in Android 2.3:

These are the logs generated:
LOG A:
03-17 13:57:17.509: D/debugging(403): toggle amagar. Child visibility is :0. Clickable? Child: true. Parent: true
03-17 13:57:17.521: D/debugging(403): aplicant. Visible = 0
03-17 13:57:17.549: D/debugging(403): aplicant. Visible = 0
03-17 13:57:17.619: D/debugging(403): aplicant. Visible = 0
03-17 13:57:17.699: D/debugging(403): aplicant. Visible = 0
03-17 13:57:17.789: D/debugging(403): aplicant. Visible = 0
03-17 13:57:17.929: D/debugging(403): aplicant. Visible = 0
03-17 13:57:18.119: D/debugging(403): aplicant. Visible = 0
03-17 13:57:18.189: D/debugging(403): aplicant. Visible = 8

LOG B
03-17 13:57:45.439: D/debugging(403): toggle amagar. Child visibility is :8. Clickable? Child: true. Parent: true

Now I'm doing the same but in 4.2 (4.0.4 real device works the same way):

These are the logs:
LOG A:
03-17 14:13:06.104: D/debugging(815): toggle amagar. Child visibility is :0. Clickable? Child: true. Parent: true
03-17 14:13:06.192: D/debugging(815): aplicant. Visible = 0
03-17 14:13:06.212: D/debugging(815): aplicant. Visible = 0
03-17 14:13:06.475: D/debugging(815): aplicant. Visible = 0
03-17 14:13:06.692: D/debugging(815): aplicant. Visible = 0
03-17 14:13:06.792: D/debugging(815): aplicant. Visible = 8

LOG B:
03-17 14:13:08.923: D/debugging(815): toggle amagar. Child visibility is :8. Clickable? Child: true. Parent: true
03-17 14:13:09.013: D/debugging(815): aplicant. Visible = 0
03-17 14:13:09.022: D/debugging(815): aplicant. Visible = 0
03-17 14:13:09.232: D/debugging(815): aplicant. Visible = 0
03-17 14:13:09.442: D/debugging(815): aplicant. Visible = 0
03-17 14:13:09.666: D/debugging(815): aplicant. Visible = 0
03-17 14:13:09.803: D/debugging(815): aplicant. Visible = 0

As you can see, the only difference, is that the second click isn't applying the animation on 2.3 device.
I've tested it on a real device with 2.3, and other with 4.0.4 and it's happening too. Those are virtualized.
If you need any more information ask me.
Oh, by the way, the setClickable() trick inside the Animation class, is to prevent users to double click and bug the animation and layout, in case you are wondering it.
Thank you.
Sergi
Edit
Tried with several SDKS:

*

*2.2 -> Bug

*2.3 -> Bug

*4.2 -> OK

*4.0 -> OK

Edit 19/03
Update: Still happening, and I can't find out why.
Tomorrow I will keep debugging if noone finds an answer before... Thanks.


text:
Q: Summation of TFIDF sparse vector values for each document in Spark with Python I calculated the TFIDF for 3 sample text documents using HashingTF and IDF of Pyspark and I got the following SparseVector result:
(1048576,[558379],[1.43841036226])
(1048576,[181911,558379,959994],  [0.287682072452,0.287682072452,0.287682072452])
(1048576,[181911,959994],[0.287682072452,0.287682072452])

How to calculate the sum of TFIDF values for all terms within a document.
E.g. (0.287682072452 + 0.287682072452) for the 3d document.

A: Output from IDF is just a PySpark SparseVector when it is exposed to Python and its values are standard NumPy array so all you need is sum call:
from pyspark.mllib.linalg import SparseVector

v = SparseVector(1048576,[181911,959994],[0.287682072452,0.287682072452])
v.values.sum()
## 0.57536414490400001

or over RDD:
rdd = sc.parallelize([
  SparseVector(1048576,[558379],[1.43841036226]),
  SparseVector(1048576, [181911,558379,959994],
      [0.287682072452,0.287682072452,0.287682072452]),
  SparseVector(1048576,[181911,959994],[0.287682072452,0.287682072452])])

rdd.map(lambda v: v.values.sum())


text:
Q: Bootstrap sidenav scroll I am playing around with this bootstrap template ( github, emptypage code which I use ) and mostly just interested in the sidebar. However I cant seem to get scrollspy working on it in case the side menu gets too long. This is what I have:

             Engine of Travel

                Welcome,

User

Side Side

 Sidething

Option 2

Option 3

                            ...

Javascript:

The menu generated displays elements that can fit in the screen and after that 'breaks' as you can see in the image. WHat would be the best way to get scroll to work.


text:
Q: AngularJS undefined scope variable My problem is that every time select tag is change the value $scope.variationValue inside ProductContooller.js.coffee is undefine. Any idea why its undefine?
ProductContoller.js.coffee
controllers = angular.module('controllers')
controllers.controller("ProductController", [ '$scope', '$routeParams', '$location','Restangular'
  ($scope,$routeParams,$location,Restangular)->

    $scope.update_variation = ()->
      console.log $scope.variationValue <---- undefined why?

    Restangular.one('products', $routeParams.id).get().then (c) ->
      $scope.price = c.cheapest_variant.price
      $scope.product = c
      return
])

product.html.slim
.form-group
  label for="sel1"  Variations:
  select ng-options="variant as variant.opt1_value for variant in product.variants" ng-model="variationValue" ng-change="update_variation()"
  | Value {{variationValue.price}}


text:
Q: Modify my query to extract the data with latest "logcreateddate" I'm using Sql Server Management Studio 2012 and I have created a sql query which can be found below:
SELECT
    workorder.wonum as "WorkOrderNo",
    Workorder.description as "WorkorderDescription",
    Workorder.status as "WOstatus",
    Workorder.reportdate as "WOReportedDate",
    workorder.plusgmatrixprior as "WOPriority",
    wfassignment.startdate as "WorkflowStartDate",
    wfassignment.assigncode as "AssignedToLoginID",
    wfassignment.description as "AssignmentDescription",
    worklog.createby as "LogEnteredby",
    worklog.createdate as "LogCreatedDate",
    worklog.eventcode as "EventCode",
    worklog.logtype as "LogType",
    worklog.delayed as "ReasonforDelay",
    worklog.description as "LogDescription",
    worklog.description_long as "LoglongDescription"
FROM
    wfassignment,
    workorder,
    worklog
WHERE
    wfassignment.ownertable = 'workorder'
    AND wfassignment.ownerid = workorder.workorderid
    AND worklog.recordkey = workorder.wonum
    AND worklog.class = workorder.woclass
    AND workorder.siteid = 'adrd'
    AND wfassignment.assignstatus = 'active'
    AND wfassignment.assigncode = 'TRW4074'
    AND worklog.createby = 'TRW4074'
ORDER BY
    workorder.wonum desc;

I have ran the query. The Output table contains some rows having same WorkOrderNo against different LogCreatedDate.
I want to obtain all fields in above query with latest or maximum LogCreatedDate.
Note: I have tried using max() function and group by. But it did not work because other fields are not unique. Hence the output is containing duplicates of WorkOrderNo.
Please help modifying the above query or provide me the suggestion to obtain all fields with the latest date.

A: Use outer apply:
SELECT
    wo.wonum AS "WorkOrderNo",
    wo.description AS "WorkorderDescription",
    wo.status AS "WOstatus",
    wo.reportdate AS "WOReportedDate",
    wo.plusgmatrixprior AS "WOPriority",
    wa.startdate AS "WorkflowStartDate",
    wa.assigncode AS "AssignedToLoginID",
    wa.description AS "AssignmentDescription",
    wl.createby AS "LogEnteredby",
    wl.createdate AS "LogCreatedDate",
    wl.eventcode AS "EventCode",
    wl.logtype AS "LogType",
    wl.delayed AS "ReasonforDelay",
    wl.description AS "LogDescription",
    wl.description_long AS "LoglongDescription"
FROM wfassignment wa
JOIN workorder wo ON wa.ownerid = wo.workorderid
OUTER APPLY(SELECT TOP 1 *
            FROM worklog wl
            WHERE wl.recordkey = wo.wonum AND
                  wl.class = wo.woclass AND
                  wl.createby = 'TRW4074'
            ORDER BY wl.createdate DESC) wl
WHERE wa.ownertable = 'workorder' AND
      wo.siteid = 'adrd' AND
      wa.assignstatus = 'active' AND
      wa.assigncode = 'TRW4074'


text:
Q: GAE Update Question I have a strange question.
What I want to do is update my GAE version from 1.3.5 to 1.4.1/1.4.0.
After installing, I want to run dev_appserver.
But there is a error:
ERROR    2011-01-19 21:50:11,262 dev_appserver.py:3214] Exception encountered handling request
Traceback (most recent call last):
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3184, in _HandleRequest
    response = RewriteResponse(outfile, self.rewriter_chain)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2882, in RewriteResponse
    response_rewriter(response)
TypeError: DownloadRewriter() takes exactly 2 arguments (1 given)

Note: I didn't change my code and it worked very well on GAE 1.3.5
Thanks for any answers.

A: The problem has been solved.
We reinstalled gae again at "different folder"
"Different folder" is a key.
If you uninstall gae at the default (same) folder (c:\program files\google\google_appengine), the problems still exist.
So we installed it at c:\program files\goole\google_appending_x (x means any word).
Then it can work.

A: The problem is solved.
We found when I reinstall GAE 3.5 above. My C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py
Line 2887: def RewriteResponse code is not correct.
The right version is:
def RewriteResponse(response_file,
                response_rewriters=None,
                request_headers=None):
  if response_rewriters is None:
    response_rewriters = CreateResponseRewritersChain()

  response = AppServerResponse(response_file)
  for response_rewriter in response_rewriters:
    if response_rewriter.func_code.co_argcount == 1:
      response_rewriter(response)
    else:
      response_rewriter(response, request_headers)

  return response

But my version is
def RewriteResponse(response_file,
                    response_rewriters=None,
                    request_headers=None):
  if response_rewriters is None:
    response_rewriters = CreateResponseRewritersChain()

  response = AppServerResponse(response_file)
  for response_rewriter in response_rewriters:
    response_rewriter(response)

  return response

There is no if-else .
So the solution is that install GAE at c:\Program files\Google\google_appengine_x....
not at default folder.
Then it will be correct. ^^


text:
Q: Best approach to make a localized website What's the best way to make a website localized to multi languages?
I'm working on a website, and our manager wants it to be like:
http://www.website.com - default to english
http://fr.website.com - french
http://de.website.com - german
He says it's good for SEO, some developers wants to make it based on cookie and user's accept-language, so the url would always be http://website.com but content would be based on cookie/accept-language.
What you think?
thanks!

A: This article appears to have a good guide to your question: http://www.antezeta.com/blog/domains-seo/
Essentially, they recommend localizing by TLD most, followed by Subdomain, followed by directories
Cookies are a bad idea because Google will not be able to index your localized content.

A: This might be late answer but I will give you anyway (my hope is it will benefit others).
Should http://www.example.com/ default to English?
No. You should always detect User's preferred language. That is, web browser will give you AcceptLanguage header with languages that end user is able to understand. If it happens that the most preferred one is not the one that your web site/web application supports, you should try to fall back to next language from AcceptLanguage. Only when nothing fits, you should fall back to your default language (usually English, United States).
Should we used languages as part of domain?
It seems a good idea. When you detected the language, you might want to redirect user to appropriate page. It could be something like http://french.example.com/, http://german.example.com/ or http://www.example.com/index.html?lang=fr.
It is good to have such mechanism implemented - in this case one could actually bookmark correct language. Of course, if somebody navigates to your web site with language as a parameter, you will skip detection as it is pointless at this time.
To sum up:
You may should detect language that web browser serves you and appear as you have multiple web sites (one language each). That is how user might choose which one to bookmark. And of course web search engines will probably index the contents separately, but they would rather look for robots.txt, so... Either way it is good to appear as several language-specific web sites.

A: I once heard a teacher of mine say that when he does this, he simple makes php files called "eng.php" "fr.php" and so on...
In these files are associative arrays. The key's are always the same but the translation is different.
Then you need only require the correct language file at the top of you PHP files and if you parse the keys, it'll always be in the correct language.

A: Most open-sourced approaches to localization and globalization involve a lot of developer overhead and complexity in maintenance as copy and code become more complex.
My current company Localize.js solves this complex pain point seamlessly, by tracking website phrase changes, automated ordering of translations, as well as dynamic rendering of languages for you.
https://localizejs.com/
Feel free to email me @ johnny@localizejs.com, if you have any questions


text:
Q: Repeating an auxiliary verb like "was" after "and" for a passive tense? Should I repeat an auxiliary verb like "was" after "and" for a passive tense?
Here's an example:
It was shipped to laboratory in maximum time of one hour and was frozen at –80°C.

A: The was shipped could easily be changed to shipped, they are both acceptable. The and was frozen at -80°C however should always have the was as without it, and froze at -80°C sounds more like a scientific observation of the freezing point than a statement of action.
It is perfectly fine to repeat "and" and "was", especially when they are this separated. If it was something more list-like, such as it was made, packed and shipped then in that situation, repeating "and was" sounds awkward. This is for the same reason repeating "and" in a list sounds awkward, though it is not necessarily wrong
Most of this is my opinion, this topic is kind of subjective. I am sure you could find something to this effect in a style guide, but I should be programing right now so I'm not going to go looking for one. ;)


text:
Q: Python builtins.OSError OSError: [Errno 22] Invalid argument I am a beginner is python, I am getting the above error while i am getting data for a simple route and there is no logic written i am just redirecting the user to a new template.
I have added this project on github and have switched branch is this because of that..?
I am able to open the home page properly but the dashboard is giving this issue
    from flask import Flask, render_template, request, flash, redirect, url_for, session, logging
    from firebase import firebase
    from wtforms import Form, StringField, TextAreaField, PasswordField, validators
    from passlib.hash import sha256_crypt
    import json
    from functools import wraps

    app = Flask(__name__)
    firebase = firebase.FirebaseApplication('https://androidone-43cbb.firebaseio.com/', None)

    @app.route('/')
    def index():
    return render_template('home.html')

    @app.route('/testing')
    def testing():
        return '
This is another testing page
'

    # Dashboard
    @app.route('/dashboard')
    ##@is_logged_in
    def dashboard():
        return render_template('displayallusers.html')

    if __name__ == '__main__':
        app.run(debug=True)

The error stactrace is below
builtins.OSError
OSError: [Errno 22] Invalid argument
File "C:\Users\Rakeshvasal\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\Rakeshvasal\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\Rakeshvasal\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Rakeshvasal\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\Rakeshvasal\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Rakeshvasal\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Rakeshvasal\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Rakeshvasal\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\Rakeshvasal\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Rakeshvasal\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "D:\Rakesh\DemoTest\FlaskTest\firebaseinit.py", line 37, in dashboard
from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init

A: I faced the same problem, all the operations on the given post showed the same error, finally got this code to change the port number:
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    import os

    HOST = os.environ.get('SERVER_HOST', 'localhost')
    try:
        PORT = int(os.environ.get('SERVER_PORT', '5555'))
    except ValueError:
        PORT = 5555
    app.run(HOST, PORT)

my port number was previously set to 5000 by default now I changed it to 5555, u can change it to any port number

A: I also encountered this problem, with reference to the method upstairs, modified the port number to 5555, the problem is solved. The problem has bothered me for a day
from  flask import Flask,jsonify
app = Flask(__name__)
@app.route('/index')
data={
    'name':'python',
    'age':'18'
}
return jsonify(data)

if __name__=="__main__":
     app.run(port=5555,debug=True)

访问链接:127.0.0.1:5555/index


text:
Q: React how to update style coordinates Whenever I try to dynamically update some component in react, like for instance, position of the object on mousemove, it does throw an error:
Warning: `div` was passed a style object that has previously been mutated. Mutating `style` is deprecated. Consider cloning it beforehand.

How is this then possible to do any sort of dynamic stuff like interactive games in react if I cannot update object style props in any way. As for cloning the node that Reactjs suggests, it is not explained anywhere how to achieve the same result with cloning elements.
https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement
This isn't at all helpful.
My issue is that on mouseup event (users wants to drop the piece), i would like to update the style props for the new values taken from updated state property, i.e within the render function.
<ComponentOne style={{left: this.state.left, top: this.state.top}} />

A: This warning is coming because left or top being NaN. Initialize your left or top to zero or some value in getInitialState Function.
  getInitialState: function() {
    return {
      left:0,
      top: 0
    };

Also cloning React-Element won't help you here. Warning is saying you have to clone your style object when you are making changes to it. Which can be done as
var style1 = {myProp: "value"};
var style2 = Object.assign({}, style1, {newProp:"newValue"});

Instead of setting them directly as
<ComponentOne style={{left: this.state.left, top: this.state.top}} />

Do in this way
var myStyle = {left: this.state.left, top: this.state.top};
<ComponentOne style={myStyle} />

And then based on your changes clone your myStyle object and add changed style properties to it.


text:
Q: Менять цвет svg иконки при наведении Мне нужно чтобы при наведении на иконку менялся цвет с серого на градиент синего (есть исходники обеих вариантов).
На скрине видно что мне требуется. Так же иконки должны быть с плавной анимацией и быть кликабельными (переводить на другой сайт). Буду очень благодарен за помощь.

A:

.icon-link svg {
  transition: fill 0.3s linear;
}
.icon-link:hover svg {
  fill: red;
}

    <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 512 512">
        <path d="M512,97.248c-19.04,8.352-39.328,13.888-60.48,16.576c21.76-12.992,38.368-33.408,46.176-58.016
            c-20.288,12.096-42.688,20.64-66.56,25.408C411.872,60.704,384.416,48,354.464,48c-58.112,0-104.896,47.168-104.896,104.992
            c0,8.32,0.704,16.32,2.432,23.936c-87.264-4.256-164.48-46.08-216.352-109.792c-9.056,15.712-14.368,33.696-14.368,53.056
            c0,36.352,18.72,68.576,46.624,87.232c-16.864-0.32-33.408-5.216-47.424-12.928c0,0.32,0,0.736,0,1.152
            c0,51.008,36.384,93.376,84.096,103.136c-8.544,2.336-17.856,3.456-27.52,3.456c-6.72,0-13.504-0.384-19.872-1.792
            c13.6,41.568,52.192,72.128,98.08,73.12c-35.712,27.936-81.056,44.768-130.144,44.768c-8.608,0-16.864-0.384-25.12-1.44
            C46.496,446.88,101.6,464,161.024,464c193.152,0,298.752-160,298.752-298.688c0-4.64-0.16-9.12-0.384-13.568
            C480.224,136.96,497.728,118.496,512,97.248z"/>
    </svg>

В примере стилей используется свойство fill. В зависимости от иконки так же может использоваться свойство stroke.

A: Или HTML:

CSS:
    .fa-spinner {
      color: red;
    }
    .fa-spinner:hover {
      color: green;
    }


text:
Q: How can I prevent users on Mac from connecting to any WiFi networks and only connect to white-listed networks? I want to make it so that the user cannot connect to any other network other than the specified network. I know I can do this with GUI by removing preferred networks, but this way, I will have to do it for every single one of them. It will be even harder when more networks keep showing up in the networks list.
Is there a method that lets the Mac block every single network and only lets the user connect to specified networks? See the answer in the link below where the guy is doing this through a script for a single network at a time by periodically running the script. Is it possible to do this for all networks?
How to completely block specific Wi-Fi SSID on macOS?

A: I prefer to do this with MDM supervision as that's the easiest way.

*

*https://support.apple.com/guide/deployment-education/choose-a-mobile-device-management-solution-asm1c1be3511/web

*https://www.fleetsmith.com/

*https://app.jamfnow.com/devices
I would start with the free JAMF Now trial since I've used it but I hear great things about FleetSmith.
Here is the specific portion of MDM that lets you disable WiFi and push only the approved networks to each managed device.

*

*https://support.apple.com/guide/server/work-with-configuration-profiles-apddda213639/mac


text:
Q: ACCESS 2010 Beginner Needs Guidance So, I got a new job where I must write a database system, that is actually very simple. I need to have one full of barcodes, one full of employees, and maybe one more. I'll have no problem making the databases, however I don't know how to write programs to automate it. I need to make a program that automatically inserts barcodes when they are scanned. I also need to make a few queries that will request employee information. I'll need to delete things as well.
I have experience with SQL(PHP MySQL), and a local db program for Android. I'm very familiar with db queries and the like, however I don't know how I write these for ACCESS. Is it built in, or do I use a different language? I assume it's natively written in something like C/C++(which would be one of the more preferable languages to write this in). I don't know Java, C#, or VB. I need to learn this stuff fast, in the next few days. I can't find any good tutorials, the Microsoft one's aren't any good.
I'd appreciate any help, thank you,

A: So it sounds like your question is how do I create a form in access to insert a record?  There a tons of tutorials on the web for this sort of thing.  It's been a while since I've developed with Access (ugh, but it can be really fast developing) but it looks like things have become even more automated.  I like video tutorials.
Try this one:
Creating data-entry forms to Access 2010 Essential Training
(google something like "access 2010 create input form" for more)


text:
Q: Ghostscript PDF -> TIFF throws an untrappable exception, when consuming files with asian fonts Ghostscript curls up and dies, throwing an exception to stdout which I cannot catch and log. I am pretty sure it gets sick when I give it asian fonts. Has anybody backed into this problem and solved it?

A: It may be that you need to read stderr from the child process.


text:
Q: react js mui-datatables can't translate labelDisplayedRows text I'm using "mui-datatables": "^4.2.2", with react js 17 to handle datatable.
I created a liste of options :
const options = {
  filter: false,
  download: true,
  sort: false,
  selectableRows: true,
  print: true,
  viewColumns: false,
  searchOpen: false,
  // rowsPerPageOptions: {},
  labelDisplayedRows: ({ from, to, count }) => {
    return "Affichage de " + from + " à " + to + " sur " + count;
  },
  search: true,
  page: 0,
  pageSize: 10,
  // rowsPerPage: 10,
  rowsPerPageOptions: {},
};

I want to translate labelDisplayedRows :
 labelDisplayedRows: ({ from, to, count }) => {
    return "Affichage de " + from + " à " + to + " sur " + count;
  },

  <MUIDataTable
     title={"Accueil"}
     data={data}
     columns={columns}
     options={options}
   />

but it doesn't work.
how can i change the text correctly? thanks

A: You need to use customFooter for this not labelDisplayedRows
See this very basic example just for the proof of concept
And for a more complete example, check this demo which also includes MuiTablePagination in order to have the controls to navigate between pages.


text:
Q: iMessage extension can't access shared keychain data I created an iMessage extension, and added the extension to the container APP's app group, also set the same keychain sharing ID. But my iMessage extension can't read data from keychain which the container App stored.
I spent all day to fix this issue, but still can't fix it...


text:
Q: Add 2nd domain on heroku resolving in sub folder I'm not a DNS expert but manage to understand Route 53 + heroku quite ok now. I use a custom domain with route 53 and my main herokuapp. Now my app includes a side-project which I want to add another custom domain for, so in fact that would be a 2nd domain which resolves into a sub folder of my original app.
For this I created a 2nd hosted zone on Route 53, entered the name servers as usual. All like in the guide here https://devcenter.heroku.com/articles/route-53 with the difference that I entered the sub folder of my app into the CNAME record set: http://myapp.herokuapp.com/path-to-my-side-project/
I also added the domain via heroku domains:add www.my-side-project.com
I get this when visiting the Domain in the Browser:

The server at www.my-side-project.com can't be found, because the DNS
  lookup failed. DNS is the network service that translates a website's
  name to its Internet address. This error is most often caused by
  having no connection to the Internet or a misconfigured network. It
  can also be caused by an unresponsive DNS server or a firewall
  preventing Google Chrome from accessing the network.

Is there anything else I did not think off?


text:
Q: Accessing remote (Invoke-Command) array variable in local session I am trying to access the array variable outside the invoke command. I tried the below code, where I cannot access the remote array variable from my local session.
$serverlist = @("server1", "server2")

foreach ($server in $serverlist) {
    #Write-Host $computer

    $vinodh = Invoke-Command -ComputerName $server -ScriptBlock {
        $testVar = @("Stack", "over", "flow")
    }
}
foreach ($vars in $testVar) {
    Write-Host $vars # Unable to get the values as stack,over, flow
}

Actual results: unable to get values.
I expect the output as

stack
over
flow

A: Variables set inside the remote session were not populated to the local powershell session (About Scopes). You could return the values from the invoked session for using later.
$ReturnValues = Invoke-Command -ComputerName $Server -ScriptBlock {
    $testVar=@("Stack","over","flow")
    return  $testVar #return data
}

foreach ($ReturnValue in $ReturnValues)
{
    $ReturnValue
}


text:
Q: TDD for Web API with NUnit, NSubtitute I'm still confused with some TDD concepts and how to do it correctly. I'm trying to use it implement for a new project using Web API. I have read a lot about it, and some article suggest NUnit as a testing framework and NSubstitute to mock the repository.
What I don't understand is with NSubstitute we can define the expected result of what we want, is this valid if we want to validate our code logic?
Let's say I have a controller like this with Put and Delete method:
[BasicAuthentication]
public class ClientsController : BaseController
{
   // Dependency injection inputs new ClientsRepository
   public ClientsController(IRepository<ContactIndex> clientRepo) : base(clientRepo) { }

 [HttpPut]
    public IHttpActionResult PutClient(string accountId, long clientId, [FromBody] ClientContent data, string userId = "", string deviceId = "", string deviceName = "")
    {
        var result = repository.UpdateItem(new CommonField()
        {
            AccountId = accountId,
            DeviceId = deviceId,
            DeviceName = deviceName,
            UserId = userId
        }, clientId, data);

        if (result.Data == null)
        {
            return NotFound();
        }

        if (result.Data.Value != clientId)
        {
            return InternalServerError();
        }

        IResult<IDatabaseTable> updatedData = repository.GetItem(accountId, clientId);

        if (updatedData.Error)
        {
            return InternalServerError();
        }

        return Ok(updatedData.Data);
    }

    [HttpDelete]
    public IHttpActionResult DeleteClient(string accountId, long clientId, string userId = "", string deviceId = "")
    {
        var endResult = repository.DeleteItem(new CommonField()
        {
            AccountId = accountId,
            DeviceId = deviceId,
            DeviceName = string.Empty,
            UserId = userId
        }, clientId);

        if (endResult.Error)
        {
            return InternalServerError();
        }

        if (endResult.Data <= 0)
        {
            return NotFound();
        }

        return Ok();
    }

}

and I create some unit tests like this:
[TestFixture]
    public class ClientsControllerTest
    {
        private ClientsController _baseController;
        private IRepository<ContactIndex> clientsRepository;
        private string accountId = "account_id";
        private string userId = "user_id";
        private long clientId = 123;
        private CommonField commonField;

        [SetUp]
        public void SetUp()
        {
            clientsRepository = Substitute.For<IRepository<ContactIndex>>();
            _baseController = new ClientsController(clientsRepository);
            commonField = new CommonField()
            {
                AccountId = accountId,
                DeviceId = string.Empty,
                DeviceName = string.Empty,
                UserId = userId
            };
        }

        [Test]
        public void PostClient_ContactNameNotExists_ReturnBadRequest()
        {
            // Arrange
            var data = new ClientContent
            {
                shippingName = "TestShippingName 1",
                shippingAddress1 = "TestShippingAdress 1"
            };

            clientsRepository.CreateItem(commonField, data)
                .Returns(new Result<long>
                {
                    Message = "Bad Request"
                });

            // Act
            var result = _baseController.PostClient(accountId, data, userId);

            // Asserts
            Assert.IsInstanceOf<BadRequestErrorMessageResult>(result);
        }

        [Test]
        public void PutClient_ClientNotExists_ReturnNotFound()
        {
            // Arrange
            var data = new ClientContent
            {
                contactName = "TestContactName 1",
                shippingName = "TestShippingName 1",
                shippingAddress1 = "TestShippingAdress 1"
            };

            clientsRepository.UpdateItem(commonField, clientId, data)
                .Returns(new Result<long?>
                {
                    Message = "Data Not Found"
                });

            var result = _baseController.PutClient(accountId, clientId, data, userId);
            Assert.IsInstanceOf<NotFoundResult>(result);
        }

        [Test]
        public void PutClient_UpdateSucceed_ReturnOk()
        {
            // Arrange
            var postedData = new ClientContent
            {
                contactName = "TestContactName 1",
                shippingName = "TestShippingName 1",
                shippingAddress1 = "TestShippingAdress 1"
            };

            var expectedResult = new ContactIndex() { id = 123 };

            clientsRepository.UpdateItem(commonField, clientId, postedData)
                .Returns(new Result<long?> (123)
                {
                    Message = "Data Not Found"
                });

            clientsRepository.GetItem(accountId, clientId)
                .Returns(new Result<ContactIndex>
                (
                    expectedResult
                ));

            // Act
            var result = _baseController.PutClient(accountId, clientId, postedData, userId)
                .ShouldBeOfType<OkNegotiatedContentResult<ContactIndex>>();

            // Assert
            result.Content.ShouldBe(expectedResult);
        }

        [Test]
        public void DeleteClient_ClientNotExists_ReturnNotFound()
        {
            clientsRepository.Delete(accountId, userId, "", "", clientId)
                .Returns(new Result<int>()
                {
                    Message = ""
                });

            var result = _baseController.DeleteClient(accountId, clientId, userId);

            Assert.IsInstanceOf<NotFoundResult>(result);
        }

        [Test]
        public void DeleteClient_DeleteSucceed_ReturnOk()
        {
            clientsRepository.Delete(accountId, userId, "", "", clientId)
                .Returns(new Result<int>(123)
                {
                    Message = ""
                });

            var result = _baseController.DeleteClient(accountId, clientId, userId);

            Assert.IsInstanceOf<OkResult>(result);
        }
    }

Looking at the code above, am I writing my unit tests correctly? I feel like I'm not sure how it will validate the logic in my controller.
Please ask for more information, if there is anything that needs clarified.

A: If the code you've actually posted is a true reflection of your test to code ratio, then you don't appear to be following a TDD approach.  One of the core concepts is that you don't write code that hasn't been tested.  This means that as a basic rule, you need to have a minimum of one test for every branch in your code, otherwise there would be no reason for the branch to have been written.
Looking at your DeleteClient method there are three branches, so there should be at least three tests for the method (you've only posted two).
// Test1 - If repo returns error, ensure expected return value
DeleteClient_Error_ReturnsInternalError

// Test2 - If repo returns negative data value, ensure expected return value
DeleteClient_NoData_ReturnsNotFound

// Test3 - If repo returns no error, ensure expected return
DeleteClient_Success_ReturnsOk

You can use NSubtitute to redirect your code down these different paths so that they can be tested.  So, to redirect down the InternalError branch you would setup your substitute something like this:
clientsRepository.Delete(Args.Any<int>(), Args.Any<int>(),
                         Args.Any<string>(), Args.Any<string>(),
                         Args.Any<int>())
            .Returns(new Result<int>()
            {
                Error = SomeError;
            });

Without knowing the IRepository interface it's hard to be 100% accurate about the NSubstitute setup, but basically, the above is saying when the Delete method of the substitute is called with the given parameter types (int,int,string,string,int) the substitute should return a value which has Error set to SomeError (this is the trigger for the InternalError branch of logic).  You would then assert that when calling the system under test, it returns InternalServerError.
You need to repeat this for each of your logic branches.  Don't forget that you'll need to setup the substitute to return all appropriate values for to get to each branch of logic.  So, to get to the ReturnsNotFound branch, you'd need to make your repository return NoError and a negative Data value.
I said above, you needed a minimum of one test for each branch of logic.  It's a minimum because there are other things that you will want to test.  In the above substitute setups, you'll notice that I'm using Args.Any<int> etc.  That's because for the behaviour the tests above are interested in, it doesn't really matter if the correct values are being passed to the repository or not.  Those tests are testing the logic flows influenced by the return values of the repository.  For your testing to be complete, you'll also need to make sure that the correct values are being passed to the repository.  Depending on your approach, you might have a test per parameter, or you might have a test to validate all of the parameters in the call to your repository.
To validate all of the parameters, taking the ReturnsInternalError test as a base, you would simply have to add a validation call to the subsistute something like this to validate the parameters:
clientsRepository.Received().Delete(accountId, userId, "", "", clientId);

I'm using the ReturnsInternalError test as a base because after validating the the call, I want to get out of the method under test as fast as possible and in this instance it's by returning an error.

A: First, when coding in TDD, you must make the smallest functions possible. About three lines of code (excluding brackets and signature) THe function should have only one purpose. Ex: a function called GetEncriptedData should call two other methods GetData and EncryptData instead of getting the data and encrypt it. If your tdd is well done, that shouldn't be a problem to get to that result. When functions are too long, tests are pointless as they can't really cover all your logic. And my tests Use the having when then logic. Ex.: HavingInitialSituationA_WhenDoingB_ThenShouldBecomeC is the name of the test.
You would find three blocks of code inside your test representing these three parts. There is more. When doing tdd, you shoud always do one step at once. If you expect your function to return 2, make a test that validates if it returns two, and make your function literally return 2. Afther that you could want some conditions and test them in other test cases and all your tests should bass at the end. TDD is a completely different way to code. YOu make one test, it fails, you make the necessary code so it pass, and you make another test, it fails... This is my experience, and my way of implementing TDD tells me that you are wrong. But this is my point of view. Hope I helped you.


text:
Q: Plot Wireframe out of data not working I try to write a script for matplotlib where data points are plotted as a wireframe. I did that in gnuplot once (which is working). Nevertheless I'm migrating some of my scripts to matplotlib because I'm more conviced of it by now.
I calculated some data in cylindrical coordinates. For fixed z's I calculated the x and y coordinates depending on the phi angle. When a full circle is drawn, the next z-step is calculcated etc. The data looks like this
  6.71570E+01  0.00000E+00  6.00000E+01  4.46028E+01
  6.70761E+01  3.29524E+00  6.00000E+01  4.46028E+01
  6.68336E+01  6.58254E+00  6.00000E+01  4.46028E+01
  6.64301E+01  9.85398E+00  6.00000E+01  4.46028E+01
  6.58666E+01  1.31017E+01  6.00000E+01  4.46028E+01
  6.51444E+01  1.63178E+01  6.00000E+01  4.46028E+01
  6.42653E+01  1.94947E+01  6.00000E+01  4.46028E+01
  6.32313E+01  2.26245E+01  6.00000E+01  4.46028E+01
  [...]
  6.68336E+01 -6.58254E+00  6.00000E+01  4.46028E+01
  6.70761E+01 -3.29524E+00  6.00000E+01  4.46028E+01
  6.71570E+01 -8.51512E-13  6.00000E+01  4.46028E+01

  6.34799E+01  0.00000E+00  5.70000E+01  4.21513E+01
  6.34035E+01  3.11481E+00  5.70000E+01  4.21513E+01
  6.31742E+01  6.22212E+00  5.70000E+01  4.21513E+01
  6.27928E+01  9.31444E+00  5.70000E+01  4.21513E+01
  6.22602E+01  1.23843E+01  5.70000E+01  4.21513E+01
  6.15775E+01  1.54244E+01  5.70000E+01  4.21513E+01
  6.07465E+01  1.84272E+01  5.70000E+01  4.21513E+01
  5.97691E+01  2.13857E+01  5.70000E+01  4.21513E+01
  5.86478E+01  2.42927E+01  5.70000E+01  4.21513E+01
  5.73852E+01  2.71412E+01  5.70000E+01  4.21513E+01
  5.59843E+01  2.99242E+01  5.70000E+01  4.21513E+01
  5.44485E+01  3.26352E+01  5.70000E+01  4.21513E+01
  5.27816E+01  3.52676E+01  5.70000E+01  4.21513E+01
  [...]

where blank lines are necessary to get gnuplot to plot the wireframe, described here (lowrank.net/gnuplot/datafile-e.html, see '3-dimensional data'). Simply calling 'splot' in gnuplot draws the correct wireframe of my data.
GnuPlot plot of my wireframe
When trying to plot it in matplotlib with the following code:
import matplotlib.pyplot as plt
import numpy as np

from mpl_toolkits.mplot3d import Axes3D

plt.close('all')
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')

file_in = open('wireframe_data.dat')
with file_in as file:
    data_mani = [[np.double(digit) for digit in line.split()] for line in file]
file_in.close()

data_mani = list(filter(None, data_mani)) # remove blank lines, fastest way
data_mani = np.array(data_mani, dtype='float64')

ax.plot_wireframe(data_mani[:, 0], data_mani[:, 1], data_mani[:, 2], rcount = 10, ccount = 10, linewidth=0.7)

It only draws the circles at fixed z coordinates and one line along the the circles in z-direction, i.e. not a fully wireframe. The result loooks like this
Matplotlib plot of my wireframe (different data, but same structure)
I'm trying to figure out how to plot it correctly in python and I cannot get it working with different meshgrid callings. At the moment I'm even unsure if I even need meshgrid, because the surface data is already there. Maybe somebody has an idea and can help me here? I'm really frustrated at the moment.
Looking forward to your answers.
Best wishes,
TheOrangeman

A: Ok, I found a solution. I had to reshape my data the following way:
[...]
num_z = len(np.unique(data_mani[:, 2]))
points_per_z = len(data_mani) / num_z

XX = np.reshape(data_mani[:, 0], (num_z, points_per_z))
YY = np.reshape(data_mani[:, 1], (num_z, points_per_z))
ZZ = np.reshape(data_mani[:, 2], (num_z, points_per_z))

ax.plot_wireframe(XX, YY, ZZ)

Now it looks like this.


text:
Q: Get absolute path of a relative path of a XML file Is it possible to guess the absolute path of a relative path that I have specified for loading a XML file?  This is my coding:
$strXML = __DIR__ . "/../xml/file.xml";
$xmlFile = simplexml_load_file($strXML);

$strPath = fullPathFunction($xmlFile);  //Desired function

A: You can use realpath function:
$strXML = "../xml/file.xml";
$xmlFile = simplexml_load_file($strXML);

$strPath = realpath($strXML);


text:
Q: Can't Delete aBarcode Image in VB.NET after it was printed (KeepAutomation) I am building a Label printer with Code 128 Barcode with KeepAutomation.
In the procedure i actually:

*

*Encode the data to Barcode with the KeepAutomation Referenced module
Private Sub MakeImage()
Dim barcode As KeepAutomation.Barcode.Bean.BarCode = New KeepAutomation.Barcode.Bean.BarCode
barcode.Symbology = KeepAutomation.Barcode.Symbology.Code128Auto
barcode.CodeToEncode = Me.txtCatNum.Text
barcode.X = 2
barcode.Y = 100
barcode.BottomMargin = 0
barcode.LeftMargin = 0
barcode.RightMargin = 0
barcode.TopMargin = 0
barcode.DisplayText = True
barcode.ChecksumEnabled = True
barcode.DisplayChecksum = True
barcode.Orientation = KeepAutomation.Barcode.Orientation.Degree0
barcode.BarcodeUnit = KeepAutomation.Barcode.BarcodeUnit.Pixel
barcode.DPI = 72
barcode.TextFont = New Font("Arial", 26.0F, FontStyle.Regular)
barcode.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg
barcode.generateBarcodeToImageFile(FileToUse)

*Create a Jpeg image from the encoded data (with a static name to a specific location on the hard drive)

*Place the image in a PrintDocument

*Print It
But when I try to delete the file before I run the procedure again, It tells me it cannot delete the file because it is used by a application itself if published) or vshost32-clr2.exe (while debugging).
I have tried:

*

*disposing the PrintDocument class

*Disposing, Closing and ReOpening the form itself.
None of the above helped me.
Looking for a good idea (other then creating a different image for each label I create)
Thanks,
Guy

A: Thanks Friends,
I found the perfect answer for my problem with the lead from pinkfloydx33
I have created a FileStream for the jpeg i'm creating, Opened it as a "Read Only" and once finished placing it on the PrintDocument class, I can very easily overwrite/Delete it.
Here's The Code I use.....
       MakeImage()
    Dim fs As New FileStream(FileToUse, FileMode.Open, FileAccess.Read)
    e.Graphics.DrawImage(Image.FromStream(fs), 20, 5, 150, 80)
    e.Graphics.DrawString("Batch: ___________", BatchFont, Brushes.Black, 0, 97)
    fs.Dispose()

Conclusion, if I may.....
Whenever you open a file, especially when you do not need to modify it , Access it as FS and open as ReadOnly.....
Thanks again.


text:
Q: Save response from $http service to an array in angularjs Following is the code, which is consoling the response but unable to set the response to store in $scope.dateWiseData array. Let me know what I am doing wrong.
$scope.dateWiseData = [];
var tmpArr = [];
var x = 0;
for (var i=0; i< 7;i++) {
    $http.post('/api/getdata', {_id: currentUser._id, data: data}).then(function(response){
        console.log(response.data);
        tmpArr.push(response);
        if ( x < 7 ) {
            $scope.dateWiseData = tmpArr;
        }
        x++;
    });
}
console.log("--Week Data Array--");
console.log($scope.dateWiseData);

A: if you try to print the console.log($scope.dateWiseData); this will execute before the $scope.dateWiseData array is assigned to  data which means this will print before the data is getting from server. but your data should be assigned to that array after the http is completes. You need to check the promises in javascript
$scope.getData() = function(){
    var deferred = $q.defer();
    for (var i=0; i< 7;i++) {
        $http.post('/api/dayavailability', {_id: SessionService.currentUser._id, weekDay: new Date($scope.sevenWeekDayArr[i]).toISOString()}).then(function(response){
            tmpArr = response.data;
            if ( x < 7 ) {
                $scope.dateWiseData.push(tmpArr);
            }
            if(x==6) {
                deferred.resolve();
            }
            x++;
        });
    }
    return deferred.promise;
}

wrapt that for loop like this
and
$scope.getData().then(function() {
   // processing
});

** Dont forget to add $q in as a parameter in the controller **


text:
Q: Mixing Volume Shadow Copy and Data Deduplication in Windows Server I'm using Windows Server 2012 and I'm creating a scheduled backup for multiple Hyper-V guests (all of them are Windows Server 2012) to a dynamic VHDX on a removable USB drive (so that I can alternate two drives and have two sets of backups).
I realized that since I have a lot of similar data (many copies of OS files for each guest OS) on the drive, Data Deduplication could help. So I enabled it on the drive, and started the optimization job. It reported 8 GB of saving (on a 35GB drive I created for test, which contains backups for 3 VMs) but the VHDX file size grows 4 gigabytes.
After optimization of VHDX file (Full mode) I realized that not only deduplication didn't reduce the drive size at all, it has increased it.
The only explanation I have, is that since WSB (Windows Server Backup) has created Shadow Copies on the drive, it is possible that VSS and Deduplication can't play well. So, VSS is keeping track of changes made by Deduplication, keeping both duplicated and deduplicated versions on the volume.

*

*Am I right in my conclusion?!

*Is there a way to make deduplication work with VSS? Because backing up tens of VMs means a lot of duplicate data. It would be nice to make deduplication work!

A: You are right in your assumption that WSB has created shadow copies. It uses these copies to maintain a backup history.
If you still have backup versions (and thus shadow copies) of points in time before your dedup optimization job has run, you would not see any savings at all since the deduplicated blocks have not been freed - they are needed for an older, non-deduped version of the data which is still referenced by one of the shadow copies.
So the bottom line is that if you need deduplication savings to show, you need to remove all older shadow copies.
The increase you are seeing is probably not due to deduplication activity but simply due to the fact that additional backup jobs were run in the meantime and older shadow copies are not deleted unless necessary (i.e. the volume would not have enough space for the new backup otherwise)

A: I'm not finding this with my test machine.
I've got a 2012 machine with Hyper-V and a 1TB disk with de-dupe enabled.
I'm storing VM disks there, and also various shares - several of which are where other PCs and the server itself are backing up to, each day.  As PCs are backing up to this disk using Windows Backup, they only store one backup (and overwrite each day) so to cheat and get a catalog of different days backups, I'm using shadow copies so I can go bring back the files from previous days.
As a general rule, I'm not seeing disk usage increase


text:
Q: After Upgrade/Migration to SQL Server 2019 Databases Periodically Gets Stuck In a Inaccessible State I have a bit of a unique challenge, I have a series of test databases I use for CI type database testing, generally with each release I will restore (overwrite) these databases from a backup, update them, then subject them to a series of tests while under load. However ever since I moved to using a SQL Server 2019 (from 2016) I have been experiencing periodic issues where one of my "CI" databases becomes unavailable periodically. I have not identified any patterns to when/how this occurs, it's seemingly random.
Typically this starts with one of my releases failing because the first step of my deployment "Reset Database" times out, namely this part of it:
ALTER DATABASE TestCI10 SET OFFLINE WITH ROLLBACK IMMEDIATE

It simply runs forever while repeating the following message (You get the same thing if you try to put it into Single User Mode):

Nonqualified transactions are being rolled back. Estimated rollback
completion: 0%.

Now normally you might expect to see this on a large DB with a large transaction, but on this server the DB's are tiny, the backup file is around 17MB and it's mostly just Stored Procs, there is no table with more than 100 records in it, and no tests that take more than 1 second to run any command or proc in the DB.
I can't even access the database tables through the UI, SSMS displays when trying to display tables:

Lock request time out period exceeded. (Microsoft SQL Server, Error:
1222)

If you query who is active (sp_who2) filtered to active and examine the output you see the following:
SPID    STATUS  LOGIN   HostName    BlkBy   DBName  Command CPUTime DiskIO  LastBatch   ProgramName
72  SUSPENDED XXX\ServiceAccount DEV-XXX-200    72  TestCI10 KILLED/ROLLBACK 266 92 10/06 12:00:11  SQLAgent - TSQL JobStep (Job XXX: Step 3)

Killing this task has no effect. Examining it further (dm_exec_requests joined to a bunch of other stuff):
session_id  request_id  start_time  status  command sql_handle  statement_start_offset  statement_end_offset    plan_handle database_id user_id connection_id   blocking_session_id wait_type   wait_time   last_wait_type  wait_resource   open_transaction_count  open_resultset_count    transaction_id  context_info    percent_complete    estimated_completion_time   cpu_time    total_elapsed_time  scheduler_id    task_address    reads   writes  logical_reads   text_size   language    date_format date_first  quoted_identifier   arithabort  ansi_null_dflt_on   ansi_defaults   ansi_warnings   ansi_padding    ansi_nulls  concat_null_yields_null transaction_isolation_level lock_timeout    deadlock_priority   row_count   prev_error  nest_level  granted_query_memory    executing_managed_code  group_id    query_hash  query_plan_hash statement_sql_handle    statement_context_id    dop parallel_worker_count   external_script_request_id  is_resumable    page_resource   page_server_reads   task_address    task_state  context_switches_count  pending_io_count    pending_io_byte_count   pending_io_byte_average scheduler_id    session_id  exec_context_id request_id  worker_address  host_address    parent_task_address dbid    objectid    number  encrypted   text
72  0   2020-10-06 12:00:11.870 suspended   KILLED/ROLLBACK 0x010012002B85F21A209A3C439002000000000000000000000000000000000000000000000000000000000000  0   -1  0x060012002B85F21A609C70FA8D02000001000000000000000000000000000000000000000000000000000000  18  1   AC603F4F-5F34-4E0F-8C41-932AA9E1484C    72  LCK_M_SCH_M 7598636 LCK_M_SCH_M OBJECT: 2:-1293663577:0     0   1   0   0x  0   0   287 7599057 3   0x00000290A732A8C8  0   92  14273   1024    us_english  mdy 7   1   0   1   0   1   1   1   1   2   -1  -5  0   0   3   0   0   1   NULL    NULL    NULL    NULL    1   NULL    NULL    0   NULL    0   0x00000290A732A8C8  SUSPENDED   126 0   0   0   3   72  0   0   0x000002879EB5A160  0x0000000000000000  NULL    18  NULL    NULL    0   {Command that typically takes no time}

Doesn't reveal any more information on this, other than the task is stuck on a "LCK_M_SCH_M" wait. Stopping the associated SQL agent jobs doesn't seem to have any effect, restarting the SQL agent doesn't seem to have any effect either.
In this situation I've restored to stopping the SQL Server service, deleting my "CI" MDF and LDF files, starting the service and removing/deleting the instance via the SSMS UI, then rerunning the release (it will restore the instance from a backup). This is a labor intensive process and time consuming, I've not yet automated this logic as I don't want to restart the SQL Server service 10 times a day and it delays the rest of the CI releases.
I would like to:

*

*Determine why my CI databases are locking up and prevent it in the first place.
OR

*Find a easier way to nuke a instance and restore it from backup without having restart the entire SQL service.
If you google around with associated phrases such as "Inaccessible Database Instance" "Lock Request Timeout Exceeded" you will encounter more posts than can be ever possibly be read suggesting you use a combination of the methods mentioned above or to "simply wait", as I have attempted both with no success I wonder if anyone else has a alternative suggestion to address this issue?
Update 1
A coworker suggested that I look at the "AUTO_UPDATE_STATISTICS_ASYNC" option, it's been reported this can cause lockups with Single User Mode. I checked that all databases have this option set to false:
SELECT name, is_auto_update_stats_on, is_auto_update_stats_async_on
FROM sys.databases

So I don't believe this is the issue, because it isn't set on any of my CI databases...
This post claims that a better way to put a database into single user mode is to set the deadlock priority before executing the command:
SET DEADLOCK_PRIORITY 10;
ALTER DATABASE [YourDBName] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

I will try that before setting my DB offline in my "Reset Database" script, and update this post with the results as soon as I encounter another locked up instance.
Update 2
Since I have not received any answers to this yet I've added a script that reboots the SQL service before each CI run, like this(Powershell):
Stop-Service -Force "SQLSERVERAGENT"
Restart-Service -Force "MSSQLSERVER"
Start-Service -Force "SQLSERVERAGENT"

This clears up most of the issues with instances with instances only rarely experiences the issue after a service reset (and before the CI tests are run), still basically have the issue though, I see this more as a patch than a actual solution.
Update 3
I did more digging, this is a very similar post, same issue really, in my case it seems that the instance is always getting caught up in the same section of a proc that should take less than one second to run. Specifically it has "LCK_M_SCH_M" set on a temp table that's generated in that proc. Not sure why this is blocking continued execution, but it is, my difficulty comes in when you search around on this issue, everyone just says to restart SQL server, which I now am, every 15 minutes, all day...
Update 4
Ok so I dug so more, it's always a proc call with a specific set of parameters getting locked up on a particular temp table at a particular point in the proc. Thankfully the specific set of parameters passed in always guarantee that the number of records will be small so I've branched the proc into two sections, one for normal records (using the temp table), another for this specific set of parameters (using a massive nested query), and this works great, no more issues in CI I haven't seen the issue since...
Not really a solution, but the end of my investigation, I'm still convinced that there is a "bug" (or call it what you want to) with SQL server 2019 that under a certain set of conditions it will lock up a database, I just don't know how to reproduce properly with a single query or single process.


text:
Q: apply custom filter to $_GET variables everywhere everytime codeigniter I need to trim every $this->input->get('q', true); in my projects. is there a way to do this instead of adding trim() every time?
Naim Malek told me to use helper, but I don't quite understand how it would work in this case..

A: You can use hooks for trimming every 'q' get parameter.
First enable hooks in application/config/config.php
$config['enable_hooks'] = TRUE;

Then create a file with custom name (example: Trim_hooks.php) in application/hooks and write below code in hook config file(application/config/hooks.php) file.
$hook['post_controller_constructor'] = array(
    'class' => 'Trim_hook',
    'function' => 'run',
    'filename' => 'Trim_hooks.php',
    'filepath' => 'hooks',
);

At the end create Trim_hooks.php file in application/hooks:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Trim_hook
{
  function run()
  {
    if (isset($_GET['q']))
    {
      $_GET['q'] = trim($_GET['q']);
    }
  }
}

Every time you have q parameter in GET, it's trimming after run controllers constructoror.