text:
Q: 'WSGIRequest' object has no attribute 'current_app' in my AdminSite (Django Suit 0.2.14 + Django 1.7.8), I use an action to activate a process on the item selected.
admin.py
class DealAdminBase(AdminVideoMixin, admin.ModelAdmin):

  form = DealAdminForm

  actions = [
    'action_add_session',
  ]
  ...

  def get_urls(self):
    from django.conf.urls import patterns, url
    original_urls = super(DealAdminBase, self).get_urls()

    info = self.model._meta.app_label, self.model._meta.model_name

    my_urls = patterns('',
        url(r'^stats/$', self.admin_site.admin_view(self.view_stats), name='stats'),
        url(r'^add_session/(?P<deal_pk>\d+)/$', self.admin_site.admin_view(self.view_add_session), name='%s_%s_add_session' % info),
    )
    return my_urls + original_urls

  def action_add_session(self, request, queryset):
    if len(queryset) > 1:
        self.message_user(request, 'Select only one.')
        return

    info = self.model._meta.app_label, self.model._meta.model_name
    deal_pk = queryset[0].pk

    return HttpResponseRedirect(reverse('admin:%s_%s_add_session' % info, args=[deal_pk,]))

  def view_add_session(self, request, deal_pk):
     deal = get_object_or_404(self.model, pk=deal_pk)
     has_session = bool(deal.active_session)

     def _make_add_session_form(_session):
        fields = {
            'number': forms.IntegerField(min_value=1),
        }
        if not _session:
            fields['first_start'] = forms.DateTimeField(widget=SuitSplitDateTimeWidget)

        return type('AddSessionForm', (forms.BaseForm,), { 'base_fields': fields })

    form = _make_add_session_form(has_session)(request.POST or None)

    if form.is_valid():
        deal.numero_totale += form.cleaned_data['number']
        deal.numero_rimanente += form.cleaned_data['number']
        deal.save()

        if not has_session:
            deal.create_session(form.cleaned_data['first_start'])

        info = self.model._meta.app_label, self.model._meta.model_name
        return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % info))

    return render_to_response(
        'admin/deal/add_session.html', {
            'form': form,
        }, RequestContext(request))

When I select the item in the /admin and apply the action "action_add_session" I get the following error
 Request Method:    GET
 Request URL:      http://192.168.33.10:8000/admin/deal/dealgroup/add_session/19/
 Django Version:    1.7.8
 Exception Type:    AttributeError
 Exception Value:
 'WSGIRequest' object has no attribute 'current_app'
 Exception Location:    /vagrant/.virtualenv/local/lib/python2.7/site-ackages/suit/templatetags/suit_menu.py in get_menu, line 33

Error during template rendering

In template /vagrant/.virtualenv/local/lib/python2.7/site- packages/suit/templates/suit/menu.html, error at line 15
'WSGIRequest' object has no attribute 'current_app'
 5

 6

 7      {% block menu_home %}
 8        {% url 'admin:index' as index_url %}
 9

10          {% trans   'Home' %}
11
12

13      {% endblock %}
14
15      **{% get_menu request as app_list %}**

I'm wondering if this error could be django suit related or if I'm not seeing the obvious.
Thank you in advance for any help.
EDIT
Code for get_menu in /lib/python2.7/site-packages/suit/templatetags/suit_menu.py
@register.assignment_tag(takes_context=True)
def get_menu(context, request):
  """
  :type request: WSGIRequest
  """
 if not isinstance(request, WSGIRequest):
    return None

 # Try to get app list
 try:
    template_response = get_admin_site(context.current_app).index(request)
except NoReverseMatch:
    # Django 1.8 uses request.current_app instead of context.current_app
    template_response = get_admin_site(request.current_app).index(request)

try:
    app_list = template_response.context_data['app_list']
except Exception:
    return

return Menu(context, request, app_list).get_app_list()

I see that suit calls current_app, how can I solve it? Sorry, but I'm almost a newby in Django

A: You should set request.current_app yourself.


text:
Q: Is there a faster way (than this) to calculate the hash of a file (using hashlib) in Python? My current approach is this:
def get_hash(path=PATH, hash_type='md5'):
    func = getattr(hashlib, hash_type)()
    with open(path, 'rb') as f:
         for block in iter(lambda: f.read(1024*func.block_size, b''):
             func.update(block)
    return func.hexdigest()

It takes about 3.5 seconds to calculate the md5sum of a 842MB iso file on an i5 @ 1.7 GHz. I have tried different methods of reading the file, but all of them yield slower results. Is there, perhaps, a faster solution?
EDIT: I replaced 2**16 (inside the f.read()) with 1024*func.block_size, since the default block_size for most hashing functions supported by hashlib is 64 (except for 'sha384' and 'sha512' - for them, the default block_size is 128). Therefore, the block size is still the same (65536 bits).
EDIT(2): I did something wrong. It takes 8.4 seconds instead of 3.5. :(
EDIT(3): Apparently Windows was using the disk at +80% when I ran the function again. It really takes 3.5 seconds. Phew.
Another solution (~-0.5 sec, slightly faster) is to use os.open():
def get_hash(path=PATH, hash_type='md5'):
    func = getattr(hashlib, hash_type)()
    f = os.open(path, (os.O_RDWR | os.O_BINARY))
    for block in iter(lambda: os.read(f, 2048*func.block_size), b''):
        func.update(block)
    os.close(f)
    return func.hexdigest()

Note that these results are not final.

A: Using an 874 MiB random data file which required 2 seconds with the md5 openssl tool I was able to improve speed as follows.

*

*Using your first method required 21 seconds.

*Reading the entire file (21 seconds) to buffer and then updating required 2 seconds.

*Using the following function with a buffer size of 8096 required 17 seconds.

*Using the following function with a buffer size of 32767 required 11 seconds.

*Using the following function with a buffer size of 65536 required 8 seconds.

*Using the following function with a buffer size of 131072 required 8 seconds.

*Using the following function with a buffer size of 1048576 required 12 seconds.

def md5_speedcheck(path, size):
    pts = time.process_time()
    ats = time.time()
    m = hashlib.md5()
    with open(path, 'rb') as f:
        b = f.read(size)
        while len(b) > 0:
            m.update(b)
            b = f.read(size)
    print("{0:.3f} s".format(time.process_time() - pts))
    print("{0:.3f} s".format(time.time() - ats))

Human time is what I noted above. Whereas processor time for all of these is about the same with the difference being taken in IO blocking.
The key determinant here is to have a buffer size that is big enough to mitigate disk latency, but small enough to avoid VM page swaps. For my particular machine it appears that 64 KiB is about optimal.

redpajama_set_name: RedPajamaStackExchange


text:
Q: php artisan serve not working, error ""In ProviderRepository.php line 208: Class 'Intervention\Image\ImageServiceProvider' not found"" when I run php artisan serve it gives the following error.
"In ProviderRepository.php line 208:
Class 'Intervention\Image\ImageServiceProvider' not found"
Tried to run composer install but it gives the same error


text:
Q: Getting Distinct records for a day but counting them multiple times for date range I am working on a query where i am searching for order numbers. I need to filter the order numbers unique for the day. For that i used count(distinct order_number) in my main query. This query takes start and end date from the front end and uses them. However i have a catch, if there is same order_number for 2 days in the range it will be counted for both of the days. i.e.
Counting the number of unique orders for a day. Initially i thought to use some loop over dates and sum the results, but that does not looks right to me. I would be more interested to use the same query and modify it for distinct orders based on date. Here is my query :
SELECT 'site1' AS site,
  DATE_FORMAT(l.login_time, '%m/%d/%Y') AS DATE,
  COUNT(DISTINCT osh.order_num) AS total_orders
FROM order_history o
INNER JOIN logs l ON o.userID = l.id
WHERE o.date_time BETWEEN 1380524400 AND 1380610799
  AND l.LOGIN BETWEEN FROM_UNIXTIME(1380524400) AND FROM_UNIXTIME(1380610799)
GROUP BY DATE

Example
Suppose for date 29Aug, i have orders o1,o2,o1,o3,o2 i will count them as 3 distinct orders i.e. o1,o2,03
for 30 Aug, i have orders o1, o4, o4, o1 i will count them as 2 distinct orders i.e. o1, o4
but when i query for 29-30 aug i must get count of 3+2 = 5 i.e. o1 is counted twice in the range sicne it belongs to two diff dates.

A: I think in this case the WITH ROLLUP modifier might server your purpose
SELECT 'site1' AS site,
  DATE_FORMAT(l.login_time, '%m/%d/%Y') AS `DATE`,
  COUNT(DISTINCT osh.order_num) AS total_orders
FROM order_history o
INNER JOIN logs l ON o.userID = l.id
WHERE o.date_time BETWEEN 1380524400 AND 1380610799
  AND l.LOGIN BETWEEN FROM_UNIXTIME(1380524400) AND FROM_UNIXTIME(1380610799)
GROUP BY `DATE` WITH ROLLUP

This would add an extra row at the end of your data that would sum the total_orders data (with a NULL value for DATE)
Here is documentation on this modifier: http://dev.mysql.com/doc/refman/5.5/en/group-by-modifiers.html


text:
Q: Calling a stored procedure from global.asax file Hello I had developed the below code to save the dataset in Global.asax file. To consume that in webpage.aspx.vb file, now it is working fine.
In the similar way, how could I call the stored procedure in Global.asax?
Please help, Thank You in Advance!
Shared _cache As Cache = Nothing

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    _cache = Context.Cache
    RefreshCache(Nothing, Nothing, 0)
End Sub

Private Shared Sub RefreshCache(ByVal key As String, ByVal item As Object, ByVal reason As CacheItemRemovedReason)
    Dim adapter As New SqlDataAdapter("SELECT * FROM dbo.table where logid = 1", "server=server;database=database;uid=userid;pwd=password")

    Dim ds As New DataSet()
    adapter.Fill(ds, "Quotations")

    Dim onRemove As CacheItemRemovedCallback

    onRemove = New CacheItemRemovedCallback(AddressOf RefreshCache)

    _cache.Insert("Quotes", ds, New CacheDependency("C:\AspNetSql\Quotes.Quotations"), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.[Default], onRemove)
End Sub

A: Got the solution with below code.
<%@ Application Language="VB" %>
<%@ Import Namespace="System.DirectoryServices.AccountManagement" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.Common" %>
<%@ Import Namespace="System.Runtime.Remoting.Contexts" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.Caching" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Web.Caching.Cache" %>

<script RunAt="server">

    Shared _cache As Cache = Nothing
    Protected Shared db As Database

    Private cnPubs As SqlConnection
    Private daPubs As SqlDataAdapter
    Private cmdSelPubInfo As SqlCommand

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)

        _cache = Context.Cache
        RefreshCache(Nothing, Nothing, 0)
    End Sub

    Public Sub New(ByVal databaseName As String)
        db = New Database(databaseName)
    End Sub

    Private Sub RefreshCache(ByVal key As String, ByVal item As Object, ByVal reason As CacheItemRemovedReason)

        cnPubs = New SqlConnection("server=Servername;database=databasename;uid=userid;pwd=password")
        'select command
        cmdSelPubInfo = New SqlCommand
        cmdSelPubInfo.Connection = cnPubs
        cmdSelPubInfo.CommandType = CommandType.StoredProcedure
        cmdSelPubInfo.CommandText = "storedprocedurename"

        cmdSelPubInfo.Parameters.Add(New SqlParameter("@pStartDate", "01/01/2011"))
        cmdSelPubInfo.Parameters.Add(New SqlParameter("@pEndDate", "01/01/2012"))
        cmdSelPubInfo.Parameters.Add(New SqlParameter("@pErrorMessage", ""))

        'DataApapter
        daPubs = New SqlDataAdapter
        daPubs.SelectCommand = cmdSelPubInfo
        Dim dsPubs = New DataSet

        'Dim ds As New DataSet()
        daPubs.Fill(dsPubs)

        Dim onRemove As CacheItemRemovedCallback

        onRemove = New CacheItemRemovedCallback(AddressOf RefreshCache)

        '' Add the DataSet to the application cache.
        _cache.Insert("Quotes", dsPubs, New CacheDependency("C:\AspNetSql\Quotes.Quotations"), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.[Default], onRemove)
    End Sub
</script>


text:
Q: Send data with putExtra and getExtra I have a question about send data between two activity files. Below code is a part of pdf viewer application.
Main Activity
private void init() {
    lv_pdf = (ListView)findViewById(R.id.lv_pdf);
    dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
    fn_permission();

    lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent = new Intent(MainActivity.this, PdfActivity.class);
            intent.putExtra("position", i);
            startActivity(intent);
            Log.e("Position", i + "");
        }
    });
}

onItemClick() method sends data from main activity to second activity(PdfActivity.java) with putExtra.('position' is a index of pdf files)
Second Activity
private void init() {
    pdfView = (PDFView)findViewById(R.id.pdfView);
    position = getIntent().getIntExtra("position", 0);

    File pdfFile = new File(Environment.getExternalStorageDirectory(),"PdfFile.pdf");

    if (pdfFile.exists()) {
        Uri path = Uri.fromFile(pdfFile);
        Intent objIntent = new Intent(Intent.ACTION_VIEW);
        objIntent.setDataAndType(path, "application/pdf");
        objIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(objIntent);
    }

    displayFromSdcard();
}

private void displayFromSdcard() {
    pdfFileName = MainActivity.fileList.get(position).getName();

    pdfView.fromFile(MainActivity.fileList.get(position))
            .defaultPage(pageNumber)
            .enableSwipe(true)
            .swipeHorizontal(false)
            .onPageChange(this)
            .enableAnnotationRendering(true)
            .onLoad(this)
            .scrollHandle(new DefaultScrollHandle(this))
            .load();
}

In second activity, 'position' gets data with getintExtra() method and default value is 0. position variable is used for rendering pdf files.
Problem:
'Default value 0' is the first index number. It means the last saved file on the SD card. But if I clicked a pdf file in app chooser, no matter which file is clicked, the last saved file is always opened.
How do I change default value to open the pdf file that I clicked?
Following code is manifest.xml file about second activity file.
<activity
    android:name=".PdfActivity"
    android:screenOrientation="portrait"
    android:parentActivityName=".MainActivity">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.pdffilefromsdcard.MainActivity" />
    <intent-filter >
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="application/pdf" />
    </intent-filter>
</activity>

What I've tried:
I made an additional variable positionStr that data type is string and put it into file path, but application was stopped suddenly when I launched it.

A: You are not using the position variable anywhere in your code. The code line
File pdfFile = new File(Environment.getExternalStorageDirectory(),"PdfFile.pdf");
always gets the same pdf file, therefore you should appropriately pass the position parameter to this line to open the desired file.


text:
Q: Calling javascript Function from HTML with multiple parameters I'm trying to call a javascript function called confirmRemove(title, id) to remove an element from a table. This function should be called when the user clicks on a link that looks like an "X". I attached my code below to show how I went about doing this, but I'm seeming to be having some errors and I'm not sure why. Most of the elements are able to be removed, but for a few when I click the link to call the function, nothing happens. Is there a better way of doing this? Not sure why this would happen.
<?php echo 'X';?>

A: You can try this code
 <a onclick="confirmRemove('<?php echo $title; ?>','<?php echo $id; ?>')"
   href="javascript:void(0)">X

A: You asked if there is a better way of doing this - I would suggest that there is and that it is to use  an externally registered event handler bound to the specific HTML elements in question - notably a hyperlink in this example.
If you assign relevant attributes to the hyperlink ( dataset attributes are very useful for this sort of task ) you can process them within your event listener very easily. There is not need for complicated escaping for quotes by adopting this approach and best of all you can separate HTML from Javascript - the event handlers can be in another file

    <a class='removal' href='javascript:void(0)' data-title="<?php echo $title;>" data-id="<?php echo $id;?>">X


text:
Q: How to save an Excel worksheet as CSV I want to write a Python script that reads in an Excel spreadsheet and saves some of its worksheets as CSV files.
How can I do this?
I have found third-party modules for reading and writing Excel files from Python, but as far as I can tell, they can only save files in Excel (i.e. *.xls) format.  If I'm wrong here, some example code showing how to do what I'm trying to do with these modules would be appreciated.
I also came across one solution that I can't quite understand, but seems to be Windows-specific, and therefore would not help me anyway, since I want to do this in Unix.  At any rate, it's not clear to me that this solution can be extended to do what I want to do, even under Windows.

A: The most basic examples using the two libraries described line by line:

*

*Open the xls workbook

*Reference the first spreadsheet

*Open in binary write the target csv file

*Create the default csv writer object

*Loop over all the rows of the first spreadsheet

*Dump the rows into the csv

import xlrd
import csv

with xlrd.open_workbook('a_file.xls') as wb:
    sh = wb.sheet_by_index(0)  # or wb.sheet_by_name('name_of_the_sheet_here')
    with open('a_file.csv', 'wb') as f:   # open('a_file.csv', 'w', newline="") for python 3
        c = csv.writer(f)
        for r in range(sh.nrows):
            c.writerow(sh.row_values(r))

import openpyxl
import csv

wb = openpyxl.load_workbook('test.xlsx')
sh = wb.active
with open('test.csv', 'wb') as f:  # open('test.csv', 'w', newline="") for python 3
    c = csv.writer(f)
    for r in sh.rows:
        c.writerow([cell.value for cell in r])

A: Use the xlrd  or openpyxlmodule to read xls or xlsx documents respectively, and the csv module to write.
Alternately, if using Jython, you can use the Apache POI library to read either .xls or .xlsx, and the native CSV module will still be available.

A: Using pandas will be a bit shorter:
import pandas as pd

df = pd.read_excel('my_file', sheetname='my_sheet_name')  # sheetname is optional
df.to_csv('output_file_name', index=False)  # index=False prevents pandas to write row index

# oneliner
pd.read_excel('my_file', sheetname='my_sheet_name').to_csv('output_file_name', index=False)

A: As of December 2021 and Python 3:
The openpyxl API has changed sufficiently (see https://openpyxl.readthedocs.io/en/stable/usage.html) that I have updated this part of the answer by @Boud (now @Zeugma?), as follows:
import openpyxl
import csv

wb = openpyxl.load_workbook('test.xlsx')
sh = wb.active # was .get_active_sheet()
with open('test.csv', 'w', newline="") as file_handle:
    csv_writer = csv.writer(file_handle)
    for row in sh.iter_rows(): # generator; was sh.rows
        csv_writer.writerow([cell.value for cell in row])

@Leonid made some helpful comments - in particular:
csv.writer provides some additional options e.g. custom delimiter:
csv_writer = csv.writer(fout, delimiter='|', quotechar='"', quoting=csv.QUOTE_MINIMAL)

HTH

A: First read your Excel spreadsheet into Pandas. The code below will import your Excel spreadsheet into Pandas as an OrderedDict which contains all of your worksheets as DataFrames. Then, simply use the worksheet_name as a key to access specific worksheet as a DataFrame and save only the required worksheet as a csv file by using df.to_csv(). Hope this will work in your case.
import pandas as pd
df = pd.read_excel('YourExcel.xlsx', sheet_name=None)
df['worksheet_name'].to_csv('output.csv')


text:
Q: Magento 1.9.4.0 DivisionByZeroError (PHP fatal error) when accessing Connect Manager I'm getting a PHP fatal error when accessing Connect Manager in Magento 1.9.4.0.
I've updated to php 7.2 on Ubuntu with Nginx. The files and folders have nginx user as owner and the file permissions are correct.
Everything else seems to work ok, but just can't access the Connect Manager. If I put Magento in developper mode I still get no errors, just the 500 error from the server.
Here's the error:
FastCGI sent in stderr: "PHP message: PHP Fatal error:  Uncaught DivisionByZeroError: Modulo by zero in /path/to/magento/downloader/Maged/BruteForce/Validator.php:59

Stack trace:

0 /path/to/magento/downloader/Maged/Controller.php(844): Maged_BruteForce_Validator->isCanLogin()
1 /path/to/magento/downloader/Maged/Controller.php(518): Maged_Controller->dispatch()
2 /path/to/magento/downloader/index.php(36): Maged_Controller::run()
3 {main}

Any ideas how to fix this?

A: In case somebody else has this error.
Just delete the bruteforce.ini in the var folder. I at first only modified the file, not remove it. Not sure if some date / file permission check is done to it too.
Here's what the bruteforce.ini looks like after magento regenerated it:
brute-force-bad-attempts-count = 0
brute-force-diff-time-to-attempt = 180

I first edited it myself the sameway, but that didn't work.
Also remember if you have Nginx blocking download folder to allow it while using Magento Connect! This in case you get the 404 error, ofcourse.


text:
Q: How does breaking up a big method into smaller methods improve unit testability when the methods are all private? I'm presently reading Building Maintainable Software by Joost Visser and some of the maintenance guidelines they recommend include: A) each unit/method should be short (less than 15 lines per method) and B) methods should have a low cyclomatic complexity. It suggests that both these guideline helps with testing.
The example below is from the book explaining how they would refactor a complex method to reduce the per method cyclomatic complexity.
Before:
public static int calculateDepth(BinaryTreeNode<Integer> t, int n) {
    int depth = 0;
    if (t.getValue() == n) {
        return depth;
    } else {
        if (n < t.getValue()) {
            BinaryTreeNode<Integer> left = t.getLeft();
            if (left == null) {
                throw new TreeException("Value not found in tree!");
            } else {
                return 1 + calculateDepth(left, n);
            }
        } else {
             BinaryTreeNode<Integer> right = t.getRight();
             if (right == null) {
                throw new TreeException("Value not found in tree!");
             } else {
                return 1 + calculateDepth(right, n);
             }
        }
    }
}

After:
public static int calculateDepth(BinaryTreeNode<Integer> t, int n) {
     int depth = 0;
     if (t.getValue() == n)
        return depth;
     else
        return traverseByValue(t, n);
}
private static int traverseByValue(BinaryTreeNode<Integer> t, int n) {
     BinaryTreeNode<Integer> childNode = getChildNode(t, n);
     if (childNode == null) {
        throw new TreeException("Value not found in tree!");
     } else {
        return 1 + calculateDepth(childNode, n);
     }
}
private static BinaryTreeNode<Integer> getChildNode(
     BinaryTreeNode<Integer> t, int n) {
     if (n < t.getValue()) {
        return t.getLeft();
     } else {
        return t.getRight();
     }
}

In their justification they state (emphasis mine):
Argument:

"Replacing one method with McCabe 15 by three methods with McCabe 5
  each means that overall McCabe is still 15 (and therefore, there are
  15 control ow branches overall). So nothing is gained."

Counter Argument:

Of course, you will not decrease the overall McCabe complexity of a system by
  refactoring a method into several new methods. But from a
  maintainability perspective, there is an advantage to doing so: it
  will become easier to test and understand the code that was written.
  So, as we already mentioned, newly written unit tests allow you to
  more easily identify the root cause of your failing tests.

Question: How does it become easier to test?
According to the answers to this question, this question, this question, this question and this blog we should not be testing private methods directly. Which means we need to test them via the public methods that use them. So going back to the example in the book, if we are testing the private methods via the public method, then how does the unit tests functionality improve, or change at all for that matter?

A: After having written lots of test, I am strongly in favour of splitting up large methods, and of testing private methods. Splitting up functionality into smaller steps has two great advantages:

*

*By introducing a name for an operation, the code becomes more self-documenting.

*By using smaller methods, the code is simpler and thus more likely correct. E.g. you can immediately understand getChildNode().
While the overall program cyclomatic complexity isn't reduced, these two advantages outweigh the bit of extra code in my book. There is a third advantage: the code becomes much easier to test, assuming we can get around the private access modifier.
People who advise against testing private implementation details make a good point: the test should show that the implementation adheres to it's public interface, but this can only be done by black-box tests of the public methods. Such tests don't require that you get 100% coverage, but missing coverage is an indication of dead code that's not required by the specification. Since TDD tests should define externally observable behaviour, such tests fall into this category.
But you can also use a different approach to testing: showing that an existing implementation is likely correct, and works as the programmer expected. Since we already have the code, we can design our tests to maximize coverage. We can use boundary values to meticulously exercise the behaviour of the program. In other words, we can write white-box tests that know about implementation details of the system under test. These tests are highly coupled to the implementation, but that is OK as long as you also have more general black-box tests.
As a result, I prefer a few black-box tests that walk through the "happy path" and basic guarantees of the interface. But it is way to cumbersome to exercise all possibilities: with each input parameter or state variable in the function, the test space increases exponentially! A function f(bool) might take two tests, a function f(bool, bool) 2²=4, and f(bool, bool, bool, bool) already 24=16. This is untenable. But by splitting a large function into smaller functions, I only have to show that each smaller function works as expected, and that the functions work together correctly (I call this testing by induction). My workload now adds, instead of multiplying – a great improvement if you want to be thorough!

In your concrete example, either possibility is suboptimal because in the first try there's loads of code duplication requiring duplicate testing, and in the second try there are interdependencies between the functions that cannot be mocked away. Only getChildNode() is easy to test, but this function is incorrect if n is equal to t.getValue(), which will never happen if that function is only ever called by traverseByValue(). An easy to test alternative would be:
public static int calculateDepth(BinaryTreeNode<Integer> t, int n) {
    if (t == null) {
        throw new TreeException("Value not found in tree!");
    }

    if (t.getValue() == n) {
        return 0;
    }

    BinaryTreeNode<Integer> child = null;
    if (n < t.getValue()) {
        child = t.getLeft();
    } else {
        child = t.getRight();
    }

    return 1 + calculateDepth(child, n);
}

This specific case doesn't even use any helper functions, because it's simple enough to do without – there are only 4 paths through this code. Your previous implementation hid this by nesting conditionals when the other branch had already been terminated by a throw or return, and by unnecessary code duplication.
However, testing a recursion or loop can be difficult. While we could create a fairly complex tree and check for the correct result, we would like a way to check the loop invariant. In a language with higher-order functions, this might be:
public static int calculateDepth(
        BinaryTreeNode<Integer> t,
        int n)
{
    return calculateDepthLoop(t, n, calculateDepthLoop);
}

type Recurser = int(BinaryTreeNode<Integer>, int, Recurser);

private static int calculateDepthLoop(
         BinaryTreeNode<Integer> t,
         int n,
         Recurser recurse)
{
    if (t == null) {
        throw new TreeException("Value not found in tree!");
    }

    if (t.getValue() == n) {
        return 0;
    }

    BinaryTreeNode<Integer> child = null;
    if (n < t.getValue()) {
        child = t.getLeft();
    } else {
        child = t.getRight();
    }

    return 1 + recurse(child, n, recurse);
}

Now we could run a test plan like:

*

*calculateDepthLoop(null, ANY, ANY) throws.

*calculateDepthLoop(Tree(x, ANY, ANY), x, ANY) is0`.

*calculateDepthLoop(Tree(x, left, ANY), y, callback) for y < x invokes result = callback(left, y, callback) and returns the result + 1.

*calculateDepthLoop(Tree(x, ANY, right), y, callback) for x < y invokes result = callback(right, y, callback) and returns the result + 1.

with only 4 tests (one for each path) we can be sure that calculateDepthLoop() works as expected. We might want a couple more just to be sure that everything works for all valid values of x and y. Now we only need another test to check that everything integrates as it should, this can be done with a black-box test of calculateDepth(), which I'd do by creating a moderately complex tree requiring the function to recurse both left and right and return some value.

A: I can see 2 possibilities :

*

*The author is referring to private method names being included in the stack trace when a unit test fails unexpectedly.
Hence

as we already mentioned, newly written unit tests allow you to more easily identify the
  root cause of your failing tests.

What still puzzles me is newly written unit tests. What does he mean, and what is it that he already mentioned ?

*The author got carried away by how marvelous refactoring to private methods is and forgot that they're extremely difficult to test in isolation.
I suspect the latter. The other benefit he mentions (better understandability) remains valid though.

A: This is a very good question and has been bugging me for a while..
There are the following possibilities:

*

*Split into private methods as shown, but then change the acceess modifiere from private to package protected and test each such method with its own unit test

*Extract the methods in a static 'helper' class and mock that class with Powermockito , but also cover the methods in that static class with their respective unit tests

*Extract the methods in a non static collection of methods in a separate class and mock that one with Mockito..
None of these seem to be working well because in case 1 you need to also test the public method and you end up preparing test data twice.. (once for the protected method and once for the public) - but this could be overcome with refactoring the unit test common functionality into unit test helper methods..

A:
But from a maintainability perspective, there is an advantage to
  doing so: it will become easier to test and understand the code that
  was written.

Let's start with the second claim first:
it will become easier to understand the code
I think so far in this discussion that this point is more-or-less accepted.
So, the question becomes:  If code becomes easier to understand, does it therefore become easier to test?
I would suggest that it obviously does, if for no other reason then it makes it easier to identify those inputs and conditions which are especially at risk for failure.

A: I would suggest not splitting into smaller bits, but just making the function itself smaller and more readable. In addition, I fixed the second argument type, and throw an exception if the argument t is null where the original code crashes. Plus no unnecessary function calls. Plus no code duplication. Plus one function to test only.
public static int calculateDepth(BinaryTreeNode<Integer> t, Integer n) {
    for (int depth = 0; t != null; ++depth) {
        Integer value = t.getValue();
        if (n == value)
            return depth;
        t = n < value ? t.getLeft() : t.getRight();
    }
    throw new TreeException("Value not found in tree!");
}

A: Technically, it doesn't become easier to test: The code written to test your big, complex method should still work to test your smaller, prettier and simpler method. It is, however, easier to understand, which in return, would make it easier to test if you don't already have tests.
The private methods don't really help with that either: you don't need to write tests for them. Private methods are supposed to be an abstraction of some parts of the original method. You are not going to need or use them anywhere else, and writing code to test your main method will (inevitably) test your private methods. This is all a matter of making the code easier to read.


text:
Q: Problems with processing HTML forms in PHP I have the following problem: Although I actually use "if isset" to check whether the variable contains a value, it is sufficient if only in $besteatigung has a value and the empty $ email is simply ignored. Can someone help me please?
(I am a beginner)

    <link rel="stylesheet" href="style.css">
        <title>Newslatter Anmeldung</title>
        <meta charset="utf-8">

        <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">

Ihre E-Mail adresse bitte:

            <input type="email" name="Email">

Anrede: (optional)

            <input type="radio" name="Geschlecht" value="Mann">
            Mann

            <input type="radio" name="Geschlecht" value="Frau">
            Frau

Vorname: (optional)

            <input type="text" name="Vorname">

Nachname: (optional)

            <input type="text" name="Nachname">

<input type="checkbox" name="bestaetigung">hiermit bin ich einverstanden,
 dass meine Daten elektronisch gespeichert werden,
 damit mir die gewünschte Newsletter zugestellt werden kann ...
(gesetzliches Blahblah zum Datenschutz und Speicherung der Daten ....)

            <input type="submit" value="Anmelden" name="submit">
        </form>

<?php
if(isset($_POST['submit'])){
    if(isset($_POST['Email'])){
        if(isset($_POST['bestaetigung'])){
            $Email = htmlspecialchars(stripslashes(trim($_POST['Email'])));
            $Geschlecht = $_POST['Geschlecht'];
            $Vorname = htmlspecialchars(stripslashes(trim($_POST['Vorname'])));
            $Nachname = htmlspecialchars(stripslashes(trim($_POST['Nachname'])));

            $date = date("syHjin");

            $file = fopen("nl-anwaerter.txt", "a");
            fwrite($file, "$Email");
            fwrite($file, "|");
            fwrite($file, "$Geschlecht");
            fwrite($file, "|");
            fwrite($file, "$Vorname");
            fwrite($file, "|");
            fwrite($file, "$Nachname");
            fwrite($file, "|");
            fwrite($file, "$date");
            fwrite($file, "\n");
            fclose($file);

            $empaenger = "$Email";
            $betreff = "Ihre Newsletter Anmeldung";
            $from = "From: PHP mailer <deinnews@letter.de>\r\n ";
            $from .= "Reply-To: php@mail.com\r\n";
            $from .= "Content-Type: text/html\r\n";
            $msg = "
Newsletter Anmeldung

Hallo $Name $Nachname um dich entgültig für den Nwesletter anzumelden Klicke bitte auf folgenden Linl: ";

            if(mail($empaenger,$betreff,$msg,$from)){
                echo "Eine E-Mail wurde erfolgreich an $Email gesendet, bitte klicke auf den Link in dieser um die Anmeldung zu bestätiegen";
            }

        }
    }

}
?>

Hello, I have the following problem: Although I actually use "if isset" to check whether the variable contains a value, it is sufficient if only in $besteatigung has a value and the empty $ email is simply ignored. Can someone help me please?
(I am a beginner)

A: The isset function does not check if the variable is empty. An empty string (what your e-mail input will be if the input is left blank) is considered as set. Consult the type comparison table.
Instead, you should use empty to check if the e-mail field has a value:
if(!empty($_POST['Email'])){


text:
Q: Autofac is resolving duplicate instances I want to get a list of all validators of a particular command using Autofac. I have created an interface
    public interface IValidate<T>
    {
        void Validate(T command);
    }

And I have implemented 2 validators for this interface
    public class ValidateRule1 : IValidate<CreateEnrollmentCommand>
    {
        public void Validate(CreateEnrollmentCommand command)
        {
        }
    }

    public class ValidateRule2 : IValidate<CreateEnrollmentCommand>
    {
        public void Validate(CreateEnrollmentCommand command)
        {
        }
    }

I am injecting these validators in an IEnumerable like this
public class MyCommandHandler
{
    private readonly IRepository _repository;
    private readonly IEnumerable<IValidate<CreateEnrollmentCommand>> _validators;

    public MyCommandHandler(IEnrollmentRepository enrollmentRepository, IEnumerable<IValidate<CreateEnrollmentCommand>> validators)
    {
        _enrollmentRepository = enrollmentRepository;
        _validators = validators;
    }
 }

Here is my Autofac Configuration
    public class AutofacModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            // Register API Assembly
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .AsImplementedInterfaces();

            // Register Data Access
            var api = typeof(CreateStudentCommand).Assembly;
            builder.RegisterAssemblyTypes(api)
                .AsImplementedInterfaces();

            // Register Data Access
            var dataAccess = typeof(StudentRepository).Assembly;
            builder.RegisterAssemblyTypes(dataAccess)
                .AsImplementedInterfaces();

            builder
                .RegisterType<Mediator>()
                .As<IMediator>()
                .InstancePerLifetimeScope();

            builder.Register<ServiceFactory>(context =>
            {
                var c = context.Resolve<IComponentContext>();
                return t => c.Resolve(t);
            });

            builder.RegisterAssemblyTypes(typeof(CreateStudentCommand).GetTypeInfo().Assembly).AsImplementedInterfaces(); // via assembly scan
        }
    }

I am expecting two validators to be injected by Autofac, but it is actually injecting 2 instances of each validator. I am getting total of 4 validator instances in the IEnumerable property. Any idea what am I doing wrong?
Edit:
The IValidate interface and the validators are all located in the same assembly as pointed out by @Lasse V. Karlsen

A: You have several calls that register all types in an assembly, in particular I would check:

*

*The duplicate registration of all types in the assembly that contains the CreateStudentCommand type

*Whether all the types used to identify "all types in assembly" are in separate assemblies


text:
Q: Eigenvalues in the semiclassical limit Consider the Schrödinger operator $H_\hbar = -\hbar^2\Delta + V$ on $M=\mathbb{R}^n$, where $V$ is a potential that behaves well in a certain sense ($C^\infty$, bounded from below, going to infinity for large $|x|$, ...).
In the case $V = x^2$, $n=1$, the eigenfunctions are $\psi_n(x/\sqrt{\hbar})$ where the $\psi_n$ are hermite functions, and the corresponding eigenvalues are $\hbar(2n+1)$.
My question is: Is it a well-known theorem, that in the semiclassical limit $\hbar \rightarrow 0$, the eigenvalues tend to the minimum or minima of $V$ and the corresponding eigenvectors behave asymptotically like delta peaks? Can you give me references?
What about if M is a (possibly compact) riemannian manifold and $\Delta$ the Laplace-Beltrami operator?

A: Another reference is Helffer and several Coauthors (Sjöstrand, Nier, Klein, Garyard, ...) using the Witten-Laplace approach.
An introduction is given in the book
Semiclassical analysis, Witten Laplacians, and statistical mechanics
Later sharp asymptotics for the low lying spectra in the case where $V$ consists of several minima were obtained. Some lecture note on this topic Low lying eigenvalues of Witten Laplacians and metastability (after Helffer-Klein-Nier and Helffer-Nier).
If you are only interessted in the Schrödinger Operator, maybe the book Semi-Classical Analysis for the Schrödinger Operator and Applications is the most interesting for you. There are also lecture notes available Semiclassical Analysis for Schrödinger Operators, Laplace Integrals and Transfer Operators in large dimension: an introduction.

A: The canonical reference is:
Introduction to spectral theory: with applications to Schrödinger operators by Hislop and Sigal.
Your statement about the semiclassical behavior of eigenvalues seems to be proved by Barry Simon in:
http://archive.numdam.org/ARCHIVE/AIHPA/AIHPA_1983__38_3/AIHPA_1983__38_3_295_0/AIHPA_1983__38_3_295_0.pdf
(where he calls it a "folk theorem").


text:
Q: How do I show and hide a DIV using this method in Javascript? I am trying to show and hide a DIV using a button which I have programmed to change text using the data-text-swap method (which I found online). My DIV is set to 'display: none' in CSS but I want to change this using Javascript. What am I doing wrong in my code?

var showMixerBtn = document.getElementById("showMixer");
  showMixerBtn.addEventListener("click", showMixerBtnActions);

  function showMixerBtnActions() {
   if (showMixerBtn.getAttribute("data-text-swap") == showMixerBtn.innerHTML) {
    showMixerBtn.innerHTML = showMixerBtn.getAttribute("data-text-original");
   }
   else {
    showMixerBtn.setAttribute("data-text-original", showMixerBtn.innerHTML);
    showMixerBtn.innerHTML = showMixerBtn.getAttribute("data-text-swap");
   }
  }

  var mixerSliders = document.getElementById("mixerSliders");
  mixerSliders.addEventListener("click", showMixerActions);

  function showMixerActions() {
   if (showMixerBtn.getAttribute("data-text-original")) {
    mixerSliders.style.display = "block";
   }
   else {
    mixerSliders.style.display = "none";
   }
  }
div#mixerSliders {
   display: none;
  }
<button id="showMixer" data-text-swap="Hide Mixer">Show Mixer</button>

  <canvas class="gainSliders" id="kickSlider" nx="slider"></canvas>
  <canvas class="gainSliders" id="snareSlider" nx="slider"></canvas>
  <canvas class="gainSliders" id="clapSlider" nx="slider"></canvas>
  <canvas class="gainSliders" id="cHatSlider" nx="slider"></canvas>
  <canvas class="gainSliders" id="oHatSlider" nx="slider"></canvas>
  <canvas class="gainSliders" id="tomSlider" nx="slider"></canvas>
  <canvas class="gainSliders" id="perc1Slider" nx="slider"></canvas>
  <canvas class="gainSliders" id="perc2Slider" nx="slider"></canvas>

A:

var showMixerBtn = document.getElementById("showMixer");
  showMixerBtn.addEventListener("click", showMixerBtnActions);

  function showMixerBtnActions() {
   if (showMixerBtn.getAttribute("data-text-swap") == showMixerBtn.innerHTML) {
    showMixerBtn.innerHTML = showMixerBtn.getAttribute("data-text-original");
        mixerSliders.style.display = "none";
   }
   else {
    showMixerBtn.setAttribute("data-text-original", showMixerBtn.innerHTML);
    showMixerBtn.innerHTML = showMixerBtn.getAttribute("data-text-swap");
        mixerSliders.style.display = "block";
   }
  }
div#mixerSliders {
   display: none;
  }

.gainSliders {
  border: 2px inset brown;
}
<button id="showMixer" data-text-swap="Hide Mixer">Show Mixer</button>

  <canvas class="gainSliders" id="kickSlider" nx="slider"></canvas>
  <canvas class="gainSliders" id="snareSlider" nx="slider"></canvas>
  <canvas class="gainSliders" id="clapSlider" nx="slider"></canvas>
  <canvas class="gainSliders" id="cHatSlider" nx="slider"></canvas>
  <canvas class="gainSliders" id="oHatSlider" nx="slider"></canvas>
  <canvas class="gainSliders" id="tomSlider" nx="slider"></canvas>
  <canvas class="gainSliders" id="perc1Slider" nx="slider"></canvas>
  <canvas class="gainSliders" id="perc2Slider" nx="slider"></canvas>

This will make the text change and the slide show or hide as appropriate.

A: I did differently , rather than using display none , as you are using jquery you can use toggle function , it will easy up the things

$(document).ready(function(){
    $("#hide").click(function(){

        var el = $(this);
        el.text() == el.data("text-swap")
         ? el.text(el.data("text-original"))
         : el.text(el.data("text-swap"));

        $("p").toggle();

    });
});

If you click on the "Hide" button, I will disappear.

<button id="hide" data-text-swap="Hide" data-text-original="Show">Hide</button>


text:
Q: How to use external configuration file properties with a common one included in Spring Boot 2 In my Spring Boot 2 Application, I want to load a specific properties file (by profile) located in an external path, but I want that they load the common application.properties file in the project:
My config folder:
D:/config
         | -> hello-dev.properties (server.port=7777)
         | -> hello-prod.properties (server.port=5555)
And in my local application.properties:
logging.file=firstLog.log
So my aim, is to launch my spring boot application with devprofile and the 2 properties will be loaded (server.port=7777 and logging.file=firstLog.log)
I am also conscient that my external property configuration files are prefixed by hello instead of default one application.properties
Thank you for your help

A: Try this one:
java -jar myproject.jar --spring.config.additional-location=classpath:/default.properties,classpath:/override.properties

Look at the chapter about externalized configuration:
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html


text:
Q: Como eu coloco um botão dentro de iframe Tentei de várias formas e não consegui. Fiz assim:

 <input type="button" /> ou <button...></button>

Não consegui fazer aparecer o botão dentro do iframe.

A: Amigo, fica mais facil se você deixar alguns pontos claros a respeito do iframe e o que você pretende fazer.

*

*O domain do iframe é o mesmo da pagina na qual ele esta inserido ?
Você não tem permissão para alterar o conteudo de um iframe que pertence a um outro dominio, por exemplo, se a sua pagina esta rodando em http://localhost e o seu iframe tem o atributo src com o valor http://google.com, por exemplo, você não vai poder fazer nenhuma alteração no conteudo deste iframe.

*Você deseja adicionar o botão dinamicamente utilizando Javascript ?
Caso você deseja apenas adicionar um botão e tem acesso ao arquivo que o iframe referencia é mais fácil alterar este arquivo diretamente, caso você precise fazer isto dinamicamente com Javascript você pode acessar o conteúdo do iframe com window.frames[0].document. Lembre-se, você so poderá alterar utilizando Javascript se o conteúdo do iframe estiver no mesmo dominio da sua pagina.
Neste link você pode aprender um pouco mais sobre o elemento iframe e como utiliza-lo https://developer.mozilla.org/pt-BR/docs/Web/HTML/Element/iframe

A: Utilize um DIV para este objetivo, um iFrame serve para carregar outro HTML, outro arquivo.

A: Assim como os demais colegas, não consigo ver utilidade nesta abordagem, mas uma possibilidade é criar um documento em memoria:

var iFrames = document.querySelectorAll("[data-content]");
[].forEach.call(iFrames, function(frameElement, indice) {
  var frameContent = document.getElementById(frameElement.dataset.content);
  var blob = new Blob([frameContent.innerHTML], { type: "text/html" });
  frameElement.src = URL.createObjectURL(blob);
  frameContent.parentNode.removeChild(frameContent);
});

P.S: a técnica acima é bastante útil quando se deseja imprimir apenas um trecho da pagina e o uso de @media print não é o suficiente para se alcançar o resultado desejado.


text:
Q: How to make drop down boxes appear when a specific value has been selected? So as it says above I have drop-down boxes that I want to appear in winforms C# when the value in the box matches the value of the previous drop-down. Here is an example but it does not work.
if (devicemodel.SelectedText == "iPod");
{
  Show.comboBox1;

A: Set comboBox1.Visible = false on form load. Then:
if (devicemodel.Text == "iPod")
{
  comboBox1.Visible=true;
}

A: Try:
comboBox1.Visible = true;


text:
Q: Dot product in pyspark dataframes with MLLIB I have a very simple dataframe in pyspark, something like this:
from pyspark.sql import Row
from pyspark.mllib.linalg import DenseVector

row = Row("a", "b")
df = spark.sparkContext.parallelize([
    offer_row(DenseVector([1, 1, 1]), DenseVector([1, 0, 0])),
]).toDF()

and I would like to compute the dot product of these vectors without resorting to a UDF call.
The spark MLLIB documentation references a dot method on DenseVectors but if I try to apply this as follows:
df_offers = df_offers.withColumn("c", col("a").dot(col("b")))

I get errors like:
TypeError: 'Column' object is not callable

Does anyone know if these mllib methods are able to be called on DataFrame objects?

A: Here, you're applying the dot method on a column and not on a DenseVector, which indeed does not work :
df_offers = df_offers.withColumn("c", col("a").dot(col("b")))

You will have to use an udf :
from pyspark.sql.functions import udf, array
from pyspark.sql.types import DoubleType

def dot_fun(array):
    return array[0].dot(array[1])

dot_udf = udf(dot_fun, DoubleType())

df_offers = df_offers.withColumn("c", dot_udf(array('a', 'b')))

A: There are not. You'll have to use an udf:
from pyspark.sql.functions import udf

@udf("double")
def dot(x, y):
    if x is not None and y is not None:
        return float(x.dot(y))

A: You can multiply two columns without using UDF by first converting them into BlockMatrix and multiplying them like the example below

from pyspark.mllib.linalg.distributed import IndexedRow, IndexedRowMatrix

ac = offer_row.select('a')
bc = offer_row.select('a')
mata = IndexedRowMatrix(ac.rdd.map(lambda row: IndexedRow(*row)))
matb = IndexedRowMatrix(bc.rdd.map(lambda row: IndexedRow(*row)))

ma = mata.toBlockMatrix(100,100)
mb = matb.toBlockMatrix(100,100)

ans = ma.multiply(mb.transpose())

A: This is a hack but might be more performant than a Python udf. You could just convert the dot product into SQL:
import pandas as pd
from pyspark.sql.functions import expr

coefs = pd.Series({'a': 1.0, 'b': 2.0})
dot_sql = ' + '.join(
    '{} * {}'.format(coef, colname)
    for colname, coef
    in coefs.items()
)
dot_expr = expr(dot_sql)

df.withColumn('dot_product', dot_expr)


text:
Q: how to reduce an array of objects of stringed price var groceries = [
  {
    id: 1,
    product: 'Olive Oil',
    price: '$' + 12.1
  },
  {
    id: 2,
    product: 'Tomato Soup',
    price: '$' + 3.48
  },
  {
    id: 3,
    product: 'Cheesecake',
    price: '$' + 17.36
  },
  {
    id: 4,
    product: 'Sirloin Steak',
    price: '$' + 14.8
  },
  {
    id: 5,
    product: 'Brie Cheese',
    price: '$' + 23.28
  }
];

var sum = _.reduce(products, function (total, price) {
    return total + price;
  }, 0);

I'm not so sure how to remove the '$' from the price before we starting adding the values up. I've tried my best to look for other solutions here (I'm new), but there seems to be only examples where "price" are only numbers.
Sorry if this a similar problem already been posted somewhere else, but am still learning how to navigate here, and I have yet to find a similar situation unless someone can point me to it!

A: In the code, the price that you currently use is the object for every iteration with the properties from the array. Instead, you could take the price property from the object.
In your example data, there are only leading $ that you could remove from the price property. Then you can use for example parseFloat and only add the value if the conversion does not yield NaN.
Then pass the groceries variable to reduce instead of products which is not present in the example code.
Note that currently we are adding values of the same currency, and if you have different currencies you have have to account for that when calculating the sum.

var groceries=[{id:1,product:'Olive Oil',price:'$'+12.1},{id:2,product:'Tomato Soup',price:'$'+3.48},{id:3,product:'Cheesecake',price:'$'+17.36},{id:4,product:'Sirloin Steak',price:'$'+14.8},{id:5,product:'Brie Cheese',price:'$'+23.28},{id:6,product:'Product with invalid price',price:'$'+"hello"}];

var sum = _.reduce(groceries, function (total, obj) {
  var price = parseFloat(obj.price.replace(/^\$/, ''));
  if (!isNaN(price)) {
    return total + price;
  }
  return total;
}, 0);

console.log(sum)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"></script>

A: Here, I have used Javascript's default function reduce for getting the cumulative sum.

var groceries = [
  {
    id: 1,
    product: 'Olive Oil',
    price: '$' + 12.1
  },
  {
    id: 2,
    product: 'Tomato Soup',
    price: '$' + 3.48
  },
  {
    id: 3,
    product: 'Cheesecake',
    price: '$' + 17.36
  },
  {
    id: 4,
    product: 'Sirloin Steak',
    price: '$' + 14.8
  },
  {
    id: 5,
    product: 'Brie Cheese',
    price: '$' + 23.28
  }
];

//reduce((total, currentIteratedValue) => {}, initialCumulativeValue)
//Initially we take sum as 0
const sum = groceries.reduce(function (currentTotal, obj) {
  var price = parseFloat(obj.price.slice(1));
  if (!isNaN(price)) return currentTotal + price;
  return currentTotal;
}, 0);

console.log(sum)


text:
Q: Images not appearing on Emulator or Phone I'm testing out an application I've created but I've run into 1 issue. Some of the images that should load up and render into the app, don't show up at all. As far as I can see there is nothing I am doing different for either the images that show up or the images that won't. The application works in both DreamWeaver and in Google Chrome with no issues. I'm storing the images in a image folder inside of the www folder. All image names are named correctly.
The way I am calling these images is like this

There is obviously something I am doing wrong, I just can't see what it is, any help would be appreciated


text:
Q: Jenkins git fetch fails with unknown option --progress We have been using jenkins to build a project for over two years. We recently updated the jenkins and plugins (we need the maven-3 features), and now it's unable to do a simple git fetch. Here's the error message:
    FATAL: Failed to fetch from https://github.com/powertac/sample-broker.git
hudson.plugins.git.GitException: Failed to fetch from https://github.com/powertac/sample-broker.git
    at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:625)
    at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:847)
    ...
Caused by: hudson.plugins.git.GitException: Command "git fetch --tags --progress https://github.com/powertac/sample-broker.git +refs/heads/*:refs/remotes/origin/*" returned status code 129:
stdout:
stderr: error: unknown option `progress'
usage: git fetch [options] [ ..]
As you can see, the command line issued by jenkins contains an unknown option --progress. I have searched through the config files and cannot find where this is coming from. Here are the relevant version numbers:
Jenkins: 1.550
JenkinsGitPlugin: 2.0.1
git: 1.7.0.4
OS: Ubuntu 10.04
What am I missing?

A: Unfortunately it is hardcoded in Git Client Plugin, which is dependency for Git Plugin.
Git --progress option for fetch command become available in version 1.7.1.
Git Client Plugin started using --progress option for git fetch command since version 1.5.0.
Prior to that, in version 1.4.6, Git Client Plugin used git clone command instead of fetch, and made a check of installed git version before deciding whether to use --progress option (which become available for git clone command since git version 1.7.0).
So possible ways to solve your problem, starting with the most straightforward one, are:

*

*get a newer (1.7.1+) version of git on your system; getting up-to-date versions of software on Ubuntu may become a problem, so you might want to check this thread

*ask Git Client Plugin team to add support for git 1.7.0, wait until they release new version, and then use it

*install older (1.4.6) version of Git Client Plugin; beware that you may also need to downgrade Git Plugin in order to preserve compatibility

*patch Git Client Plugin on your own locally

*...come up with something even more painful :)


text:
Q: Hibernate @ManyToOne It`s possible to create one map with hibernate @ManyToOne just like this:
public class IndicadorAtos {
    @JsonIgnore
    @Id
    @Column(name="cod_ato_praticado")
    private Integer codAtoPraticado;
    @Column(name="descricao_ato")
    private String ato;

    @JoinColumn(name = "cod_ato", referencedColumnName = "cod_ato")
    @ManyToOne
    @Fetch(FetchMode.SUBSELECT)
    private Atos atos;

}

But in some cases I dont have association or in my table IndicadorAtos have one code, that don`t existis in table Atos
this is my tables:
create table IndicadorAtos (
  codAtoPraticado integer primary key,
  ato varchar(250),
  cod_ato integer
);

create table Atos(
  cod_ato integer primary key.
  name varchar(250)
)

I try to create this join:
Select t FROM IndicadorAtos t , Atos a where t.cod_ato = a.cod_ato, but I need to return all records from my IndicadorAtos, and with this select he only return all itens that have one item in Atos.
tks

A:
It`s possible to create one map with hibernate @ManyToOne

Yes; it is called unidirectional relationship.
If I understood your question properly, you want to select all entries from IndicadorAtos with possibly associated entries from Atos. You can achieve this by using left join as follows:
SELECT t FROM IndicadorAtos t LEFT JOIN t.atos at

provided that you have an entity Atos defined like:
@Entity
public class Atos {
    @Id @GeneratedValue
    private int cod_ato;

    private String name;

    // getters and setters
}


text:
Q: Rescaled Coordinates in a polynomial equation. I have this question from Murdock's textbook called: "Perturbations: Methods and Theory":
Use rescaling to solve: $\phi(x,\epsilon) = \epsilon x^2 + x+1 = 0$ and $\varphi (x,\epsilon) = \epsilon x^3+ x^2 - 4=0$.
I'll write my attempt at solving these two equations, first the first polynomial.
According to the book I first need to find an undetermined gauge that solves the above equation when $\epsilon = 0$, which means I need to guess $x \approx -1 +y \delta_1(\epsilon)$, now I plug it back to the above equation to find the following equation:
$$\epsilon -2y\epsilon \delta_1 + y^2 \delta_1^2 \epsilon +y \delta_1 = 0 $$
Now my problem is in finding a suitable gauge for $\delta_1(\epsilon)$ that solves the above last equation, it should be proportional to some power of $\epsilon$, i.e $\epsilon^r$, such that higher powers of $\epsilon$ in the last equation get neglected and we can find a solution for $y$ which gives a non-zero solution to $y$, but I don't see it.
Any help?


text:
Q: inequality with $a_{1}a_{2}\cdots a_{n}=1$ let $a_{i}>0$,and such $$a_{1}a_{2}\cdots a_{n}=1$$
find all real numbers $\alpha$,then
$$\sum_{i=1}^{n}\dfrac{a^{\alpha}_{i}}{a^2_{i}-a_{i}+1}\ge n$$
I have solve $\alpha\ge 3$,But I can't sure $\alpha>1$ this inequality right?

A: Just some incomplete thoughts.
By playing around with some plots, we can see that
$$
\frac{x^\alpha}{x^2-x+1}\geq 1+(\alpha-1)\log(x)
$$
for all $x>0$ and $\alpha\geq\alpha_0$ where $\alpha_0\approx 2.7461845658404$. Clearly this then immediately implies your original inequality. Also we see that if the inequality works for some $\alpha$, then it also works for $2-\alpha$ (just replace each $a_i$ by $\frac{1}{a_i}$).
On the other hand, with $(a_1,…,a_n)=(x,\frac{1}{x},1,…,1)$, the left hand side of your inequality is equal to
$$
\frac{x^\alpha}{x^2-x+1}+\frac{x^{-\alpha}}{x^{-2}-x^{-1}+1}+n-2=\frac{x^\alpha+x^{2-\alpha}}{x^2-x+1}+n-2
$$
so the inequality for this tupel is equivalent to
$$
x^\alpha+x^{2-\alpha}\geq 2(x^2-x+1).
$$
As we have equality for $x=1$ and also the derivatives of the two sides agree at $x=1$, we must have that the second derivative of the left hand side at $x=1$ is greater than or equal to the second derivative of the right hand side at $x=1$. By calculation, this then amounts to $2(\alpha-1)^2\geq 4$, i.e. either $\alpha\geq 1+\sqrt{2}\approx 2.414$, or $\alpha\leq 1-\sqrt{2}\approx -0.586$.
So in summary the inequality holds for all $\alpha\in (-\infty,2-\alpha_0]\cup[\alpha_0,\infty)$ (with $\alpha_0\approx 2.7461845658404$), and it doesn't hold in general for all $\alpha\in (1-\sqrt{2},1+\sqrt{2})$. So it remains to see what happens for $\alpha\in(2-\alpha_0,1-\sqrt{2}]\cup[1+\sqrt{2},\alpha_0)$.


text:
Q: How to pass parametes to a function inside datatable which is binded using jquery Hi I am having a datatable which I am binding to data using ajax call. So inside that table one button is present which is having 2 parameters .But I am getting error on the button click saying save(a,b) not defined
my code is given below
      var Action=''

and my function is like
  show(a,b)
    {
******
*****
    }

A: Corrected code is shown below:
var Action =
    ''
    + ''


text:
Q: Output of model.predict_generator()] I am new to Keras and i have a question. When i run predict_generator on my test dataset i get weird output. How can i get number between 0 and 1?
model.predict_generator(generator=test_generator, verbose = 1)

And when i try it i get someting like this.
       [9.11257455100e-01, 1.11224177e-01, 6.96873654e-03, 6.45312342e-01,

How i provided my train data:
Basically i have 5 folder lets say named A,B,C,D,E and every folder has full of pictures related to its category name.
datagen = tf.keras.preprocessing.image.ImageDataGenerator(
        rescale = 1./255,
        validation_split=0.2,
        featurewise_center=False,
        samplewise_center=False,
        featurewise_std_normalization=False,
        samplewise_std_normalization=False,
        zca_whitening=False,
        zoom_range = 0.1,
        width_shift_range=0.1,
        height_shift_range=0.2,

       )

And finally:
hist = model.fit_generator(
                     train_generator,
                     epochs=100,
                     shuffle = True,
                     validation_data= validation_generator,
                     steps_per_epoch = 64,
                     verbose = 1
                     )

A: It is not as complicated as it seems. When you run model predict it makes a predictionon each input sample. Each row in the array corresponds to a prediction for a sample. Now the number of columns in the array is equal to the number of classes your model was  trained on which in your case looks to be 5 classes. The number in the column is the probability that the sample is in the class represented by the row. For example in the first row of the matrix the value of 2.30657243e-10 represents the probability that the sample belongs to class 1. The value 4.47556471e-11 in column 2 represents the probability that sample 1 belongs to class 2 etc. The value 1.00000000e+00 in column 4 means there is essentially a 100% probability the sample belongs in class 4. The data in the next row is similarly structured for the second sample. To find the most probable class you use np.argmax to find the column with the highest probability to get the most likely prediction for the class. To make the printed result more readable use the code below
preds=model.predict_generator(generator=test_generator, verbose = 1)
preds=preds.round(decimals=2)
for p in preds:
    print (p)

I am assuming you used the ImageDataGenerator to create your test samples. If you did here is how to print out your results clearly.
test_file_names=test_gen.filenames  # sequential list of name of test files of each sample
test_labels=test_gen.labels # is a sequential list  of test labels for each image sample
class_dict= test_gen.class_indices # a dictionary where key is the class name and value is the corresponding label for the class
print (class_dict) # have a look at the dictionary
new_dict={}
for key in class_dict: # set key in new_dict to value in class_dict and value in new_dict to key in class_dict
    value=class_dict[key]
    new_dict[value]=key
print('PREDICTED CLASS  TRUE CLASS       FILENAME ' ) # adjust spacing based on your class names
for i, p in enumerate(preds):
    pred_index=np.argmax(p) # get the index that has the highest probability
    pred_class=new_dict[pred_index]  # find the predicted class based on the index
    true_class=new_dict[test_labels[i]] # use the test label to get the true class of the test file
    file=test_file_names[i]
    print(f'    {pred_class}       {true_class}       {file}')


text:
Q: Image Not Moving Back To Correct Place I am trying to move an image back to a certain point on the screen. I am using the following code:
[UIView beginAnimations:nil context:nil]; //Move To Start Position With Animation
    [UIView setAnimationDuration:0.5];
    plustwo.center = CGPointMake(36, 134);
    [UIView commitAnimations];

The problem is that the image does not back to the correct point on the screen. I am initiating this from an if statement that states:if this image collides with another image(PanGestureRecogizer) it moves back to its place. Am I doing something wrong?
Thanks

A: I don't know if u did wrong?
As you didn't told the previous state of ur image if the co-ordinate you have given is the previous state then may be the u r using center here and image would have moved from origin, or if this code may not work.. so use this
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:1.0];
[UIView commitAnimations];

and for more clear response, give clear question...


text:
Q: Cannot infer type arguments for ResponseEntity<> I want to implement Spring endpoint in which I can return XML object NotificationEchoResponse and http status code. I tried this:
@PostMapping(value = "/v1/notification", produces = "application/xml")
  public ResponseEntity<?> handleNotifications(@RequestParam MultiValueMap<String, Object> keyValuePairs) {

   if (!tnx_sirnature.equals(signature))
     {
         return new ResponseEntity<>("Please contact technical support!", HttpStatus.INTERNAL_SERVER_ERROR);
     }

    return new ResponseEntity<>(new NotificationEchoResponse(unique_id), HttpStatus.OK);
  }

But I get error: Cannot infer type arguments for ResponseEntity<> at this line: return new ResponseEntity<>("Please contact technical support!", HttpStatus.INTERNAL_SERVER_ERROR); Do you know know how I can fix this issue?

A: You can use the
    ResponseEntity<Object>

like that
OR
You can make you own custom class like ResponseData and in that class put a field like paylod
  public class ResponseData {
      private Object payload;
   }

and use like that ResponseEntity and set that value.
Now your controller will look like that
    @PostMapping(value = "/v1/notification", produces = "application/xml")
    public ResponseEntity<ResponseData> handleNotifications(@RequestParam
    MultiValueMap<String, Object> keyValuePairs) {

   if (!tnx_sirnature.equals(signature))
   {
     return new ResponseEntity<ResponseData>(new ResponseData("Please contact to technical support"),
    HttpStatus.INTERNAL_SERVER_ERROR);
   }

   return new ResponseEntity<ResponseData>(new ResponseData(new NotificationEchoResponse(unique_id)),
   HttpStatus.OK);
   }

You can replace the response data with Object also , then the
  @PostMapping(value = "/v1/notification", produces = "application/xml")
    public ResponseEntity<Object> handleNotifications(@RequestParam
    MultiValueMap<String, Object> keyValuePairs) {

   if (!tnx_sirnature.equals(signature))
   {
     return new ResponseEntity<Object>("Please contact to technical support",
    HttpStatus.INTERNAL_SERVER_ERROR);
   }

   return new ResponseEntity<Object>(new NotificationEchoResponse(unique_id),
   HttpStatus.OK);
   }

A: public ResponseEntity<BasicCreateUpdateResponse> deleteProductPrefix(@RequestBody ProductPrefixEntity inputFields) {
    if(inputFields.getRecid().isEmpty()) {
        throw new ApplicationException(NPIConstants.ERR_500, HttpStatus.OK, null, null);
    }
    logger.info("Inside resources updateProduct method() .........");
    return new ResponseEntity<>(productPrefixService.deleteProductPrefix(inputFields),HttpStatus.OK);
}

in this code return type of "productPrefixService.deleteProductPrefix(inputFields)" must be ResponseEntity.

A: The return type of ResponseEntity should be <String>.
As you are returning this string: "Please contact technical support!"
Or you can simply do ResponseEntity<Object>


text:
Q: Pass input from one step to other step in Column transformer scikit pipeline I have a pipeline that looks like this:
categorical_transformer = Pipeline(steps=[
    ('categorical_imputer', SimpleImputer(strategy="constant", fill_value='Unknown')),
    ('encoder', OneHotEncoder(handle_unknown='ignore'))
])

fill_na_zero_transformer = Pipeline(steps=[
    ('zero_imputer', SimpleImputer(strategy='constant', fill_value=0))
])

numeric_transformer = Pipeline(steps=[
       ('imputer', SimpleImputer(strategy = "constant", fill_value=-1, add_indicator=True)),
       ('scaler', StandardScaler())
])

preprocess_ppl = ColumnTransformer(
    transformers=[
        ('categorical', categorical_transformer, ['MARITAL_STATUS']),
        ('zero_impute', fill_na_zero_transformer, fill_zero_cols),
        ('numeric', numeric_transformer, num_cols)
    ]
)

pipeline = Pipeline(
    steps=[
        ('dropper', drop_cols),
        ('remover',feature_remover),
        ("preprocessor", preprocess_ppl),
        ("estimator", LinearRegression())]
)

dropper drops some cols, feature remover also drops based on some logic. In ('numeric', numeric_transformer, num_cols) instead of num_cols I want to get the latest transformed data columns and pass it to 'numeric'.
I.e Lets say that the intermediate data before 'numeric' step is X I want to pass
[col for col in num_cols if col in X.columns]

instead of num_cols
Is this possible?

A: Yes; from the docs, the options for the columns entry of the transformers triples:

columns : str, array-like of str, int, array-like of int, array-like of bool, slice or callable
[...] A callable is passed the input data X and can return any of the above. [...]

So at the most basic, lambda X: [col for col in num_cols if col in X.columns] should work.


text:
Q: Syntax question
Good men, the last wave by, crying how bright
  Their frail deeds might have danced in a green bay,
  Rage, rage against the dying of the light.

From Dylan's Poem Do not go gentle into that good night
"The last wave by" is this an adverb in the passive form that if written in an active voice would be: by the last wave --- indicating a presence of time?

A: There are layers of meanings.
"The last wave" refers to the most recent(=last) generation(=wave) of good men to go by, or perhaps the final generation of good men. It has allusions to the last stage of life of the "good men" and to a farewell wave to their loved ones, metaphorically it suggests a sea wave that will soon crash against the rocks of the "green pay"
The syntax is a shortening of "The last wave to go by" but poetry often breaks some or all the rules of syntax to create images.


text:
Q: How to RowFilter a column with a period in the name? I have a DataTable pupulated from a cube with the column names declared as:

[Measures].[Stock Qty]

The DataTable fills correctly, however when trying to apply a RowFilter using:

"[Measures].[Stock Qty] >= 2000"

I get the following error:

"[Measures.StockQty] not found

I also tried using just the column name:

"[Stock Qty] >= 2000"

but this also fails with a not found error.
Is it at all possible to filter a DataTable using column names that contain periods, if so how?

A: Why do you want to use the RowFilter at all? If you're using .NET 3.5 or higher i would recommend to use Linq-To-DataTable instead which is more powerful and readable:
IEnumerable<DataRow> filteredRows = tblMeasures.AsEnumerable()
    .Where(r => r.Field<int>("Stock Qty") >= 2000);

if you need a DataTable again:
DataTable tblFiltered = filteredRows.CopyToDataTable();

By the way, if the name of column in the DataTable is "Stock Qty" your last approach should work since you need to wrap it in brackets.
tblMeasures.DefaultView.RowFilter = "[Stock Qty] >= 2000";

So you should use the debugger to see the real name and type of the column.

A: You can rename the datatable columns (for replacing period with "_") & they try rowfilter.
Eg.:
dataTable.Columns["Stock Qty"].ColumnName =
                 dataTable.Columns["Stock Qty"].ColumnName.Replace(" ", "_");


text:
Q: VB.net alternative for Selection In Excel VBA I could select some cells and then use the property Selection to refer to the selected cells.
What is the VB.net alternative to refer to a number of selected cells in an Excel worksheet?
I need to replace the code Selection in the below code with the appropriate code.
xlWorkSheet.ListObjects.Add(Excel.XlListObjectSourceType.xlSrcRange,_
Selection,, Excel.XlYesNoGuess.xlYes).Name = ("Table1")

A: Remember that Selection is an Application object and can be reached throught it:
https://msdn.microsoft.com/en-us/library/office/ff840834.aspx
But, be careful. Selection represents anything in Excel, a Range, a Picture. Through interop, it returns a dynamic object.
Try to play with Immediate Window in VBA, executing the code below, selecting different types of objects:
?TypeName(Application.Selection)

Happy coding!


text: Q: Move cell brackets on the left of a notebook Is there a way to put cell brackets on the left of a current notebook? In order to visualize better a notebook structure. An image is added to illustrate the point.


text:
Q: What does StringInterpolationSegment do? (swift) I continued on my math question project, and it could now generate questions, so I need to try to use a global variable to use my answer's in generating the answer itself and putting the answer randomly into one of 4 choices. I decided to put a secret label outside of my view that shows the answer. Here's my code:
    //important stuff
@IBOutlet var secretAnsarrrrr: UILabel!
//useless code
        //declare the value of secretAnsarrrr
        secretAnsarrrrr.text = String(answer)
        numA.text = String(Int(randomNumber))
        numB.text = String(Int(randomNumber2))
    }
    generateQuestion()
}
var optionAnswer:UInt32 = arc4random_uniform(4)
@IBAction func answerA(sender: UIButton) {
    var otherAns:String = String(secretAnsarrrrr) //error
    if optionAnswer == 0 {
        optionA.text = secretAnsarrrrr.text
    }

Doing so gives me the error of 'Missing argument label: StringInterpolationSegment in call'. It tells me to place it behind 'secretAnsarrrrr' in the parentheses. What does stringInterpolationSegment do and how do I fix this?

A: secretAnsarrrrr is not a string itself - it is a UILabel which also contains information like color and font. You need to tell Swift to use its text property:
 var otherAns:String = String(secretAnsarrrrr.text)

A: I just encountered this error, and after some head scratching, I realised that I needed to unwrap an optional integer which I was trying to parse with String(...). As soon as I added the exclamation mark, the problem was solved:
var num: Int? = 1
var str = String(num!)

A: it is Better to write:
var num: Int? = 1
var str = num.map { String($0) } // if num == nil then str = nil else str = string representation


text:
Q: rt-mailgate not making tickets with fetchmail and procmail I'm trying to use my mail so that any mail sent to support@mydomain.com are turned into tickets by RT4.
The process currently breaks down in the send mail step. My server is running fetchmail. The mail is being found by fetchmail, as my fetchmail.log reports two found.
Thats where it goes downhill. No mail is sent, and no logs generated.
Here is my ~/.fetchmailrc:
set daemon 60
set invisible
set no bouncemail
set no syslog
set logfile /var/log/fetchmail.log
poll 'mydomain.com' protocol IMAP username 'support@mydomain.com' password 'removedforthisexample'
mda "/usr/bin/procmail -Y -d %T"

which leads to my .procmailrc file:
VERBOSE=YES
LOGFILE=/home/ubuntu/proclog.log
LOGABSTRACT=YES
:0
* ^Subject:.*Spam:.*
/home/ubuntu/Rejected/

:0
* ^From:.*(noreply|donotreply|nobody)@.*
/home/ubuntu/Rejected/

:0
* ^To:.*support@mydomain.com.*
|/usr/bin/perl /opt/rt4/bin/rt-mailgate --no-verify-ssl --url http://rt.mydomain.com/ --queue "Support" --action correspond

Nothing is being created in my proclog.log file, anyone have any ideas?
Thanks,


text:
Q: Using Visual Studio Code HTML features in template languages Visual Studio Code supports rich prettify and formatting options for HTML. Advanced HTML editing features include Intellisense, CSS class auto-completion and so on.
How these features could be enabled for HTML producing template languages, including but not limited to

*

*Nunjucks .njk

*Jinja .jinja

*Handlebars

*Django

These languages are very similar to HTML, with some formatting tags embedded in. For example, on the Jetbrains products (IDEA, Webstorm, Pycharm) one can quite directly use advanced HTML options in these templates, even though those templates are not pure HTML.

I would assume there is some setting where specific file extensions can be tagged as "HTML like", which would allow sue the features.


text:
Q: Modifying the Lemniscate of Bernoulli to have asymmetry along one axis I'm looking for ideas on how to modify the Lemniscate of Bernoulli to include some asymmetry across one axis.
The parametric equations of the lemniscate are
$$x(t)=\frac {a\sqrt{2}\cos t }{\sin^2t+1} \qquad y(t)=\frac {a\sqrt{2}\cos t\sin t }{\sin^2 t+1}$$
The type of curve I'm trying to fit looks like this. The boundary of the figures defines the curve. It's symmetric across the $x$-axis, but across the $y$-axis that I need the asymmetry.

Ideas for parameterizing this curve in the complex plane and calculating its length by (numerical) contour integration?
Perhaps, by defining some angle parameter, the amount of rotation of the contact points around the focus of the lobe where the tangent line touches the curve on either side could be determined and also another parameter to determine whether the lobes are bent to the left or right and by how much. I guess it's more like a bent or warped elliptic curve, the two lobes of the curve intersecting at a Riemann zero.


text:
Q: YouTube API V3 not returning "statistics" part for /videos endpoint I stopped getting "statistics" part, from 06-April-2017, It was working perfectly fine and now for several videos I am not getting "statistics" part. when I make this call, https://www.googleapis.com/youtube/v3/videos?part=statistics&key=validKey&id=3cxixDgHUYw
FYI, I also tried getting "statistics" part from here, but not receiveing it. https://developers.google.com/youtube/v3/docs/videos/list

A: Same issue as well, someone has opened up an issue at Google's issue tracker here


text:
Q: Test Matrix for pre-computed kernel in libsvm (scikit learn) I am using Weisfeiler-Lehman Graph Kernels from here to get the precomputed kernel for the Scikit learn SVM see description.
At test time, what should be the format of my data? I'm really confused about that. See dimension requirements.
Thanks very much.


text:
Q: Can i have the PDF revision history or revision number or value in the DITA PDF output? I need to provide a way for the customers to know the PDF revision numbers or date. I need to have the revision value or timestamp or anything similar at the footnote of the PDF. I tried adding tags in the bookmeta, but they are not picked during the build. Can someone help?

A: Of course you can, but you won't get it by default using the DITA Open Toolkit (which I assume that you are using). You'll need to create a customized PDF plug-in that will generate footers that pick up information from where ever it is in the DITA source.
The DITA-OT documentation and Leigh White's book "DITA For Print" will probably help you learn to create a customized plug-in. Or modify one, if you are working with a customized PDF plug-in to begin with.
You might want to post about this on the dita-users list. You can join the dita-users list at https://dita-users.groups.io/g/main ; be sure to scroll down to the bottom of the page

A: If you would use for publishing DITA to PDF Oxygen's specific "DITA Map PDF - based on HTML5 & CSS" transformation scenario which uses CSS for customizing the PDF output, you can use CSS pagination techniques:
https://www.oxygenxml.com/doc/versions/24.1/ug-editor/topics/dcpp_headers_and_footers.html#ariaid-title7
If the DITA Map looks like this:
 <map>
   <title>Growing Flowers</title>
   <topicmeta>
     <critdates>
       <revised modified="2022-06-03"/>
     </critdates>

define for example a stringset with a certain name and use the stringset in the header for example:
 *[class ~= "topic/revised"] {
   string-set: hdrstr attr(modified);
  }
  @page {
   @top-left-corner {
     content: string(hdrstr);
   }
  }


text:
Q: Ubuntu couldn't detect my scanner Ubuntu 16.04, GNOME.
Don't know why, but Simple Scan stoped working - firstly, the error "no devices was found", after reinstalling last version of hplip and configuring this problem was solved. But still after trying to press Scan button, or run scanimage -L infinite waiting is appeared (with animation of moving circles in Simple Scan). I've googled really a lot, but nothing works.
lsusb:
Bus 003 Device 011: ID 03f0:042a Hewlett-Packard LaserJet M1132 MFP

sane-find-scanner:
  # sane-find-scanner will now attempt to detect your scanner. If the
  # result is different from what you expected, first make sure your
  # scanner is powered up and properly connected to your computer.

  # No SCSI scanners found. If you expected something different, make sure that
  # you have loaded a kernel SCSI driver for your SCSI adapter.

found USB scanner (vendor=0x03f0 [Hewlett-Packard], product=0x042a [HP LaserJet Professional M1132 MFP]) at libusb:003:011
could not fetch string descriptor: Pipe error
  # Your USB scanner was (probably) detected. It may or may not be supported by
  # SANE. Try scanimage -L and read the backend's manpage.

  # Not checking for parallel port scanners.

  # Most Scanners connected to the parallel port or other proprietary ports
  # can't be detected by this program.

So, what can I do? /etc/hp/hplip.conf doesn't contain any interesting information, as I could see. File's owner is me, not root.


text:
Q: Dialogflow CX import entities using C# Unfortunately there is no API sample for c# to push entity type from an Dotnet project. Is there anyone working with it?? A sample code will be helpful.

A: The google-cloud-dotnet github has a set of snippets that have examples of using the CX API in C#, including one that shows List, Get, Create, Update, and Delete for EntityTypes.


text:
Q: Android - How to Store HashMap with Custom Key (and custom data) to internal storage? I was wondering if it was possible to store a hash map with a special key function (similar to the solution posted by Jon Skeet at Using a byte array as Map key) and thus data wrapper inside the android internal storage
And how to get them out again.
Namely, the data underlying it all is char [], but that char [] is wrapped around in this custom class that is used in the hashmap.
The value part is simple string, but the key is the important bit where I need the data inside it to be preserved on each opening of the app.
Do I need to overwrite certain functions in the wrapper to make sure it works with the FileOutputStream? How do I import it back again?

A: I don't have a direct answer for you.  However I can suggest simply saving your hashmap as an xml file.  Writing the xml is pretty easy.  You will need to write the higher level parts of parsing to read it back.

A: Use Gson to convert the map to a JSON string. Then write that string to disk. To get it back, use Gson again. Prob could accomplish this 5 lines of code. No messing with convertors or parsing needed.


text:
Q: Configure zabbix_agent on macOS High Sierra According to Zabbix agent installation, you can install just the zabbix-agent on macOS with brew install zabbix --without-server-proxy
Nothing explained how to configure the agent, tells him where to send the information ? Is there any configuration file located somewhere ?
There are some files in /usr/local/Cellar/zabbix/<version number>/ but nothing similar to a .conf.

A: Checking brew installer or configure/make messages often help to determine where files and folders are stored or how and where to configure services or apps:
Example output after installing the required dependencies:
...
==> Installing zabbix --without-server-proxy
==> Downloading https://downloads.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/3.4.7/zabbix-3.4.7.tar.gz
==> Downloading from https://10gbps-io.dl.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/3.4.7/zabbix-3.4.7.tar.gz
######################################################################## 100.0%
==> ./configure --prefix=/usr/local/Cellar/zabbix/3.4.7 --sysconfdir=/usr/local/etc/zabbix --enable-agent --with-iconv=/Applications/
==> make install
  /usr/local/Cellar/zabbix/3.4.7: 13 files, 1.4MB, built in 1 minute 31 seconds

One ./configure flag of zabbix is --sysconfdir=/usr/local/etc/zabbix.
Consequently the configuration file(s) and folders (i.e. zabbix_agentd.conf.d) can be found here:
/usr/local/etc/zabbix/

Additional zabbix* man files can be found here:
/usr/local/share/man/man1/
/usr/local/share/man/man8/

Additional steps to perform:

*

*Add /usr/local/sbin to your path. Some brew-installed binaries are installed to this folder (e.g. dnsmasq or zabbix)

*Get the zabbix agent to launch at boot time with a launch daemon/agent. I haven't found one accompanying the brew-installed zabbix.
Several can be found at github though:

*

*com.zabbix.zabbix_agentd.plist (the config dir in the plist has to be modified though).

*zabbix_agentd_osx_installer (either the UserName/GroupName keys have to removed or a User and Group each with the name zabbix have to be added as special user/group with dscl or the Users & Groups prefpane though or the daemon will fail)
The older zabbix 2.2.5 installer uses the following postinstall script to add a zabbix user & group/modify files and folders:
#!/usr/bin/env bash

#To create a group:
sudo dscl /Local/Default -create /Groups/zabbix
sudo dscl /Local/Default -create /Groups/zabbix PrimaryGroupID 113
sudo dscl /Local/Default -create /Groups/zabbix Password \*

#To create a user:
sudo dscl /Local/Default -create /Users/zabbix
sudo dscl /Local/Default -create /Users/zabbix UniqueID 113
sudo dscl /Local/Default -create /Users/zabbix UserShell /usr/bin/false
sudo dscl /Local/Default -create /Users/zabbix RealName 'Zabbix user'
sudo dscl /Local/Default -create /Users/zabbix NFSHomeDirectory /var/empty
sudo dscl /Local/Default -create /Users/zabbix PrimaryGroupID 113
sudo dscl /Local/Default -create /Users/zabbix Password \*

#Create needed directories
sudo mkdir -p /var/run/zabbix-agent
sudo mkdir -p /var/log/zabbix-agent
sudo mkdir -p /usr/local/bin
sudo mkdir -p /usr/local/sbin
sudo mkdir -p /usr/local/etc/zabbix

sudo chown -Rf zabbix:zabbix /var/run/zabbix-agent
sudo chown -Rf zabbix:zabbix /var/log/zabbix-agent

sudo chown root:wheel /Library/LaunchDaemons/com.zabbix.zabbix_agentd.plist
sudo chown root:wheel /usr/local/etc/zabbix/zabbix_agentd.conf
sudo chown root:wheel /usr/local/etc/zabbix_agentd.conf

sudo chown -Rf root:wheel /usr/local/sbin
sudo chown -Rf root:wheel /usr/local/bin
sudo chmod -Rf 755 /usr/local/bin
sudo chmod -Rf 755 /usr/local/sbin

sudo chmod 755 /usr/local/etc/zabbix
#sudo kill -9 `ps aux | grep zabbix_agentd | cut -f11 -d" "`
#sudo kill -9 `ps -aef | grep zabbix_agentd | grep -v grep | awk '{print $2}'`
#sudo rm -Rf /tmp/zabbix*

It's not recommended to execute all these steps but the script may serve as an example how to get it to work. Some have already been executed by installing zabbix with brew (e.g. some sudo mkdir ... commands). Some aren't necessary (e.g. some sudo chown root:wheel ... commands) or will even break brew (e.g. sudo chown -Rf root:wheel /usr/local/bin). If you choose to create a zabbix user/group, make sure that the user can read, write and execute files in the /usr/local/etc|sbin|bin branches.
Move the edited plist file to /Library/LaunchDaemons/ and load it - after editing the zabbix config file - with:
sudo launchctl load /Library/LaunchDaemons/com.zabbix.zabbix_agentd.plist


text:
Q: SQL Server DSN-Less ODBC Specify 32 bit Driver I'm working with an older application that I recently updated to .NET 4.5. The application has been using DSN ODBC connections. However, in the case of the application, it is accessed from a single location on a network drive, so it doesn't make sense to require a DSN, and it will ease deployment and updates to use a DSN-less connection string in place. I'm doing a basic string as such:
Driver={SQL Server}; Server=; Database=; UID=; PWD=

The issue I have is that the application is compiled as 32 bit, but may be used on a 32 bit or 64 bit machine. On 64 bit machines I get this error:

The specified DSN contains an architecture mismatch between the Driver
  and Application

Which essentially means it's trying to use the 64 bit driver for the 32 bit application. That's easy enough to deal with except the driver name for SQL Server appears to be the same for 32 and 64 bit. So how can I specify only the 32 bit driver in the connection string?

A: "To manage a data source that connects to a 32-bit driver under 64-bit platform, use c:\windows\sysWOW64\odbcad32.exe. To manage a data source that connects to a 64-bit driver, use c:\windows\system32\odbcad32.exe. In Administrative Tools on a 64-bit Windows 8 operating system, there are icons for both the 32-bit and 64-bit ODBC Data Source Administrator dialog box. Read more"
If you use the 64-bit odbcad32.exe to configure or remove a DSN that connects to a 32-bit driver, you will receive the following error message:

The specified DSN contains an architecture mismatch between the Driver and Application

To resolve this error, use the 32-bit odbcad32.exe to configure or remove the DSN.
References

*

*The specified DSN contains an architecture mismatch between the Driver and Application

*Managing Data Sources

Side Note: make sure that all references Copy Local property is set to True, even the System assemblies. I think that the issue may be from the assemblies location saved in GAC, so when copying the assemblies locally it may fix that


text:
Q: How to support tabs on Android 2.2+? I'm trying to offer tab support for all Android versions 2.2 and above. Is there a way of achieving this without using any deprecated classes/methods?

A: The Problem is as following:
TabActivity is deprecated because it derives from ActivityGroup which is deprecated, too. Problems are, to start Activitys inside Tabs and don't break callbacks like onActivityResume. There are some 'Hacks' around which solve this but they are ALL relying on the deprecated LocalActivityManager. So I see no solution of using Tabs without ANY deprecated calls. Since Android 3.X google invented Fragments for this kind of things which are supported on lower Versions with the SupportPackage. You should definetly try them in Combination with the new ActionBar if you want to avoid deprecated classes/methods
EDIT:
Link to FragmentTabs for further reference

A: I recon with with the answer Rafael gave.
Instead of resorting to the TabActivity you can sill use the regular TabHost to show tabs in all versions of android.


text:
Q: Can you give helpers a variable and change the function it uses in CodeIgniter I am creating a form and I want to make a custom error log, for example when the user leaves e-mail empty, I want to give my error_helper the variable email, sending to the user that he did not fill in this variable and log that he left this empty. I am a starter with codeIgniter and i've read the manual but I did not find anything helpful. Here is my code:
    public function submitCheck() {
    $this->load->model("User");
    if(empty($post['email'] || 'email'==""))
    {
        echo "Email is empty."; //This will be changed to a view for user
        $this->load->helper('error'); //Loading the helper
        errorLog('Firstname'); //Variable I want to give to the errorLog function.
        exit();
    }

So here I've given my errorLog a variable, wich I want to use in my error_helper
    function errorLog(){
     if(errorLog() == 'email') //Here I want to change the error function based on what variable I give to errorLog
     {
        log_message('error', 'Email was empty');
        exit();
     }
}

Is this possible to do or some other way how I can change the function based on what variable I give my errorLog.
Thanks in advance

A: You need to pass parameter into your helper function
Controller file
public function submitCheck() {
    $this->load->model("User");
    if(empty($post['email']))
    {
       // echo "Email is empty."; //This will be changed to a view for user
        $this->load->helper('error'); //Loading the helper
     echo  $msg= errorLog('Firstname'); //Variable I want to give to the errorLog function.
    }

Helper file
    function errorLog($var){ // get the variable thet you have pass from your helper
         if($var == 'email') //Here I want to change the error function based on what variable I give to errorLog
         {
            return log_message('error', 'Email was empty');// here you use return type

         }
         if($var == 'test')
         {
            return log_message('error', 'Test was empty');// here you use return type

         }
}

Also load your helper in controller constructor file or autoload.php file

A: Read parameter in the function:
    function errorLog($var){
     if($var== 'email') //Here I want to change the error function based on what variable I give to errorLog
     {
        log_message('error', 'Email was empty');
        exit();
     }
}


text:
Q: Multiple vertical background colors in CSS3 Problem:
Trying to create a solution that would allow me to have five multiple background colors that fill out a webpage regardless of width. I have managed to do this with 5 div tags but I wonder if it's possible to do this completely using CSS3?
The outcome I would like is:

I have searched Stackoverflow and the web without any results, or I am simply very bad at searching.

A: Look at this i made a trick for this .http://jsfiddle.net/753gugpt/
I used linear-gradient CSS3 property like this:

#container {
  width: 100%;
  /*or 900px for example */
  overflow-x: hidden;
}
#exampleB {
  width: 32700px;
  height: 285px;
  background-color: #a8e9ff;
  filter: progid: DXImageTransform.Microsoft.gradient(GradientType=1, startColorstr=#a8e9ff, endColorstr=#052afc);
  background-image: -moz-linear-gradient(left, #a8e9ff 0%, #052afc 0%, #485e69 12%, #ff8d00 1%);
  background-image: linear-gradient(left, #a8e9ff 0%, #052afc 0%, #485e69 12%, #ff8d00 1%);
  background-image: -webkit-linear-gradient(left, #a8e9ff 0%, #052afc 0%, #485e69 12%, #ff8d00 1%);
  background-image: -o-linear-gradient(left, #a8e9ff 0%, #052afc 0%, #485e69 12%, #ff8d00 1%);
  background-image: -ms-linear-gradient(left, #a8e9ff 0%, #052afc 0%, #485e69 12%, #ff8d00 1%);
  background-image: -webkit-gradient(linear, left bottom, right bottom, color-stop(0%, #a8e9ff), color-stop(0%, #052afc), color-stop(12%, #485e69), color-stop(1%, #ff8d00));
}

Maybe this will work for you :)

A: You could use linear-gradients to achieve this.
Example Here
html, body {
    height: 100%;
}
body {
    background-image: linear-gradient(90deg,
        #F6D6A8 20%,
        #F5BA55 20%, #F5BA55 40%,
        #F09741 40%, #F09741 60%,
        #327AB2 60%, #327AB2 80%,
        #3A94F6 80%);
}

Just add vendor prefixes for additional browser support
body {
    background: -moz-linear-gradient(90deg, #F6D6A8 20%, #F5BA55 20%, #F5BA55 40%, #F09741 40%, #F09741 60%, #327AB2 60%, #327AB2 80%, #3A94F6 80%);
    background: -webkit-linear-gradient(90deg, #F6D6A8 20%, #F5BA55 20%, #F5BA55 40%, #F09741 40%, #F09741 60%, #327AB2 60%, #327AB2 80%, #3A94F6 80%);
    background: linear-gradient(90deg, #F6D6A8 20%, #F5BA55 20%, #F5BA55 40%, #F09741 40%, #F09741 60%, #327AB2 60%, #327AB2 80%, #3A94F6 80%);
}

Browser support can be found here.