text:
Q: Why my webform with bootstrap does not look good with class form-inline in phone? I have a webform in ASP.NET with VB.NET, it's made with Bootstrap, but when i put 3 elements (a dropdownlist with selectpicker class, a textbox and a button)in class="form-inline" on PC looks good but in phone no:
Form-inline on PC
But in phone it's look like this:
Form-inline on Phone
Here is my .aspx:

Directorio Telefónico

                <asp:DropDownList ID="ddlBuscar" CssClass="selectpicker" runat="server">
                    <asp:ListItem Value="">Seleccione elemento</asp:ListItem>
                    <asp:ListItem Value="departamento">Departamento</asp:ListItem>
                    <asp:ListItem Value="ubicacion">Ubicación</asp:ListItem>
                    <asp:ListItem Value="extension">Num. extensión</asp:ListItem>
                    <asp:ListItem Value="usuario">Nombre usuario</asp:ListItem>
                    <asp:ListItem Value="apellidop">Apellido p. usuario</asp:ListItem>
                    <asp:ListItem Value="apellidom">Apellido m. usuario</asp:ListItem>
                    <asp:ListItem Value="linea">Tipo de línea</asp:ListItem>
                </asp:DropDownList>

                    <asp:TextBox ID="txtBuscar" placeholder="Ingrese búsqueda" CssClass="form-control " runat="server" ClientIDMode="Static" onkeypress="return EnterEvent(event)"></asp:TextBox>

                <asp:LinkButton ID="loading" CssClass="btn btn-default" runat="server" OnClientClick="waitingDialog.show('Procesando búsqueda, espere...', {onHide: function Carga(){ var objO = document.getElementByid('<%=loading.ClientID %>'); objO.click();}})" Text=" Buscar"></asp:LinkButton>

Thank you for your help

A: Please read the documentation on Bootstrap's inline form:

Add .form-inline to your form (which doesn't have to be a ) for
  left-aligned and inline-block controls. This only applies to forms
  within viewports that are at least 768px wide.

You can add some margin to the form-controls to make them stack nicer on mobile.


text:
Q: Is admin url stored in any table associated with order? I'm wondering if custom admin url is stored in any table associate with orders in database?

A: The only place you can find the admin URL is under core_config_data and this table is not associated with any entity data (including orders).
According to the comment, it seems like the entry you're referring to are coming from an RMA extension.

redpajama_set_name: RedPajamaStackExchange


text:
Q: TypeError: string indices must be integers ? how i can solve it how i can return key and value for this dic?
store_group_details={'app_group3': ['calculater', 'google'],
 'Date': '2022-02-14',
 'Time': '03:00:00',
'group name': 'test1'}

✔ output
app_group3:
 ['calculater', 'google']
Date:
 2022-02-14
Time:
03:00:00
group name:
 test1

A: You can iterate the dict by using .items() method
store_group_details = {'app_group3': ['calculater', 'google'],
                           'Date': '2022-02-14',
                           'Time': '03:00:00',
                           'group name': 'test1'}
for k,v in store_group_details.items():
    print(k, '\n', v)

You may read more here


text:
Q: Making a class in Swift 2 How should I correctly create such a class which can be used from any .swift-file of my project and does not need to be initialized with a variable?
I mean that I want not to have to write something like
someVar = myClass()

in each file where I want this class to be usable. I just want this class to have a global public variables and change them from a .swift-file of my project by doing something like
myClass.myVar = value

I'm thinking about making this class a separate file. What's a correct way to do this?

A: You can create a static property inside a class or struct and call it anywhere. E.g:
//Config.swift
struct Config
{
    static var field1 : String = "Field_Value"
    static var field2 : String = "Field_Value"
}

You can use the property calling StructName.propertyName.
E.g:
//MyCode.swift
print(Config.field1)
Config.field1 = "New Value"

A: You can create a new class, make a variable off that class outside any class.
Class Awesome{
}

let awesomeness = Awesome()

you can than use 'awesomeness' as class instance in every other swift file


text:
Q: Chrome right click option "search google for xxx" become mobile style, how to fix it?
Open any website in chrome, select some words then right click them, then click "search google for 'xxx'"

A: Google added Side search -feature with Chrome v.106. To enable / disable the feature:

*

*Open Chrome, type chrome://flags/ in address bar and press Enter to open the advanced configuration page

*Type side search in the Search flags box

*To enable/disable the Side Search Panel, select Enabled/Disabled from the drop-down box

*Restart the browser with the "Relaunch now" button
If you want to restore default setting in the future, select "Default" option from the drop-down box and restart the browser.
Source

A: Tl;Dr: It's unclear what caused that sidesearch=1 is added to the Google Search results query but apparently this is related to the Side Panel. Updating OS, Chrome and disabling extensions very likely to solve the problem. Alternative: use Chrome flags to disable Side Search. Proceed with caution.

No repro
Chrome version 110.0.5481.110
Google domain: google.com
Language: English US
MacOS Ventura 13.1

I opened the screenshot from the question in a new window in order to be able to examine it in detail. I observed that it includes in the URL the parameter sidesearch=1. Adding this parameter to the URL of a search results page (pre-pending &), the page results style change to the mobile version without showing the side panel.
Without &sidesearch=1 in the URL

With &sidesearch=1 in the URL

I googled for this parameter but I only was able to find a couple of files from Google Git for unit tests. From one of this files:

// Tests to see if `navigated_url` matches `stored_url`. We cannot directly
// compare as the "sidesearch=1" query param may have been appended to the
// `stored_url` to ensure Google serves the side search SRP to the chrome
// client.

Anyway, I don't think that might be possible for me learn anything helpful for end-users, as this problem can't be reproduced under "normal" circunstances nine days after the question was posted, specially without having the complete details.
Other symptoms that might or might not be relevant

*

*A lot of taps open

*The Google domain is google.com.hk.

*It's evident that there are multiple extensions installed

*The page results show mixed language, some texts are in Chinese and other in English.

This problem looks to be part of Side Panel. It is opened when clicking the Side Panel button in the top right of the Chrome window and might be openend by doing other actions, i.e., when the Side Panel is closed, the Chrome address bar will show a button with the Google logo (G):

*

*Clicking this (G) button will open the Side Panel. As mentioned above, you might click the Side Panel button to hide the panel, or by clicking the Close button (X)

*Like in the case reported by the OP, by selecting "Search Google for...". I was not able to reproduce under normal circuntances the behavior reported, even when using a reduced window and Chrome set with a high Zoom in value (> 100%)

In the previous answer it was suggested to use a Chrome flag. It might make sense as a workaround, but I don't think that it is necessary to use the flag as a permanent measure. By the other hand Chrome flags are intended to be used by Chrome developers for testing and for advanced users for troubleshooting. It's discouraged their use by corporate IT departments in production.

Just in case that someone is unfamiliar with the Side Panel:

*

*To hide panel, click the Side Panel button.

*Also you might close the Side Panel by clicking the Close button (X).

Besides the URL / query string parameter there might be other things that might cause that Google shows the mobile view instea of the desktop view like the use of a Chrome extension that changes the user agent.
Resources

*

*Manage Chrome Side panel

*What are Chrome flags?
Related

*

*Prevent tab change on contextual "Search Google for '{selected text}'"

*How can I view the mobile version of a webpage in Google Chrome for Desktop?

*How to remove Google Chrome's Google search engine parameters?

*Desktop Chrome stuck displaying mobile site

*Is there a keyboard shortcut to show/hide the side panel?


text:
Q: Looking for marg_setValue fix in iPhoneOS I am trying to compile a library originally written for Cocoa. Things are good until it looks for the function marg_setValue(). It says there is a syntax error before char in
marg_setValue(argumentList,argumentOffset,char,(char)lua_toboolean(state,luaArgument));

(it's talking about the third argument, not (char) )
I am trying to port LuaObjectiveCBridge to the iPhone. It has two choices, either using Runtime or Foundation. I have discovered there are some problems with foundation so I am trying runtime. But the compiler is not co-operating.

A: Check to see if you can get rid of the marg_XXX macros:

*

*they are deprecated and not considered as reliable.

*marg_list is to be used with objc_msgSendv which is absent from modern runtime.

I suggest to go with NSInvocation. It is pretty simple to use, and powerful enough for a bridge. Check this entry for completeness.

A: The modern Objective-C ABI/API is available on Cocoa Touch.  It lacks some of the legacy features of the 32-bit desktop runtime (namely, ones that were horrendously fragile).
marg_setValue() and friends are a part of that legacy runtime that is not supported in Objective-C 2.0.   It was -- always was -- broken anyway.  You aren't missing much.
The real question is:  What are you trying to do?


text:
Q: Good practice to delete after merge? If deleted, how do I track merging history? My buddy and I are working on a personal project, making branches as we go, and merging them back into master when the feature is done. But merging, and then deleting the branch, makes it a straight line on the log (see picture), which seems bad for keeping track of history. What should we do to work as a team and track history like it shows before a branch is deleted?

A: If you merge a feature branch to master and no other commits were made on master, git defaults to a fast-forward-merge. This means it will not do a real merge but simply forward master to the current commit. This results in the correct content, but causes this usually unwanted linear history.
You usually do git merge --no-ff to avoid fast-forward merges and create an explicit merge commit.
Also have a look at What is wrong with merge commits?.


text:
Q: Insert query refinement - SQL Server I'm working with an ASP.NET MVC3 application and I have a database table for bus journeys which lists them with start and end dates, and the days of operation.  Here is a snippet below:
JourneyID   StartDate   EndDate     Monday  Tuesday Wednesday   etc
676         02 Jan 2012 01 Mar 2012 True    False   True        etc
696         02 Jan 2012 01 Mar 2012 False   False   True        etc
650         02 Jan 2012 25 Mar 2012 True    True    True        etc

So if the date of 2 Jan 2012 is a Monday, and Monday is set to true, then there is a journey on that day.
I'm trying to insert these into a new table row for each day that they run, so that would become:
JourneyID   Date
676         02 Jan 2012
676         04 Jan 2012
696         04 Jan 2012
650         02 Jan 2012
650         03 Jan 2012

The query to do this that is currently on the system is quite slow - it uses nested while loops in t-sql. There was also a version in C# but that was slightly slower - although it did use a similar process (It used the nested loop process, then saved items to be inserted in a generic list, then bulk inserted them)
The process in use currently loops through every journey, and within each journey, loops through every date between the start and end date to check what day it falls on and if that day is set to true. This can take a long time to perform.
Can anyone think of a more efficient way to perform this insert?  It can currently loop through about 100,000 journeys an hour, but there could potentially be millions of journeys so it could take a long time.

A: Effectively you're unpivoting and then filtering.
;with cte as
(
    select JourneyID, StartDate,EndDate,Days
    from yourtable s unpivot (active for days in (Monday, tuesday, wednesday, ...)) u
    where active = 1
)
    select JourneyID, JourneyDate
    from (
        select
            DATEADD(D, number, (Select MIN(startdate) from cte)) as JourneyDate
        from master..spt_values
        where type='p'
        and number < (select datediff(d,MIN(StartDate),max(enddate)) from cte)
    ) numbers
        cross join cte
    where
        days = datename(weekday, JourneyDate)
        and JourneyDatebetween StartDate and EndDate
    order by JourneyDate, JourneyID

A: Create a calendar table and join it. The day of week is a bit trickier cause of your table setup (Boolean monday, tuesday etc.). It would be far easier if you would normalize and extract the days the tour runs to a child table.
With such setup you could write a query like this:
INSERT INTO NewTable (Journey, Date)
SELECT J.JourneyId, C.Date FROM Journey J
INNER JOIN JourneyWeekdays JW ON J.Id = JW.JourneyId
INNER JOIN Calendar C ON (C.Date BETWEEN JT.StartDate AND JT.EndDate) AND C.DayOfWeek = JW.DayOfWeek

With proper indexing this should result in good performance.


text:
Q: Transfer of Data in Specific Rows in Specific Worksheet Need your help and expertise on my problem.
I have a report with vba code that enables it to pull the reports based on the path inputted in "List" sheet. However, it does not read in which exact cell it should be inputted based on the location I dictated.
Expected:
The data that will be inputted in "MasterData" sheet should start at Row 1 since the report has its own header.
The data that will be inputted in "2ndsheet" and "3rdsheet" should start at Row 2 since I will be the one to create the header. This is already correct as it starts at Row 2.
In my my file, "List" sheet, there is the cell location of the reports where to paste it but even if I locate it to the expected cells, the code is not following it.
Below is the vba:
Public strFileName As String
Public currentWB As Workbook
Public dataWB As Workbook
Public strCopyRange As String

Sub GetData()
    Dim strWhereToCopy As String, strStartCellColName As String
    Dim strListSheet As String

strListSheet = "List"

On Error GoTo ErrH
Sheets(strListSheet).Select
Range("B2").Select

'this is the main loop, we will open the files one by one and copy their data into the masterdata sheet
Set currentWB = ActiveWorkbook
Do While ActiveCell.Value <> ""

    strFileName = ActiveCell.Offset(0, 1) & ActiveCell.Value
    strCopyRange = ActiveCell.Offset(0, 2) & ":" & ActiveCell.Offset(0, 3)
    strWhereToCopy = ActiveCell.Offset(0, 4).Value
    strStartCellColName = Mid(ActiveCell.Offset(0, 5), 2, 1)

    Application.Workbooks.Open strFileName, UpdateLinks:=False, ReadOnly:=False
    Set dataWB = ActiveWorkbook

    Range(strCopyRange).Select
    Selection.Copy

    currentWB.Activate
    Sheets(strWhereToCopy).Select
    lastRow = LastRowInOneColumn(strStartCellColName)
    Cells(lastRow + 1, 1).Select

    Selection.PasteSpecial xlPasteAll, xlPasteSpecialOperationNone
    Application.CutCopyMode = False
    dataWB.Close False
    Sheets("List").Select
    ActiveCell.Offset(1, 0).Select

Loop

Exit Sub

ErrH:
    MsgBox "It seems some file was missing. The data copy operation is not complete."
    Exit Sub
End Sub

Public Function LastRowInOneColumn(col)
    Dim lastRow As Long
    With ActiveSheet
    lastRow = .Cells(.Rows.Count, col).End(xlUp).Row
    End With
    LastRowInOneColumn = lastRow
End Function

Please see attached screenshots:
List sheet:

MasterData sheet:

2ndsheet - correct row:

Thanks.


text:
Q: Volume of 4-cube and n-cubes with edge length 3cm What is the volume (I have to clarify this: not the "volume" in the context of a 4-cube but in our everyday life where it is always a cubic unit) of a $4$-cube in $\text{cm}^3$? A 4-cube contains eight $3$-cubes. So it should be $8 * 3\text{cm}^3 = 216\text{cm}^3$. But is this all there is?
And if so, what volume does a $5$-cube have? A 5-cube has besides some $4$-cubes, 40 $3$-cubes, which have $40 * 3\text{cm}^3 = 1080\text{cm}^3$ in total.
Is this the exact volume of a $5$-cube?
Also consider the following thought experiment: You have a $3$-cube and fill it with water. You pour it's content into a $5$-cube. How many times could you do this until the $5$-cube is full?

A: Consider an analogy. A 1-cube is just a segment of length $L\ \textrm{cm}$. The 2-cube, the square, has four 1-cubes for its sides. Does this mean that the area of a square is $4L\ \textrm{cm}?$ No. The perimeter of the square is measured in centimeters, but its area is measured in square centimeters, and has nothing (directly) to do with the 1-cubes that are on its face.
In $n$ dimensions, volume has units $\textrm{cm}^n$. There is potential for confusion because we use the same word -- volume -- to refer to different quantities: just like length and area are not the same thing, 3-dimensional volume and 4-dimensional volume are also unrelated, and you don't calculate the latter by adding up the former. The $n$-cube of side length $L$ has $n$-dimensional volume $L^n\ \textrm{cm}^n$. Notice the units. Adding up the volumes of the $n-1$-cubes gives you the $n-1$-dimensional volume of the $n$-cube's boundary -- you can think of this as surface area -- which is $2nL^{n-1}\ \textrm{cm}^{n-1}.$


text:
Q: Appinventor - finding the launch icon / starting appinventor Could someone explain how to start Appinventor after installing?
I downloaded the file and placed in folder as indicated in the provided instructions but am unable to find the launching icon for the Appinventor editor.
http://appinventor.googlelabs.com/about/

A: You need to sign up for an invitation. That is just the extras folder. Go to the main page, submit your email, and wait.

A: go to beta.appinventor.mit.edu and sign up if you haven't already. Download the setup provided in the 'support'. This download just supports functioning of the blocks editor and emulator (virtual device).
there isn't any icon on your PC, you need to go to the earlier mentioned link and that is your workspace - all on the cloud.
earlier answer from Blaze:
of course they can be placed on the Play Store. Why not?

A: There isn't an icon like say MS Word or Excel. It's based on the web. So you go to http://www.appinventorbeta.com/about/ and log in to your Google Account and start creating an app from there. All your projects are stored on the web, so you can work on them where ever you are.

A: This questions refers to Appinventor version 1 which had to be installed on the client. This version 1 is not available any longer, Version 2 is a web service and requires no installation at all.
The Appinventor main page is here: http://appinventor.mit.edu
and the Application for creating Apps here: http://ai2.appinventor.mit.edu
You only need to register with a Google Account in order to start.
Maybe the whole question should be removed as it is some kind of misleading?

A: Just sign up for a google ID (if you don't already have one) and google it (or go to the more selection under the "More>>" menu)
I believe that the apps made by the AppInventor cannot be places on the Android Market, I know this from personal experience


text:
Q: C# stopwatch Class I'm pretty new to programming so would just like to ask the following question regarding the .net built in stopwatch class using system.diagnostics in C#.
Does it automatically take care of garbage collection each time it is called or would I still have to implement garbage collection?
Regards

A: You never have to implement garbage collection.
You may have to manage resources. For that, check whether a Type implements IDisposable.
And when it does, use the instance in a using() {}block or implement IDisposable on your own class.
But the Stopwatch class is not IDisposable so in this case, no action is required.

A: If you mean with garbage collection the process of tidying up the memory after using variables, methods etc., all .Net languages (and so even C#) take this for you.

A: You never have to implement garbage collection. That's the point if it.
If the class implements IDisposable then you can manage it resource wise with something like
using(MyDisposable myDisposable = new MyDisposable())
{
   myDisposable.DoSomething();
}


text:
Q: for loop to check if a number in array divides all elements in array I'm new to coding, and stack Overflow. I just wanted to see what's the BEST approach to solve this problem.
My approach// run a for loop that assigns the number to a variable if it's dividing all elements. Problem is I can't represent the for loop properly. Is my approach wrong? Would you use a dictionary instead? I just need the approach & maybe the loop. THANK YOU!
the greatest common divisor (GCD), also called highest common factor(HCF) of N numbers is the largest positive integer that divides all numbers without giving a remainder. Write an algorithm to determine the GCD of N positive integers.
func generalizedGCD(num:INT, arr:[Int])->Int

num- an integer representing the number of positive integers(N), arr - list of positive integers
input/ num = 5, arr = [2,4,6,8,10] Output/ 2
input/ num = 5, arr = [2,3,4,5,6] output/ 1

A: A point of attention is that a prime number may enter several times in gcd, hence need for some repeat loops…
let arr = [4, 8, 12] // [2,4,6,8,10]

// 1. build the list of prime numbers (up to 100 is enough to test GCD of numbers upto 10_000). You could also build this list by code.
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

// 2. Find the min in your array. No need to test divisor beyond the min, to speed up
var minimum = arr.min() ?? 1

// 3. Loop through primes to test as divisor or minumum element
var goOn = true
var possibleDivisors : [Int] = []
for prime in primes where minimum > 1 {
    var primeAtPower = 1
    repeat {        // A same prime may be multiple times in gcd. ex: arr = [4, 8, 12]: 2 will appear twice as divisor of 4
        if minimum % prime == 0 {
            primeAtPower *= prime
            minimum /= prime
        } else {
            goOn = false
        }
        goOn = goOn && minimum > 1
    }
    while goOn
    possibleDivisors.append(primeAtPower)
}

var gcd = 1 // Initialize
for divisor in possibleDivisors {
    var possibleDivisor = true
    for val in arr where possibleDivisor {
        if val % divisor != 0 { possibleDivisor = false }
    }
    // 4. If common divisor, gcd includes it
    if possibleDivisor { gcd *= divisor }
}
print("gcd of \(arr) is", gcd)

Yields
gcd of [4, 8, 12] is 4


text:
Q: How can I get back the Tools menu in VS 2010 I was fiddling around with the menu bar via Tools->Customize (the menu bar seems way bloated in this iteration) and accidentally removed the Tools menu itself!
Is there a failsafe to get back into this dialog or otherwise restore the item?

A: If you haven't made any changes to the toolbar that you want to keep, you could try resetting it.
Right click in the toolbar....Customize...Commands...Reset All.


text:
Q: Преобразование списка списков в граф Есть вот такой список (условно 3 на 3, но будет лучше если можно будет увеличить его)
simple_example = [
    [3, 0, 4],
    [5, 7, 1],
    [2, 6, 8]
]

Нужна функция, которая сможет преобразовать такой список в граф следующего вида
Запись такого графа должна выглядеть вот так
graph = {
    3:[{'node':5, 'price':1}, {'node':0, 'price':1}],
    0:[{'node':3, 'price':1}, {'node':7, 'price':1}, {'node':4, 'price':1}],
    4:[{'node':0, 'price':1}, {'node':1, 'price':1}],
    5:[{'node':3, 'price':1}, {'node':7, 'price':1}, {'node':2, 'price':1}],
    # и т.д
}

Функция должна принимать в качестве аргумента нужный нам список списков, а на выходе выдавать граф.
Я попытался найти какие-нибудь закономерности, наложил граф на систему координат, где ось ординат была перевернута (что бы совпадала с индексированием в Python). Вроде что-то есть, но много условностей.

A: Решение в точном соответствии с тем, что вы написали. Если же у вас условие предполагало нечто другое, то, надеюсь, легкую модификацию задачи вам будет сделать самостоятельно не сложно:
simple_example = [
    [1,2,3],
    [4,5,6],
    [7,8,9]
]
simp=np.array(simple_example)
n=simp.shape[0]
graph = {}
def pruff_neighbors(simp,i,j):
    neighbors=[(i-1,j),(i,j-1),(i,j+1),(i+1,j)]
    nodes=[]
    for nb in neighbors:
        if (nb[0]>=0 and nb[1]>=0 and nb[0]<n and nb[1]<n):
            nodes.append(simp[nb[0],nb[1]])
    return nodes
for i in range (n):
       for j in range(n):
           print('j',j)
           nodes=pruff_neighbors(simp,i,j)
           graph[simp[i,j]]=[{'node':nb,'price':1} for nb in nodes]
print (graph)

Результат:
{1: [{'node': 2, 'price': 1}, {'node': 4, 'price': 1}],
 2: [{'node': 1, 'price': 1}, {'node': 3, 'price': 1}, {'node': 5, 'price': 1}],
 3: [{'node': 2, 'price': 1}, {'node': 6, 'price': 1}],
 4: [{'node': 1, 'price': 1}, {'node': 5, 'price': 1}, {'node': 7, 'price': 1}],
 5: [{'node': 2, 'price': 1}, {'node': 4, 'price': 1}, {'node': 6, 'price': 1}{'node': 8, 'price': 1}],
 6: [{'node': 3, 'price': 1}, {'node': 5, 'price': 1}, {'node': 9, 'price': 1}],
 7: [{'node': 4, 'price': 1}, {'node': 8, 'price': 1}],
 8: [{'node': 5, 'price': 1}, {'node': 7, 'price': 1}, {'node': 9, 'price': 1}],
 9: [{'node': 6, 'price': 1}, {'node': 8, 'price': 1}]}


text:
Q: Php file download is putting two lines with a line feed at the top I have a script that receives a parameter then downloads a file to the clients browser. The file is not located in a folder accessible under the docent root
When my script executes pdf's work fine but word docents do not.
I have examined the files with notepad++ with show symbols on and both the pdf's and docs have two lines at the top containing a LF according to notepad++ (looks like adobe reader is more forgiving).
I have checked everything I can think of. I have tried passing the file to trim befor outputting, checked there is no whitespace before opening php tags, tried creating a file as an array looping every element and not echoing the forst two if they contain "\n",
Could this be apache set up issues?
Example Script:
<?php
class TrainingDatabase_IndexController extends Zend_Controller_Action
{

public function downloadAction()
{
            $this->view->layout()->disableLayout();
            $this->_helper->viewRenderer->setNoRender(true);

            // Get filepath and decode it from get param
            $filepath = urldecode( $this->_request->getParam('directory') );

            // Return the basename for save as filename
            $filename = basename($filepath);

            // Set the headers
            header('Content-Disposition: attachment; filename="' . $filename . '"' );
            header('Content-Description: File Transfer');
            header('Content-Transfer-Encoding: binary');
            header('Content-Type: application/octet-stream');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Expires: 0');
            header('Content-Length: '.filesize($filepath));

            // Make sure nothing is left in the browser
            ob_clean();
            flush();

            // Output the file
            readfile($filepath);
   }
}

A: I had checked every file used in the rendering of the page for closing php tags or whitespace before the opening php tags.
However I had not checked the custom Action Helpers I had created. I didn't even think to check this as I wasn't using them in this action.
These action helpers had closing php tags, having removed those it fixed the problem.
Thanks to everyone for your help!
Ronnie


text:
Q: How to make rounded percentages add up to 100% in C# I want to know the percentage increase in the price being rounded off, I have 3 textboxes in winforms :  txtCost_Price, SalesPrice, and txtMarkup.value "txtCost_Price" is = 52500and the value of "SalesPrice" is = 54300result of "txtMarkup" = 3.42857142857143how to make percentage result from txtMarkup not have multiple numbers after comma? I use Indonesian currency.
double CostPrice; double results, SalesPrice;

CostPrice = Convert.ToInt32(C_1_1_txtCost_Price.Text);
SalesPrice = Convert.ToInt32(C_1_3_SalesPrice.Text);
results = (SalesPrice - CostPrice) / CostPrice * 100;

C_1_2_txtMarkup.Text = Convert.ToString(results);


text:
Q: Running single replica Kubernetes service at public IP address and without load balancing I am running a service in GKE/Kubernetes that exposes a single UDP port at a staric IP address. (I've promoted the static IP address from an ephemeral one in GCE.) If I deploy it with fields as follows the service is reachable.
spec:
  type: LoadBalancer
  loadBalancerIP: <static-ip-address>

However, I don't plan to run more than a single replica of my service and I am not even sure if GKE's load balancers work with UDP, hence I'd like to try without one.
The following alternative configuration does not yet work. With it, the service comes up, but at a different IP address and hence not reachable from external as desired.
spec:
  type: NodePort
  externalIPs:
  - <static-IP-address>

So is running an externally visible service at an "own" static IP address without load balancer even possible, and if so how?
UPDATE Further progress indicates that the work balancer also works with UDP, but it still seems redundant.

A: An L3/4 load balancer will take incoming UDP packets and pick a backend to send them to. If you only have one backend, then all of the packets will end up there. Once you have multiple backends, then you will need to understand if the load balancer balances individual packets of packet flows (which are based on the 5-tuple of {source ip, dest ip, source port, dest port, protocol}). You should read this section to understand how GCP's UDP load balancing works.


text:
Q: How can I put arrows and dotted lines within a calendar in TikZ? I'm trying put many arrows-connections and dotted lines between events into calendar/timetable but I have problem with 'draw' statement:
This is a picture of my actual calendar and we see a wrong arrow overlapping lines:

and this is what I want:

This is my script and I tried to draw line between node (a) to (b):
\documentclass[a4paper,11pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{fourier}
\usepackage{tikz}
\usepackage{amssymb, amsmath}
\usepackage{verbatim}
\usepackage[active,tightpage]{preview}

\PreviewEnvironment{tikzpicture}
\setlength\PreviewBorder{5pt}

\usetikzlibrary[positioning]
\usetikzlibrary{patterns}
\usepackage[french]{babel} % styles français

\title{A simple Timetable}
\author{Laurent Dutriaux}
\date{\today}
\newcommand{\daywidth}{2.2 cm}
\begin{document}
\maketitle

\begin{tikzpicture}[x=\daywidth, y=-1cm, node distance=0 cm,outer sep = 0pt]

% Style for Days
\tikzstyle{room}=[draw, rectangle,  minimum height=1cm, minimum width=\daywidth, fill=yellow!20,anchor=south west]

% Style for hours
\tikzstyle{timeslots}=[draw, rectangle, minimum height=1 cm, minimum width=1.5 cm, fill=yellow!30,anchor=north east]

% Styles for events
% Duration of sequences
\tikzstyle{events}=[rectangle,draw, minimum width=\daywidth, anchor=north west,text centered,text width=5 em]

\tikzstyle{1event}=[events,minimum height=1cm]
\tikzstyle{2events}=[events,minimum height=2cm]
\tikzstyle{3event2}=[events,minimum height=3cm]

%Style for type of sequence
\tikzstyle{Ang2h}=[1event,fill=green!20]
\tikzstyle{Phys2h}=[1event,fill=red!20]
\tikzstyle{Math2h}=[1event,fill=blue!20]
\tikzstyle{TIPE2h}=[1event,fill=blue!10]
\tikzstyle{TP2h}=[2events, pattern=north east lines, pattern color=magenta]
\tikzstyle{G3h}=[3event2, pattern=north west lines, pattern color=magenta!60!white]
\tikzstyle{Planche}=[1event,fill=white]

% Positioning labels for days and hours
\node[room] (A) at (1,8) {$r_{1}$};
\node[room] (B) [right = of A] {$r_{2}$};
\node[room] (C) [right = of B] {$r_{3}$};
\node[room] (D) [right = of C] {$r_{4}$};

\node[timeslots] (AA) at (1,8) {$t_{1}$};
\node[timeslots] (BB) [below = of AA] {$t_{2}$};
\node[timeslots] (CC) [below= of BB] {$t_{3}$};
\node[timeslots] (DD) [below = of CC] {$t_{4}$};
\node[timeslots] (EE) [below  = of DD] {$t_{5}$};

%Position of sequences
\node[Phys2h] (a) at (1,8) {$e_{8}$};   %node a
\node[Phys2h] at (1,9) {};
\node[Phys2h] at (1,10) {};
\node[Phys2h] at (1,11) {$e_{16}$};
\node[Phys2h] at (1,12) {};

\node[Math2h] at (2,8) {};
\node[Math2h] (b) at (2,9) {$e_{7}$}; %node b
\node[Math2h] at (2,10) {};
\node[Math2h] at (2,11) {$e_{20}$};
\node[Math2h] at (2,12) {};

%Here my problem.......
\draw [-latex,thick] (a) --  node [anchor=135,outer sep=2pt] { } (b) ;

\node[TIPE2h] at (3,8) {};
\node[TIPE2h] at (3,9) {};
\node[TIPE2h] at (3,10) {$e_{11}$};
\node[TIPE2h] at (3,11) {};
\node[TIPE2h] at (3,12) {};

\node[TIPE2h] at (4,8) {};
\node[TIPE2h] at (4,9) {};
\node[TIPE2h] at (4,10) {};
\node[TIPE2h] at (4,11) {};
\node[TIPE2h] at (4,12) {};

\end{tikzpicture}
\end{document}

Is there an efficient way to connect events through arrows or dotted lines?
regards,

A: Nodes are extended objects. You may connect the centers and shorten the arrows a bit.
\documentclass[a4paper,11pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{fourier}
\usepackage{tikz}
\usepackage{amssymb, amsmath}
\usepackage{verbatim}
\usepackage[active,tightpage]{preview}

\PreviewEnvironment{tikzpicture}
\setlength\PreviewBorder{5pt}

\usetikzlibrary[positioning]
\usetikzlibrary{patterns}
\usepackage[french]{babel} % styles français

\title{A simple Timetable}
\author{Laurent Dutriaux}
\date{\today}
\newcommand{\daywidth}{2.2 cm}
\begin{document}
\maketitle

\begin{tikzpicture}[x=\daywidth, y=-1cm, node distance=0 cm,outer sep = 0pt]

% Style for Days
\tikzstyle{room}=[draw, rectangle,  minimum height=1cm, minimum width=\daywidth, fill=yellow!20,anchor=south west]

% Style for hours
\tikzstyle{timeslots}=[draw, rectangle, minimum height=1 cm, minimum width=1.5 cm, fill=yellow!30,anchor=north east]

% Styles for events
% Duration of sequences
\tikzstyle{events}=[rectangle,draw, minimum width=\daywidth, anchor=north west,text centered,text width=5 em]

\tikzstyle{1event}=[events,minimum height=1cm]
\tikzstyle{2events}=[events,minimum height=2cm]
\tikzstyle{3event2}=[events,minimum height=3cm]

%Style for type of sequence
\tikzstyle{Ang2h}=[1event,fill=green!20]
\tikzstyle{Phys2h}=[1event,fill=red!20]
\tikzstyle{Math2h}=[1event,fill=blue!20]
\tikzstyle{TIPE2h}=[1event,fill=blue!10]
\tikzstyle{TP2h}=[2events, pattern=north east lines, pattern color=magenta]
\tikzstyle{G3h}=[3event2, pattern=north west lines, pattern color=magenta!60!white]
\tikzstyle{Planche}=[1event,fill=white]

% Positioning labels for days and hours
\node[room] (A) at (1,8) {$r_{1}$};
\node[room] (B) [right = of A] {$r_{2}$};
\node[room] (C) [right = of B] {$r_{3}$};
\node[room] (D) [right = of C] {$r_{4}$};

\node[timeslots] (AA) at (1,8) {$t_{1}$};
\node[timeslots] (BB) [below = of AA] {$t_{2}$};
\node[timeslots] (CC) [below= of BB] {$t_{3}$};
\node[timeslots] (DD) [below = of CC] {$t_{4}$};
\node[timeslots] (EE) [below  = of DD] {$t_{5}$};

%Position of sequences
\node[Phys2h] (a) at (1,8) {$e_{8}$};   %node a
\node[Phys2h] at (1,9) {};
\node[Phys2h] at (1,10) {};
\node[Phys2h] (e) at (1,11) {$e_{16}$};
\node[Phys2h] at (1,12) {};

\node[Math2h] at (2,8) {};
\node[Math2h] (b) at (2,9) {$e_{7}$}; %node b
\node[Math2h] at (2,10) {};
\node[Math2h] (c) at (2,11) {$e_{20}$};
\node[Math2h] at (2,12) {};

\node[TIPE2h] at (3,8) {};
\node[TIPE2h] at (3,9) {};
\node[TIPE2h] (d) at (3,10) {$e_{11}$};
\node[TIPE2h] at (3,11) {};
\node[TIPE2h] at (3,12) {};

\node[TIPE2h] at (4,8) {};
\node[TIPE2h] at (4,9) {};
\node[TIPE2h] at (4,10) {};
\node[TIPE2h] at (4,11) {};
\node[TIPE2h] at (4,12) {};

%Arrows
\draw [-latex,thick,shorten >=5pt,shorten <=5pt] (a.center) --  node [anchor=135,outer sep=2pt] { }
(b.center) ;
\draw [-latex,thick,shorten >=5pt,shorten <=5pt] (b.center) --  node [anchor=135,outer sep=2pt] { }
(c.center) ;
\draw [-latex,thick,shorten >=7pt,shorten <=7pt] (c.center) --  node [anchor=135,outer sep=2pt] { }
(e.center) ;
\draw [-latex,thick,shorten >=5pt,shorten <=7pt] (e.center) to[bend right=40]  node [anchor=135,outer sep=2pt] { }
(d.center) ;
% dotted line
\draw[very thick,dotted,shorten >=6pt] (EE.center) -- ++(0,-1.5cm);

\end{tikzpicture}
\end{document}


text:
Q: How to remove from list if only given partial match I have a situation where I want to remove items from a list.  I only have part of the list item, so the typical remove from list isn't working for me since it's not a complete match.
I want to delete all instances of the match, and not just the first match.
I know exactly how many indexes are in the list item; however my search will only contain 3 of the 6 index items.
I'm using Python 3.6
Name of list is DV
This is what I'm trying so far:
c = Brian,Eats,Dinner
if c in DV:
     DV.remove(str(Brian,Eats,Dinner))

Sample of the list:
OrderedDict([('Category', 'Random'), ('Date Added', '03-03-2017'), ('Location', ''), ('Name', 'Brian'), ('Activity', 'Eats'), ('Meal', 'Dinner')])
OrderedDict([('Category', 'Random'), ('Date Added', '03-03-2017'), ('Location', ''), ('Name', 'Joe'), ('Activity', 'Runs'), ('Meal', 'Breakfast')])
OrderedDict([('Category', 'Random'), ('Date Added', '03-03-2017'), ('Location', ''), ('Name', 'Brian'), ('Activity', 'Eats'), ('Meal', 'Dinner')])
OrderedDict([('Category', 'Random'), ('Date Added', '03-03-2017'), ('Location', ''), ('Name', 'Brian'), ('Activity', 'Eats'), ('Meal', 'Dinner')])

This doesn't work, because I don't have the complete part, I think.
If I try it with the complete value, it removes it from the list.  The problem is that I only know for a fact the value of 3 of the items.  The other 3 are irrelevant.
Thanks in advance!

A: You can create a new list containing only those that don't match all of the specified values.
from collections import OrderedDict

data = [
    OrderedDict([('Category', 'Random'), ('Date Added', '03-03-2017'), ('Location', ''),
                 ('Name', 'Brian'), ('Activity', 'Eats'), ('Meal', 'Dinner')]),
    OrderedDict([('Category', 'Random'), ('Date Added', '03-03-2017'), ('Location', ''),
                 ('Name', 'Joe'), ('Activity', 'Runs'), ('Meal', 'Breakfast')]),
    OrderedDict([('Category', 'Random'), ('Date Added', '03-03-2017'), ('Location', ''),
                 ('Name', 'Brian'), ('Activity', 'Eats'), ('Meal', 'Dinner')]),
    OrderedDict([('Category', 'Random'), ('Date Added', '03-03-2017'), ('Location', ''),
                 ('Name', 'Brian'), ('Activity', 'Eats'), ('Meal', 'Dinner')])
]

# tuple of key, value pairs to check
key_values = ('Name', 'Brian'), ('Activity', 'Eats'), ('Meal', 'Dinner')
res = [d for d in data if not all(d.get(k) == v for k, v in key_values)]

If you want to have multiple groups of checks then you can do.
key_values_lst = [
    (('Name', 'Brian'), ('Activity', 'Eats'), ('Meal', 'Dinner')),
    (('Name', 'Joe'), ('Activity', 'Eats'), ('Meal', 'Breakfast'))
]

res = [d for d in data if not any(all(d.get(k) == v for k, v in key_values)
                                  for key_values in key_values_lst)]

You can also trim down the list using the following instead if you will always use the same keys and want to reduce typing if you have lots of groups.
keys = 'Name', 'Activity', 'Meal'
key_values_lst = [
    list(zip(keys, ('Brian', 'Eats', 'Dinner'))),
    list(zip(keys, ('Joe', 'Eats', 'Breakfast')))
]

Output
[OrderedDict([('Category', 'Random'),
              ('Date Added', '03-03-2017'),
              ('Location', ''),
              ('Name', 'Joe'),
              ('Activity', 'Runs'),
              ('Meal', 'Breakfast')])]


text:
Q: QR reader app that interacts with an api I have created a database on a web server where there is a table called USERS and they have a flag whether yes or no, and each user is related to a QR code.
I will create a wifi network between a server and iPhone device.
Is there an iPhone app I can use, when I scan the QR code, it can interact with the database I created to turn the flag to ON? What API I can use for this purpose?

A: Normally, a mobile phone application reading a QR Code will start a browser to open the URL in the QR Code. (Similarly, it will call a phone number or prepare a text message or store a contact code, if the information in the QR Code is encoded correctly for those purposes.)
So, what you (rather simply) can do is make a web application to act on incoming HTTP requests. The QR Codes related to your users should contain the URL to that application, and it also contains some ID for the user. Once your application registers an incoming request with a valid ID, you update your database record.


text:
Q: Implementation details of Windows Performance Counters I am new to Windows performance counters. I am working on a project that uses custom performance counters. I want to understand how windows performance counters are actually implemented. I am looking for answers to the following questions.

*

*What happens to performance counter values when machine restarts?

*When would one set raw values for performance counters?

*Do these counters ever overflow?

thanks,
Imran

A: Performance counter is not like a counter for numbers and it doesn't grow infinitely and cannot overflow. This is the answer for the third question.
Performance counter is a metric bound to the time. For example, it could be number of bytes sent or received in every moment of time, or hard drive throughput. Or number of active sessions in the database or the operating system itself. You can win+R -> perfmon, then click system monitor in the tree at left and then click green 'plus' button to get the list of the all counters found in your system.
I don't think that this is possible or at least could be needed to provide the data when the machine is powered off, but after restart, the performance data generation would be restored. This is for the first question.
And the answer to the second question: when you have something which provides some new sort of performace data, you need to provide data for it. Here is the link to the documentation for the process of producing the data: https://msdn.microsoft.com/ru-ru/library/windows/desktop/aa373165(v=vs.85).aspx


text:
Q: Can the equivalence of electric and magnetic fields be demonstrated using just two charged particles rather than a particle and wire? The equivalence of the electric and magnetic fields can be demonstrated by considering a current flowing in a wire and a test charge moving relative to the wire. In the frame of reference where the wire is stationary and the charge is moving there is a magnetic force applied to the test charge due to the magnetic field created by the wire. If you then consider a reference frame in which the test charge is not moving then there is no magnetic force, however the length contraction of the charges in the wire produces a net electric field that creates an equivalent electric force on the charged particle in this reference frame.
I can understand this mathematical derivation, but in another scenario where the current carrying wire is replaced by a single moving charge, this equivalence appears to breakdown. If you start with a frame of reference where one of the charges is moving to the left and the other charge is moving to the right, at the point where they pass each other they will be attracted by a magnetic field in addition to the electric field. Now if you take another reference where one of the charges is stationary and the other is moving left at twice the speed, there is no longer a magnetic force of attraction by either particle. But in this case the length contraction of the single charge does not increase the electric field to compensate, as it does with the concentration of charges in the wire.
So in this scenario how can you derive the same equivalence?


text:
Q: Vertex Color to UV Map -> Remesh -> Texture mapping I have a polygon mesh of a room in high resolution, and I want to extract vertices color information and map them as a UV map, so I can generate a texture atlas of the room.
After that, I want to remesh the model in order to reduce the number of polygons and map the hi-res texture onto the new mesh in lower resolution.
So far I've found this link to do it in Blender, but I would like to do it programmatically. Do you know about any library/code that could help my in my task?
I guess first of all I have to segment the model (normals criterion could be helpful) and then cut each mesh segment, so only then I am able to parameterize it. About parameterization, LSCM seems to provide good results for simple models. Once having available the texture atlas, I think the problem becomes a simple task of texture mapping.
My main problem is segmentation and mesh cutting. I'm using CGAL library for that purpose, but the algorithm is too simple to cut complex shapes. Any hint about a better segmentation/cutting algorithm that performs well for room-sized models?
EDIT:
The mesh consists in a room reconstructed with a RGB-D camera, with 2.5 million vertices and 4.7 million faces. The point is to extract high resolution texture, remesh the model to reduce number of polygons and then remap the texture onto it. It's not a closed mesh, and there are holes due to reconstruction, so I'm guessing if my task is not possible to accomplish at all.
I attach a capture of the mesh.

A: I would suggest using the following 4-steps procedure:

*

*Step 1: remesh
For this type of mesh that comes from computer vision, you need a remesher that is robust to holes, overlaps, skinny triangles etc... You can use my GEOGRAM software [1]. Use the following command:
vorpalite my_input.obj my_output.obj pre=false post=false pts=30000

where 30000 is the number of desired points (adapt it to the complexity of your input). Note: I am deactivating pre and post-processing (pre=false post=false) that may remove too much parts of the mesh for this type of mesh.

*

*Step 2: segment the remesh
My favourite method is "Variational Shape Approximation" [3]. I like it because it is simple to implement and gives reasonable results in most cases.

*

*Step 3: parameterize
Besides my LSCM method, you may use ABF++ that we developed after [4], that gives much better results in most cases. You may also try ARAP [5].

*

*Step 4: bake the texture
Once the simplified mesh is parameterized, you need to copy the colors from the original mesh onto the new one. This means determining for each pixel of the texture where it goes in 3D, and finding the nearest point in the original 3D mesh.
Segmentation, parameterization and baking are implemented in my Graphite software [2] (use the old version 2.x, the newer version 3.x does not have all the texturing functionalities).
[1] geogram: http://alice.loria.fr/software/geogram/doc/html/index.html
[2] graphite: http://alice.loria.fr/software/graphite/doc/html/
[3] Variational Shape Approximation (Cohen-Steiner, Alliez, Desbrun, SIGGRAPH 2004):  http://www.geometry.caltech.edu/pubs/CAD04.pdf
[4] ABF++: http://alice.loria.fr/index.php/publications.html?redirect=1&Paper=ABF_plus_plus@2004
[5] ARAP: cs.harvard.edu/~sjg/papers/arap.pdf

A: For reducing the number of polygons, I prefer using mesh decimation. My recommended workflow: (Input: High resolution mesh(mesh0) with vertex color).

*

*Compute uv coordinates for mesh0.

*Generate texture image(textureImage) by vertex color. Thus, you have a texture mesh(mesh0 with uv coordinates, textureImage).

*Apply mesh decimation to mesh0, and the decimation should take uv coorindates into consideration.

I have an example about this workflow in my site, the example image: Decimation of texture mesh .
Or you can refer my site for details.


text:
Q: Format string with updated integer values to display with textbox as columns if I have string with updated integer values with 8 digits maximum:
 string Str = ("A1: [ " + int1 + " ] A2: [ " + int2  + " ]" +
           "\r\nA3: [ " + int3 + " ] A4: [ " + int4  + " ]" +
           "\r\nB1: [ " + int5 + " ] B2: [ " + int6  + " ]" +
           "\r\nB3: [ " + int7 + " ] B4: [ " + int2  + " ]\r\n");

which is:
  A1: [ 126.453 ] A2: [ 8.940 ]
  A3: [ 11.3 ] A4: [ 122.4 ]
  B1: [ 6566.2 ] B2: [ 3444.76 ]
  B3: [ 6.562 ] B4: [ 34.76 ]

How can I format it for iterations display with textbox output side by side as columns with corresponding spacing between part with count integer size:
  A1: [ 126.453 ] A2: [ 348656.2 ]    B1: [ 35.7 ] B2: [ 65.1 ]
  A3: [ 8.90 ] A4: [ 34.76 ]          B3: [ 3.97770 ] B4: [ 87700.67 ]

I found several ways, but not really sure how to use it for this case, how to figure out with updated numbers and assign my string to integer length this way:
    int pd = 3;
    int mx1 = "Hello World!".Length;
    int mx2 = "1234.56732".Length;
    int mx3 = "Name".Length;

    string f0 = "{0,-" + (mx1 + pd) + "}";
    string f1 = "{1,-" + (mx2 + pd) + "}";
    string f2 = "{2,-" + (mx3 + pd) + "}";

    string f = f0 + f1 + f2;

    Console.WriteLine(f, "Hello World!", 1234.56732, "Month");
    Console.WriteLine(f, "How are you?", 78.44, "Day");
    Console.WriteLine(f, "Hi", 2311.654, "Year");

It would be good to hear some useful advice

A: You could use String.PadRight() method to align values:
var nums = new List<double>() {
    126.453, 8.94, 11.3, 122.4, 6566.2, 3444.76, 6.562, 34.76
};

var maxLen = nums.Select(n => n.ToString().Length).Max();
var strVals = nums.Select(n => n.ToString().PadRight(maxLen)).ToList();

textBox1.Font = new Font(FontFamily.GenericMonospace, 10);
var pos = 0;
foreach (var strVal in strVals)
    //Debug.Write($"NUM{++pos}: [ {strVal} ]    {(pos % 2 == 0 ? "\r\n" : "")}");
    textBox1.Text += $"NUM{++pos}: [ {strVal} ]    {(pos % 2 == 0 ? "\r\n" : "")}";

Output:
NUM1: [ 126,453 ]    NUM2: [ 8,94    ]
NUM3: [ 11,3    ]    NUM4: [ 122,4   ]
NUM5: [ 6566,2  ]    NUM6: [ 3444,76 ]
NUM7: [ 6,562   ]    NUM8: [ 34,76   ]


text:
Q: Loading SQL Server driver via RJDBC on Ubuntu RStudio Server throws Error in .jfield("java/lang/Integer", "Ljava/lang/Class;", "TYPE") rJava and RJDBC load without error on this Ubuntu (Azure Data Science image) installation of RStudio Server:
dyn.load('/usr/lib/jvm/java-11-openjdk-amd64/lib/server/libjvm.so')
library(rJava)
require(RJDBC)
Loading required package: RJDBC
Loading required package: DBI

However, when I go to load the MS SQL Server driver it throws this error:
drv  <- RJDBC::JDBC("com.microsoft.sqlserver.jdbc.SQLServerDriver")
Error in .jfield("java/lang/Integer", "Ljava/lang/Class;", "TYPE") :
  cannot find class java/lang/Integer

Re-running it or trying to proceed to make a JDBC connection seems to result in RStudio Server throwing an "error in transmission" pop-up and restarting the R session.
When I search on the error message I find Java language threads pertaining to Int vs Integer though in this case I wonder if it's to do with the rJava installation, which was simple for the server's terminal installation of R but which took extra work to get rJava to load with RStudio Server (updating environment variables, the $PATH and using dyn.load)...


text:
Q: How to return a Fractional expression in JAVA I am making a fraction calculator in JAVA that keeps inputting a fraction and then an operator and then the next fraction and so on. I've successfully made this thing work for matrices and integers but can't make a function to input fraction so that I can call that function from the loop every time a new fraction has to be inputted.
This is how its working for now but I want the inputting fraction part to be another function so that the function could be used for various occasions .
System.out.println("Enter Numerator 1");
num1=Integer.parseInt(sc.readLine());

System.out.println("Enter Denominator 1");
den1=Integer.parseInt(sc.readLine());

System.out.println("Enter Numerator 2");
num2=Integer.parseInt(sc.readLine());

System.out.println("Enter Denominator 2");
den2=Integer.parseInt(sc.readLine());

A: Here is an example of a Fraction class that can prompt user for a new fraction.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Fraction {
    private final int nom;
    private final int den;
    public Fraction(int nom, int den) {
        if (den <= 0)
            throw new IllegalArgumentException("Invalid denominator: " + den);
        this.nom = nom;
        this.den = den;
    }
    public int getNom() {
        return this.nom;
    }
    public int getDen() {
        return this.den;
    }
    @Override
    public String toString() {
        return (this.den == 1 ? String.valueOf(this.nom) : this.nom + "/" + this.den);
    }

    public static Fraction prompt(Scanner sc, String message) {
        Pattern p = Pattern.compile("\\s*(?:(?:(\\d+)\\s+)?(\\d+)/)?(\\d+)\\s*");
        for (;;) {
            System.out.print(message + ": ");
            String line = sc.nextLine();
            Matcher m = p.matcher(line);
            if (m.matches()) {
                if (m.start(2) == -1)
                    return new Fraction(Integer.parseInt(m.group(3)), 1); // whole number
                int nom = Integer.parseInt(m.group(2));
                int den = Integer.parseInt(m.group(3));
                if (m.start(1) != -1)
                    nom += Integer.parseInt(m.group(1)) * den;
                return new Fraction(nom, den);
            }
            System.out.println("** Not a valid fraction. Please enter values like 2/3 or 4 3/7 or 13");
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        for (;;) {
            Fraction fraction = Fraction.prompt(sc, "Enter value");
            if (fraction.getNom() == 0)
                break;
            System.out.println("You entered: " + fraction);
        }
    }
}


text:
Q: JUnit test case to check if file was created I have created a simple program that wil create the dat file through buffered writer and will write some data into that file  , now please advise what junit test cases I can have through which  I can check whether the file is created or not in c: drive , I am using junit 3 , please advise.

A: File file = new File("c:/pathOfTheCreatedFile");
assertTrue(file.exists());
// TODO: read the file. Check that it contains what it's supposed to contain


text:
Q: data is not transferred to the Angular component I use my-table Angular component from the AngularJS code:
// AngularJS code
// src/template/expanded-table.html

...

      <my-table ng-if="tableLoadedSuccess"
                [model]="tableModel"
                [dataSource]="data">
      </my-table>

...

In the Controller I have:
// AngularJS code
// src/js/modules/ExpandedTableController.js

function ExpandedTableController(
    trailsService,
    ...
) {
...
   var searchTrails = function() {
        let settings = $scope.persistState.trails.trailsExpandedTableSettings;
        trailsService
            .getTrailEvents(settings, $scope.filterParam)
            .then(function(resp) {
                $scope.data = [1,2,3]; // just to test with this simple array
                $scope.tableLoadedSuccess = true;
            });
    };
...
    _.extend($scope, {
        ...
        tableLoadedSuccess: false,
        data: [],
        tableModel: new EventTableModel(trailsExpandedTableSettings),
        ...
    });

    ...
    searchTrails();
    ...

TableComponent:
// Angular code
// src/ts/app/shared/components/table/table.component.ts

...
export class TableComponent<T> implements OnInit {
   @Input() dataSource: T[];
   ...
   ngOnInit() {
        console.log('Table component dataSource: ' + this.dataSource);
   }
   ...

For some reason, I have undefined in this.dataSource in the code above.

UPDATED: I tried to wrap $scope.tableLoadedSuccess = truein timeout in case if the data might not be retrieved yet when hitting ngOnInit lifecycle hook:
// AngularJS code
// src/js/modules/ExpandedTableController.js

...
trailsService
            .getTrailEvents(settings, $scope.filterParam)
            .then(function(resp) {
                $scope.data = [1, 2, 3];
                $timeout(function () {
                    if ($scope.tableLoadedSuccess) {
                        $scope.tableLoadedSuccess = true;
                        $scope.$apply();
                    }
                }, 50000);
            });
...

I got dataSource as undefined, but TableComponent is rendered after some time (50000).

A: I have found a solution. I need to pass data to the component without camel case, but with a dash (like this [data-source]="data"):
// AngularJS code
// src/template/expanded-table.html

...

      <my-table ng-if="tableLoadedSuccess"
                [model]="tableModel"
                [data-source]="data">
      </my-table>

...


text:
Q: why can't I import geopandas? My only line of code is
import geopandas

and it gives me the error
OSError: Could not find libspatialindex_c library file

has anyone encountered this before? my script was working just fine until this error came up.
**Note that rtree module not found was an issue fisrt, and upon installation I received the above error instead.

A: Linux installation steps for Docker users:
RUN apt-get update
RUN apt-get install -y --fix-missing curl autoconf libtool automake
RUN curl -L https://github.com/libspatialindex/libspatialindex/archive/1.8.5.tar.gz | tar -xz
RUN cd libspatialindex-1.8.5 && ./autogen.sh && ./configure && make && make install && ldconfig

A: I had the same issue while working in Linux Subsystem at Windows 10 (speaking about this). What helped was installing the version for developers using apt. Namely:
sudo apt install libspatialindex-dev did the job.
I did not need to work with make.
edit: Nice to see my answer has been upvoted so many times; in the time of writing it, however, this was not the most popular answer and it was preceeded by the other answers that suggested using make. This is why I am referring to this command; and I think the other answers are worth reading anyway.

A: If you are using MacOS, it's as simple as follow:
brew install spatialindex
pip install rtree

If you are working on linux environment you have to build this from source:

*

*Install spatialindex

curl -L https://github.com/libspatialindex/libspatialindex/archive/1.8.5.tar.gz | tar xz
cd libspatialindex-1.8.5/
./autogen.sh
./configure
make
sudo make install
sudo ldconfig

*install rtree:  pip install rtree

A: User DYZ provided the correct answer in the comments.

You need to install spatialindex.

This question should be set to answered so it is not misleading


text:
Q: Pattern matching in AWK I have following requirement. I want to skip first and last lines in file. And in all other lines, have to check for space in first two characters. For this I am replacing spaces with some characters and extracting the first characters. I should compare them with # and throw some error if it matches
AWK 'NR>2 {gsub(/\ /,"#",prev);}{print substr(prev,1,2)}{prev=$0}' input file

With this I am able to replace and extract, but not able to compare the substring with ##. Please help

A: no need to substitute and test the substitute, instead you can do this
$ awk 'p~/^  /{exit 1} NR>1{p=$0}' file

delayed computation will skip the last record, to skip the first record condition on NR>1, if a record starts with two spaces exit with error code, otherwise it will exit with success (default).


text:
Q: Which method will be called when UITabelViewCell is no more appear in UItableView Suppose there are 20 items to display in UITableView. At a time 5 UITableViewCell  are visible. I am adding observer in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPathmethod. Now if user scrolls the table then suppose first row is not visible. So my quesion is how can I remove the observer? Any method will be called when UITableViewCell is no more visible in UITableView?
Any help will be appreciated..

A: Here, here and here you can find the solutions for your problem.
You should use below UITableViewDelegate method:
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath


text:
Q: Load balancing for performance We have a SQL Server 2005 Standart server with two databases which are used by tons of applications. The server seems to slow down at certain times of day due to high traffic. We're certainly going to scale up but we also have a few Compaq Proliant servers lying around doing nothing and I thought maybe we should scale out instead. At first I thought of dividing the two databases into separate servers but they each have tables that the other depends on so we fear that it could be slow when we separate them. Could you please give me any suggestions about scaling out for having a faster running database system?

A:
Could you please give me any
  suggestions about scaling out for
  having a faster running database
  system?

No. Not possible. Simple like that. In general. Basically buy faster hardware or optimize your code.

A: It is not easy to give advice based on such a tiny description, and usually scaling is to be thought through early, from design time.
However, you may want to look in some specific areas - that may or may not fit your systems topology and design. Sorry if some items are pretty obvious, but, again, it is hard to provide targeted and relevant advices from just a small description.

*

*Indexes: developers sometimes create queries that DB admins are not aware of, and indexes are missing. Usually the cost is exponential, being sometimes barely noticeable for several months (depending on how your DBs grow).

*DB server configuration tuning. A lot is to be found on the net, and extending memory for indexes, for this or that may sometimes change your server life. Adding memory? Is your server swapping?

*Where is the bottleneck? Is it really the DB server itself, not the bandwidth? Don't you have other processes on the same server that eat resources?
Scaling
Regarding the scaling, it depends actually how your two databases are linked, and how much cost it would take for the developers to use the tables from two different servers. If, fortunately, you can give it a try, ensure the two DB servers can communicate efficiently, via a 1Gb link for instance.


text:
Q: No of monthly days between two dates diff(seq(as.Date("2016-12-21"), as.Date("2017-04-05"), by="month"))
Time differences in days
[1] 31 31 28

The above code generates no of days in the month Dec, Jan and Feb.
However, my requirement is as follows
#Results that I need
#monthly days from date 2016-12-21 to 2017-04-05
11, 31, 28, 31, 5
#i.e 11 days of Dec, 31 of Jan, 28 of Feb, 31 of Mar and 5 days of Apr.

I even tried days_in_month from lubridate but not able to achieve the result
library(lubridate)
days_in_month(c(as.Date("2016-12-21"), as.Date("2017-04-05")))
Dec Apr
 31  30

A: Try this:
x = rle(format(seq(as.Date("2016-12-21"), as.Date("2017-04-05"), by=1), '%b'))

> setNames(x$lengths, x$values)
# Dec Jan Feb Mar Apr
#  11  31  28  31   5

A: Although we have seen a clever replacement of table by rle and a pure table solution, I want to add two approaches using grouping. All approaches have in common that they create a sequence of days between the two given dates and aggregate by month but in different ways.
aggregate()
This one uses base R:
# create sequence of days
days <- seq(as.Date("2016-12-21"), as.Date("2017-04-05"), by = 1)
# aggregate by month
aggregate(days, list(month = format(days, "%b")), length)
#  month  x
#1   Apr  5
#2   Dez 11
#3   Feb 28
#4   Jan 31
#5   Mrz 31

Unfortunately, the months are ordered alphabetically as it happened with the simple table() approach. In these situations, I do prefer the  ISO8601 way of unambiguously naming the months:
aggregate(days, list(month = format(days, "%Y-%m")), length)
#    month  x
#1 2016-12 11
#2 2017-01 31
#3 2017-02 28
#4 2017-03 31
#5 2017-04  5

data.table
Now that I've got used to the data.table syntax, this is my preferred approach:
library(data.table)
data.table(days)[, .N, .(month = format(days, "%b"))]
#   month  N
#1:   Dez 11
#2:   Jan 31
#3:   Feb 28
#4:   Mrz 31
#5:   Apr  5

The order of months is kept as they have appeared in the input vector.


text:
Q: ssh-agent: How to keep the login key, and add more identities? When I log in to my local Ubuntu 14 instance from Windows (I use SecureCRT as a SSH client) using my RSA key, the key is available for forwarding for further SSH sessions (it is listed with ssh-add -l). However, I can't add more identities to the default agent:
# ssh-add -l
2047 29:c7:24:ca:ee:21:c8:1c:8e:31:7b:60:d9:45:45:df "rsa-vwal-20160112" (RSA)
# ps aux | grep ssh-agent
ville      3102  0.0  0.1  12968  2280 pts/3    S+   02:13   0:00 grep --color=auto ssh-agent
# env | grep SSH
SSH_CLIENT=192.168.50.101 30920 22
SSH_CONNECTION=192.168.50.101 30920 192.168.220.20 22
SSH_TTY=/dev/pts/3
SSH_AUTH_SOCK=/tmp/ssh-UVKqhSow2l/agent.2679
# ssh-add /home/ville/.ssh/keys/gitkey/gitkey
Enter passphrase for /home/ville/.ssh/keys/gitkey/gitkey:
SSH_AGENT_FAILURE
Could not add identity: /home/ville/.ssh/keys/gitkey/gitkey
#

I assume this is because there is no real ssh-agent process; apparently the initial agent is provided by sshd(?)
Now if I start a new agent and apply the environment variables it generates so that the SSH_AUTH_SOCK changes, I can add identities to the agent...
# ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-G8dg8bePFC8K/agent.3115; export SSH_AUTH_SOCK;
SSH_AGENT_PID=3116; export SSH_AGENT_PID;
echo Agent pid 3116;
# SSH_AUTH_SOCK=/tmp/ssh-G8dg8bePFC8K/agent.3115; export SSH_AUTH_SOCK;
# SSH_AGENT_PID=3116; export SSH_AGENT_PID;
# ps aux | grep ssh-agent
ville      3116  0.0  0.0  10628   320 ?        Ss   02:16   0:00 ssh-agent
ville      3128  0.0  0.1  12968  2120 pts/3    S+   02:20   0:00 grep --color=auto ssh-agent
# ssh-add -l
The agent has no identities.
# ssh-add /home/ville/.ssh/keys/gitkey/gitkey
Enter passphrase for /home/ville/.ssh/keys/gitkey/gitkey:
Identity added: /home/ville/.ssh/keys/gitkey/gitkey (/home/ville/.ssh/keys/gitkey/gitkey)
# ssh-add -l
2048 05:9c:bc:b5:cd:e4:4e:a1:53:60:57:b4:39:e4:18:d5 /home/ville/.ssh/keys/gitkey/gitkey (RSA)
#

... but obviously the initial key is no longer available because the agent is now different.
My question is: Is it possible to retain the login key in the agent, AND be able to add more identities to it with ssh-add? Can I, for example, make the initial agent accept additional identities to it, or perhaps somehow duplicate the login key into the explicitly instantiated agent?

A: It is not a problem of ssh-agent, but of your Windows client (providing ssh-agent interface). It looks like it does not implement interface to add another key from the socket. This should not be a problem with normal ssh-agent.
Only possible solution today, I know about is to copy the key to your local host.
There is open upstream openssh bug (client changes) requesting similar functionality (support for the list of agents), which should solve your issue.


text:
Q: getLocationOnScreen() in onCreate() just returns zeroes Calling getLocationOnScreen() on an ImageView (or other View) in a response to a button click gives correct values.
But when calling getLocationOnScreen() from Activity::onCreate(), I only get [0, 0]. How can I fix this?
Is onCreate() too early for all calculations to be done? Is there a later better place to hook to start animations?

A: It's too early to check for getLocationOnScreen() in onCreate(). The better place is at view level (if you are using custom views), is at onLayout(). Only here, the view's size and position are calculated. In case, you aren't creating custom views, you could obtain it in activity level at onWindowFocusChanged() (with the activity having the focus).


text:
Q: Sending data from C process to Python process using pipes I'm trying to send data from a C program to a python program (both are running simultaneously). I'm attempting to use the popen function in C. The way I understand it, whatever I write to the file descriptor in C can be read from stdin in the python program. However, the python program appears to hang at the point where it reads from stdin. Any suggestions?
Here's the C program:
test.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(void) {

    FILE * fp = popen("sudo python display.py", "w");
    if (fp == NULL) {
        printf("popen error\n");
        exit(1);
    }

    int inc = 0;
    char buf[10];

    while(1) {
        sprintf(buf, "%d", inc);
        fputs(buf, fp);
        inc++;
        sleep(1);
    }

    return (0);
}

Here is the python program, which should read the value of "inc" and output it
display.py
import sys

value = 0

while(True):
    value = sys.stdin.read()
    print value

The program seems to hang at value = sys.stdin.read(). I have tried readline() and readlines() as well with the same result.

A: readline() would work if you were outputting lines from your C program.
Since you never print a newline, readline will wait forever.
read() with no parameters will wait until the C program exits (or otherwise closes stdout). Again this is never going to happen with your program

A: You rather should use fprintf(3) instead of mixing sprintf (which is unsafe, prefer snprintf(3)) with fputs.
You really want to output whole lines (because textual protocols are so convenient to debug). And use readline on the Python side.
At last, a FILE* obtained by popen(3) is not even guaranteed to be line-buffered (but could have a much larger buffer, perhaps 4Kbytes or more). You might set its buffer using setvbuf(3) but you really should flush explicitly the FILE* buffer with fflush(3). If you don't, the output could stay in the buffer for a long time (without any actual  write(2) done by stdio functions like fprintf or fputs) so the pipe(7) stays empty.
(so you have problems even on the C side)

The program seems to hang at value = sys.stdin.read().

I guess that not a single byte was actually written by your C code (you could check by using strace(1)) because your fputs stayed in the buffer. You might need to wait a long time (perhaps 1000 seconds, to fill a buffer of a few kilobytes) to have it actually write something on the pipe, because you forgot the fflush .
A popen-ed file should absolutely be pclosed.
So you should replace your (incorrect) while loop with:
while(1) {
    fprintf(fp, "%d\n", inc);
    inc++;
    fflush(fp);
    sleep(1);
}

And your loop should be exited somehow. Perhaps you might catch some signal(7) -probably SIGTERM- (but be sure to read signal-safety(7)). Be sure to pclose (to avoid zombie processes).
(I am assuming you are on Linux or some other POSIX system)


text:
Q: Get h3 text value in lightbox title var heading = $("#accordion h3").text();
 if(heading != ''){
$('h2.title').text(heading);
 }

I have list items with h3 as title and onclick(h3) lightbox gets open. I want to replace Lightbox title with text of respective Clicked h3. I have code but ALL h3 text gets added to title div.


text:
Q: Compress PDF after manipulation I have the following problem:
I am receiving various scanned PDF files from a Kyocera Scanner Device.
I have to automatically manipulate these PDF Files in order to:

*

*Delete the colors from textmarkers

*Convert the PDF to grayscale

*Put it in our DMS

I am using a Bash-Script to do the job.
For deleting the textmarker colors and converting to grayscale I use Imagemagick:
convert -density 150 INPUT.pdf \
-channel rgba \
-alpha set \
-fuzz 15% \
-fill white \
-opaque 'rgb(255,200,195)' \
-opaque 'rgb(255,253,177)' \
-opaque 'rgb(255,155,240)' \
-opaque 'rgb(255,91,193)' \
-colorspace gray OUTPUT-convert.pdf

The resulting image is quite good, BUT the size of the PDF is huge:
Original: 365K
Converted: 1.358K
So I've found a ghostscript command to do the job and reduce the file size:
gs -dSAFER -dBATCH -dNOPAUSE -dNOCACHE -dCompatibilityLevel=1.4 \
-sDEVICE=pdfwrite   \
-sColorConversionStrategy=/LeaveColorUnchanged \
-dPDFSETTINGS=/ebook \
-sOutputFile=OUTPUT-ghostscript.pdf OUTPUT-convert.pdf

Now the file sizes are:
Original: 365K
Converted: 1.358K (OUTPUT-convert.pdf)
Ghostscript: 500K (OUTPUT-ghostscript.pdf)
I can't figure out why the size of the PDF after manipulation, from color to grayscale, is higher then the original document. The density (150 dpi) is the resolution of the original document.
When I put the converted PDF (1.358K) through Adobe Acrobat on Windows and recreate the PDF, the size is 213K. I have no loss in quality. How can I achieve this under linux with a bash script?
Any help is appreciated!
Here is a link for example PDF Files:
http://62.75.158.162/download/yKLu3fkbLy7MgkczDrKdG6osHdXh3jvy/

A: Its not really possible to comment very much without seeing an example file, to determine exactly what has happened at each stage.
However, I very strongly suspect that you have 'lost quality', its just that, at screen resolutions, you can't tell. Your original PDF file was created using ImageMagick at a resolution of 150 dpi. Most probably the image is stored uncompressed in the PDF file, which is why its large.
When you run that PDF file back through Ghostscript there are two effects. Firstly you've used the PDFSETTINGS canned set of job configuration. That (amongst many other things) downsamples grey images to a resolution of 150 dpi (so fortunately for you, no effect). It also compresses the image data using JPEG compression.
Now I've no idea what's in the original PDF file, but if the data there was compressed using JPEG, as seems likely, then you are double applying JPEG quantisation. That's a lossy process and will result in a loss of quality.
Since you are altering the original image data (to change the colour) you have no choice about decompressing the image data. However, to preserve quality you should then not use JPEG compression again, instead you should use Flate compression. The compression ration won't be as good, but it will keep the quality unchanged. To do that you would need to specify the GrayImageFilter using distillerparams, you can't use a PDFSETTINGS for that.
I can't imagine what Acrobat has done to decrease the file size still further (and you haven't said how you 'recreate the PDF file'), but I would imagine it involves reducing the quality of the image still further. Its hard to see how it could save 50% of the file size without doing so. Its also possible it is (like Ghostscript) JPEG compressing the grayscale data but using a more aggressive set of JPEG parameters (resulting in still more loss of quality, of course).
If you posted examples of the original, Ghostscript output, and Acrobat output I might be able to tell you more, but not from this.
For what its worth, there's a new feature in Ghostscript (requires version 9.23 or better) which allows you to create a PDF file which consists only of an image, and choose the colour model. You could run the original PDF file through Ghostscript using something like:
gs -sDEVICE=pdfimage8 -r150 -sOutputFile=gs.pdf
which would produce a pretty minimal PDF file where the original input has been rendered to a gray scale image (at 150 dpi), and that image wrapped up as a PDF file. I've no idea if that might work better for you.
Later EDIT
Yep, its pretty much what I expected.
The original file has what appears to be marked JPEG compression artefacts (all the rectangular 'speckles' round the text). Obviously without seeing the original document I can't tell whether this is because the original document was a JPEG printed to paper, or whether the artefacts were introduced by the scanner, or (more likely) whatever application converted the scanned image into a PDF. Checking the image stored in the PDF file I see that it is indeed a JPEG image.
Nevertheless, the original image is (in my opinion) really very noisy.
Now the output from 'convert' is arguably slightly better (in terms of legibility) than the original. I presume this is 'something' to do with your convert command line, can't be sure. The image in this case is not a JPEG, its compressed with RunLength encoding which is of course lossless. Its also less efficient as a compression method, so the image is bigger. For reasons best known to ImageMagick it also applies a soft mask to the image data. So that's two images per page now instead of just 1. Not too surprising that its larger than the original!
I suspect that the soft mask is due to your command line including RGBA. I assume that produces an alpha channel, and PDF doens't support simple alpha channel blending, its own transparency model is much more sophisticated. So I sort of suspect you are actually making the output file here larger than it needs to be. I'm afraid I can't help you with ImageMagick, I don't know anything about it, but getting rid of that second image would help a great deal.
Note that both your original file and the output from ImageMagick are essentially uncompressed (in terms of the PDF file 'structure').
Then we come to the Ghostscript produced PDF. The 'structure' of the PDF file is itself compressed, giving small size benefits. The images are all JPEG compressed, giving additional compression, but at the cost of quality. Applying JPEG quantisation multiple times always costs quality. By simply comparing the output from 'convert' with the output from Ghostscript I can easily see the degradation in quality.
Now we come to the Acrobat output. Ccomparing it with the other files it shows the worst quality. The JPEG artefacts are very clearly visible in the displayed image. In this case both the image and the soft mask have been compressed with the JPEG2000 compression scheme, which is a 'better' compression than JPEG. However, it looks like applying it to data which has already been quantised for JPEG yields pretty poor quality results. Or at least, applying it to a soft-masked JPEG image does :-)
The main problem with JPEG2000 is that it is patent encumbered. While decoders can be written royalty-free, to write an encoder you must licence the patented technology from the (many) patent holders, an expensive process.
So the AGPL version of Ghostscript does not include a JPEG2000 decoder, and as such cannot write JPEG2000 images.
Obviously you could use a copy of Acrobat to rewrite your PDF file with JPEG2000 compression as you have done here.
Assuming you want to avoid doing that, then my suggestion would be to investigate why convert is producing an image with a soft mask applied. I strongly suspect this is due to the use of rgba instead of rgb.
Avoiding the creation of the second (soft mask) image would (I believe) significantly decrease the size of the PDF file produced by 'convert'. You could gain at least some additional benefit, without any loss of quality, by running it through Ghostscript's pdfwrite device and specifying /FlateEncode for the GrayImageFilter. That would produce a PDF file where the PDF furniture is compressed, and where a better compression scheme is applied to the image data.
You could also just leave the Ghostscript line as it is, the quality degradation may be enough for you to live with.

A: if you use ubuntu you can try this on the command line. the result is impressive
Install ghostscript, for Ubuntu/Debian:
sudo apt-get install ghostscript

Resize your pdf  with the command:
gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dQUIET -dBATCH -sOutputFile=output.pdf input.pdf

Replace the file names output.pdf and input.pdf with your file names.

A: PDFs can start as vectors. But once you read it into ImageMagick, it gets rasterized. When writing back to PDF, it just imbeds the raster image into a vector PDF shell. So it has not been re-vectorized.
Your use of -density 150 has increased the rasterized file. The nominal density is 72. So have right there increased by 4x, which would just about cover your size increase. I think you stated your increase wrong. It probably should be Original: 365K Converted: 1.358M not Original: 365K Converted: 1.358K
Also if the scanned PDF was a raster in a vector, it may have had limited colors in palette form or simply compressed JPG form. Your rasterizing has converted to 24-bit color and by processing has increased the colors. So even as non-compressed grayscale it is larger.
You can compress your output PDF in ImageMagick as follows by writing the raster image to compressed JPG format and piping to another convert to write to PDF.
convert -density XXX input.pdf ... -colorspace gray -quality 50 JPG:- | convert - output.pdf

Adjust the quality value as desired


text:
Q: Javascript JSON custom deserialisation I'm using a C# app where data classes I use look like this :
class Node {
  public string name;
  public int id;
  public Node parent;
  public Node[] children;
  public Data data;
}

class Community {
  public Node[] nodes;
}

class Data {
  public string info;
  public int value;
}

I declare in javascript these objects :
var Node = {
  name: '',
  id: '',,
  parent: '',
  children: '',
  data: ''
}

var Community = {
  nodes: ''
}

var Data = {
  info: '',
  value: ''
}

Those are obviously simplified versions of the real deal, but I'd like to know how I can tell the javascript JSON deserializer to build the fields properly, using the objects I declared.
I need to make some sort of CMS for this so it's important that all the keys are available, even if they hold no value, which is why I want to declare objects and have the deserialiser use them.
For instance, I want to be able to access Community.nodes[3].data.info even if it wasn't set in the JSON file.

A: A lot of people (including Microsoft ASP.NET) use the NuGet package Json.NET.
The JsonSerializer class offers a large degree of customisation over how objects are serialized.
However to access a deeply nested field like Community.people[3].job.salary you must make sure that there are no null nested objects before you access the last field.
In your example you would probably want to set Person.Job to be a default value or pass the Job in the constructor for Person.
If the issue is on the JavaScript side I suggest you take a look at the prototype pattern as a starting point and this question for reference to assigning to it from a JSON string.


text:
Q: How do I make a query based on the return of another query in Angular with Firestore? Im trying to get some Ids from a collection, and then trying to use each of these Ids to get more data from another collection. Here is what I got done so far:
Basically, I have blog app in which multiple users will be able to post an article. And said article has categories. The thing is, when a user selects a category to filter, it will bring me all USERS that have an article in said category (instead of bringing all articles of the selected category).
So, in Firestore I have:
categories/{categoryId}/users/{userId}

Although the {userId} has more info inside it (like the articles ids in this {categoryId}), I'm just interested in the userId itself for now.
What I want to do is to use the recovered userIds from the above path, and use it to get the user data from the following path:
users/{userId}

And here's where I'm stuck and not sure how to proceed next.. Should I store the ids in a array, and then make requests to Firestore using a forEach loop in said array? Should I duplicate the user data on categories/{categoryId}/users/{userId}? Perhaps change my Firestore data structure? Or perhaps theres a different way to do it in Angular?
this.afs.collection<Category>('categories').doc(category.name).collection<User>('users')
            .snapshotChanges().map(docChangeActionArray => {
                return docChangeActionArray.map(value2 => {
                    return value2.payload.doc.id;
                })
            }).subscribe(ids => {

                //WHAT TO DO HERE?
            })

I apologise for such a simple question. I'm still getting the hang of Angular and Firestore, but appreciate any help!
Thanks.
UPDATE
I did the following:
.subscribe(ids => {
    ids.map(id => {
        this.afs.collection('users').doc<User>(id).valueChanges().map(user => {
            return user;
        }).subscribe(user => {
            console.log(user); //Got it!
        })
    })
})

A:
What I want to do is to use the recovered userIds from the above path, and use it to get the user data from the following path: users/{userId}

You're almost there. What you need to do, is to use the id of the user that you get from the database inside a new reference. So in this case, you need to use nested listeners. So inside your first callback, just create a new reference using the user id and get the details for each user like this:
return docChangeActionArray.map(value2 => {
    return value2.payload.doc.id;

    this.afs.collection<User>('users').doc(value2.payload.doc.id).snapshotChanges().map(/* ... */);
})

Note, that is nothing wrong about nested listeners in Cloud Firestore.

Should I store the ids in a array, and then make requests to Firestore using a forEach loop in said array?

There is no need for that.

Should I duplicate the user data on categories/{categoryId}/users/{userId}? Perhaps change my Firestore data structure?

It depends on use-case of your app. How much duplication data versus extra database calls is optimal for you, it really depends on your project's requirements. For more informations, please see my answer from this post.

Or perhaps theres a different way to do it in Angular?

I cannot see another approach in this case. It's up to you to decide which solution might be better for you, given the information in the answer from the post above.


text:
Q: How to only get the nested keys from a JSON structure in python I have a JSON structure that looks like this:
json_structure =
{
"a":1,
"b":2,
"c":[
     {
     "d":4,
     "e":5,
     "f":{
         "g":6
         }
     }
    ]
"d":[
     {
      "h": 7,
      "i": 8,
      }
    ]
}

I am able to get a, b, c, d no problem using:
json_structure.keys()

But now I want to get only the c nested keys (d, e, f).
Haven't found a way to do this when explicitly stating c keys only.

A: You could write a few utility functions that recursively drill down the structure to access any specific value, keys or items.  This could process lists as if they were dictionaries with the keys being the indices.
def deepValue(D,key,*rest,default=None):
    try:    return deepValue(D[key],*rest,default=default) if rest else D[key]
    except: return default

def deepKeys(D,key,*rest):
    try:
        return deepKeys(D[key],*rest) if rest \
          else D[key].keys() if isinstance(D[key],dict) \
          else range(len(D[key]))
    except:
        return []

def deepItems(D,key,*rest):
    try:
        if rest:
            yield from deepItems(D[key],*rest)
        elif isinstance(D[key],dict):
            yield from D[key].items()
        else:
            yield from enumerate(D[key])
    except: return

output:
for k in deepKeys(json_structure,"c",0):
    print(k)

# d
# e
# f

print(deepValue(json_structure,"c",0))

# {'d': 4, 'e': 5, 'f': {'g': 6}}

print(deepValue(json_structure,"c",0,"d"))

# 4

for k,v in deepItems(json_structure,"c",0):
    print(k,v)

# d 4
# e 5
# f {'g': 6}


text:
Q: Flatened Firebase query in iOS issues I have a "flatened" Firebase structure and trying to retrieve a dictionary of values from a "secondary" database member. In other words, I have a conversation which has a "to" cell which has the key to a business listing. With this key, I'm trying to retrieve the business listing and its children (url, description, title). For some reason, I can print the snapshot2.value and it responds with the expected value, but I can't pass it to my class initialization.
DataService.ds.REF_CONVOS.observeEventType(.Value, withBlock: {snapshot in
        self.convoListings.removeAll()
        self.convoListings = []
        //Data parsing from Firebase. The goal is to breakdown the data received and store in a local model.
        if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
            for snap in snapshots {
                for convo in userConvos {
                // Going into the children of the main object for the conversations.
                    //print("\(snap)")
                    if convo == snap.key {
                        //print(snap.value)
                        print(snap.value)
                        if let businessDict = snap.value as? Dictionary<String, AnyObject> {
                            businessName.removeAll()
                            let test = businessDict["to"] as? String
                            DataService.ds.REF_BusinessListing.childByAppendingPath(test).childByAppendingPath("title/").observeSingleEventOfType(.Value, withBlock: { snapshot2 in
                                print(snapshot2.value)
                            })
                            let key = snap.key
                            let post = ConvoListing(convoKey: key, dictionary: businessDict, businessName: self.test2)
                            self.convoListings.append(post)
                        }
                    }
                }
            }
        }

        self.tableView.reloadData()
    })

A: Your nesting seems of:
DataService.ds.REF_BusinessListing.childByAppendingPath(test).childByAppendingPath("title/").observeSingleEventOfType(.Value, withBlock: { snapshot2 in
     print(snapshot2.value)
})
let key = snap.key
let post = ConvoListing(convoKey: key, dictionary: businessDict, businessName: self.test2)
self.convoListings.append(post)

Keep in mind the observeSingleEventOfType loads the data asynchronously. For this reason, if you have code that needs the value that you loaded, you need to put that code in the block:
DataService.ds.REF_BusinessListing.childByAppendingPath(test).childByAppendingPath("title/").observeSingleEventOfType(.Value, withBlock: { snapshot2 in
    print(snapshot2.value)
    let key = snap.key
    let post = ConvoListing(convoKey: key, dictionary: businessDict, businessName: self.test2)
    self.convoListings.append(post)
})


text:
Q: CSS: Width 100% is not 100% of Screen On my sandbox site there is a white bar across the top. It is contained within the body(which has the background image), and the navbars styles are
#topnav4 {background: #fff;  width: 100%; height: 70px;  }

But the bar doesn't reach the edges of the screen. Furthermore, I don`t have any margins or padding set.  does anyone know how to fix this?
Update, also note that the navbar is not at the very top of the screen. There is space between the top of the navbar and the top of the page. How do I get rid of this?
Update, I added this code but the problem is still not fixed
#topnav4 {background: #fff; position: absolute; left: 0px; top: 0px; width: 100%; height: 70px;  }

A: You probably need to set the margin and padding of your body to 0.
body {
    margin: 0;
    padding: 0;
}

A: You don't have a doctype on the page, so it will be rendered in Quirks Mode. This means that the browser tries to be compatible with ancient versions of the browser.
It's especially bad for IE, where it also will use a non-standard box model: http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug
Add a doctype to the page: http://www.w3.org/QA/2002/04/valid-dtd-list.html

A: Add the following to the top of your CSS file, then go and read about CSS Resets:
* { margin: 0; padding: 0; }

Here's some resources that I found helpful:

*

*Best CSS Reset

*W3 Schools (The Doctype)

*The Box Model

A: The snippet you're looking for is:
html, body {
    margin: 0;
    padding: 0;
}

That will remove the default user agent "page margins" in all browsers.
Remove your position: absolute-based additions - that's not the optimal way to solve this problem.

A: Solved it for me.
min-width:100%

A: .container {display: grid;}
in the website and
.container {display: block;}
in the mobile view.
I was having the same problem and noticed that my display was set to grid and so it was adjusting to 100% of the column instead of the entire screen.


text:
Q: Nginx config root path I am trying to launch a server and my nginx is testing out okay but I still get the "Welcome to nginx" page when loading it up in the web browser.  my path to my applications public folder is here:
home/dev/application/public/

and my nginx config looks like this:
server {
        listen       80;
        server_name  xxxx.com;
        passenger_enabled on;
        root /home/dev/application/public;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   home/dev/application/public;
            index  index.html index.htm;
        }

I followed the examples as best as I could but it is not loading up my application.  I am sure I am doing my root wrong and I thank anyone who knows what the deal is here.

A: Do the following:

cd /etc/nginx/sites-enabled/
ls -l

It should contain your config file (Best practise to make a soft link to /etc/nginx/sites-available/your.conf)
If sites-enabled contains default, remove it: rm default
After removing, default file and verifying your correct conf file exists, restart the server:
service nginx restart
Creating a Soft Link
ln -s /etc/nginx/sites-available/your_nginx.conf /etc/nginx/sites-enabled/your_server_name


text:
Q: Private or public read-only Organization Wide Settings for custom object? I would like to know about how can I distinguish whether a Custom Object OWS is set to Private or Public read-only via Apex. As far as I know and find referenced here Get object sharing setting on Organization-Wide Defaults, if I look into Schema.getGlobalDescribe and try to instantiate the MyCustomObject__Share object I will be able to guess whether MyCustomObject is set to private/public read-only or public read/write.
Then my question comes when I wonder how may I guess whether the setting is either private or public read-only. I guess it is possible to do it but I haven't been able to find out the how-to. I would appreciate any help on your side.
Thank you so much.
Martín.

A: After much research time and some headaches... I've found a solution: You can obtain the Organization Wide Default Settings of a Custom Object by using the Metadata API (http://www.salesforce.com/us/developer/docs/api_meta/). It is a Soap Web Service which is provided by Salesforce and you can use it to get many of the configurations that you have set up for your organization.
The WSDL is provided in the API section of your setup panel in the Salesforce Portal. But it is not that trivial as compiling the WSDL... You will find some errors related to "anyType" types contained in the WSDL. This can be solved by replacing these "anyType" tokens by "string". Then, after a correct compilation of the WSDL to Apex, you will try to execute some requests which certainly won't work. You would receive some error like "callout response field not found in your ReadResult class: fullName". You can try to manually solve this issue.... but in my opinion it was a waste of time. There's much effort to exert just to make it work. It is better to know that someone has been working on this: https://github.com/financialforcedev/apex-mdapi/blob/master/apex-mdapi/src/classes/MetadataService.cls .
It is very easy, just copy the code of the MetadataService.cls and insert it in a new Apex class of your Force.com organization. Then, you can just perform in your Execute Anonymous something like:
MetadataService.MetadataPort metadataWS = new MetadataService.MetadataPort();
metadataWs.SessionHeader = new MetadataService.SessionHeader_element();
metadataWs.SessionHeader.sessionId = UserInfo.getSessionId();
MetadataService.ReadCustomObjectResult rs = (MetadataService.ReadCustomObjectResult) metadataWS.readMetadata('CustomObject', new String[] {'MyCustomObject__c', 'MyOtherCustomObject__c'});
for (MetadataService.Metadata md : rs.getRecords()) {
    if (md != null) {
        MetadataService.CustomObject obj = (MetadataService.CustomObject) md;
        System.debug('Custom object full name: ' + obj.fullName);
        System.debug('Label: ' + obj.label);
        System.debug('Sharing model: ' + obj.sharingmodel);
    } else {
        System.debug('Empty metadata.');
    }
}

I hope this may help other people wondering about this same topic as it has been a complex topic for me.

A: You can actually now get this through the Tooling API! It is on the Entity Definition table.
So you can run a query like this:
List<EntityDefinition> sharingModel = [Select InternalSharingModel, ExternalSharingModel FROM EntityDefinition WHERE QualifiedApiName =: objectName];

Even if the Object has an OWD of Controlled by Parent, it will make the jumps for you and give you the end result.
https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/tooling_api_objects_entitydefinition.htm

A: Partially answering my own question:
One can watch the access level that every user has to every record by querying to UserRecordAccess (https://www.salesforce.com/developer/docs/api/Content/sforce_api_objects_userrecordaccess.htm). Something like:
SELECT RecordId, HasReadAccess, MaxAccessLevel FROM UserRecordAccess WHere UserId = '005D0000004LEbWIAW' AND RecordId = 'a0Kc000000FSWwhEAH'.

It is mandatory to set both conditions in the WHERE clause (UserId and RecordId), otherwise one would get an exception.
But still some doubts: What if I want to know either the permissions of a big set of users (for example, 1000 users) to one record or the permissions of one user to a big set of records (for example, 10 000 records)? Wouldn't it be better to query (if possible) the Organization Wide Settings of the objects which I'm interested in?