text:
Q: JavaFX ScrollPane not recognizing my oversized VBox I'm pretty new to JavaFX and i've got following Problem:
I have a program that calculates all possible matches between teams in aneveryone against everyone- scenario. That's why there are a lot of matches in total. And there comes my problem: I've got a ScrollPane containing an AnchorPane that holds a VBox (VBOX_matches in the code). This VBox contains HBoxes based on the amount of all possible matches.
My thought was: as it extends the size of the program window the other matches have to be seen. Let's add a scrollpane as many people suggested in a forum. But this scrollpane always stays at 100% and is not scrollable. What am i doing wrong? Is this even possible?
https://ibb.co/c3WVEc  //Link to the screenshot. I can't upload pictures somehow
  this.matches = gameManagement.getMatches();
  for (int i = 0; i < matches.size(); i++) {
        String team1 = ((Team)((Pair)matches.get(i)).getKey()).getTeamname();
        String team2 = ((Team)((Pair)matches.get(i)).getValue()).getTeamname();
        HBox box = new HBox();
        box.setSpacing(20);
        Label first = new Label(team1);
        first.setMinSize(LABEL_TEAM_WIDTH,LABEL_TEAM_HEIGHT);
        first.setMaxSize(LABEL_TEAM_WIDTH,LABEL_TEAM_HEIGHT);
        first.setPadding(new Insets(0,0,0,PADDING));
        first.setTextAlignment(TextAlignment.CENTER);
        first.setFont(Font.font("Bold",TEAM_FONT_SIZE));

        box.getChildren().add(first);

        VBOX_matches.getChildren().add(box);

FXML File:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.media.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.text.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="700.0"
            prefWidth="1100.0" style="-fx-background-color: gray;" xmlns="http://javafx.com/javafx/8"
            xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.gui.GameController">
    <children>
        <SplitPane dividerPositions="0.6539162112932605" layoutX="377.0" layoutY="253.0" prefHeight="700.0"
                   prefWidth="1100.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0"
                   AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
            <items>
                <ScrollPane fx:id="scroll" fitToHeight="true" fitToWidth="true" maxHeight="1.7976931348623157E308"
                            maxWidth="1.7976931348623157E308" minHeight="-Infinity" minWidth="-Infinity" pannable="true"
                            prefHeight="698.0" prefWidth="682.0" vbarPolicy="ALWAYS"
                            SplitPane.resizableWithParent="false">
                    <content>
                        <AnchorPane fx:id="scroll_pane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"
                                    minWidth="-Infinity" prefHeight="698.0" prefWidth="714.0">
                            <children>
                                <VBox fx:id="VBOX_matches" layoutX="-6.0" maxHeight="-Infinity" maxWidth="-Infinity"
                                      minHeight="-Infinity" minWidth="-Infinity" prefHeight="698.0" prefWidth="714.0"
                                      AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0"
                                      AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0"/>
                            </children>
                        </AnchorPane>
                    </content>
                </ScrollPane>


text:
Q: redirect module function stdout to flask socket I have a file with a function that counts to 15 in a for loop. I want to redirect the output to a socket.
test.py
def counttest():
    x = 0
    for x in range(0,15):
        x = x+1
        print("Number: "+ str(x))
        time.sleep(1)

I have been able to do this by using the subprocess module and using a script like so:
test_app.py
@sock.route('/echo')
def echo(ws):
    data = ws.receive()
    with subprocess.Popen(['powershell', ".\pingtest.ps1"],stdout=subprocess.PIPE, bufsize=1,universal_newlines=True) as process:
            for line in process.stdout:
                line = line.rstrip()
                print(line)
                try:
                    ws.send(line+ "\n")
                except:
                    pass

However, I don't think you can use subprocess on functions or imported modules. I wanted to use the multiprocessing module but they don't seem to have a stdout  parameter like the subprocess module does.
Is there a way I can send the stdout from a function into a variable constantly? like a forloop that gets updated with realtime stdout from a function?
I tried using the multiprocessing module but I am sure that is not how I a suppose to use this:
import multiprocessing as Process

@sock.route('/echo')
def echo(ws):
    data = ws.receive()
    testprocess = Process(target=test.counttest())
    ws.send(testprocess)

###THIS FAILS, THE OUTPUT STILL SHOWS IN THE CONSOLE INSTEAD OF GETTING REDIRECTED TO THE SOCKET LIKE THE SUBPROCESS MODULE CAN DO###

If there is no other choice, I could just make my test.counttest() redirect output by forcing the file itself to be ran with subprocess but that is the last choice I want to make
Example of what I mean:
@sock.route('/echo')
def echo(ws):
    data = ws.receive()
    with subprocess.Popen(['python', ".\test.py"],stdout=subprocess.PIPE, bufsize=1,universal_newlines=True) as process:
            for line in process.stdout:
                line = line.rstrip()
                print(line)
                try:
                    ws.send(line+ "\n")
                except:
                    pass

redpajama_set_name: RedPajamaStackExchange


text:
Q: Text selection CTRL+SHIFT+Cursor Keys in shell? I'm using guake and zsh and I'd like to use Ctrl+Shift+Arrows to select word-by-word, Ctrl+Arrows to jump around words, Shift+Arrows to select char-by-char in terminal. This is working as expected in applications like gedit.
Is it possible in any shell?

A: The only way I know to select text from a shell without using the mouse is using GNU screen.
Quick tutorial:
Note: All GNU Screen commands are of the form:  Ctrl+A followed by another key or combination

*

*Install GNU Screen: sudo apt-get install screen

*Open screen: screen (or screen myprog my args here)

*Run your program, producing the output you want copied

*Enter copy mode: Ctrl+A [

*Move the cursor to a starting point and hit Enter to start selecting

*Move the cursor to the ending point and hit Enter to finish selection

*Paste with Ctrl+A ]

Read more:

*

*How do I copy text from the program "screen" to my clipboard?

*GNU Screen Survival Guide - Stackoverflow

*How do I copy text from my xterm without a mouse - Stackoverflow


text:
Q: Styling Telerik WPF NumericUpDown Control I use Telerik WPF controls and need to add a NumericUpDown control to my UI. The thing is when used "as it is" it doesn't fit the rest of the application visually
<TL;DR>
This is a bigger application, that's not been written fully by me. Other people somehow managed to "import" other telerik controls and assign them other styles. Sadly, nobody's used the UpDown control before.
</>

I added the control to my UI:
<telerik:RadNumericUpDown
  Minimum="0"
  Maximum="10"
  SmallChange="1"
  NumberDecimalDigits="0"
  IsInteger="True"
  Value="{Binding Path=Counter}" />

Also, I've added some styling to a ResourceDictionary:
  <Style TargetType="{x:Type telerikInput:RadNumericUpDown}">
    <Setter Property="Padding" Value="1"/>
    <Setter Property="Margin" Value="2"/>
    <Setter Property="Border.CornerRadius" Value="2" />
    <Setter Property="Border.Background" Value="{StaticResource ControlBackgroundBrush}" />
    <Setter Property="Border.BorderBrush" Value="{StaticResource SolidBorderBrush}" />
    <Setter Property="Border.BorderThickness" Value="1" />
  </Style>

And this handles some basic styling features (border, margin, etc). In general it looks "good enough". There's only one problem - when a mouse pointer hovers over the control, it becomes shiny and glossy. That's not like my other controls behave - is there an easy way to remove this effect ?
I've tried experimenting with Triggers:
<Style>
...
  <Style.Triggers>
    <Trigger Property="IsMouseOver" Value="True">
      <Setter Property="Foreground" Value="Red" />
      <Setter Property="Border.BorderBrush" Value="Black" />
      ...
  </Style.Triggers>
</Style>

But this didn't do much. I've also tried setting IncreaseButtonContentTemplate field, but this turned out no good either.

A: You need to modify the default ControlTemplates and remove any "shiny and glossy" effects from them. The easiest way to do this would be to copy the default templates from the Themes.Implicit folder in your Telerik installation directory into your solution and then edit them as per your requirements.
There is no "DisableEffects" property that you can simply set on the control I am afraid.


text:
Q: Mouting error bash on ubutun on Windows I was running md5sum on a usb hard-drive via bash on Windows, but I had to terminated the program because of some errors. I tried to remount the drive and gives no error , but I was unable to cd ( invalid argument), so I used df -h and it was returned following error:
df: '/mnt/f': Input/output error

Any ideas on what causes this ? The drive works just fine when I plugged it in a ubuntu machine .
I followed the instruction from here :
https://blogs.msdn.microsoft.com/wsl/2017/04/18/file-system-improvements-to-the-windows-subsystem-for-linux/


text:
Q: Keep getting build fail when scaffold-DbContext for a remote SQL server database I am just trying to Scaffold a DbContext using command in package console manager. I follow this tutorial for Db-first approach but I always getting "Build failed" error message.
https://www.entityframeworktutorial.net/efcore/create-model-for-existing-database-in-ef-core.aspx
Below is the command I use:
Scaffold-DbContext "Server=den1.mssql8.gear.host;Database=testdb;User Id=testdb;Password=actualPassword" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Unlike the tutorial, I was trying to use remote SQL server (sadly all the tutorial online use local sql server as if it is the only kind of db in the world)
I have ensured that I have installed the EntityFramework Provider for SQL server, along with the Tools from Nuget.
I have been digging for hours and can't find the answer for this, so any kind of help would be really appreciated.

A: this worked for me after so many hours of unfruitful search
Scaffold-DbContext "Server=serverIpAddress;Database=testdb;User Id=testdb;Password=actualPassword" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
try it.

A: For the VS22 M1 machine following command work for me
dotnet ef dbcontext scaffold "Server=111.11.111.11;Database=MyDataBase;User Id=MyUserName;Password=MyPassword" Microsoft.EntityFrameworkCore.SqlServer -o Models


text:
Q: How do I properly bind a WPF TreeView control and effectively display a hierarchy of the data? Ok, so I normally wait until the last possible moment to submit a question but I could really use some help.
I'm attempting to bind an ObservableCollection<Contact_Info> to a WPF TreeView Control. Contact_Info contains properties for contact information and implements INotifyPropertyChanged. It also contains a list of more detailed information for the given Contact.
I'm having trouble with 2 things. 1) I need to display on the TreeViewItem header the name of the Company however, a lot of the Contacts have a missing Company Name in which, I want to use the First and Last name. I have attempted to use things like FallBackValue and TargetNullValue but the CompanyName is not null, its just empty so I can't seem to get that right. Do I need a converter? 2) I cannot seem to get the hierarchy correct in that, I want all Contacts of the same AccountID to be grouped together within a TreeViewItem. Currently, I can only get the Company Name to display on the TreeViewItem and expanding it displays a blank value and there are still duplicate Company Names displayed..
Code for my attempt at a HierarchicalDataTemplate placed under the DockPanel.Resources (not sure if that's the right place either).
    <local:Main_Interface x:Key="MyList" />
       <HierarchicalDataTemplate DataType = "{x:Type
                                 local:Contact_Info}" ItemsSource = "{Binding Path=OppDataList}">
            <TextBlock Text="{Binding Path=CompanyName}"/>
        </HierarchicalDataTemplate>
       <DataTemplate DataType = "{x:Type sharpspring:SharpspringOpportunityDataModel}" >
             <TextBlock Text="{Binding Path=ProjectName}"/>
        </DataTemplate>

The above code is the most recent thing I have tried among countless other ways. I feel that I'm really close but at this point I could really use some help from SO..
The other classes are a little long so let me know if you need more. Any help provided is greatly appreciated!
Edit 1: Contact_Info
public class Contact_Info : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    internal SharpspringLeadDataModel LeadDataModel;
    internal SharpspringOpportunityDataModel OppData;
    public List<SharpspringOpportunityDataModel> OppDataList { get; set; }// Should i make this ObservableCollection?

    public Project_Info ProjectInfo { get; set; }
    public bool IsDirty { get; set; }
    public bool IsNew { get; set; }

    #region Properties

    public long AccountID
    {
        get => LeadDataModel.AccountID;
        set
        {
            if (value != LeadDataModel.AccountID)
            {
                LeadDataModel.AccountID = value;
                NotifyPropertyChanged();
            }
        }
    }
    public long LeadID
    {
        get => LeadDataModel.LeadID;
        set
        {
            if (value != LeadDataModel.LeadID)
            {
                LeadDataModel.LeadID = value;
                NotifyPropertyChanged();
            }
        }
    }
    // Lead Info
    public string CompanyName
    {
        get => LeadDataModel.CompanyName;
        set
        {
            if (value != LeadDataModel.CompanyName)
            {
                LeadDataModel.FaxNumber = value;
                NotifyPropertyChanged();
            }
        }
    }

    public Contact_Info(SharpspringLeadDataModel lead, SharpspringOpportunityDataModel opp)
    {
        LeadDataModel = lead;
        OppData = opp;
        ProjectInfo = new Project_Info(this);

    }

    public SharpspringLeadDataModel GetDataModel()
    {
        return LeadDataModel;
    }

    public SharpspringOpportunityDataModel GetOppModel()
    {
        return OppData;
    }

    public Project_Info GetProjectInfoModel()
    {
        return ProjectInfo;
    }

    public void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        IsDirty = true;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Edit 2: Currently populates tree but does not group Companies together...
private void PopulateTreeView(List<SharpspringLeadDataModel> lead_list, List<SharpspringOpportunityDataModel> opp_list)
    {
        Contacts = new ObservableCollection<Contact_Info>();
        var complete2 =
                        from lead in lead_list
                        let oppList = from o in opp_list
                                      where o.PrimaryLeadID == lead.LeadID
                                      select o
                        select new Contact_Info()
                        {
                            LeadDataModel = lead,
                            OppData = oppList.DefaultIfEmpty(new SharpspringOpportunityDataModel()).First(),
                            OppDataList = oppList.ToList(),
                        };

        Contacts = complete2.ToObservableCollection();
   Lead_Treeview.ItemsSource = Contacts;
}

A: I think your problem is really with using List instead of ObservableCollection for OppDataList. Using your code (reduced to minimal needed) but with the ObservableCollection driving the collection it works fine for me.
Note that my code will work fine with List even because its all static but in a proper app you'll need OC to track changes in collection.
Disclaimer: I'm using code behind to answer this question to keep it simple but I do not recommend any such use in any real app

MainWindow.xaml

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="240" Width="320">
    <TreeView ItemsSource="{Binding Contacts}">
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate DataType="{x:Type local:Contact_Info}" ItemsSource="{Binding Path=OppDataList}">
                <HierarchicalDataTemplate.ItemTemplate>
                    <DataTemplate DataType="{x:Type local:SharpspringOpportunityDataModel}">
                        <TextBlock Text="{Binding Path=ProjectName}" />
                    </DataTemplate>
                </HierarchicalDataTemplate.ItemTemplate>
                <TextBlock Text="{Binding Path=CompanyName}" />
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
</Window>

MainWindow.xaml.cs

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using WpfApp1.Annotations;

namespace WpfApp1
{
    public partial class MainWindow : INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
        }

        public ObservableCollection<Contact_Info> Contacts { get; } =
            new ObservableCollection<Contact_Info>
            {
                new Contact_Info
                {
                    CompanyName = "Apple",
                    OppDataList = {new SharpspringOpportunityDataModel {ProjectName = "World take over"}}
                },
                new Contact_Info
                {
                    CompanyName = "Google",
                    OppDataList = {new SharpspringOpportunityDataModel {ProjectName = "World take over"}}
                },
                new Contact_Info
                {
                    CompanyName = "Microsoft",
                    OppDataList = {new SharpspringOpportunityDataModel {ProjectName = "World take over"}}
                }
            };

        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class Contact_Info
    {
        public string CompanyName { get; set; }

        public ObservableCollection<SharpspringOpportunityDataModel> OppDataList { get; } =
            new ObservableCollection<SharpspringOpportunityDataModel>();
    }

    public class SharpspringOpportunityDataModel
    {
        public string ProjectName { get; set; }
    }
}

Screenshot

A: based on my understanding your OppDataList is the sub property for the given Contract info and you want it to be collapsible.
In such case you can do
    <ListBox ItemsSource="{Binding YourContactList}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Expander Header="{Binding ProjectName}">
                    <Expander Header="{Binding CompanyName}">
                        <ListBox ItemsSource="{Binding OppDataList}">
                            <!--Your OppDataList display-->
                        </ListBox>
                    </Expander>
                </Expander>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

End result will look similar to this
+Contract1
-Contract2
   -Project2
      -Company2
         -Opp
            1
            2
            3
+Contract3


text:
Q: Why can't I resize my existing partition? I just finished downloading my copy of Lion and wanted to install it on a new second partition. I freed up just over 50 GBs from my hard drive and am now stuck trying to shrink my existing partition. I'm using the Disk Utility, but am continually getting:

Partition failed
Partition failed with the error:
The partition cannot be resized. Try
  reducing the amount of change in the
  size of the partition.

I've tried just resizing by 1 gigabyte and it still fails. Any free tools to fix this? Thanks.

A: You've probably got fragmentation of your free space. For some reason, Disk Utility can't figure this out on its own; it just fails.
I found a stunningly simple way to resolve this: create a new disk image with Disk Utility that's a little bit smaller than the remaining space on your drive.
It took several minutes on my SSD, presumably while OS X moved things around. I imagine it would take significantly longer on a hard drive.
When it's done, delete the disk image you just created. You should now be able to resize your partition!

A: The GUI for Disk Utility has always had problems with resizing volumes.
You could try diskutil from the command line, if you trust your skills enough.
I'd start the Terminal and write diskutil list to see all devices connected.
To resize a volume from the list you'd write something like this (Let's assume that disk2s2 is 100GB):
diskutil resizeVolume disk2s2 50g HFS+ Lion 0b
This should create a secod partition with 50gb size, HFS+ format(mac format) and the name Lion

A: When I ran into this problem, I used iDefrag to defragment the volume, and that let me shrink it.  Unfortunately it's not free.
It has since occurred to me that it might work better to dismount the partition before shrinking.  If you want to try this, you'll need to boot from something else, like your O S X install DVD.

A: I don't mean to open up an age old thread, but simply running fsck -fy from single user mode fixed it for me.
From the man page:
-f     Force fsck to check `clean' filesystems when preening.
-y     Assume a yes response to all questions asked by fsck; this should
       be used with great caution as this is a free license to continue
       after essentially unlimited trouble has been encountered.

A: This is what worked for me, and avoided backing up and restoring the volume.
While you are resizing your partition, do tail -f /var/log/kernel.log or run the Console application and select kernel.log.
This will tell you why the resize is failing.
Unfortunately, it will only give you the inode number for the file or directory that is preventing the resize.
To find the file name corresponding to this inode, you can use the find command from the terminal:
$ cd /Volumes/<volume you are trying to resize>
$ find -x . -inum <the inode number from kernel.log>

Once you find the file, copy it to a different volume, if you want to save it, and then delete it on the volume you are resizing.
Then rerun the resize operation and it should succeed. If it doesn't, repeat the above procedure until you are successful.
Ref:  https://discussions.apple.com/thread/2742302


text:
Q: Filter by URL in Search Results Webpart I've got a search results web part which searches for pages in a sharepoint library. I'd like to add a query text that limits the search to only certain URLs, such as 'mysite.com/sites/somepagename'
But I just can't figure out what the field containing the URL is supposed to be.
I've checked the 'Property filter' dropdown and there is no field named 'URL'. Tried using properties with like 'Location' , 'Site' and 'urls' filtering for results that contain 'somepagename' without any success.
How do I filter by URL?
EDIT: Sorry for confusing you guys, it's actually a Search Results web part. Not Content Query.

A: The path property should give you what you're looking for - but note that you need to include the whole path, http:// and all.
path:"https://sharepointsite.sharepoint.com/mysite"

and you can control whether or not to include subsites with the UrlDepth property
path:"https://sharepointsite.sharepoint.com/mysite"  UrlDepth=1

Will return results from https://sharepointsite.sharepoint.com/mysite only
path:"https://sharepointsite.sharepoint.com/mysite"  UrlDepth=2

Will return results from https://sharepointsite.sharepoint.com/mysite/subsite1, https://sharepointsite.sharepoint.com/mysite/subsite2 etc.

A: Note completely sure if this answers your question, but if you want your Search Results Web Part to only include hits from that site, place your results page in edit mode, and select the "Results"  web part for editing, On the right, you will see a button for "Change Query".
Typically by default the Query Text is set to
{searchboxquery}
You just need to adjust to look like
{searchboxquery} Path:{Site.URL}
and now it will only include results from that root site and down.
Another option is to use the "Site Title" refiner. If you go into managed properties, you will see one called "SiteTitle". You will have to update this to map to the crawled property of "ows_SiteName".
Once you do that, you can add "Site Title" as a refiner and users can then filter their results down based on which SITE the item was found.


text:
Q: Add thousand separator s to all columns of dataframe I have a dataframe with multiple numeric columns that need a thousand separator added to every column. Is there a simple way of doing this?
I have tried using mutate_all and prettyNum(var, big.mark=",") but I am an R newbie and can't figure out the syntax for just applying this across a whole dataframe. I have tried doing things like this:
    df <- df %>%
  mutate_all(prettyNum(var, big.mark = ","))

Any help appreciated.

A: mutate_all was superseded. You can use across, by the default it will apply the function to all columns, but you can also use the argument .cols to set a specific group of variables to apply.
df %>%
  mutate(across(.fns = ~prettyNum(., big.mark = ",")))


text:
Q: Calculate poisson probability percentage When you use the POISSON function in Excel (or in OpenOffice Calc), it takes two arguments:

*

*an integer

*an 'average' number

and returns a float.
In Python (I tried RandomArray and NumPy) it returns an array of random poisson numbers.
What I really want is the percentage that this event will occur (it is a constant number and the array has every time different numbers - so is it an average?).
for example:
print poisson(2.6,6)

returns [1 3 3 0 1 3] (and every time I run it, it's different).
The number I get from calc/excel is 3.19 (POISSON(6,2.16,0)*100).
Am I using the python's poisson wrong (no pun!) or am I missing something?

A: scipy has what you want
>>> scipy.stats.distributions
<module 'scipy.stats.distributions' from '/home/coventry/lib/python2.5/site-packages/scipy/stats/distributions.pyc'>
>>> scipy.stats.distributions.poisson.pmf(6, 2.6)
array(0.031867055625524499)

It's worth noting that it's pretty easy to calculate by hand, too.

A: It is easy to do by hand, but you can overflow doing it that way.  You can do the exponent and factorial in a loop to avoid the overflow:
def poisson_probability(actual, mean):
    # naive:   math.exp(-mean) * mean**actual / factorial(actual)

    # iterative, to keep the components from getting too large or small:
    p = math.exp(-mean)
    for i in xrange(actual):
        p *= mean
        p /= i+1
    return p

A: This page explains why you get an array, and the meaning of the numbers in it, at least.


text:
Q: Read MAC Iteration from pkcs#12-file in Java My aim is to read the MAC Iteration value in Java from a pkcs#12 file, just like openssl prints it out using following command in a shell:
/home/foo> openssl pkcs12 -info -in myPkcs12.pfx -passin pass:myPassword
MAC Iteration 25000
MAC verified OK
PKCS7 Data
...

A: I managed to easily read the MAC Iteration count with the Bouncy Castle (Bouncy Castle + Bouncy Castle Provider) library.
final File certFile = ...;
final PKCS12PfxPdu pfx = new PKCS12PfxPdu(Files.readAllBytes(certFile.toPath()));
final Pfx asn1Structure = pfx.toASN1Structure();
final MacData macData = asn1Structure.getMacData();
final BigInteger iterationCount = macData.getIterationCount();


text:
Q: How can mock object replace all system functionality being tested? I am fairly new to unit testing. And at the moment I have trouble on trying to unit test a Google oAuth Picasa authentication. It involves major changes to the code if I would like to unit tested it (yeah, I develop unit test after the app works).
I have read that Mock Object is probably the way to go. But if I use Mock, how do I know that the functionality (that is Google oAuth Picasa authentication), is really working?
Or, aside that I develop unit testing after the app finished, did I made other mistakes in understanding Mock?

A: When unit testing, you test a particular unit (function/method...) in isolation, meaning that you don't care if other components that your function uses, work (since there are other unit test cases that cover those).
So to answer your question - it's out of the scope of your unit tests whether an external service like Google oAuth works. You just need to tests that you make a correct call to it, and here's where Mock comes in handy. It remembers the call for you to inspect and make some assertions about it, but it prevents the request for actually going out to the external service / component / library / whatever.
Edit: If you find your code is too complex and difficult to test, that might be an indication that it should be refactored into smaller more manageable pieces.


text:
Q: TCP IP server which can handle multiple requests? I'm learning about TCP/IP and am trying to use it to execute different commands on my server.
I thought i'd start small and build up. I've got a current example running which has a server and client connect, and then the server sends the current time to the client.
Now i want to make it such that the server can handle multiple clients.
How can I do this? I think i could use fork, but is there a way to do it without having multiple processes to worry about?
Are there any good primers on this sort of thing, or could you provide some instructions on how to modify my existing code?
Thanks,

A: glibc Manual has a nice example. The missing code bits can be found earlier in the chapter. The nice thing about the example is that you do not need multiple threads

A: I would recommend the use of threads:

*

*One server thread has the sole purpose of listening at the server socket for incoming connections.  Once a connection is received, it is passed off to a worker thread, while the server keeps listening.

*One or more worker threads.  These threads will do the majority of the work.  You can choose to use one thread per socket, or you can use the select function to allow one thread to handle multiple sockets.

I don't know any primers off the top of my head, sorry.

A: Take a look at Erik's answer on this other question. You don't really need to do multithreading.


text:
Q: Microsoft Team System value within only a Dev Team Microsoft Team System appears to be a great platform for process-oriented systems implementation, however if you strip out access for the BAs, PM and Business Users and just purely use it within a Dev team does it have any more value than just using Visual Studio Professional, SourceSafe, a Defect Tracking Tool and a continuous integration server like CruiseControl or TeamCity?

A: Yes.  Every replacement technology you've mentioned is something that is supported by the Team System package (either in this release or the next).  All of these components are designed to integrate and work with each other in TFS.  This is a high priority of the TFS team for all components.  The result is a set of features which in most cases seamlessly integrate with each other.
I'm not familiar with several of the other projects you mentioned but it's unlikely that they integrate as well with each other as the corresponding TFS components.  This is not to say they have no integration or perform poorly as products.  Just that they are not designed ground up to work with each other.  Hence the interaction will not be as crisp as the TFS components.
Is this valuable enough to continue using TFS?  Don't know because it would be highly dependent on how much you value this integration.

A: One of the big selling points for TFS for my team is the coherency it provides to our overall product life cycle. We do allow BAs, PMs and Business Users to have certain levels of access to TFS, but even if we did not, the product would still be of great value to use. The ability to manage our workflows within TFS and enforce consistency across the development team is great.
Some of the features that TFS provides that we use: security, reporting, work flow management, integrated builds, email alerts, branching / merging.
Could you pull it off with a hodge-podge of other tools? Probably, but it wouldn't be as easy to manage and maintain and you probably wouldn't be able to pull out the kind of data necessary for reporting and tracking the way you can with TFS.
On a sidenote, if your counting on Visual SourceSafe as your repository I would highly suggest looking elsewhere. From personal and business experience, I can attest that it cannot be counted on as a stable/robust repository.
My thoughts.

A: Sure it has value.  There are a ton of client features only in the Team SKUs (don't let the name fool you -- they are primarily just the new "super premium" kitchen-sink versions, that also have the nice bonus of including a server CAL for TFS.)  Exact specs available here: http://www.microsoft.com/visualstudio/en-us/products/teamsystem/default.mspx
Looking specifically at the collaboration features, again there's clear value in a system whose components were design to "just work" with each other.  The setup is streamlined (though it has a ways to go); the UIs are consistent and accessible from each other; the backend feeds a unified reporting/analysis service.  If you have a large team, the overall perf/scalability also far exceeds what the typical OSS suite is capable of at the moment.
The question is whether it's worth the $$ to you.  Why use Visual Studio Professional instead of SharpDevelop?  Why SourceSafe instead of Git?  Why not Notepad and specially labeled folders?
All of the commercial products are commercial for a reason (ok, maybe not SourceSafe!).  If you want something with a broad feature set, tight integration, well-defined support & testing lifecycle, good fit & finish, etc then it's usually worthwhile to spend the $$ and let your development staff get on with their work.  If you don't mind doing setup & troubleshooting yourself, switching between several applications as part of the development workflow, losing the ability to query & report on team statistics as a whole, etc then by all means go open source -- many OSS dev tools are very solid nowadays.


text:
Q: Load SWF from embedded file in Flash Usually we load external swf file into Flash using 'Loader' class.
var loader:Loader = new Loader();
loader.load(new URLRequest("http://domain/path/my-external-swf.swf"));

However, the external swf file is now embedded in my flash document:
[Embed("my-external-swf.swf")]
public var component:Class;

Is it possible to tell 'Loader' to load from embedded content instead?

A: I think you should use loadBytes of Loader class, similar to described solution here: how to embed swf file

A: You should be able to simply do this:
addChild(new component());

Hopefully the name component won't collide with any reserved variables.
If you still would like to use the Loader class, as @Lukasz advises, use the loadBytes() method and pass the embedded asset. If your swf also contains code, you might need to initialize the LoaderContext:
var ctx:LoaderContext = new LoaderContext(false,this.loaderInfo.applicationDomain);
ctx.allowCodeImport = true;
Loader(addChild(new Loader())).loadBytes(new Components(),ctx);


text:
Q: how can i print id and sub_id in nested table in rails i am printing nested table in rails. now i want to print their id as 1,2,3 and so on and nested content sub_id as 1.1,1.2...3.1 and so on. how can i do that  in rails?

        Task Name
        Planned start date
        Planned end date

      <% @stages.each do |stage| %>

          <%= stage.stage %>
          <%= stage.planned_start_date.strftime("%d-%m-%Y") %>
          <%= stage.planned_end_date.strftime("%d-%m-%Y") %>

        <% stage.tasks.each do |task| %>

            <%= task.task_name %>
            <%= task.planned_start_date.strftime("%d-%m-%Y") %>
            <%= task.planned_end_date.strftime("%d-%m-%Y") %>

          <% task.sub_tasks.each do |sub_task| %>

              <%= sub_task.sub_task_name %>
              <%= sub_task.planned_start_date.strftime("%d-%m-%Y") %>
              <%= sub_task.planned_end_date.strftime("%d-%m-%Y") %>

          <% end %>
        <% end %>
      <% end %>

how can i add column to user and print 1 for task and 1.1,1.2... for sub_task. i can't take id from table because their is multiple user(profiling). i want to print id from front end.

A: It sounds like you need a task counter and a sub-task counter.
...
<% stage.tasks.each_with_index do |task, task_index| %>

    <%= "#{task_index + 1} #{task.task_name}"%>
    <%= task.planned_start_date.strftime("%d-%m-%Y") %>
    <%= task.planned_end_date.strftime("%d-%m-%Y") %>

  <% task.sub_tasks.each_with_index do |sub_task, sub_task_index| %>

      <%= "#{task_index + 1}.#{sub_task_index + 1} #{sub_task.sub_task_name }"%>
      <%= sub_task.planned_start_date.strftime("%d-%m-%Y") %>
      <%= sub_task.planned_end_date.strftime("%d-%m-%Y") %>

  <% end %>
<% end %>

Read more about Enumerable#each_with_index


text:
Q: How can I achieve a similar plot output in R? In Matlab, I had the following line to plot:
plot(x,y,'o',xx,YFIT,'-')

The output looked like this:

What is the best way to go about the syntax for R plotting? First time working with plotting in R, so I'm asking for help. I can go into further explanation about my variables but since I'm just trying to translate the syntax, I wasn't sure if I'd need it.

A: Try something like this:
matplot(xx,yy,type="l")
matlines (xx, YFIT, type = "l", lty = 1:ncol(yy), col = 1:ncol(yy))

A: Below I've given a tiny example of using ggplot to do what you want. Of course you don't want to prep your data as shown in the example. I suggest to use the 'melt' function in package 'reshape2' to translate your data from matrix format to long format expected by ggplot.
a.df <- data.frame(
    X=c(0,0.5,1.0),
    Y=c(0,0.25,1.0),
    ID = c("A","A","A")
)

b.df <- data.frame(
    X=c(0,0.5,1.0),
    Y=c(0,0.5,1.0),
    ID = c("B","B","B")
)

c.df <- data.frame(
    X=c(0,0.5,1.0),
    Y=c(0,0.75,1.0),
    ID = c("C","C","C")
)

display.df <- rbind(a.df, b.df, c.df)

ggplot(display.df, aes(X, Y, color=ID)) + geom_line()


text:
Q: Conexion SQL desde JAVA Quiero conectar mi programa de prueba con la base de datos de mi pc, desde java a sql server 2017.
Ya hice todas las configuraciones, y el test de conexion me da ok, pero en el momento de llamar a la conexion con el programa abierto me arroja un mensaje de error.
Este es el error:

A: Chicos, gracias por responder... el jar ya estaba instalado en la carpeta libreria, me Di cuenta más tarde que el problema es la versión del jar,  tenía la 7, y no funcionó con el sql 2017, puse la 6.2 y listo, ya conecta perfecto.. Gracias a todos!


text:
Q: How to display code blocks in my private blog I want to display code blocks in my private blogging site. I am creating it from the scratch.
How to proceed with it. I am totally confused.

A: Use the proper markup to make the code monospaced and keep whitespace as-is. This basically means using
 and :

your();
code = "here";

After that you just need to add some nice CSS styling to make it look nice. And if you want syntax highlighting like here on Stack Overflow simply the easiest way to get it is adding google's prettify: http://code.google.com/p/google-code-prettify/

A: Try Syntax Highlighter. Its easy and looks really good.
Demo Link


text:
Q: I am making P2P chat program in python. The thrying to connect keeps looping how to fix So im making this p2p chat program and ive made it so that if one persn disconnect it wil find a new host but whe i first start it up it loops trying to connect
while True:
    try:
        print("Trying to connect ...")
        time.sleep(randint(1,5))
        for peer in p2p.peers:
            try:
                client = Client(peer)
            except KeyboardInterrupt:
                sys.exit(0)
            except:
                pass
            if randint(1, 20) == 1:
                try:
                    server = Server()
                except KeyboardInterrupt:
                    sys.exit(0)
                except:
                    print("Couldn't start the server ...")
    except KeyboardInterrupt:
            sys.exit(0)

i have the p2p set up just not the reconnect part


text:
Q: OSMNX graph to distance matrix and DBSCAN I'm having troubles programming to get the distance matrix from a Graph of coordinates (LAT,LON).
I want to connect an arbitrarily group of points (let's say, 200.000 firms), get their nearests representations in the Graph, created with ox.graph_from_place().
I am working with dask arrays and dataframes (da.array, df.DataFrame)
if __name__ == "__main__":

    # OPTION B: Use a strongly (instead of weakly) connected graph
    Gs = ox.utils_graph.get_largest_component(G, strongly=True)
    Gs.__name__ = "Gs"

    # attach nearest network node to each firm
    df["nn"] =  da.array(ox.get_nearest_nodes(Gs, X=df['longitude'], Y=df['latitude'], method='balltree') )

    # we'll get distances for each pair of nodes that have firms attached to them
    nodes_unique = pd.Series(df['nn'].unique())
    nodes_unique.index = nodes_unique.values

    # convert MultiDiGraph to DiGraph for simpler faster distance matrix computation
    G_dm = nx.DiGraph(Gs)
    G_dm.__name__ = "G_dm"

    save_pickle(Gs)
    save_pickle(G_dm)

    print("len df['nn']:", len(df['nn']))
    print("len nodes_unique:", len(nodes_unique))

Some code has been avoided to go to the heart of the matter, then, I've tried following https://networkx.org/documentation/stable/reference/algorithms/shortest_paths.html and a network_distance_matrix() function using a strongly connected graph Gs, but this is so inefficient in computation time. I have seen in the docs a bunch of functions, but I haven't seen one to efficiently compute a distance-matrix between pairs of unique nodes belonging to the Graph and following paths through it.
I would like to know if there is any way to parallelize this process, and/or make it go through a generative way and not storing all that RAM.
My objective is to provide a pre-computed matrix in a DBSCAN (sklearn.clustering) model, and it has to be quickly so that I can kind of "grid-search" through parameters. I am a beginner to these libraries.


text:
Q: Aplication Error, Code=H14 "No web processes running", path="/favicon.ico" Heroku returns me this message when i try open the app

Application error
An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command
heroku logs --tail

the error is:
2020-06-23T20: 04: 27.882267 + 00: 00 heroku [router]: at=error code=H14 desc="No se están ejecutando procesos web" método=GET ruta="/favicon.ico" host =proyectojoao.herokuapp.com request_id=852edcba-a708-41ec-90e4-306366cf68d3 fwd="104.33. 31.5 " dyno= connect=  service= estatus=503 bytes= protocol=https

I tried scale dynos, but this return:
Couldn't find that process type (web)

And i have the Procfile archive in the root of my project whit:
web: gunicorn blog.wsgi --log-file -


text:
Q: mongoose, node, cannot use the method defined in user.model.js I am using node and mongoose to build an app. And when testing, there exists a strange problem. Here is my auth.index.js(for user login).
auth.index.js:
var express = require('express');
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('../config/environment');
var User = require('../api/user/user.model');
var jwt = require('jsonwebtoken');
var auth = require('./auth.service');
var router = express.Router();
router.post('/login', function (req, res, next){
User.find({email: req.body.email}, function (err, user){
    if (err) {
        return next(err);
    } else if (!user) {
        return res.json({message: 'Invalid email.'});
    } else {
            if(!user.authenticate(req.body.password)){
               return res.json({message: 'Invalid password.'});
            };
            var token = auth.signToken(user._id, user.username, user.role);
            return res.json({token: token});
    };
  });
});

Here is the user.model.js:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
  username: String,
  password: String,
  email: {type: String, lowercase: true},
  role: {type: String, default: 'user'},
  provider: String,
  date: String
});
UserSchema.methods = {
//check password
  authenticate: function(plainText) {
    return plainText === this.password;
  }
};

However, in the command window, it returns that

user.authenticat is not a function.

I wanna know why, and does it mean that I cannot use the method directly or I need to invoke the method through passport ? Thanks.

A: I think you have misplaced your methods. It should be like this.
UserSchema.methods.authenticate: function(plainText) {
       return plainText === this.password;
}

See the following link for the complete example. https://scotch.io/tutorials/using-mongoosejs-in-node-js-and-mongodb-applications


text:
Q: Display category image under link text in opencart I've used OpenCart v2.2.0.0 for a client's website as it was their eCommerce system of choice. We have gotten a lot of the preliminary design added onto the website - that's not a problem.
The issue we are having is with the category pages.
Currently, the subcategories are displaying as normal text links: http://i.imgur.com/1LORcrg.jpg
What we would like to accomplish is to feed through unique images underneath these links.
What I had in mind was whether it was possible to feed the category image below the text, so that it looks similar to this: http://i.imgur.com/zTv2hHN.jpg
Is this possible within this version of OpenCart?
Any help would be much appreciated.
Cheers,
Euan

A: Step 1:
Go to catalog\view\theme\THEMEACTIVE\template\product\category.tpl
Find following line of code (in default theme there are in two places)
<?php foreach ($categories as $category) { ?>

Then add following lines of code (if in default then add on both places)
<a href="<?php echo $category['href']; ?>">
            <img src="<?php echo $category['category_image']; ?>" />

Step 2:
Go to catalog\controller\product\category.php
Find following lines of code:
$data['categories'][] = array(
                'name' => $result['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),

Add following lines of code just below it:
'category_image' =>$this->model_tool_image->resize($result['image'], 200,200),

Here 200 is the size of image, first is width and second is height. Save and it will show images
Better to make OCMOD for it. Instead of directly writing code in core file.


text:
Q: Profiling C# application without using external tools I have a C# (dotnet core) application that gets input from the queue and processes it. The processing time is determined by many factors. One of them is the request itself.
My code looks something like this:
public static void main()
{
    DoWork(new TaskInformation("abc"));
}

public static void DoWork(TaskInformation input)
{
    InnerWork1(input);
    InnerWork2(input);
}

private static void InnerWork1(TaskInformation input)
{
    // Running code here.
    Thread.Sleep(1000);
}

private static void InnerWork2(TaskInformation input)
{
    // Running code here.
    Thread.Sleep(2000);
}

In order to improve the performance of my application, I want to develop a small tool that will run and mesure execution time. If the time is above some threshold - it will do something.
So, what I want to do is "wrap" my inner functions (InnerWork1\2) with Stopwatch automatically - without doing it programmatically.
The way I'll turn on this profiling feature should be something like:
public static void main()
{
    RunWithProfiling(DoWork, new TaskInformation("abc"));
}

So, in this case the expected profiling result will be:
DoWork - took 3 seconds
    InnerWork1 - took 1 second
    InnerWork2 - took 2 second

Questions:

*

*The question is if it possible to implement a mechanism like this? Maybe with reflection?

*Is this possible to run a C# profiler from code? Something like "the code will profile itself".

A: You can use a delegate to pass your method to a RunWithProfiling method, in my example I will use Action, then measure its invoke time with Stopwatch:
private static void RunWithProfiling(Action method)
{
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();
    method.Invoke();
    stopwatch.Stop();

    Console.WriteLine($"{method.Method.Name} - took {stopwatch.Elapsed.Seconds} second(s).");

}

and usage
public static void DoWork()
{
    RunWithProfiling(InnerWork1);
    RunWithProfiling(InnerWork2);
}

You can for example return long with RunWithProfiling method, then sum results up to get whole execution time.


text:
Q: Connect to SQL Server Management Studio I'm new to this, and i don't understand how to do it, so i went through this tutorial here:
http://blogs.msdn.com/b/bethmassi/archive/2011/02/18/step-by-step-installing-sql-server-management-studio-2008-express-after-visual-studio-2010.aspx
And i installed everything i needed.
The point is when i get to the login form, i choose:
Windows Authentication
So it means i don't need to enter data. My problem is with the server name which by default is: (local).
I tried to do like this:
Go to SQL Server Configuration Manager > SQL Server Services > In Right Side window show all the servers which may stop. If you are using "SQLEXPRESS" then , Right click on SQL Server(SQLEXPRESS) and start. After try to connect server... I had same problem but I resolved by these steps.
But there was nothing under SQL Server Services. Someone please help me with this..
Thanks

A: It seems like you've only installed the client tools, so there is no local database engine to connect to. That tutorial assumed you had already installed SQL Server Express as part of Visual Studio setup.
You should uninstall the version of Management Studio you have now, IMHO. Then you need to download SQLEXPRWT_x64_ENU.exe from this link:

*

*http://www.microsoft.com/en-us/download/details.aspx?id=43351
Run the installer, and on the feature selection screen, make sure you choose Database Engine Services as well as Management Tools - Complete. On the instance configuration screen, it should be pre-selected to SQLEXPRESS. On the database engine configuration screen, you want to make sure you have mixed authentication, enter a secure password for the sa account, and add your current user to the list of administrators. These steps will help prevent you from getting locked out of the instance if you log on as a different user or you forget the sa password.
(Sorry if I am remembering those screens out of order.)


text:
Q: Ghost processes / batch processes (NA34 and NA39) 3-30-2017 Just got a call from sf tier one wanting me to show them how to replicate the issue SMH. They then point me to the dev forums and closed the case ugh

We are seeing multiple customers having issues with external systems logging transactions from Salesforce IP's during times when there are no batch processes running in salesforce.
Background

*

*Daily batch that sends records to an external system

*Batch runs without issue daily starting at 2AM

*Batch takes on average 5-10 to complete

We are seeing within the last week or so customers complaining that duplicate transactions are occurring daily
Several of these customer have been running the same version of our software for over 5 years without any issues. No org changes have occurred (not sure of a split). nothing shows up in audit trail. Same records have been sent on a routine basis to the external system (monthly/annually) without change. It just started happening out of the blue
Heuristics

*

*Duplicate timestamps are varying times (i.e. 4:23AM, 5:31AM)

*NO batch processes are running in the org at the time

*Some customers have Full Sandboxes, some do not

*Ids sent to the external system match an Id of a record in the production org

*No timestamps in that timeframe exist on the records

*Our error logging does not log anything

*No records indicating the communication took place are created

Summary
We can find nothing that is running in the orgs that would be sending the records to the external system. Given some customers do not have full sandboxes, I ruled out the possibility fo the process be ran from a sandbox by mistake. Either way, the timestamps would suggest that not be the case as well
Question

*

*Is anyone else seeing this behavior?

*Is it possible that there is a critical issue where shadow processes are being run for whatever reason by SF? Maybe an org split causing things to go haywire?

I know this is a bit broad and subjective, etc but I would really
  appreciate if anyone that may have seen something similar chime in.
  Trying to put this in as a support ticket to SF would be, well, I
  would rather get married again, poke my eye with glass, pull all my
  fingernails off, you get the point.

I have never ran into anything like this in the last 7 years working on the platform and I am at a complete loss. My only hope is to find others that have seen a similar thing occurring in the last week or so
Any suggestions on troubleshooting (other than contacting SF support) or if you have seen anything similar would be helpful.....

A: Not sure this is worthy of an answer, but too much to put as a comment. The only time I have seen anything remotely similar was with this and I was able to prove to support that a job had run and created duplicates.
The info I got back from Tier 3 at the time:

As we discussed, during the execution, an internal server error on the asynchronous process for the batch, resulted in cloned message in the asynchronous queue to not be removed resulting in duplicate messages getting worked.
As a result of unlucky timing when an exception is thrown, this may result in cloned messages not being deleted and actually executed in parallel to actual messages
A Bug has been logged to fix this issue from Salesforce end.
It is scheduled in patch release next week.

'Last week' was just over 2 years ago. I can share my case # if you wish. The case status is currently: Closed - Bug Fix Submitted
Worth noting our customer stopped using our app ~6 months after but I never saw a re-occurrence in that time. It would also have been an EUn pod.
Good luck.

A: Seems I got some attention after submitting a case or this post or whatever, just got this notification: A bit late but at least I know the cause

On March 16, 2017, Salesforce identified a misconfiguration in our
  test environment that allowed Apex callouts and outbound messages to
  reach endpoints outside of the test environment. At the same time,
  these Apex callouts and outbound messages were being executed, as
  expected, in your production environment. The simultaneous execution
  of callouts and messages from both environments may have resulted in
  duplicate or unexpected results. The issue was resolved at
  approximately 5:30 p.m. PDT on March 16, 2017. However, the fix did
  not correct the duplicate or unexpected results from Apex callouts and
  outbound messages that occurred as early as February 28 through March
  16, 2017.
We have identified that your org is associated with Apex callouts
  and/or outbound messages that executed in the testing environment
  between February 28 and March 16, 2017. However, we are unable to
  confirm if these jobs produced duplicate or unexpected results as they
  are customized to your implementation.

A: This just in from SF:

On March 16, 2017, Salesforce identified a misconfiguration in our
  test environment that allowed Apex callouts and outbound messages to
  reach endpoints outside of the test environment. At the same time,
  these Apex callouts and outbound messages were being executed, as
  expected, in your production environment. The simultaneous execution
  of callouts and messages from both environments may have resulted in
  duplicate or unexpected results. The issue was resolved at
  approximately 5:30 p.m. PDT on March 16, 2017. However, the fix did
  not correct the duplicate or unexpected results from Apex callouts and
  outbound messages that occurred as early as February 28 through March
  16, 2017.
We have identified that your org is associated with Apex callouts
  and/or outbound messages that executed in the testing environment
  between February 28 and March 16, 2017. However, we are unable to
  confirm if these jobs produced duplicate or unexpected results as they
  are customized to your implementation.

Which sounds like it could have just the results that you were seeing!

A: It seems possible these duplicate callouts may have been related to Hammer Testing. Our CSM didn't give us any dates but reached out to us proactively. Relevant communication:

Summary:
  Our internal functional testing environments, known as "hammer tests," were unexpectedly performing customer scheduled Apex job callouts to external endpoints through outbound proxies due to a configuration in our "hammer" environment.  This resulted in the processing  of some customers' Apex scheduled batch jobs that were present in the hammer test copy of production.  As part of the current hammer test run, a CRON job scheduler process was enabled, which had not been used in previous hammer tests. When the CRON job scheduler was enabled, the scheduler began processing scheduled Apex jobs that were present in the hammer environment. As these Apex jobs started getting executed, they initiated callouts to external endpoints via outbound proxies. These unexpected API callout activities caused hammer test environments and production to process the same scheduled jobs and could have resulted in duplicate or unexpected results which will need to be investigated by someone familiar with the callouts/processes on the customer side.
Preventive Actions:
  Internal hammer testing environments across all Salesforce instances were shut down to prevent any additional Apex jobs from running in the hammer test environment.  The engineering team is investigating options to provide greater isolation of the hammer test environment from external endpoints in order to prevent them from making any outbound calls in the future. Additionally, the CRON job scheduler will not be enabled in hammer test environment going forward.


text:
Q: airplayit replacement I was using Aitplayit on my iPhone and iPad and it worked perfectly.  After updating to iOS 7, it no longer works properly. After visiting their website over some time, it definitely appears its no longer supported.
I looked for replacements, and I tried a few, but none seemed to work as well as Airplayit did.
Any suggestions for a replacement?
PS I use a PC for the server

A: Use.  Streamtomeme
It is much better than airplayit and has windows server software.
http://zqueue.com/streamtome/
The app is $2.99.  But we'll worth it.   Server is free


text:
Q: spring integration + cron + quartz in cluster? I have a spring integration flow triggered by the cron expression like follows:
<int-ftp:inbound-channel-adapter id="my-input-endpoint" ...>
    <int:poller trigger="my-trigger"/>
</int-ftp:inbound-channel-adapter>

<bean id="my-trigger"
   class="org.springframework.scheduling.support.CronTrigger">
  <constructor-arg value="0 * * * * *" />
</bean>

It works fine. But now I have to extend the implementation to make it cluster ready (job execution on only one cluster node at the same point of time).
My wish would be to use the Quartz framework in the cluster mode (persisting the job status in the database) to trigger this integration flow. Quartz provides a beautful solution out of the box.  The only problem is how to integrate the Quartz with the existing inbout-channer-adaptor? The "trigger" attribute of the "poller" accepts only the subclasses of the org.springframework.scheduling.Trigger. I could not find any bridge between "poller trigger" and the Quartz framework.
many thanks in advance!

A: Here's one way...
Set the auto-startup attribute on the inbound-adapter to false.
Create a custom trigger that only fires once, immediately...
public static class FireOnceTrigger implements Trigger {

    boolean done;

    public Date nextExecutionTime(TriggerContext triggerContext) {
        if (done) {
            return null;
        }
        done = true;
        return new Date();
    }

    public void reset() {
        done = false;
    }
}

In your quartz job, get a reference to the trigger and the SourcePollingChannelAdapter.
When the quartz trigger fires, have the quartz job

*

*adapter.stop()

*trigger.reset()

*adapter.start()

A: the solution from Gary works. This my spring context:
<int-ftp:inbound-channel-adapter id="my-endpoint"
        auto-startup="false">
    <int:poller trigger="my-endpoint-trigger"/>
</int-ftp:inbound-channel-adapter>

<bean id="my-endpoint-trigger" class="com.my.FireOnceTrigger"/>

<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">

    <property name="triggers">
        <list>
            <ref bean="my-job-trigger" />
        </list>
    </property>

    <property name="schedulerContextAsMap">
        <map>
            <entry key="inputEndpoint"><ref bean="my-input-endpoint" /></entry>
            <entry key="inputEndpointTrigger"><ref bean="my-endpoint-trigger" /></entry>
        </map>
    </property>
</bean>

<bean id="my-job-trigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
    <property name="cronExpression" value="0 * * * * ?" />
    <property name="jobDetail" ref="my-job" />
</bean>

<bean name="my-job" class="org.springframework.scheduling.quartz.JobDetailBean">
    <property name="jobClass" value="com.my.MyActivatorJob " />
</bean>

and MyActivatorJob class:
public class MyActivatorJob extends QuartzJobBean implements {

private AbstractEndpoint inputEndpoint;

private FireOnceTrigger inputEndpointTrigger;

public void setInputEndpoint(final AbstractEndpoint pInputEndpoint) {
    this.inputEndpoint = pInputEndpoint;
}

public void setInputEndpointTrigger(final FireOnceTrigger pInputEndpointTrigger) {
    this.inputEndpointTrigger = pInputEndpointTrigger;
}

@Override
protected void executeInternal(final JobExecutionContext pParamJobExecutionContext)
throws JobExecutionException {

    inputEndpoint.stop();
    inputEndpointTrigger.reset();
    inputEndpoint.start();
}

}
As a next step this spring context would have to be refactored to replace the usage of schedulerContextAsMap with something more flexible and be able to define more jobs activating and deactivating many different endpoints.
Thanks Gary so far!

A: tried to integrate the quartz and spring as you proposed but faced two other problems:
1.) IncompatibleClassChangeError exception when using Quartz 2.x and Spring 3.x. It is a known problem but I did not find any solution for that.
2.) Injection of other spring bean into the Quarz job instance. I found some solutions but no one works for me. I've tried the one with using
<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    <property name="jobFactory">
        <bean class="org.springframework.scheduling.quartz.SpringBeanJobFactory" />
    </property>

    <property name="triggers">
        ...
    </property>

    <property name="schedulerContextAsMap">
        <map>
            <entry key="inputEndpoint" value-ref="my-endpoint" />
        </map>
    </property>
</bean>

to inject other beans into the job but after adding this property into the SchedulerFactoryBean the jobs is not being executed (and I dont see any exception). Removing the property "schedulerContextAsMap" out makes the job running again.

A: I haven't tried it but see that the Quartz 2 and Spring compatibility issues seem to have been fixed in Spring 3.1.1. See https://jira.springsource.org/browse/SPR-8889


text:
Q: Min value while ignoring zeros Is there another way to get the smallest values, while ignoring the 0s, out of the Instr i show in the code below? I tried to use If a couple of times in order to get the smallest value but it does not work everytime because if the first two lines (letters) are empty or equals to 0 the rest of the If will always be 0. I also tried to use Application.WorksheetFunction.Min but didn't manage to find a way in vba to include a condition to ignore the 0s.
    If carater = "d" Then
    str_f = str_f & str_var
        b = InStr(1, Mid(cel, 1, 999), "/", vbTextCompare) 'cel = (dAA11b+dAA12b)/dAA13b*100
        c = InStr(1, Mid(cel, 1, 999), "*", vbTextCompare)
        d = InStr(1, Mid(cel, 1, 999), "-", vbTextCompare)
        e = InStr(1, Mid(cel, 1, 999), "+", vbTextCompare)
        f = InStr(1, Mid(cel, 1, 999), ")", vbTextCompare)

        minimo = 0
        If b <> 0 Then
        minimo = b
        End If

        'test = Application.WorksheetFunction.Min

        If c <> 0 And c < minimo Then
        minimo = c
        End If

        If d <> 0 And d < minimo Then
        minimo = d
        End If

        If e <> 0 And e < minimo Then
        minimo = e
        End If

        If f <> 0 And f < minimo Then
        minimo = f
        End If

        'a = Mid(cel, i, minimo - 2)
        'str_f = str_f & a & str_var1
        '.Cells(567, 3).Value = str_f

    End If

A: I'm not sure what you're trying to do here, but it looks as if you're trying to find the first occurrence of a character that exists in a list. A common way of doing this is to iterate each character in your string and test if it exists within the list. As soon as you've found a match, you can exit the routine with the found index value. Code would look something like this:
Option Explicit

Public Sub RunMe()
    Dim result As Long

    result = firstOccurence(Sheet1.Range("A1"))

    If result = 0 Then
        MsgBox "No operator found."
    Else
        MsgBox "Operator found at " & result
    End If

End Sub

Private Function firstOccurence( _
    cellToTest As Range, _
    Optional oprSet As String = "/*-+)") As Long

    Dim chrSet As String, chr As String, opr As String
    Dim c As Long, o As Long

    'You should sense check the parameters here.

    ' ...

    'Test if each character of the string to be tested
    'exists in the operator list.
    'As soon as one is found, exit the function.
    chrSet = cellToTest.Value2

    For c = 1 To Len(chrSet) 'the test string
        chr = Mid(chrSet, c, 1)
        For o = 1 To Len(oprSet) 'the operator list
            opr = Mid(oprSet, o, 1)
            If chr = opr Then 'found one!
                firstOccurence = c
                Exit Function
            End If
        Next
    Next

    'Nothing found so function returns 0.

End Function


text:
Q: Creating Individual PDF Reports - Access I have an interesting requirement. In Access (2010) I need to generate individual PDF reports, in which the unique ID is in the report i.e. F9902_ReportName.pdf
The below code successfully can generate individual reports exactly how I want them to work, the only problem is it hits resource limits when running. As a result I get the following error: Run-time error '3035'. System resource exceeded. If I understand it right the DoCmd.OpenReport & DoCmd.OutputTo are both opening reports but only one is being closed in the DoCmd.Close command, the other stays hidden and holds resources and once the loop processes about 400 time it hits the resource limit. I have looked through several web pages to solve this issue but every one seems to stop at this specific issue.
The problem is I want to use the DoCmd.OutputTo function only but it does not allow me to filter on a per record basis (to my knowledge) which is why I must utilize the DoCmd.OpenReport before it.
Private Sub Command526_Click()
    Dim db As DAO.Database
    Dim rs As DAO.Recordset
    Dim MyFileName As String
    Dim mypath As String
    Dim temp As String

    mypath = "C:\location\"

    Set db = CurrentDb()
    Set rs = db.OpenRecordset("SELECT * FROM [NameOfTable]", dbOpenDynaset)

    Do While Not rs.EOF

    temp = rs("Ref#")
    MyFileName = temp & "_PdfOutput.pdf"

    DoCmd.OpenReport "ReportName", acViewReport, , "[Ref#]='" & temp & "'"
    DoCmd.OutputTo acOutputReport, "", acFormatPDF, mypath & MyFileName
    DoCmd.Close acReport, "ReportName"

    rs.MoveNext
    Loop

    Set rs = Nothing
    Set db = Nothing

End Sub

Any help is much appreciated.

A: One way is to not filter the report when opening it, but filter its recordsource by using a public function.
In a public module, you have this code:
Dim strCurRef as string

Public Function GetCurrentRef() As String
    GetCurrentRef = strCurRef
End Function

Public Sub SetCurrentRef(strRef As String)
    strCurRef = strRef
End Sub

And you create a query as recordsource for the report that filters the data by GetCurrentRef():
SELECT * FROM myTable WHERE [Ref#] = GetCurrentRef()

And before exporting your report to PDF, you set the current data:
temp = rs("Ref#")
MyFileName = temp & "_PdfOutput.pdf"
Call SetCurrentRef(temp)

DoCmd.OutputTo acOutputReport, "ReportName", acFormatPDF, mypath & MyFileName


text:
Q: Maven surefire plugin Nothing to compile - all classes are up to date When I ran  clean test or
clean test -DsuiteFile=src/main/resources/testng/SmokeTestSuite.xml in eclipse
following is the output.No test running but Build is success.
I have been struggling for this for quite a few weeks.Would be great if someone can explain me what was the issue and a proper solution.
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building eselenium-ellis-tests 0.0.1
[INFO] ------------------------------------------------------------------------
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Downloading: https://devops-tools.pearson.com/nexus-master/content/repositories/releases/com/pearson/eselenium-pageobjects-ellis/1.0.1-SNAPSHOT/maven-metadata.xml
Downloading: https://devops-tools.pearson.com/nexus-deps/content/groups/all-deps/com/pearson/eselenium-pageobjects-ellis/1.0.1-SNAPSHOT/maven-metadata.xml
Downloaded: https://devops-tools.pearson.com/nexus-deps/content/groups/all-deps/com/pearson/eselenium-pageobjects-ellis/1.0.1-SNAPSHOT/maven-metadata.xml (788 B at 0.2 KB/sec)
Downloading: https://devops-tools.pearson.com/nexus-deps/content/groups/all-deps/com/pearson/eselenium-pageobjects-ellis/1.0.1-SNAPSHOT/maven-metadata.xml
Downloading: https://devops-tools.pearson.com/nexus-master/content/repositories/releases/com/pearson/eselenium-pageobjects-ellis/1.0.1-SNAPSHOT/maven-metadata.xml
Downloaded: https://devops-tools.pearson.com/nexus-deps/content/groups/all-deps/com/pearson/eselenium-pageobjects-ellis/1.0.1-SNAPSHOT/maven-metadata.xml (788 B at 0.2 KB/sec)
[INFO]
[INFO] --- maven-clean-plugin:2.4.1:clean (default-clean) @ eselenium-ellis-tests ---
[INFO] Deleting C:\ATDD\workspace\galaxy-tests\target
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:resources (default-resources) @ eselenium-ellis-tests ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 8 resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ eselenium-ellis-tests ---
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 19 source files to C:\ATDD\workspace\galaxy-tests\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:testResources (default-testResources) @ eselenium-ellis-tests ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ eselenium-ellis-tests ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ eselenium-ellis-tests ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 21.003s
[INFO] Finished at: Sun Oct 19 09:48:48 IST 2014
[INFO] Final Memory: 20M/153M
[INFO] ------------------------------------------------------------------------

AND My POM file looks like below.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.pearson</groupId>
    <artifactId>eselenium-ellis-tests</artifactId>
    <version>0.0.1</version>
    <properties>
        <suiteXmlFile>${suiteFile}</suiteXmlFile>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.pearson</groupId>
            <artifactId>eselenium.framework</artifactId>
            <version>1.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.pearson</groupId>
            <artifactId>eselenium-pageobjects-ellis</artifactId>
            <version>1.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.5.2</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12.4</version>
                <configuration>
                    <testFailureIgnore>true</testFailureIgnore>
                    <suiteXmlFiles>
                        <suiteXmlFile>${suiteFile}</suiteXmlFile>
                        <!--<suiteXmlFile>src/main/resources/testng/SmokeTestSuite.xml</suiteXmlFile> -->
                    </suiteXmlFiles>
                    <reportsDirectory>test-output</reportsDirectory>
                    <reportsDirectory>test-output\archive\${timestamp}</reportsDirectory>
                    <systemProperties>
                        <property>
                            <name>browser.NAME</name>
                            <value>${browser.NAME}</value>
                        </property>
                    </systemProperties>
                </configuration>
            </plugin>
        </plugins>
    </build>

A: Your issue is actually not being able to provide pom.xml value from command prompt. Its a duplicate of
Passing command line arguments from Maven as properties in pom.xml
you will find solution there. You need to double quote your parameter.


text:
Q: How to force my F# application to run as administrator? For an F# application, I attempted to follow these instructions:
How to force my .NET application to run as administrator?
Alas, Visual Studio does not have the same commands and project configuration pages for F# projects as for C# projects. I have created a throwaway C# project, copied its app.manifest into my F# project, and modified the <requestedExecutionLevel> as per the issue above. Nevertheless, the .exe still runs without administrator privileges.
So then, how do I build an F# application so that it only runs as administrator?

A: C# project files (.csproj) contain the following lines:
<PropertyGroup>
  <ApplicationManifest>app.manifest</ApplicationManifest>
</PropertyGroup>

I just copied and pasted those lines into my .fsproj file just above the following line:
<Import Project="$(FSharpTargetsPath)" />

... and lo, my .exe now has the little shield badge on its icon and prompts me for elevated privileges every time I run it.


text:
Q: Vector Spaces and Subspaces of a System I am trying to make an example of a 3x5 matrix with a solution set which is a 4d hyperplane.
What I have is a 3x5 where 2 of the columns are linearly dependent. I know that if all of the columns are independent then the solution would be 5 dimensional, so does that mean if 2 are dependent, the solution will be 4 dimensions?


text:
Q: elsarticle with no reference but warnings I followed this link and these are the code I used in overleaf
In the file main.tex
\documentclass[preprint,12pt]{elsarticle}

\begin{document}
\section{Introduction}

Several researchers studied ruin probability, but for a survey
see\cite{AsmussenandAlbrecher2010}. For bulk arrival queues see
\cite{ChaudhryandTempleton1983}

\nocite{*}

\section{\refname}
\bibliography{mybib}

\end{document}

In the file mybib.bib (in the same folder)
@BOOK{AsmussenandAlbrecher2010,
  author  = {Asmussen, S. and Albrecher, H.},
  title   = {Ruin probabilities},
  edition = {2nd ed.},
  address = {Singapore},
  publisher = {World Scientific},
  year    = {2010}
}

@ARTICLE{Botta1987,
  author  = {Botta, R. F. and Harris, C. M. and Marchal, W. G.},
  title   = {Characterisation of generalised hyperexponential distribution functions},
  journal = {Stochastic Models},
  volume  = {3},
  year    = {1987},
  pages   = {115-148}
}

@BOOK{ChaudhryandTempleton1983,
  author  = {Chaudhry, M. L. and Templeton, J. G. C.},
  title   = {A First Course in Bulk Queues},
  address = {New York},
  publisher = {Wiley},
  year    = {1983}
}

Afer I run it, I got this

with warnings


text:
Q: How do I implement ChangeTime and ChangeUser columns using NHibernate? I'm trying to use NHibernate with an existing database. In the data-model there is columns in each table that contains the time and username of the last update made to a row. How do I do this using NHibernate?
I tried to implement a interceptor that sets ChangeTime and ChangeUser in the entities before it gets saved using the IInterceptor.OnSave method. This didn't work because setting these properties triggers an update to the row even if no other properties has been modified.
It could have worked if there was any way to tell NHibernate to exclude the ChangeTime and ChangeUser properties then it does it's dirty-checking. But i haven't found any way to accomplish this.
Thanks for any help.

A: Hey I just had to solve this on a project I am working on, here is my answer
public interface IDateModified
{
    DateTime Created { get; set; }
    DateTime Modified { get; set; }
}

public class CustomDefaultSaveOrUpdateEventListener
    : DefaultSaveOrUpdateEventListener
{
    protected override object EntityIsPersistent(SaveOrUpdateEvent evt)
    {
        var entity = evt.Entity as IDateModified;
        if (entity != null)
        {
                entity.Modified = DateTime.Now;
        }

        return base.EntityIsPersistent(evt);
    }

    protected override object EntityIsTransient(SaveOrUpdateEvent evt)
    {
        var entity = evt.Entity as IDateModified;
        if (entity != null)
        {
            entity.Created = entity.Modified = DateTime.Now;
        }

        return base.EntityIsTransient(evt);
    }
}

Then in my configuration (I am using Fluent NHibernate to configure my unit tests in code)
configuration.EventListeners.SaveOrUpdateEventListeners
= new ISaveOrUpdateEventListener[]
{
    new CustomDefaultSaveOrUpdateEventListener()
};

AWESOMENESSSSSSSS!

A: You should register a listener to the pre insert and pre update events. You can do it through your configuration like so:
<hibernate-configuration>
    ...
    <event type="pre-update">
        <listener class="MyListener, MyAssembly"/>
    </event>
    <event type="pre-insert">
        <listener class="MyListener, MyAssembly"/>
    </event>
</hibernate-configuration>

and then implement a listener - something like this (might not be entirely accurate - written off my memory):
public class MyListener : IPreUpdateEventListener, IPreInsertEventListener
{
    public bool OnPreUpdate(PreUpdateEvent evt)
    {
        if (evt.Entity is IHasLastModified)
            UpdateLastModified(evt.State, evt.Persister.PropertyNames);

        return false;
    }

    public bool OnPreInsert(PreInsertEvent evt)
    {
        if (evt.Entity is IHasLastModified)
            UpdateLastModified(evt.State, evt.Persister.PropertyNames);

        return false;
    }

    void UpdateLastModified(object[] state, string[] names)
    {
        var index = Array.FindIndex(names, n => n == "LastModified");

        state[index] = DateTime.Now;
    }
}

and do the same thing with the pre update event.
EDIT: This one takes care of insert as well as update and it seems to work.

A: Mookid's answer is correct although I would like to point out that if one is using S#arp Architecture, the NHib configuration should be set up as follows:
<hibernate-configuration>
    <session-factory>
    ...
        <event type="pre-update">
            <listener class="MyListener, MyAssembly"/>
        </event>
        <event type="pre-insert">
            <listener class="MyListener, MyAssembly"/>
        </event>
    </session-factory>
</hibernate-configuration>

The event elements go into the session-factory element.

A: Instead of using LIsteners, you can also use Interceptors:
Audit changes using interceptor


text:
Q: How to manually generate R.java My project (made in Delphi) need to manually generate for each package it's include the R.java file manually. Actually I put all resources of each library in a single .res directory and I run aapt.exe on this directory for each package like this for android.support.compat:
"aapt.exe" package -v -f -m
  -M "\libraries\android.support.compat\AndroidManifest.xml"
  -I "C:\SDKs\android\platforms\android-32\android.jar"
  -S ".\res"
  -J ".\tmp\src"
  --auto-add-overlay
  --output-text-symbols .\tmp\

and this for each package ex for android.support.coreui
"aapt.exe" package -v -f -m
  -M "\libraries\android.support.coreui\AndroidManifest.xml"
  -I "C:\SDKs\android\platforms\android-32\android.jar"
  -S ".\res"
  -J ".\tmp\src"
  --auto-add-overlay
  --output-text-symbols .\tmp\

The problem is that at the end I have for each package the same R.java that is quite big because it's include all resources ids of the whole App. ex :
package androidx.core;

public final class R {
   public static final class styleable {
      public static final int[] ActionBar = new int[]{2130771969, 2130771971, 2130771972, 2130771973, 2130771974, 2130771975, 2130771976, 2130771977, 2130771978, 2130771979, 2130771980, 2130771981, 2130771982, 2130771983, 2130771984, 2130771985, 2130771986, 2130771987, 2130771988, 2130771989, 2130771990, 2130771991, 2130771992, 2130771993, 2130771994, 2130771995, 2130771996, 2130771997, 2130772082};
      public static final int ActionBar_background = 10;
      public static final int ActionBar_backgroundSplit = 12;
....

and
package android.support.coreui;

public final class R {
   public static final class styleable {
      public static final int[] ActionBar = new int[]{2130771969, 2130771971, 2130771972, 2130771973, 2130771974, 2130771975, 2130771976, 2130771977, 2130771978, 2130771979, 2130771980, 2130771981, 2130771982, 2130771983, 2130771984, 2130771985, 2130771986, 2130771987, 2130771988, 2130771989, 2130771990, 2130771991, 2130771992, 2130771993, 2130771994, 2130771995, 2130771996, 2130771997, 2130772082};
      public static final int ActionBar_background = 10;
      public static final int ActionBar_backgroundSplit = 12;

Is there a way to generate for each package a R.java with only the resource ids need by the package?


text:
Q: Looping through array of objects, output created elements to html with javascript I have created a constructor function and a few objects that are pushed into an array.
From here I need to call a function on these objects in an array which outputs to a basic html front end.  I have created the constructor function and have it all mostly working, however I keep getting an error in dev tools stating my this.render() method shown below is not a function.
I can get this working when I try to just console.log the objects in the array (with a loop), but cannot get past this error of not being able to use render() method. Any help would be appreciated. Code below. Note that the end goal is to have the rendered info appended to a div with id of "output". Thank you

function ArtistType(name, genre, albums) {
    this.name = name;
    this.genre = genre;
    this.albums = albums;
    this.publishAlbum = function () {
        this.albums++;
    };
    this.render = function () {

        const artistName = document.createElement("h2");
        artistName.innerText = this.name;
        const genre = document.createElement("div");
        genre.innerText = this.genre;
        const albums = document.createElement("div");
        albums.innerText = this.albums;
        document.getElementById("output").appendChild(artistName, genre, albums)

    };

}

let artists = [];
const artist1 = new ArtistType("Black Sabbath", "metal", 0)
const artist2 = new ArtistType("Huey Lewis and the News", "rock", 0)
const artist3 = new ArtistType("Beastie Boys", "hip hop", 0)
artists.push(artist1, artist2, artist3);
artist1.publishAlbum();
//below some of what I have tried...
//artists.forEach(this.render())
//have also tried for...in loop and others...example:
//for (var i = 0; i < artists.length; i++) {
  //  this.render();

}

    <title>Test</title>

Name will go here

A: You have to refer to a particular object in order to use its function render().  Something like this:

function ArtistType(name, genre, albums) {
    this.name = name;
    this.genre = genre;
    this.albums = albums;
    this.publishAlbum = function () {
        this.albums++;
    };
    this.render = function () {

        const artistName = document.createElement("h2");
        artistName.innerText = this.name;
        const genre = document.createElement("div");
        genre.innerText = this.genre;
        const albums = document.createElement("div");
        albums.innerText = this.albums;
        document.getElementById("output").appendChild(artistName, genre, albums)

    };

}

let artists = [];
const artist1 = new ArtistType("Black Sabbath", "metal", 0)
const artist2 = new ArtistType("Huey Lewis and the News", "rock", 0)
const artist3 = new ArtistType("Beastie Boys", "hip hop", 0)
artists.push(artist1, artist2, artist3);
artist1.publishAlbum();
//below some of what I have tried...
//artists.forEach(this.render())
//have also tried for...in loop and others...example:
for (var i = 0; i < artists.length; i++) {
    artists[i].render();

}

A: this only exists inside the function, you can't just magically use it outside of it
Try this:
artists.forEach(artist => artist.render())

or
for (const artist of artists) {
  artist.render()
}

A: When accessing an array in a for loop, you should use bracked annotation and an index - artists[i].render();. In my example I actually used forEach to show you another way of looping. You can reference this documentation to know more about forEach.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Unless you need to support old browsers, you could consider using classes. Classes help simplify the code a bit as well and can help make it easier to access objects. More in line with other object oriented languages.
Finally, note that I am using append instead of appendChild. append lets you pass in multiple nodes and appends them all. It does not however support IE. appendChild will only append the first node you pass in.

class Artist {
  constructor(name, genre, albums) {
    this.name = name;
    this.genre = genre;
    this.albums = albums;
  }

  publishAlbum() {
    this.albums++;
  }
  render() {
    const artistName = document.createElement("h2");
    artistName.innerText = this.name;
    const genre = document.createElement("div");
    genre.innerText = this.genre;
    const albums = document.createElement("div");
    albums.innerText = this.albums;
    document.getElementById("output").append(artistName, genre, albums)
  }
}

let artists = [new Artist("Black Sabbath", "metal", 0),
  new Artist("Huey Lewis and the News", "rock", 0),
  new Artist("Beastie Boys", "hip hop", 0)
];
artists[0].publishAlbum();
artists.forEach(function(artist) {
  artist.render();
});

A: You can do:

function ArtistType(name, genre, albums) {
  this.name = name
  this.genre = genre
  this.albums = albums
  this.publishAlbum = function (event) {
    // Logic to publish album
    console.log('event', event.target)
    this.albums++
  }
  this.render = function () {
    const wrapper = document.createElement('div')

    const name = document.createElement('h2')
    name.innerHTML = this.name

    const genreP = document.createElement('p')
    genreP.innerHTML = `Genre: ${this.genre.toUpperCase()}`

    const albumsP = document.createElement('p')
    albumsP.innerHTML = `Albums: ${this.albums}`
    albumsP.addEventListener('click', this.publishAlbum)

    const elems = [name, genreP, albumsP]
    elems.forEach(el => wrapper.appendChild(el))

    document
      .getElementById('output')
      .appendChild(wrapper)
  }
}

const data = [{name: 'Black Sabbath',genre: 'metal',albums: 0,},{name: 'Huey Lewis and the News',genre: 'rock',albums: 0,},{name: 'Beastie Boys',genre: 'hip hop',albums: 0,},]

data.forEach(({ name, genre, albums }) => {
  const artist = new ArtistType(name, genre, albums)
  artist.render()
})


text:
Q: How Can I Get Thumbnails For Picasa Images Selected From The Gallery? I'm working on an application where the user is able to select files, either a new image from the camera, an image from the gallery, or a plain old file. It then shows an icon and the name for the selected item.  I have this working with one exception. The gallery application integrates picasaweb pictures. If the user selects a picture from a picasa album, I'm not able to get a thumbnail for it.
I'm using the MediaStore.Images.Thumbnails.getThumbnail() method, and it works for other images in the gallery just fine, but for the picasaweb files, I get, regardless of what "kind" of thumbnail I attempt to get (although MICRO is what I'm after):

ERROR/MiniThumbFile(2051): Got exception when reading magic, id =
  5634890756050069570, disk full or mount read-only? class
  java.lang.IllegalArgumentException

I noticed the URI's given for the selected files are different. The local image files look like:

content://media/external/images/media/6912

and the picasaweb urls look like:

content://com.android.gallery3d.provider/picasa/item/5634890756050069570

I attempted to use a query to get at the raw THUMB_DATA, using Thumbnails.queryMiniThumbnails(), with Thumbnails.THUMB_DATA in the projection array, but I got a "no such column" error.
Is there another method for getting thumbnails that would work better? And will I have the same problem when I try and access the full image data?

A: What I have found is that on my Galaxy Nexus, the images for Picassa are stored in one of subdirectories under the /sdcard/Android/data/com.google.android.apps.plus/cache directory. When the content provider is com.google.android.gallery3d.provider then the number after "item" in the URL contains the name of the image (in your example above "5634890756050069570"). This data correspondes to a file in one of the subdirectories under /sdcard/Android/data/com.google.android.apps.plus/cache with the extension ".screen". If you were to copy this image from your phone (in your case 5634890756050069570.screen) using DDMS and rename it with the extension ".jpeg" you could open it and view it on your computer.
The following onActivityResult method will check for this content provider being returned, and then will recursively search for the file in the /sdcard/Android/data/com.google.android.apps.plus/cache directory. The private member variable fileSearchPathResults is filled in by the recursive search method walkDirectoryRecursivelySearchingForFile().
private String fileSearchPathResult = null;

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            String filePath = null;

            // This code is required to get the image path on content providers
            // on API > 10 where the image is from a picassa web album, since Google changed
            // the content provider in versions with API > 10
            if (selectedImage.toString().contains("com.google.android.gallery3d.provider")) {
                StringBuilder contentProviderPath = new StringBuilder(selectedImage.toString());
                int beginningIndex = contentProviderPath.lastIndexOf("/");
                String fileNameWithoutExt = contentProviderPath.subSequence(beginningIndex + 1,
                        contentProviderPath.length()).toString();
                Log.i(TAG, fileNameWithoutExt);
                try {
                    File path = new File("/sdcard/Android/data/com.google.android.apps.plus/cache");
                    if (path.exists() && path.isDirectory()) {
                        fileSearchPathResult = null;
                        walkDirectoryRecursivelySearchingForFile(fileNameWithoutExt, path);
                        if (fileSearchPathResult != null) {
                            filePath = fileSearchPathResult;
                        }
                    }
                } catch (Exception e) {
                    Log.i(TAG, "Picassa gallery content provider directory not found.");
                }
            }
    }

    public void walkDirectoryRecursivelySearchingForFile(String fileName, File dir) {
        String pattern = fileName;

        File listFile[] = dir.listFiles();
        if (listFile != null) {
            for (int i = 0; i < listFile.length; i++) {
                if (listFile[i].isDirectory()) {
                    walkDirectoryRecursivelySearchingForFile(fileName, listFile[i]);
                } else {
                    if (listFile[i].getName().contains(pattern)) {
                        fileSearchPathResult = listFile[i].getPath();
                    }
                }
            }
        }
    }

With the filePath, you can create a Bitmap of the image with the following code:
        Bitmap sourceImageBitmap = BitmapFactory.decodeFile(filePath);

A: ACTIVITYRESULT_CHOOSEPICTURE is the int you use when calling startActivity(intent, requestCode);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if(requestCode == ACTIVITYRESULT_CHOOSEPICTURE) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 4;
    final InputStream is = context.getContentResolver().openInputStream(intent.getData());
    final Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
    is.close();
  }
}

That code will load the whole image. You can adjust the sample size to something reasonable to get a thumbnail sized image.


text:
Q: How to create tornado streaming server? I need to create a server which sends the incoming data to the client side. Data is as network packets and depending on the token in this packet I have to send it to all the clients who are subscribed to that token. I am using tornado server to do this. So my questions are

*

*Shall I have a single IO loop to handle incoming data and sending it to clients? What if I use multiple IO loops?

*What if I use multiprocess? One process send data to clients and one to handle incoming data.

What will be the performance issues with both?