text:
Q: How do I set border color for the checkbox using jetpack compose I need to implement checkbox that looks like this

I have tried to explore all the aspects provided by compose to alter the checkbox as below
colors: CheckboxColors = CheckboxDefaults.colors()

I found some alternative solution here but

*

*It doesn't works for me

*I feel just to change the checkbox border color there shouldn't be so much work around right.

Note: checkmark color can be changed by using color field
colors = CheckboxDefaults.colors(checkmarkColor = Black)

Any help is appreciated

A: There is default colors function CheckboxDefaults.colors().
You can change the specific color.
@Composable
fun myCheckBoxColors(): CheckboxColors {
    return CheckboxDefaults.colors(
        checkedColor = Color.red,
        uncheckedColor = Color.transparent
    )
}

A: You need to implement CheckboxColors interface and create your color scheme.
I just copied the implementation of DefaultCheckboxColors:
@Stable
class YourCheckboxColors(
    private val checkedCheckmarkColor: Color,
    private val uncheckedCheckmarkColor: Color,
    private val checkedBoxColor: Color,
    private val uncheckedBoxColor: Color,
    private val disabledCheckedBoxColor: Color,
    private val disabledUncheckedBoxColor: Color,
    private val disabledIndeterminateBoxColor: Color,
    private val checkedBorderColor: Color,
    private val uncheckedBorderColor: Color,
    private val disabledBorderColor: Color,
    private val disabledIndeterminateBorderColor: Color
) : CheckboxColors {

    private val BoxInDuration = 50
    private val BoxOutDuration = 100
    private val CheckAnimationDuration = 100

    private val CheckboxRippleRadius = 24.dp
    private val CheckboxDefaultPadding = 2.dp
    private val CheckboxSize = 20.dp
    private val StrokeWidth = 2.dp
    private val RadiusSize = 2.dp

    @Composable
    override fun checkmarkColor(state: ToggleableState): State<Color> {
        val target = if (state == ToggleableState.Off) {
            uncheckedCheckmarkColor
        } else {
            checkedCheckmarkColor
        }

        val duration = if (state == ToggleableState.Off) BoxOutDuration else BoxInDuration
        return animateColorAsState(target, tween(durationMillis = duration))
    }

    @Composable
    override fun boxColor(enabled: Boolean, state: ToggleableState): State<Color> {
        val target = if (enabled) {
            when (state) {
                ToggleableState.On, ToggleableState.Indeterminate -> checkedBoxColor
                ToggleableState.Off -> uncheckedBoxColor
            }
        } else {
            when (state) {
                ToggleableState.On -> disabledCheckedBoxColor
                ToggleableState.Indeterminate -> disabledIndeterminateBoxColor
                ToggleableState.Off -> disabledUncheckedBoxColor
            }
        }

        // If not enabled 'snap' to the disabled state, as there should be no animations between
        // enabled / disabled.
        return if (enabled) {
            val duration = if (state == ToggleableState.Off) BoxOutDuration else BoxInDuration
            animateColorAsState(target, tween(durationMillis = duration))
        } else {
            rememberUpdatedState(target)
        }
    }

    @Composable
    override fun borderColor(enabled: Boolean, state: ToggleableState): State<Color> {
        val target = if (enabled) {
            when (state) {
                ToggleableState.On, ToggleableState.Indeterminate -> checkedBorderColor
                ToggleableState.Off -> uncheckedBorderColor
            }
        } else {
            when (state) {
                ToggleableState.Indeterminate -> disabledIndeterminateBorderColor
                ToggleableState.On, ToggleableState.Off -> disabledBorderColor
            }
        }

        // If not enabled 'snap' to the disabled state, as there should be no animations between
        // enabled / disabled.
        return if (enabled) {
            val duration = if (state == ToggleableState.Off) BoxOutDuration else BoxInDuration
            animateColorAsState(target, tween(durationMillis = duration))
        } else {
            rememberUpdatedState(target)
        }
    }
}

And then you can set the colors by simply:
        Checkbox(
            colors = YourCheckboxColors(
                checkedBorderColor = Ink900,
                checkedBoxColor = Light,
                checkedCheckmarkColor = Ink900,
                uncheckedCheckmarkColor = Ink900.copy(alpha = 0f),
                uncheckedBoxColor = Light.copy(alpha = 0f),
                disabledCheckedBoxColor = Light,
                disabledUncheckedBoxColor = Light.copy(alpha = 0f),
                disabledIndeterminateBoxColor = Light,
                uncheckedBorderColor = Ink900,
                disabledBorderColor = Ink900,
                disabledIndeterminateBorderColor = Ink900,
            ),
            onCheckedChange = {}
        )

A: You can try the below code and customize the checkbox border using Box.
@Composable
fun CustomCheckBox(
checked: Boolean,
onCheckedChange: ((Boolean) -> Unit),
checkBoxSize: Dp = 60.dp,
checkBoxBorderWidth: Dp = 1.dp,
checkBoxBorderColorSelected: Int = R.color.black,
checkBoxBorderColorUnSelected: Int = R.color.teal_200,
checkBoxCheckedIconColor: Int = R.color.black,
) {
// state is used to hold the checkbox click or not by default is false
val checkBoxState = remember { mutableStateOf(checked) }
// Ui for checkbox
Box(
    modifier = Modifier
        .border(BorderStroke(checkBoxBorderWidth,
            if (checkBoxState.value) colorResource(id = checkBoxBorderColorSelected)
            else colorResource(id = checkBoxBorderColorUnSelected)))
        .size(checkBoxSize)
        .background(Color.Transparent)
        .clickable {
            onCheckedChange(!checkBoxState.value)
            checkBoxState.value = !checkBoxState.value
        },
    contentAlignment = Alignment.Center
) {
    if (checkBoxState.value)
        Icon(Icons.Default.Check,
            tint = colorResource(id = checkBoxCheckedIconColor),
            contentDescription = "Custom CheckBox")
}
}


text:
Q: Android detect missed call I am attempting to have my application recognize when there is a missed call. I have created a BroadcastReceiver that detects when the phone's state has changed. Here is my onReceive() method:
public void onReceive(Context context, Intent intent) {
    boolean ringing = false, callReceived = false;
    String callerPhoneNumber = "";
    String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

    if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
        ringing = true;
        Bundle bundle = intent.getExtras();
        callerPhoneNumber= bundle.getString("incoming_number");

        if (ringing) {
            Toast.makeText(context, "Phone call from: " + callerPhoneNumber, Toast.LENGTH_LONG).show();
        }
    }

    if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(state)) {
        callReceived = true;
        Toast.makeText(context, "Call received.", Toast.LENGTH_LONG).show();
    }

    if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) {
//          Toast.makeText(context, "Phone is idle", Toast.LENGTH_LONG).show();

        if (ringing) {
            Toast.makeText(context, "ringing is true", Toast.LENGTH_LONG).show();
        }

//          if (ringing && !callReceived) {
//              Toast.makeText(context, "It was A MISSED CALL from : " + callerPhoneNumber, Toast.LENGTH_LONG).show();
//          }
    }

The issue I am having is the application detects when the phone is ringing, sets ringing to true, and shows the appropriate toast message. However, when the phone's state is idle, it does not enter the if (ringing) statement to show the ringing is true toast message. However, if I comment in the toast message just above it, it will correctly print that the Phone is idle.
Is it possible that ringing is being reset to false somewhere between the phone ringing and the phone becoming idle again?

A: You can not store any "state" information in a broadcast receiver. If you want to do a comparison old state / new state, I think you can use a service.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Xamarin build action warning XA0101 I'm getting following warning while building the Xamarin Android project.
Warning XA0101: @(Content) build action is not supported (XA0101)

For this topic I found resources below, but I can't figure out the solution to get rid of this warning. Can somebody help me?
http://developer.xamarin.com/guides/android/under_the_hood/build_process/#Content
http://developer.xamarin.com/releases/android/xamarin.android_5/xamarin.android_5.1/#Bug_Fixes

A: It's a warning that came with the new Xamarin Update.
If you want to get rid of it, change the Build Action for AndroidManifest.xml to "none".

A: " New projects created from templates show ignorable build warning: "@(Content) build action is not supported ... AndroidManifest.xml". Workaround: change the build action of "AndroidManifest.xml" to "none". Now fixed in the Alpha and Beta channels. "
-- by Stable release: XamarinVS 3.11.445, new features and bug fixes (Brendan Zagaeski)
Refer : Bug 28210 - Bugzilla

A: My case was similar but for a slightly different reason. I was using msbuild /t:pack to package my Android package into a NuGet package (NUPKG) and wanted to include some static content in the generated NUPKG.
I had this, which worked in most projects, but not the Android ones:
  <ItemGroup>
    <Content Include="..\THIRD-PARTY-NOTICES.txt" Link="THIRD-PARTY-NOTICES.txt">
      <Pack>true</Pack>
      <PackagePath></PackagePath>
    </Content>
  </ItemGroup>

But based on other answers in this question, I updated <Content ...> to <None ...>:
  <ItemGroup>
    <None Include="..\THIRD-PARTY-NOTICES.txt" Link="THIRD-PARTY-NOTICES.txt">
      <Pack>true</Pack>
      <PackagePath></PackagePath>
    </None>
  </ItemGroup>

And this still works just fine in all my projects (class lib, Android, iOS, others). The txt file got correctly picked up and embedded in the generated NUPKG.


text:
Q: OpenJPA Entity not updated when value is zero I've an issue with an Entity which has a field mapped to an INT type in DB. The problem is that when I update the field to a value, like 1337 for instance, it's correctly persisted in the DB but it's not the case when I set it to zero.
To be more specific:

*

*I have a row in my DB with a field "record" that is INT type and with a NULL value

*I retrieve that row as a managed Entity "anEntity"

*When I do "anEntity.setRecord(1337)", the record value is changed in DB but it's not the case when I do "anEntity.setRecord(0)" (it stays NULL in DB).

Is there a way to fix it ?
a bit of code, the one who updates:
@Stateless
public class AClass {

    @EJB
    ARepository arepository;

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void produceOutgoingMessage(int idOfOutputToProduce) {
        AnEntity anEntity = arepository.find(idOfOutputToProduce);
        //...
        doSomething(anEntity);
    }

    private void doSomething(AnEntity anEntity) {
        //...
        anEntity.setRecord(0); // record stays NULL in DB
        anEntity.setRecord(1337); // record is correctly set in DB
    }
}

And the Entity:
@Entity
@Table(name = "MY_TABLE")
public class AnEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "C_I_IDF")
    private Long id;

    @Column(name = "N_I_RECORD")
    private int record;

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public int getRecord() {
        return record;
    }

    public void setRecord(int record) {
        this.record = record;
    }
}

A: An "int" field should never be configured as allowing NULL in the database. This is likely the cause of the problems. Fix that and it should work.
If it doesnt then report a bug in OpenJPA.


text:
Q: Vue.js - Clearing Child Form Fields from Parent Component I have a child sidebar component with some dropdowns. Simplified example:

You select a status here and it re renders the table/dashboard view in the parent component. That is handled via $emit in the child component like so:
selectedStatus: function(status) {
  this.$emit('updateStatus', status)
},

No issues there. Now I'd like to be able to clear or reset this input from the parent component. As I said this is a simplified example and there are many dropdowns, a couple datetime selectors, and other inputs to clear.
If I do something like
this.selectedStatus = [] in the parent, it does indeed reset/re render the table/data properly but it still shows the UI piece (ie, the selected status in the dropdown).
If I do something like
this.selectedStatus = [] in the child it does correctly remove/alter the UI piece to where it clears the dropdown.
What is the correct approach here to clear child filters/inputs from the parent?

A: I recommend you to read this article, it explains all the ways to make a child component rerender (and therefore reset it's state).


text:
Q: Как менять свойства xaml элементов из кода? Привет. Есть dataGridview -
<DataGrid x:Name="DataGridXAML" HorizontalAlignment="Left" Height="441" Margin="10,89,0,0" VerticalAlignment="Top" Width="1044">
            <DataGrid.Columns>
                <DataGridTextColumn Header="ID сотрудника"/>
                <DataGridTextColumn Header="Имя" Width="100"/>
                <DataGridTextColumn Header="Фамилия" Width="120"/>
                <DataGridTextColumn Header="Отчество" Width="*"/>
            </DataGrid.Columns>
</DataGrid>

Каким образом можно поменять через код количество колонок, их имя и другие параметры?
Из другой xaml страницы.

A: А в чем проблема? Например:
DataGridXAML.Columns.Add(
    new DataGridTextColumn()
    {
        Header="Дед Мороз",
        Width="200"
    });

Чтобы поменять:
DataGridXAML.Columns[0].Header="Снегурочка";

Документация: https://msdn.microsoft.com/ru-ru/library/system.windows.controls.datagrid.columns(v=vs.110).aspx
Если вам нужен доступ из другой страницы, сделайте эту страницу доступной другой странице любым путём, и получайте доступ через yourPage.DataGridXAML.Columns....


text:
Q: How to Accept POST request with IIS? I need to develop a web service to accept and save XML files transfered via POST requests. The chosen platform is IIS - problem is, I have zero experience handling ASP.net so far. While I think that handling the request object and saving it to the system should be easily doable, I am very insecure how to deal with the components of IIS itself.
AFAIK the source system (SAP) throws a POST directly at an URL, so I don't neccessarily need an actual form or page, but how do I weave it all together?
Do I still need a page or just a handler, how would I register it, to what extension?
I would be very happy if someone could give me a little jump start and point me in the right direction.
Thanks in advance,
Christian


text:
Q: OpenLayers : 4326 ol.proj.transform not working Issue

When I click on the map I want to transform the coordinates to format of 4326. When I do this it seems the Latitude part of the array transforms fine, but the Longitude part is incorrect and not valid.
Code

When I click on the Map, the SingleClick event fires, I then get the coordinates of where the user clicked:
Example of pPointClicked = [-40364190.03366159, 7054830.416117247];
session.Map.on('singleclick', function (e) {
    var pPointClicked = e.coordinate;
});

I try and transform these coordinates into 4326 by using the code below:
Example of coord4326 = [-362.59768838343064, 53.38659640004323];
session.Map.on('singleclick', function (e) {
    var pPointClicked = e.coordinate;

    var coord4326 = ol.proj.transform(pPointClicked, 'EPSG:3857', 'EPSG:4326');
});

As you can see the first value in the transformed variable is -362.59768838343064 which is incorrect? Does anyone know why this is happening.

A: The transformation seems to be working.  Here's what I think is happening: you are not within the "original extent" of your map, i.e. you panned west and wrapped the entire world at least twice.
Try zooming out completely, then pan at the "same" location to the east twice, then click again.  You should have the coordinate you're looking for.
Here's an other tip: the world extent, in EPSG:3857, is:
[
  -20037508.342789244,
  -20037508.342789244,
  20037508.342789244,
  20037508.342789244
]

[-40364190.03366159, 7054830.416117247] is out of that extent, but if you pan to wrap the world twice, you should get: 289173.348083102, 7054830.416117247], which is within the extent.


text:
Q: Python - why does this for loop only print 1 letter? def caesar(plaintext,shift):
    alphabet=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

    #Create our substitution dictionary
    dic={}
    for i in range(0,len(alphabet)):
        dic[alphabet[i]]=alphabet[(i+shift)%len(alphabet)]

    #Convert each letter of plaintext to the corrsponding
    #encrypted letter in our dictionary creating the cryptext
    ciphertext=("")
    for l in plaintext.lower():
            if l in dic:
                l=dic[l]
                ciphertext+=l
            return ciphertext

#Example useage
plaintext="the cat sat on the mat"
print "Plaintext:", plaintext
print "Cipertext:", (caesar(plaintext,29))

The cipertext prints just one letter, instead of printing the 'plaintext' variable in caesar shift. I want it to print the whole sentence.
Thanks

A: This is because your return ciphertext is indented wrong. You return from the first iteration of the for loop. (Indentation matters a lot in Python!)
    for l in plaintext.lower():
            if l in dic:
                l=dic[l]
                ciphertext+=l
            return ciphertext  # Indented to match level of `if`.

Fix it to.
    for l in plaintext.lower():
        if l in dic:
            l=dic[l]
            ciphertext+=l
    return ciphertext

Couple of Pointers

*

*Instead of listing out all alphabets in your code, you can just set alphabets = string.ascii_lowercase.

*You don't need a variable to store dic[l], just do ciphertext += dic[l].

A: do it better with string.translate :)
import string
def caesar(plaintext,shift):
    alphabet=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
    alphabet_shifted = alphabet[shift:]+alphabet[:shift]
    tab =    string.maketrans("".join(alphabet),"".join(alphabet_shifted))
    return plaintext.translate(tab)

A: You need to fix the indents for the return statement:
for l in plaintext.lower():
    if l in dic:
       l=dic[l]
       ciphertext+=l
    # <-- if you return here, then you will loop only once.
return ciphertext


text:
Q: Cayley's Theorem - Discourse on Fraleigh's proof or Alternative Easier proof I have hard time understanding Fraleigh's proof. Can someone either explain Fraleigh's or provide an alternative, perhaps easier proof?
Thanks so much.

A: Let $n=|G|$.  Think about the elements of $S_n$ - these are permutations of the numbers $1$ to $n$.  Now let's arbitrarily number the elements of $G$ so that $G=\{g_1,g_2,\ldots, g_n\}$.  Now, we could talk about the permutations in $S_n$ being applied to these elements of $G$, correct?  For example, $(123)$ would permute $g_1$ and $g_2$ and $g_3$ accordingly.  We call this "letting $S_n$ act on $G$."
Cayley's theorem does exactly what we just did, only backwards.  He starts by labeling $G=\{g_1,g_2,\ldots, g_n\}$.  Then he picks an element $x\in G$ and multiplies everything in $G$ on the left by $x$.  Doing so rearranges the elements in $G$ in some way from their original order.  He then finds the associated permutation in $S_n$, which he calls $\theta_x$.

Example. Let $|G|=3$ and suppose you start with elements $g_1,g_2,g_3$ (in that order).  Then, suppose you multiply everything by some $x\in G$, and you end up with $g_2,g_3,g_1$ (in that order).  Then $x$ will be associated with the permutation $\theta_x=(123)$ in $S_3$.

Once he finds this with all the $x\in G$, he looks at the subset $\{\theta_x:x\in G\}\subseteq S_n$.  He then proves that that set is a subgroup, and in fact is isomorphic to $G$.
So, to sum everything up, Cayley's theorem simply shows that the permutations of a $G$'s elements induced by left multiplication by each element $x\in G$ form a group which itself isomorphic to $G$.  Read the above explanation a few times and I think you'll see.

A: It's basically all about that the maps $g\cdot:G\to G$ (sending $x\mapsto gx$) are distinct permutations, that is, $(g\cdot)\in Sym(G)$, moreover this assignment $G\to Sym(G)$, sending $g\mapsto (g\cdot)$ is an injective group homomorphism.


text:
Q: How to use an image DOM element as a value for the source property in jCanvas? I want to test this example : http://calebevans.me/projects/jcanvas/sandbox.php#%24%28%22canvas%22%29.drawImage%28%7B%0A%20%20source%3A%20%24%28%27%23image-fish%27%29%5B0%5D%2C%0A%20%20x%3A%2050%2C%20y%3A%2050%2C%0A%20%20width%3A%20100%2C%0A%20%20fromCenter%3A%20false%0A%7D%29%3B
But I don't see any result in the browser except image by default "img src". Please someone help me. How can I use this function?
  <!doctype html>

        <meta charset="utf-8">
        <title>Demo</title>
        <canvas width="500" height="250"></canvas>

Thanks.

A: image tag is not fully loaded when source for the canvas tag is set. As a result, $('#draggable')[0] is returning undefined. try calling drawImage on load of the document.
The following should fix your problem.
 <!doctype html>

        <meta charset="utf-8">
        <title>Demo</title>
        <canvas width="500" height="250"></canvas>


text:
Q: Cannot map an object ? Cannot read property 'map' of undefined So i'm currently making a receipt for my POS app.
I currently have stored an array in my database as:
mongodb collection
And I want to map them to a receipt page
function renderTable(orderlist) {
    return (

{orderlist.name}

{orderlist.qty}

{orderlist.subtotal}

    );
  }

const showReceipt = ({
    values,
    errors,
    touched,
    handleChange,
    handleSubmit,
    isSubmitting,
  }) => {
    return (

Item

Qty

              {values.order_list.map((orders) => {
                renderTable(orders.order_list);
              })}

tax

$419.25

Total

{values.total}

          {/*

            Thank you for your business!  Payment is
            expected within 31 days; please process this invoice within that
            time. There will be a 5% interest charge per month on late invoices.

 */}

    );

And it is currently showing me this error:

TypeError: Cannot read property 'map' of undefined

I can't for some reason map this one particular object.
I can, however, Return them as string with :
JSON.Stringify(orderlist)
I can also log the object in console
For whatever reason I just can't map them. I want the function to return a row for each Order_list content

A: 99% of the time with these problems, your values are available at some point, but since you are getting them from an api and that takes time, not during your first render.
Before mapping over it, check if values is alreaady set and otherwise show a loading indicator.

A: When you call api. The values.order_list is a initial value you defined on the reducer. So if you don't defined the initial of order_list, values.order_list is undefined. You can use optional chaining to check before call map like this.
values.order_list?.map


text:
Q: Combining two rows in sql I have a really hard time figuring this out. I got one table called voeding and two rows plantaardig and insecten with data. Also check the image below to illustrate my question.

Which query should I use to find out which type of voeding (plantaardig and insecten together) is most used?
To give some backgroud. The use case is which type of food is most eaten by reptiles

A: Use GROUP BY like
select plantaardig, count(plantaardig) as count1
from voeding
group by plantaardig

In case you want to mix then both then use UNION like
select * from (
select plantaardig as Foodee, count(plantaardig) as count1
from voeding
group by plantaardig

UNION

select insecten, count(insecten)
from voeding
group by insecten ) xxx order by count1 desc;

A: If I understand you correctly, you want to query that returns the plantaardig with the most insecten.
The following query should do the trick:
SELECT plantaardig
FROM Voeding
GROUP BY plantaardig
HAVING COUNT(*) >= ALL (SELECT COUNT(*)
                        FROM Voeding
                        GROUP BY plantaardig)

EDIT
To get the insecten as well you can do the following:
SELECT V.plantaardig, V.insecten
FROM Voeding AS V JOIN (SELECT plantaardig
                        FROM Voeding
                        GROUP BY plantaardig
                        HAVING COUNT(*) >= ALL (SELECT COUNT(*)
                                                FROM Voeding
                                                GROUP BY plantaardig)) AS t
     ON V.plantaardig = t.plantaardig


text:
Q: ng-model not updating select value I have a problem updating <select> with ng-init.
HTML:
<form data-ng-init="showStudent()">
<select id="studbranch" data-ng-model="student.branch"
    data-ng-options="obj.name for obj in branches track by obj.id" required>
    <option value="">-- Select Branch --</option>
</select>
</form>

Outputs:
<option value="">-- Select Branch --</option>
<option value="1">Branch 1</option>
<option value="2">Branch 2</option>
<option value="3">Branch 3</option>

In JS file:
$scope.branches = [{"id":"1","name":"Branch 1"},{"id":"2","name":"Branch 2"},{"id":"3","name":"Branch 3"}];

$scope.showStudent = function() {
    $.getJSON('student.php', function(data) {
        $scope.student = data[0]; $scope.$apply();
        alert($scope.student.branch);
    });
}

On page load (init), it alerts 3. That means student.branch is set to 3. But the select is not updated. It stays at default value. What could be wrong? Are the select values set after init?
If I add $('#studbranch').val($scope.student.branch); after the alert() it works fine.

A: Please try do that in angular way not jQuery
    app.controller(function($scope, $http){
    ...
$scope.student = [];
     $scope.showStudent = function() {
        $http.get('student.php').then( function(data) {
          angular.copy(data[0], $scope.student);
           alert($scope.student.branch);
        });
    };
    ...
    }

A: Your ng-options should be formatted like so:
data-ng-options="obj.id as obj.name for obj in branches track by obj.id"

Assigning the ng-model of the select to the right id will now update the select.


text:
Q: What is the correct way to upgrade pip in stretch debian? I have gone through some notes that it is not a good idea to do pip upgrade using sudo command. My question is if I don't give sudo I get permission errors. How can I resolve this? Also, what is the reason sudo is not suggested in order to upgrade pip?
$python -m pip install --upgrade pip
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Collecting pip
  Using cached https://files.pythonhosted.org/packages/54/0c/d01aa759fdc501a58f431eb594a17495f15b88da142ce14b5845662c13f3/pip-20.0.2-py2.py3-none-any.whl
Installing collected packages: pip
  Found existing installation: pip 19.2.3
    Uninstalling pip-19.2.3:
      Successfully uninstalled pip-19.2.3
  Rolling back uninstall of pip
  Moving to /home/abc/.local/bin/pip
   from /tmp/pip-uninstall-V4F8Pj/pip
  Moving to /home/abc/.local/bin/pip2
   from /tmp/pip-uninstall-V4F8Pj/pip2
  Moving to /home/abc/.local/bin/pip2.7
   from /tmp/pip-uninstall-V4F8Pj/pip2.7
  Moving to /home/abc/.local/lib/python2.7/site-packages/pip-19.2.3.dist-info/
   from /home/abc/.local/lib/python2.7/site-packages/~ip-19.2.3.dist-info
  Moving to /home/abc/.local/lib/python2.7/site-packages/pip/
   from /home/abc/.local/lib/python2.7/site-packages/~ip
ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/pip-20.0.2.dist-info/top_level.txt'
Consider using the `--user` option or check the permissions.

WARNING: You are using pip version 19.2.3, however version 20.0.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

A: Adding to Stephens answer, you also shouldn't be installing packages globally using pip (i.e., sudo pip install foo). Like upgrading pip, this interferes with distribution-provided files, leading to potential conflicts.
For Python packages on Debian, there are two viable strategies, which you should not mix. Pick one. You can switch from one to the other as the situation demands.
1) Use Debian-provided packages only
That is, anything you can apt install. Need PIL? apt install python-pil or apt install python3-pil. This ensures all the files are correctly managed by Debian, and you get free security support along with the rest of Debian's packages. Well, until July-ish anyway, when Stretch will start to lose security support.
This means you'll sometimes have to settle for a bit older version of a package. Sometimes you might not be able to find the package you need at all. Perhaps this can be supplemented with packages installed using pip --user as Stephen describes, I haven't tried this.
2) Use virtualenv
You can set up a Python Virtual Environment (sudo apt install virtualenv; virtualenv venv; source venv/bin/activate). You can install packages (or upgrade pip) within this virtualenv, and all such installs will be completely contained in that virtualenv. This also means that you can use different versions of packages for different projects, and anything that's on PyPi is available. rm -r venv/ will get rid of the entire Virtual Environment, including any packages. No conflicts with OS files.
This approach makes it a lot more explicit what your project needs, and makes managing that easier. On the other hand, the burden of updating those packages for security fixes becomes yours. It's a bit heavy-handed for small one-off projects, but can be quite useful in specific cases.

A: Never upgrade the OS provided version of tools outside of the package management system, because if there's a new package released it will overwrite your changes.
So sudo pip install --upgrade pip is a bad thing.  The OS package system believes it controls the files, and you've overridden them.  Odd behaviour may result, including installing of an older version than you've previously installed!
If you want a newer version then you can install it in the user profile
% pip install --upgrade --user pip
Collecting pip
  Downloading https://files.pythonhosted.org/packages/54/0c/d01aa759fdc501a58f431eb594a17495f15b88da142ce14b5845662c13f3/pip-20.0.2-py2.py3-none-any.whl (1.4MB)
    100% |################################| 1.4MB 615kB/s
Installing collected packages: pip
Successfully installed pip-20.0.2

This will install the latest version in $HOME/.local/bin
% ls -l .local/bin/pip
-rwxr-xr-x 1 sweh sweh 223 Feb 16 21:49 .local/bin/pip

If you have $HOME/.local/bin on your PATH then you'll always pick up user pip installed programs.
Most of the time, however, you don't need to upgrade pip.


text:
Q: No cookie matching signin id found I have implemented identityserver3 and it work well but sometime , i get error while redirecting to IDS(for login). Log says No matching Cookie signin Id .
I can see initial login cookie is not being sent to identityserver from our application in some cases.
I did some googling and it seems like existing issue with Katana and suggestion was too use app.UseKentorOwinCookieSaver() but even after that it doesn't seems to be working.
Another strange this is that .. problem appear only one time per browser session (that too 1st time) and doesn't appear after that or if i get app-pool reset it doesn't happen for sometime.
Is there something else i can try? Looking forward for any direction.
Thanks in advance.
Identity Log
04/19/2017 07:52:53 -07:00 [Information] ()
Posting to https://applicationURl/
04/19/2017 07:52:53 -07:00 [Information] ()
Login page submitted
04/19/2017 07:52:53 -07:00 [Information] ()
No cookie matching signin id found
04/19/2017 07:52:53 -07:00 [Information] ()
Start discovery request
04/19/2017 07:52:53 -07:00 [Information] ()
Start key discovery request
04/19/2017 07:52:53 -07:00 [Information] ()
CSP Report endpoint requested

A: Same issue was reported on GitHub.
Maybe this blog post helps: Catching the System.Web/Owin Cookie Monster.
It suggests to workaround this issue by adding app.UseKentorOwinCookieSaver(); to the Owin pipeline using the Kentor.OwinCookieSaver NuGet package.


text:
Q: What is difference between dataframe and list in R? What is difference between dataframe and list in R? Which one should be used when? Which is easier to loop over?
Exact problem: I have to first store 3 string elements like "a", "b", "c". Later for each of these, I need to append 3 more elements; for instance for "a" I have to add "a1", "a2", "a3". Later I have to use nested for loops to access these elements.
So I am confused to use dataframe or list or some other data type, in which I could first store and then append (kind of each column)?
Currently I am getting errors, like "number of items to replace is not a multiple of replacement length"

A: The question isn't as stupid as some people think it is. I know plenty of people struggling with that difference, and what to use where. To summarize :
Lists are by far the most flexible data structure in R. They can be seen as a collection of elements without any restriction on the class, length or structure of each element. The only thing you need to take care of, is that you don't give two elements the same name. That might cause a lot of confusion, and R doesn't give errors for that:
> X <- list(a=1,b=2,a=3)
> X$a
[1] 1

Data frames are lists as well, but they have a few restrictions:

*

*you can't use the same name for two different variables

*all elements of a data frame are vectors

*all elements of a data frame have an equal length.

Due to these restrictions and the resulting two-dimensional structure, data frames can mimick some of the behaviour of matrices. You can select rows and do operations on rows. You can't do that with lists, as a row is undefined there.
All this implies that you should use a data frame for any dataset that fits in that twodimensional structure. Essentially, you use data frames for any dataset where a column coincides with a variable and a row coincides with a single observation in the broad sense of the word. For all other structures, lists are the way to go.
Note that if you want a nested structure, you have to use lists. As elements of a list can be lists themselves, you can create very flexible structured objects.

A: Look at the example:
If you use apply instead of sapply to get the class -
apply(iris,2,class) #  function elements are rows or columns
Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species
"character"  "character"  "character"  "character"  "character"

sapply(iris,class) # function elements are variables
Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species
"numeric"    "numeric"    "numeric"    "numeric"     "factor"


text:
Q: OSGI is it possible to have 2 persistence units in 1 bundle As the title states, is it possible to have 2 persistence units in 1 bundle, and therefore two EntiManagers
In OSGI, a persistence bundle has the following in its pom.xml file :
<Meta-Persistence>META-INF/persistence.xml</Meta-Persistence>

where persistence.xml defines the persistence unit
So if it is possible:

*

*what is the syntax to define 2 instead ?

*in my case, the persistence provider is hibernate, would that cause a problem ?

thank you

A: Yes, the OSGi JPA Specification allows for the Meta-Persistence header to be specified as a comma-separated list of resources. You can read full details in section 127.4.2 ("Meta Persistence Header") of the OSGi Compendium Release 6 Specification.
You also asked if Hibernate presents a problem. It should not, so long as the JPA Provider implementation you are using is compliant with the OSGi JPA Specification.


text:
Q: Java: Best way to remove duplicated list in a list I have a list of list:
List<List<Integer>> myList = new ArrayList<>();

What would be the best way to remove the duplicated list in myList?
For example, in the following list of list:
[[-1,0,1],[-1,-1,2],[-1,0,1]]

I would like to reduce it to:
[[-1,0,1],[-1,-1,2]]

Thanks!

A: The easiest way is to copy it into an order-preserving set (or, more generally, any kind of set, if you don't care about the ordering), and then back into the list:
myList = new ArrayList<>(new LinkedHashSet<>(myList));

A: Use a Set instead of a list. Sets do not allow duplicates. What is the difference between Set and List?


text:
Q: Why does the Higgs field have less energy when it's non-zero than when it's zero? Why  does the Higgs field have less energy when it's non-zero than when it's zero? There are references to this question on the site, but they are too heavy going for me for a while yet. Anybody want to try a non math (or minimum math ) answer/analogy?
The basis for this question is p35 of Carroll's pop-sci book "The Particle at the End of the Universe" , in which there is a diagram comparing the resting value of fields such as electrons, quarks etc. as zero but the Higgs resting value as some non-zero value. I do understand that the Higgs field is not derived from a gauge theory, and that, afaik, all other fields are.
I simply want an as physical as possible, intuitive picture, rather than maths basis, for the discrepancy between the resting values of all other fields and that of the Higgs.
I self study, so whilst I can follow most of the maths up involved in QM to the Dirac equation level, my knowledge is (very) patchy in parts and sometimes its easier, as a QFT newbie, to get a analogy before diving into the underlying maths. I do fully understand that a physical picture is often misleading, or impossible. If it's not possible to give a physical explanation/picture, then that's perfectly OK and  I will keep digging until I understand it on a maths level.

A: From the form of the Higgs potential (which is quartic, the famous Mexican hat) you can see that for $\Re \phi =0$ as well as for $\Im \phi=0$ (the real and imaginary parts of the Higgs field), it is sitting on the unstable top of the hat. Thus, a small perturbation would lead it away from $0$. Since the potential has a smaller value away from zero so does the energy. Take a look at this picture for more intuition.

A: This is more of an extended comment, because I don't know the answer, but hopefully this will be useful.
Any field with a non-zero spin must have to have a vacuum expectation value (VEV) of zero, because any other value would break Lorentz invariance. So spin 0 bosons like the Higgs are the only ones that can have non-zero VEVs.
As for the form of the Higgs potential, the one in the standard model is the only one that is renormalisable. So assuming the Higgs is correctly described by the standard model it has to have a potential of this form.
But none of this explains why the Higgs VEV is non-zero or what the physical interpretation is. I don't know of an explanation for this except that, well, that's the way the universe is.
There is a cliché you'll come across in quantum mechanics:

anything that isn't forbidden is compulsory

and it's not forbidden for the Higgs to have a non-zero VEV. So at the end of the day maybe the Higgs has a non-zero VEV because it can.


text:
Q: jQuery to stick the footer to the bottom of the page I've spent ages trying to use CSS to stick my footer to the bottom of my page, and have just about given up.
What I want is for the footer to have no extra CSS properties assigned if the height of the viewport is less than the height of the HTML document.
If the document height is less than the window height, I want the following CSS assigned to div#thefooter:
position: fixed;
bottom: 0px;
margin-left: -5px;

So here's my JS code. It does nothing, and the console log shows nothing.
$(document).ready(function(){

  $(window).bind("load", function(){ putFooter(); });
  $(window).resize(function(){ putFooter(); });

  function putFooter(){
    var wh = $(window).height();
    var dh = $(document).height();
    if(dh < wh) {
      $("#thefooter").css({"position": "fixed", "bottom": "0px", "margin-left": "-5px"});
      }
    }

});

EDIT: and here's what my HTML looks like:

...

...

...

If you want to see the whole thing my website is duncannz .com

A: Check this out, no javascript needed at all...
http://www.cssstickyfooter.com

A: OK I've got it. Not with CSS - I've already spent ages trying with that.
But I have the jQuery working. The problem was that $(document).height(); was returning the height of the viewport, since I use body{ height: 100%; } in my CSS. The answer was to use this HTML:

...

and use $("#everything").height(); instead of $(document).height();. Still requires JS unfortunately, but better than nothing. No CSS solution worked for me.
EDIT AGAIN: Here's the again-updated code:
$(document).ready(function(){

  function putFooter(){
    var wh = $(window).height();
    var dh = $("#everything").height();
    if(dh < wh - 104) { /*104: #thefooter height in px*/
      $("#thefooter").addClass("footerissticky");
      }
    else {
      $("#thefooter").removeClass("footerissticky");
      }
    }

  putFooter();
  $(window).bind("load", function(){ putFooter(); });
  $(window).resize(function(){ putFooter(); });

});

and the CSS:
.footerissticky{
  position: fixed;
  bottom: 0px;
  width: 870px;
}

A: You can avoid Javascript at all using this technique:
http://ryanfait.com/sticky-footer/

A: JQuery has added data-position="fixed" to solve this. Answered in - jQuery Mobile: Stick footer to bottom of page


text:
Q: Desencriptar una cadena recibida utilizando llave pública en PHP dentro de Laravel Tengo este código para desencriptar una cadena, de hecho dejo también la cadena por si alguien quiere probar.
$str = 'MIIBBgKBgDI/ranPo8MDfguQfSzqg7mtNlUJLLBK7tlVALyk42agbLTSFcZbs9Yw t3nSe9yNzZB9ZVrL3O9GXkEb6xvj3dqrog+wWOeFCqNV7BuJNYYC/ef4vlnUFQdw yswbd7d198qjWBZ7MiZRXxX8qKRln+osTvsDYOMZk93k0cGZgyuJAoGAHkgFohgA nH93kDPjN4sHaT9WsmZ4ailbMtcnWuLizTRJ2sdGjNrpuwT1R+x1nlYHOeDUSOu6 De0kQJX+HZuQCoha6THsdgcV297krN22FwsDZ1PItXLIr5oC7zcNQaDyAJOIv6BC ufHQ0IR+L9b9esniMbF8yV0d7EVAaBJiyRk=';

$Cifrado = base64_decode($str);
openssl_public_decrypt ($Cifrado, $decrypted , file_get_contents('D:/cert.pem'),OPENSSL_PKCS1_PADDING);
echo "Data decryption : ".$decrypted;

dd($decrypted);

El resultado siempre "da null", pero no da error. Es PHP 7.2, sobre Windows tiene todas las extensiones necesarias instaladas.
Si a alguien le ha pasado o sabe a qué se debe el error, agradecería pueda ayudarme.

PD: El resultado deberían ser 4 dígitos ejemplo 0341


text:
Q: Ajax Authorization Header has not been sent I'm having some difficulties with my Ajax Authorization header. I try to send it this way:
$.ajax({
    url: query,
    type: "GET",
    accept: "application/json",
    dataType: 'json',
    beforeSend: function (xhr) {
        alert('1');
        var bytes = Crypto.charenc.Binary.stringToBytes("xxxxxxxx:xxxxxxxxx");
        alert('2'+bytes);
        var bas64 = Crypto.util.bytesToBase64(bytes);
        alert('3'+bas64);
        xhr.setRequestHeader("Authorization", "Basic " + bas64);
        alert('up and awaaaaaaaay');
    },
    succes: function (result) {
        alert('success!');
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.responseText);
        //$('#DisplayInfoLoader').html('An Error occured....' + xhr.responseText + '');
        //$('#DisplayInfoLoader').fadeOut(3000);
    }
});

But when I try th code.. it does not send the header... Going to the query-url by hand and filling in the credentials work... and even with the credentials in a session (/client GET request sends the Authorization header perfectly) the header is NOT sent when accessing the /Project URI....

A: The solution was that the headers weren't allowed by the service. The browser removes every header that won't be allowed by the service.
Make sure the service uses the Access-Control-Allow-Headers header! That's what I have learned


text:
Q: Migrate APT repository from flat to regular format transparently to the end user I have some users, that are subscribed to my APT repository. It had been in "flat format", and its deb string looked like deb http://uri directory/.
Now, I am updating the repository format to standard pool/dists structure, so the deb string looks like deb http://uri distribution main.
Is there a way to migrate to the new-style repository format transparently for existing users?


text:
Q: TypeError: plot() missing 1 required positional argument: 'kind' I am working through a Kaggle tutorial on a network graphic with plotly. After some updating to get the code compatible with chart_studio, I am now getting the error:
TypeError: plot() missing 1 required positional argument: 'kind'

The code I have entered to try and get the graph is:
import plotly.express as px
import pandas as pd
import networkx as nx
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
import plotly.graph_objs as go
import numpy as np

init_notebook_mode(connected=True)

#AT&T network data
network_df=pd.read_csv('network_data.csv')

#source_ip and destination_ip are of our interest here. so we isolate them. We then get the unique ip addresses for getting
#the total number of nodes. We do this by taking unique values in both columns and joining them together.

A = list(network_df["source_ip"].unique())
B = list(network_df["destination_ip"].unique())
node_list = set(A+B)

#Creating the Graph

G = nx.Graph()

#Graph api to create an empty graph. And the below cells we will create nodes and edges and add them to our graph
for i in node_list:
    G.add_node(i)

G.nodes()

pos = nx.spring_layout(G, k=0.5, iterations=50)

for n, p in pos.items():
    G.nodes[n]['pos'] = p

edge_trace = go.Scatter(
    x=[],
    y=[],
    line=dict(width=0.5,color='#888'),
    hoverinfo='none',
    mode='lines')

for edge in G.edges():
    x0, y0 = G.node[edge[0]]['pos']
    x1, y1 = G.node[edge[1]]['pos']
    edge_trace['x'] += tuple([x0, x1, None])
    edge_trace['y'] += tuple([y0, y1, None])

node_trace = go.Scatter(
    x=[],
    y=[],
    text=[],
    mode='markers',
    hoverinfo='text',
    marker=dict(
        showscale=True,
        colorscale='RdBu',
        reversescale=True,
        color=[],
        size=15,
        colorbar=dict(
            thickness=10,
            title='Node Connections',
            xanchor='left',
            titleside='right'
        ),
        line=dict(width=0)))

for node in G.nodes():
    x, y = G.nodes[node]['pos']
    node_trace['x'] += tuple([x])
    node_trace['y'] += tuple([y])

for node, adjacencies in enumerate(G.adjacency()):
    node_trace['marker']['color']+=tuple([len(adjacencies[1])])
    node_info = adjacencies[0] +' # of connections: '+str(len(adjacencies[1]))
    node_trace['text']+=tuple([node_info])

#Start plotting
fig = go.Figure(data=[edge_trace, node_trace],
             layout=go.Layout(
                title='<br>AT&T network connections',
                titlefont=dict(size=16),
                showlegend=False,
                hovermode='closest',
                margin=dict(b=20,l=5,r=5,t=40),
                annotations=[ dict(
                    text="No. of connections",
                    showarrow=False,
                    xref="paper", yref="paper") ],
                xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
                yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)))

#the above code gave me an error because it wasn't set up for chart_studio

iplot(fig)
plotly.plot(fig)

from chart_studio.plotly import plot
from chart_studio import plotly
import plotly
import chart_studio

chart_studio.tools.set_credentials_file(username='anand0427', api_key='5Xd8TlYYqnpPY5pkdGll')

iplot(fig,"anand0427",filename="Network Graph.html")

iplot(fig)
plotly.plot(fig)

Any help would be appreciated.
I have looked around trying to figure out what kind means and how to adapt it for this graph.
Full traceback:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-e49e5cb9a1e3> in <module>()
      2
      3 iplot(fig)
----> 4 plotly.plot(fig)

TypeError: plot() missing 1 required positional argument: 'kind'

A: The problem comes from the ambiguous import statements that both your code and the tutorial use.
You have
from chart_studio import plotly
import plotly

which means that you define plotly twice, and only the second definition remains. The tutorial has the same problem, with from plotly import plotly followed by import plotly.
So when you call plotly.plot(), you're not calling chart_studio.plotly.plot(), which I believe is your intention, but instead you're calling the plot() function defined in plotly/__init__.py, whose in-code documentation says it's not intended to be called directly.
Unless you know you need it, remove the line import plotly, or change one of those two import lines to say as <some other name>, which will let you refer to chart_studio.plotly and the base plotly by different, unambiguous names.


text:
Q: Add Shortcode inline inside Gutenberg block In the legacy (classic editor) it was possible to add buttons to the editor toolbar via tinymce API, that will add shortcode at cursor.
seems like this is not supported anymore from the tinymce FQA and this Gutenberg migration guide
Seems like it would be possible with the plugin tinymce advanced but I wonder what is today the best practice to add add a button to a tiny mce button to the the simple text editor of paragraph block.
The format API allows to add a custom format with tag and class around text, but does not to support adding string after text
Also, seems like this in the roadmap of the format API, but its not clear id its possible or not.
What is the best practice to add a button to tinymce editor tollbar in a simple paragraph block which will add text (shortcode for example) at cursor?
I added screenshot to clarify to which toolbar I refer.

A: They have actually fixed it so you can just add the shortcode within the paragraph content and it works.
As simple as
...However, when [expand tag="span" title="this trigger" targtag="span"]hidden content[/expand] is clicked…

That would be the contents of a paragraph block with inline shortcode. See this for more information.

A: you can do this with this filter :
function do_shortcode_in_gut($block_content, $block) {
    return do_shortcode($block_content);
}
add_filter( 'render_block', 'do_shortcode_in_gut', 99, 2 );

This filtering your block render and do shortcode.

You can see in this screenshot I use a date shortcode with attributes.
And the result :


text:
Q: How do I query for distinct values in Mongoose but return all of the doc? Using mongoose and it's distinct function... how can i combine a find with regex and distict, and return the full document?
Using the distinct function https://docs.mongodb.com/manual/reference/method/db.collection.distinct/#options just returns the unique fields.
This is what i instead cobbled together with lodash..
findByTitle: ( title ) => {
    return new Promise( ( resolve, reject ) => {

        solutionModel.find( {"Title": { $regex: new RegExp( title ,'i') }}, (err, docs) => {
            if( err ) return reject( err );

            return resolve( _.uniqBy(docs, (e) => {
                return e.SolutionID;
            }) );
        });

    } );
},

Trailing with aggregate:
solutionModel.aggregate(
    [
        { "$match": {
            "Title": { $regex: new RegExp( 't' ,'i') }
        }},
        // Grouping pipeline
        { "$group": {
            "SolutionID": '$SolutionID'
        }},
        // Sorting pipeline
        { "$sort": { "Title": -1 } },
        // Optionally limit results
        // { "$limit": 5 }
    ],
    function(err,docs) {

        console.log( err );
        console.log( docs );
    }
);

Results in error:

MongoError: The field 'SolutionID' must be an accumulator object

A: Wrong syntax for $group. Please read https://docs.mongodb.com/manual/reference/operator/aggregation/group/.
E.g. grouping by SolutionID, storing the first matching document in 'doc':
{ "$group": {
    _id: "$SolutionID",
    doc: {$first: "$$ROOT"}
}


text:
Q: How to initialize correctly the zoom level in a SharpMap object? I'm working with a MapBox object from SharpMap in a Windows Forms C# app and I can't seem to find how to make the zoom level work. The MapBox object is in a TabControl object.
This class is called after the main InitializeComponent() call in my app.
public void InitializeMap(SharpMap.Forms.MapBox mapBox)
        {
            mapBox.Map.BackgroundLayer.Add(new SharpMap.Layers.TileAsyncLayer(
                new BruTile.Web.OsmTileSource(), "OSM"));

            mapBox.Map.Zoom = 10; //
            mapBox.Refresh();
        }

Whatever value written for the mapBox.Map.Zoom attribute, it's always the same high zoom level.
On the other hand, if I use mapBox.Map.ZoomToExtents() call, it zooms to the extents of the OSM layer correctly.
I suppose I'm doing wrong a simple thing, but I can't seem to find what is the problem.

A: mapBox.Map.Zoom is always the same as mapBox.Map.Envelope.Width.
Instead of just setting the zoom like that, try using mapBox.Map.ZoomToBox(new GeoAPI.Geometries.Envelope(-5.0, 5.0, -5.0, 5.0)). The map will be positioned and zoomed so that the entirety of the envelope is within the map.
The envelope in my example has a width of 10, but if your map is wider than it is high mapBox.Map.Zoom will be greater than that, since (as I stated above) its value is the same as the width of the visible part of the map.


text:
Q: Mongo failing to deserialize class with enums I have this enum:
public enum EventType
    {
        Regular = 1,
        Error = 2,
        AccessDenied = 3,
        Warning = 4,
        Maintenance = 5,
        CustomMade = 6
    }

I have the following class:
[DataContract]
    public class Event : IEvent
    {
        [DataMember(Name = "eventType", IsRequired = true)]
        public EventType EventType { get; set; }

        [DataMember(Name = "occuringDate", IsRequired = true)]
        public DateTime OccuringDate { get; set; }

        [DataMember(Name = "physicalServerId", IsRequired = true)]
        public string PhysicalServerId { get; set; }

        [DataMember(Name = "text", IsRequired = true)]
        public string Text { get; set; }

        [DataMember(Name = "systemIds", IsRequired = true)]
        public ICollection<string> SystemIds { get; set; }

        [DataMember(Name = "_id", IsRequired = true)]
        public string Id { get; set; }
    }

And when I insert it into my mongo collection I get the following object (in mongo):
{ "_id" : "1", "eventType" : 1, "occuringDate" : "2014-02-12T20:04:20.4328247+02
:00", "physicalServerId" : "10", "text" : "User has logged in successfully.", "s
ystemIds" : [  "1",  "3" ], "details" : "userId: 2" }

Now, when I try to read the the object like this:
MongoClient mongoClient = new MongoClient(connectionString);
MongoServer mongoServer = mongoClient.GetServer();
this.db = mongoServer.GetDatabase("eventsLog");
eventsCollection = this.db.GetCollection<Event>("eventsLog");
eventsCollection.Exists();
this.eventsCollection.FindAll().SetSkip((int)(page * perPage)).SetLimit((int)perPage).ToList();

I get an exception: Element 'eventType' does not match any field or property of class LogAggregation.PublicLibrary.Models.Event.
What am I doing wrong?

A: Try using the BsonAttributes to control serialization/deserialization overrides
 [BsonElement("eventType")]

Instead of
[DataMember(Name = "eventType", IsRequired = true)]


text:
Q: Casting a variable to a method in Scala "Runtime Evaluation" I want to evaluate a function passed as a variable string in scala (sorry but i'm new to scala )
def concate(a:String,b:String): String ={
  a+" "+b
}
var func="concate" //i'll get this function name from config as string

I want to perform something like
eval(func("hello","world)) //Like in Python

so output will be like

hello world

Eventually I want to execute few in built functions on a string coming from my config and I don't want to hard code the function names in the code.

EDIT

To Be More clear with my exact usecase
I have a Config file which has multiple functions defined in it that are Spark inbuilt functions on Data frame
application.conf looks like
  transformations = [
  {
    "table" : "users",
    "function" : "from_unixtime",
    "column" : "epoch"
  },
  {
    "table" : "users",
    "function" : "yearofweek",
    "column" : "epoch"
  }
]

Now functions yearofweek and from_unixtime are Spark inbuilt functions now I want to eval my Dataframe by the functions defined in config. #all the functions are applied to a column defined.
the Obvious way is to write an if else and do string comparison calling a particular inbuilt function but that is way to much..
i am looking for a better solution.

A: This is indeed possible in scala, as scala is JSR 223 compliant scripting language. Here is an example (running with scala 2.11.8). Note that you need to import your method because otherwise the interpreter will not find it:
package my.example

object EvalDemo {

  // evalutates scala code and returns the result as T
  def evalAs[T](code: String) = {
    import scala.reflect.runtime.currentMirror
    import scala.tools.reflect.ToolBox
    val toolbox = currentMirror.mkToolBox()
    import toolbox.{eval, parse}
    eval(parse(code)).asInstanceOf[T]
  }

  def concate(a: String, b: String): String = a + " " + b

  def main(args: Array[String]): Unit = {

    var func = "concate" //i'll get this function name from config as string

    val code =
      s"""
         |import my.example.EvalDemo._
         |${func}("hello","world")
         |""".stripMargin

    val result: String = evalAs[String](code)

    println(result) // "hello world"
  }
}

A: Have Function to name mapping in the code
def foo(str: String) = str + ", foo"
def bar(str: String) = str + ", bar"

val fmap = Map("foo" -> foo _, "bar" -> bar _)

fmap("foo")("hello")

now based on the function name we get from the config, pass the name to the map and lookup the corresponding function and invoke the arguments on it.
Scala repl
scala> :paste
// Entering paste mode (ctrl-D to finish)

def foo(str: String) = str + ", foo"
def bar(str: String) = str + ", bar"

val fmap = Map("foo" -> foo _, "bar" -> bar _)

fmap("foo")("hello")

// Exiting paste mode, now interpreting.

foo: (str: String)String
bar: (str: String)String
fmap: scala.collection.immutable.Map[String,String => String] = Map(foo -> $$Lambda$1104/1335082762@778a1250, bar -> $$Lambda$1105/841090268@55acec99)
res0: String = hello, foo

A: Spark offers you a way to write your transformations or queries using SQL. So, you really don't have to worry about Scala functions, casting and evaluation in this case. You just have to parse your config to generate the SQL query.
Let's say you have registered a table users with Spark and want to do a select and transform based on provided config,
// your generated query will look like this,
val query = "SELECT from_unixtime(epoch) as time, weekofyear(epoch) FROM users"

val result = spark.sql(query)

So, all you need to do is - build that query from your config.


text:
Q: Calculate business days in future to send reminder emails I am working on this employee performance review application. I need to send out reminder emails when the user has left 3 and 1 business days before the end of the 15 business day period.
Here is how I plan on doing it:
 I have the Last Modified Date for each Review which I should be able to use to find out 15 business days in future(call it deadLineToSubmit for our example). Once I got deadLineToSubmit I should check to see if currentDate + 3 days(date) == deadLineToSubmit Then add that review to my list which I will be using to send email.
I have a function called GetByDayPrior where I am sending values 3 and 1 to check if user have left 3 business days or 1. Below is the code:
    public List<int> GetByDaysPrior(int daysPrior)
    {
        List<int> response = new List<int>();

        using (DAL.HumanResourcesEntities context = new DAL.HumanResourcesEntities())
        {
            DateTime currentDate = DateTime.Now.Date;
            var lastModifiedDate = context.Reviews
                                    .Where(s => s.IsActive == false)
                                    .Where(s => s.ReviewStatusId == (int)ReviewStatuses.EmployeeSignature)
                                    .Select(v => v.ModifiedDate)
                                    .ToList();
            AddBusinessDays(lastModifiedDate, daysPrior);

            var lastRuntime = context.ApplicationRuntimeVariables.Where(y => y.ParameterName == "RemindersSentDT").Select(x => x.ParameterValue).FirstOrDefault().Date;

            DateTime deadLineToSubmitReview = currentDate.AddDays(daysPrior).Date;
            if (lastRuntime.AddHours(24).Date <= currentDate) //should it be == current date ?
            {
                var reviewIDs = context.Reviews
                                        .Where(s => s.ModifiedDate < deadLineToSubmitReview)
                                        .Where(s => s.ReviewStatusId == (int)ReviewStatuses.EmployeeSignature) //Check to make sure reminders only go when Review Status is Employee Signature
                                        .Where(s => s.IsActive == false)
                                        .Select(v => v.ReviewId)
                                        .ToList();

                response = reviewIDs.ToList();
            }

            return response;
        }
    }

I have another function called AddBusinessDays should give me the deadLineToSubmit when I pass in LastModifiedDate and 15 days as parameter. But currently its not working because firstly I cannot find out how to pass List of DataTime as a paramater in this function. Also when I defined date parameter in AddBusinessDays as List now all the instances of date and DayOfWeek are complanining

"Error   32  Cannot implicitly convert type
  'System.Collections.Generic.List' to
  'System.DateTime'

Below is my AddBusinessDays function.
 public static DateTime AddBusinessDays(List<DateTime> date, int days)
    {
        if (days < 0)
        {
            throw new ArgumentException("days cannot be negative", "days");
        }

        if (days == 0) return date;

        if (date.DayOfWeek == DayOfWeek.Saturday)
        {
            date = date.AddDays(2);
            days -= 1;
        }
        else if (date.DayOfWeek == DayOfWeek.Sunday)
        {
            date = date.AddDays(1);
            days -= 1;
        }

        date = date.AddDays(days / 5 * 7);
        int extraDays = days % 5;

        if ((int)date.DayOfWeek + extraDays > 5)
        {
            extraDays += 2;
        }

        return date.AddDays(extraDays);

    }

Here's what I need to know: How to send DateTime List as parameter in AddBusinessDays function. How to make AddBusinessDays function work because now we are passing list instead of single dateTime. Is my thinking logic correct to solve this issue ?
Thanks a Lot! :)

A: date is a list and not a single date.
You can make an operation on all items of the list by using Select
for example:
lastModifiedDate = AddBusinessDays(lastModifiedDate, daysPrior);

Step 1: Convert your function to receive a single date
private static DateTime AddBusinessDays(DateTime date, int days)
{
    if (days < 0)
    {
        throw new ArgumentException("days cannot be negative", "days");
    }

    if (days == 0) return date;

    if (date.DayOfWeek == DayOfWeek.Saturday)
    {
        date = date.AddDays(2);
        days -= 1;
    }
    else if (date.DayOfWeek == DayOfWeek.Sunday)
    {
        date = date.AddDays(1);
        days -= 1;
    }

    date = date.AddDays(days / 5 * 7);
    int extraDays = days % 5;

    if ((int)date.DayOfWeek + extraDays > 5)
    {
        extraDays += 2;
    }

    return date.AddDays(extraDays);
}

Step 2: Use the single date function for the list of dates
public static List<DateTime> AddBusinessDays(List<DateTime> date, int days)
{
    return date.Select(d => AddBusinessDays(d, days)).ToList();
}


text:
Q: Create a new db user in SQL Server 2005 how do you create a new database user with password in sql server 2005?
i will need this user/password to use in the connection string eg:
uid=*user*;pwd=*password*;

A: As of SQL Server 2005, you should basically create users in two steps:

*

*create a "login" to your SQL Server as a whole

*create users for this login in each database needed

You'd go about doing this like so:
CREATE LOGIN MyNewUser WITH PASSWORD = 'top$secret';

And the "USE" your database and create a user for that login:
USE AdventureWorks;
CREATE USER MyNewUser FOR LOGIN MyNewUser

A: As indicated, use the CREATE LOGIN to create the ability to connect to SQL Server as that account. Then use CREATE USER within the database to give that login the ability to access the database in question.
However, a few security points based on some of these comments:

*

*If at all possible, you want to use Windows authentication, not a SQL Server based login (which is what you are doing when you use user/pwd in this manner). If you are running from a computer on the same domain as SQL Server, you can use a service account that is a Windows user account. This ensures the domain is the single source for security.

*You didn't say what rights the user needed. Avoid using db_datareader and db_datawriter roles whenever possible. They give IMPLICIT access to tables and views and if someone is performing a quick permissions check on the database, they may not think to check the membership in these roles. That means your reporting on security is using. Best practices say to create your own database role, assign permissions to it, and make the user a member of that role.

*Whenever possible, use a strong password. One example had the password policies turned off. SQL Server will use the password policy from the local server (which is usually set at the domain level). You want to maintain that strong password policy, if possible.

A: CREATE LOGIN [user] WITH PASSWORD='password',
       DEFAULT_DATABASE=[your_db], CHECK_POLICY=OFF
GO

CREATE USER [user] FOR LOGIN [user]
EXEC sp_addrolemember N'db_datareader', N'your_db'
EXEC sp_addrolemember N'db_datawriter', N'your_db'
GO

Where CHECK_POLICY=OFF switches off password complexity check, etc

A: You'll have to create it first as a user, and then set up the correct permissions for the user.

*

*you'll have to ensure that your DB is configured with both User auth and SQL auth
If using the Management Studio: right-click on the Server, select "Security" ensure that server authentication is "SQL Server and Windows Authentication mode"

*in Security-logins, right click and select  "New Login", select SQL Authentication, use the username and password you like.
USE [master]
GO
CREATE LOGIN [ test] WITH PASSWORD=N'test', DEFAULT_DATABASE=[MY_DATABASE], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
GO

*on the DB you want, in security, users, select new User.  Select a username, and attach the login name you've just created, and select the roles you want to apply to this user (i.e. db_datareader, db_datawriter):
USE [MY_DATABASE]
GO
CREATE USER [myDefaultUser] FOR LOGIN [ test]
GO
USE [MY_DATABASE]
GO
EXEC sp_addrolemember N'db_datareader', N'myDefaultUser'
GO
USE [MY_DATABASE]
GO
EXEC sp_addrolemember N'db_datawriter', N'myDefaultUser'
GO

That is it. Now you can create your connection string using this password.

A: CREATE LOGIN MyNewUser WITH PASSWORD = 'top$secret'

USE AdventureWorks
CREATE USER MyNewUser FOR LOGIN MyNewUser
GO

A: USE [MASTER]

EXEC master.dbo.sp_addlogin @loginame = N'USERNAME', @passwd = 'THEPASS' @defdb = N'master', @deflanguage = N'us_english'

USE [YOUR_DB]
    EXEC dbo.sp_grantdbaccess @loginame = N'USERNAME', @name_in_db = N'USERNAME'


text:
Q: New Infopath 2013 in O 365: Select the form template to open this xml file I create a new forms library in o365/SPO. I click new document and it opens InfoPath2013 and asks for

Select the form template to open this xml file

Where do I get this from?
Also if select New InfoPath 2013 is says Find a form
I see no design option, or save as. All the design features are grayed out.
I confirmed I am logged into o365 as my corporate user that is using ADFS.
From InfoPath 2013 if I select NEW I'm only offered Find a Form.
How do I create a new Infopath form or template?
Where can I find templates?
It's an A2 Office 365 license and I have owner rights to the library.

A: You must first have a template.
Apparently it works if you open Infopath and then select the SharePoint list data source and not the other way around.


text:
Q: Rails Gecoder Nearby Logic I am trying to return a default location using the Geocoder Gem if there is nothing nearby. However, my logic always returns the first location in DB, which is what I want but it should return a valid nearby request if conditions met. Here is my controller:
def nearby
    respond_to do |format|
      @locations = Location.nearby([nearby_location_params[:latitude], nearby_location_params[:longitude]], nearby_location_params[:distance])
    if @location == 1
      format.json { render json: @locations, status: :success }
    else
      @locations = Location.first
      format.json { render json: @locations }
    end
  end
end

Its my guess that: if @location == 1 is the culprit.
Here I am trying to say, if the conditions met in distance param, show that location. If not, show first in DB.
Is there a better approach?

A: you're not setting @location, but even if, you would not want to compare it to an integer, since its supposed to be a location object. i think tou want something like
if @locations.any?

also, i'd put the default location also in an array, so that the @locations is always the (sort of) same type: something iterable.


text:
Q: How to access the object returned by a function inside python class I have the following python class:
class Example(QMainWindow):

   def onChanged(self, text):

     return text

   def buttonClicked(self):

     print(self.onChanged)

when I run the script i get the following result:
<bound method Example.onChanged of <__main__.Example object at 0x7fde1cab0550>>

My question is how to get the content of the text returned in  onChanged function ?
Thank you.

A: When you execute print(self.onChanged) you don't call the function, you should execute print(self.onChanged()) instead.


text:
Q: Convergence in Hausdorff metric Consider a sequence $(A_n)$ of bounded, convex subsets of $\mathbb{R}^n$ such that $\text{int}(A_n)\neq\emptyset$ for all $n$ and  $\text{clo}(A_n)\neq \text{clo}(A_m)$ whenever $m\neq n$, where $\text{int}(\cdot)$ and $\text{clo}(\cdot)$ denotes interior and closure, respectively.
Suppose $A_n\rightarrow A$ in the Hausdorff metric.
Is it true that every sequence $(x_n)$ in $\mathbb{R}^n$ such that $x_n\in A_n$ for all $n$ converges to a point in $A$?

A: No not quite. The sequence may jump around within $A_n$. E.g. A_n a line interval that rotates to a fixed interval $A$. And $x_n$ jumps up and down the interval as n increases. You'd have to pass to a subsequence of $x_n$ to get convergence.


text:
Q: Ranking within multiple groups - R I have a dataframe like this:
country =  c("Austria", "Austria","Austria","Austria", "Brazil", "Brazil", "Brazil", "Brazil", "USA", "USA", "USA", "USA",
             "Austria", "Austria","Austria","Austria", "Brazil", "Brazil", "Brazil", "Brazil", "USA", "USA", "USA", "USA")
tech = c("cars", "cars","cars","cars","cars","cars","cars","cars","cars","cars","cars","cars","planes","planes","planes",
         "planes","planes","planes","planes","planes","planes","planes","planes","planes")
year =  c(2010, 2011, 2012, 2013, 2010, 2011, 2012, 2013, 2010, 2011, 2012, 2013,2010, 2011, 2012, 2013, 2010, 2011, 2012,
          2013, 2010, 2011, 2012, 2013)
value = c(42, 23, 13, 13, 646,454, 23, 234, 12, 123, 1, 23, 23, 54, 2, 77, 584, 66, 767, 6767, 23, 12, 12, 99)

df = data.frame(tech, country, year, value)

I want a new column where I have rankings for the countries by year within each tech using the values.
So, in 2013, for planes, I want to be able to say "USA" ranked 1st (had the highest value for that year and tech).
I know how to rank within one group e.g. if I didnt have tech, and I wanted to rank by country and year, I would do:
df = df %>%
  group_by(year) %>%
  arrange(country) %>%
  mutate(`whatever` = order(order(value, decreasing = TRUE)))

However, I am stumped on how to add tech into the mix i.e. rank by tech for each year for the countries.
Does anyone have any guidance?

A: Does this help you?
library(tibble)
library(dplyr)

country =  c("Austria", "Austria","Austria","Austria", "Brazil", "Brazil", "Brazil", "Brazil", "USA", "USA", "USA", "USA",
             "Austria", "Austria","Austria","Austria", "Brazil", "Brazil", "Brazil", "Brazil", "USA", "USA", "USA", "USA")
tech = c("cars", "cars","cars","cars","cars","cars","cars","cars","cars","cars","cars","cars","planes","planes","planes",
         "planes","planes","planes","planes","planes","planes","planes","planes","planes")
year =  c(2010, 2011, 2012, 2013, 2010, 2011, 2012, 2013, 2010, 2011, 2012, 2013,2010, 2011, 2012, 2013, 2010, 2011, 2012,
          2013, 2010, 2011, 2012, 2013)
value = c(42, 23, 13, 13, 646,454, 23, 234, 12, 123, 1, 23, 23, 54, 2, 77, 584, 66, 767, 6767, 23, 12, 12, 99)

df = tibble(tech, country, year, value)
df
#> # A tibble: 24 x 4
#>    tech  country  year value
#>    <chr> <chr>   <dbl> <dbl>
#>  1 cars  Austria  2010    42
#>  2 cars  Austria  2011    23
#>  3 cars  Austria  2012    13
#>  4 cars  Austria  2013    13
#>  5 cars  Brazil   2010   646
#>  6 cars  Brazil   2011   454
#>  7 cars  Brazil   2012    23
#>  8 cars  Brazil   2013   234
#>  9 cars  USA      2010    12
#> 10 cars  USA      2011   123
#> # … with 14 more rows

df %>%
  group_by(tech, year) %>%
  mutate(rank = rank(value)) %>%
  arrange(tech, year, rank)
#> # A tibble: 24 x 5
#> # Groups:   tech, year [8]
#>    tech  country  year value  rank
#>    <chr> <chr>   <dbl> <dbl> <dbl>
#>  1 cars  USA      2010    12     1
#>  2 cars  Austria  2010    42     2
#>  3 cars  Brazil   2010   646     3
#>  4 cars  Austria  2011    23     1
#>  5 cars  USA      2011   123     2
#>  6 cars  Brazil   2011   454     3
#>  7 cars  USA      2012     1     1
#>  8 cars  Austria  2012    13     2
#>  9 cars  Brazil   2012    23     3
#> 10 cars  Austria  2013    13     1
#> # … with 14 more rows

Created on 2020-03-20 by the reprex package (v0.3.0)


text:
Q: Oracle circle distance search: missing results EDIT: (If u want see the old problematic, see at the bottom of this question)
With your helps i modified my statement:
SELECT *
  FROM (
          SELECT
                dest.ZC_ZIP,
                dest.ZC_LOCATION_NAME,
                ACOS(
                    SIN(RADIANS(src.ZC_LAT)) * SIN(RADIANS(dest.ZC_LAT))
                    + COS(RADIANS(src.ZC_LAT)) * COS(RADIANS(dest.ZC_LAT))
                    * COS(RADIANS(src.ZC_LON) - RADIANS(dest.ZC_LON))
                    ) * 6371 AS DISTANCE
          FROM USER.ZC_COORDINATES dest
          CROSS JOIN USER.ZC_COORDINATES src
          WHERE src.ZC_ID =
                (SELECT
                        ZC_ID
                        FROM USER.ZC_COORDINATES
                        WHERE ZC_ZIP = '64289'
                        GROUP BY ZC_ID
                )
                AND
                (dest.ZC_ID <> src.ZC_ID OR dest.ZC_ID = src.ZC_ID)
      )
  HAVING DISTANCE <= 25 /* km */
  ORDER BY DISTANCE;

After this i get the error: "Radians" are invalid identifier.
Reason: Oracle doenst implements that function (MySQL does!).
So i search and found this Code and use it:
CREATE OR REPLACE FUNCTION calc_distance(pLat1 NUMBER, pLon1 NUMBER, pLat2 NUMBER, pLon2 NUMBER)
 RETURN NUMBER IS

-- r is the spherical radius of earth in Kilometers
cSpherRad CONSTANT NUMBER := 6371;

-- The spherical radius of earth in miles is 3956
a        NUMBER;
vLat     NUMBER;
vLat1Rad NUMBER;
vLat2Rad NUMBER;
vLon     NUMBER;
vLon1Rad NUMBER;
vLon2Rad NUMBER;

BEGIN
  /*
  Most computers require the arguments of trigonometric functions to be
  expressed in radians. To convert lon1, lat1 and lon2,lat2 from
  degrees,minutes, seconds to radians, first convert them to decimal
  degrees. To convert decimal degrees to radians, multiply the number
  of degrees by pi/180 = 0.017453293 radians/degrees.
  */

  vLat1Rad := pLat1 * 0.017453293;
  vLat2Rad := pLat2 * 0.017453293;
  vLon1Rad := pLon1 * 0.017453293;
  vLon2Rad := pLon2 * 0.017453293;

  vLon := vLon2Rad - vLon1Rad;
  vLat := vLat2Rad - vLat1Rad;

  a := POWER(SIN(vLat/2),2) + COS(vLat1Rad) * COS(vLat2Rad) * POWER(SIN(vLon/2),2);

  /*
  The intermediate result c is the great circle distance in radians.
  Inverse trigonometric functions return results expressed in radians.
  To express c in decimal degrees, multiply the number of radians by
   180/pi = 57.295780 degrees/radian.
  The great circle distance d will be in the same units as r.
  */

  RETURN ROUND(cSpherRad * 2 * ATAN2(SQRT(a), SQRT(1-a)),1);
EXCEPTION
  WHEN OTHERS THEN
    RETURN 999;
END calc_distance;
/

Successfully compilation.
Now the correct modification without group by errors:
SELECT *
  FROM (
          SELECT
                dest.ZC_ZIP AS ZIP,
                dest.ZC_LOCATION_NAME AS LOCNAME,
                calc_distance(src.ZC_LAT, src.ZC_LON, dest.ZC_LAT, dest.ZC_LON) AS DISTANCE
          FROM BASE.ZC_COORDINATES dest
          CROSS JOIN BASE.ZC_COORDINATES src
          WHERE src.ZC_ID =
                (SELECT
                        ZC_ID
                        FROM BASE.ZC_COORDINATES
                        WHERE ZC_ZIP = '64289'
                        GROUP BY ZC_ID
                )
                AND
                (dest.ZC_ID <> src.ZC_ID OR dest.ZC_ID = src.ZC_ID)
      )
  HAVING DISTANCE <= 25 /* km */
  GROUP BY ZIP, LOCNAME, DISTANCE;
  --ORDER BY DISTANCE;

Whats the problem now?
Ok, on my old locals MySQL system i get these sql results (correct solution):
zc_zip  zc_location_name  distance
64291   Darmstadt         0
64297   Darmstadt         0
64289   Darmstadt         0
64283   Darmstadt         0
64285   Darmstadt         0
64295   Darmstadt         0
64293   Darmstadt         0
64287   Darmstadt         0
64347   Griesheim, Hessen 5.385545333978872
64331   Weiterstadt       5.671376373674798
64367   M├╝hltal, Hessen  6.992565870106159
64319   Pfungstadt        7.7621346384241585
64380   Roßdorf bei Darmstadt 8.134881711148836
64372   Ober-Ramstadt     8.421977582053422
64390   Erzhausen, Hessen 9.419234655429722
64572   B├╝ttelborn       9.739076077060767
64409   Messel            9.962635340560048
63329   Egelsbach, Hessen 11.274247321555363
64342   Seeheim-Jugenheim 11.743554066395413
64560   Riedstadt         12.135040456984065
64404   Bickenbach        12.597317271640899
64521   Groß-Gerau       12.637599535794854
64397   Modautal          13.260629389533909
64846   Groß-Zimmern     13.270265030251164
63225   Langen (Hessen)   13.745513110307494

Thats i get from the oracle system:
ZIP     LOCNAME     DISTANCE
64293   Darmstadt   0
64283   Darmstadt   0
64295   Darmstadt   0
64285   Darmstadt   0
64297   Darmstadt   0
64287   Darmstadt   0
64289   Darmstadt   0
64291   Darmstadt   0

You see, some reults are missing.
I think the problem is the "GROUP BY" line in the oracle statement, which are needed.
So i cant delete this line. But how i can get my other results? I'm realy confused :(

(Old problematic)
At the moment i program a circle zip search for my employee.
My tool works under construction on my MySQL Database (local).
Now i migrate my OpenGeoDB into our oracle database (successfully) and want run my sql statement which works perfectly on my local MySQL database.
The full error message:
ORA-00904: "DISTANCE": invalid indentifier
00904. 00000 -  "%s: invalid identifier"
*Cause:
*Action:
Error in line: 20 col: 7

My SQL Statement:
SELECT
    dest.zc_zip,
    dest.zc_location_name,
    ACOS(
        SIN(RADIANS(src.zc_lat)) * SIN(RADIANS(dest.zc_lat))
        + COS(RADIANS(src.zc_lat)) * COS(RADIANS(dest.zc_lat))
        * COS(RADIANS(src.zc_lon) - RADIANS(dest.zc_lon))
    ) * 6371 as distance
FROM USER.ZC_COORDINATES dest
CROSS JOIN USER.ZC_COORDINATES src
WHERE src.zc_id =
    (
    SELECT zc_id
    FROM USER.zip_coordinates
    WHERE zc_zip = '64289' /* Platzhalter fuer PLZ */
    GROUP BY zc_zip
    )

AND (dest.zc_id <> src.zc_id OR dest.zc_id = src.zc_id)
HAVING distance <= 25 /* km */
ORDER BY distance;

What I do to solve this problem?:
I switch the word "distance" with the full math calc, but after this, Oracle call invalid identifier "Radians"
Thats my problem because I dont know how I can solve this problem.
Have someone any ideas to solve that problem?
Thanks.

A: Oracle won't let you use a column computed in the SELECT list in a following ORDER BY. The following is a reasonable workaround:
SELECT *
  FROM (SELECT dest.ZC_ZIP,
               dest.ZC_LOCATION_NAME,
               ACOS(SIN(RADIANS(src.ZC_LAT)) * SIN(RADIANS(dest.ZC_LAT))
                    + COS(RADIANS(src.ZC_LAT)) * COS(RADIANS(dest.ZC_LAT))
                    * COS(RADIANS(src.ZC_LON) - RADIANS(dest.ZC_LON))
                    ) * 6371 AS DISTANCE
          FROM USER.ZC_COORDINATES dest
          CROSS JOIN USER.ZC_COORDINATES src
          WHERE src.ZC_ID = (SELECT ZC_ID
                               FROM USER.ZIP_COORDINATES
                               WHERE ZC_ZIP = '64289'
                               GROUP BY ZC_ZIP) AND
                (dest.ZC_ID <> src.ZC_ID OR
                 dest.ZC_ID = src.ZC_ID))
  HAVING DISTANCE <= 25 /* km */
  ORDER BY DISTANCE;

Oracle also doesn't provide a function for converting degrees to radians but it's easy enough to add your own:
CREATE OR REPLACE FUNCTION RADIANS(nDegrees IN NUMBER) RETURN NUMBER DETERMINISTIC IS
BEGIN
  -- radians = degrees / (180 / pi)
  -- RETURN nDegrees / (180 / ACOS(-1));  -- but 180/pi is a constant, so...
  RETURN nDegrees / 57.29577951308232087679815481410517033235;
END RADIANS;

Share and enjoy.

A: my last answer and solution for this question.
And sorry for the later answer. To much business.
A big thanks to @Bob Jarvis and @Ollie Jones for their help and experience.
What are the problems?

*

*The different between MySQL and Oracle - Statements

*Migration problem with float numbers from MySQL to Oracle with "Oracle SQL Developer"

*Not existing function radians on Oracle

Solutions:
Float number migration:
To fix that problem I do that:
Use phpMyAdmin (PMA)
1. SQL File Select
2. Only data export, no structure or something
3. 1 line for 1 data set
4. Import into existing table on oracle serv
Missing radiant function:
Use this following statement:
CREATE OR REPLACE FUNCTION RADIANS(nDEGREES IN NUMBER)
  RETURN NUMBER DETERMINISTIC IS
  BEGIN
  RETURN nDegrees / 57.29577951;
 END RADIANS;
 /

SQL-Statement (MySQL one):
SELECT
    dest.zc_zip,
    dest.zc_location_name,
    ROUND(ACOS(
        SIN(RADIANS(src.zc_lat)) * SIN(RADIANS(dest.zc_lat))
        + COS(RADIANS(src.zc_lat)) * COS(RADIANS(dest.zc_lat))
        * COS(RADIANS(src.zc_lon) - RADIANS(dest.zc_lon))
    ) * 6371,
  1) as distance
FROM zip_coordinates dest
CROSS JOIN zip_coordinates src
WHERE src.zc_id =
    (
    SELECT zc_id
    FROM zip_coordinates
    WHERE zc_zip = '/zip/' /* placeholder for zip */
    GROUP BY zc_zip
    )
AND dest.zc_lat >= src.zc_lat -((/circle/-0.5)/111.045)
AND dest.zc_lat <= src.zc_lat +((/circle/-0.5)/111.045)
AND dest.zc_lon >= src.zc_lon -((/circle/-0.5)/(111.045 * COS(RADIANS(src.ZC_LAT))))
AND dest.zc_lon <= src.zc_lon +((/circle/-0.5)/(111.045 * COS(RADIANS(src.ZC_LAT))))
HAVING distance <= (/circle/-0.5) /* km */ /* placeholder for radius */
ORDER BY distance, dest.zc_zip;

SQL-Statement (Oracle one):
SELECT *
  FROM (
          SELECT
                dest.ZC_ZIP AS ZIP,
                dest.ZC_LOCATION_NAME AS LOCNAME,
                ROUND(
                 (6371* ACOS(
                      COS(RADIANS(dest.ZC_LAT))
                      * COS(RADIANS(src.ZC_LAT))
                      * COS(RADIANS(src.ZC_LON) - RADIANS(dest.ZC_LON))
                      + SIN(RADIANS(dest.ZC_LAT))
                      * SIN(RADIANS(src.ZC_LAT))
                      )
                 ), 1
                ) AS DISTANCE
          FROM ORACLE_USER.ZC_COORDINATES dest
          CROSS JOIN ORACLE_USER.ZC_COORDINATES src
          WHERE src.ZC_ID =
                (SELECT
                        ZC_ID
                        FROM ORACLE_USER.ZC_COORDINATES
                        WHERE ZC_ZIP = '/zip/'
                        GROUP BY ZC_ID
                )
                AND dest.ZC_LAT >= src.ZC_LAT -((/circle/-0.5)/111.045)
                AND dest.ZC_LAT <= src.ZC_LAT +((/circle/-0.5)/111.045)
                AND dest.ZC_LON >= src.ZC_LON -((/circle/-0.5)/(111.045 * COS(RADIANS(src.ZC_LAT))))
                AND dest.ZC_LON <= src.ZC_LON +((/circle/-0.5)/(111.045 * COS(RADIANS(src.ZC_LAT))))
      )
  HAVING DISTANCE <= (/circle/-0.5) /* km */
  GROUP BY ZIP, LOCNAME, DISTANCE
  ORDER BY DISTANCE;


text:
Q: Passing values from child to parent window on python/tkinter I've been trying to learn Python language for fun and decided it would be best to do it with a project. Since I work in a beer factory, I thought it would be cool to create a simple GUI that would display all tanks on the factory along with each beer it holds and its current status. If I double-click on a tank, it would pop a new window allowing me to edit tank info, but I'm having trouble making the information from the child to display on the parent window (more specifically, I want to change a parent list's item from a combobox on child). Here's an image showing basically what I'm trying to accomplish:

I think that maybe the values are being passed correctly to the list, but they are not being updated to the correspondent Widget to be displayed. I tried calling .update(), .after() and .mainloop() on my function, but nothing changed.
I tried checking other answers, but I was actually hoping there is a way to solve this without resorting to Classes, as I don't quite understand them yet. Here's the simplest smallest version of my code that I could come up with:
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk

def click_duplo_tfm(event):  # recognizes double-click on tanks and opens the specific window
    if event.widget.extra == 'Widget TFM01':
        abrir_janela('01', 1)
    elif event.widget.extra == 'Widget TFM02':
        abrir_janela('02', 2)

def salvar_alteracoes():
    print('THIS FUNCTION IS SUPPOSED TO PASS CHANGES TO PARENT WINDOW')

def abrir_janela(num_tfm, ref):  # opens a new window to alter tank info
    def manter_selecao_ceva(event):
        global ceva_tqs
        ceva_tqs[referencia] = opcao_ceva.get()
        print(ceva_tqs[referencia])

    def manter_selecao_status(event):
        global status_tqs
        status_tqs[referencia] = opcao_status.get()
        print(status_tqs[referencia])

    referencia = int(ref)
    janela = tk.Toplevel(adega_grande)
    janela.title('TFM-' + num_tfm)
    janela.geometry('550x300')
    tfm = Image.open(img_tqs[referencia])
    tfm.thumbnail((300, 300), Image.ANTIALIAS)
    photo_tfm = ImageTk.PhotoImage(tfm, master=janela)
    label_tfm = tk.Label(image=photo_tfm, borderwidth=0, highlightthickness=0, master=janela)
    label_tfm.image = photo_tfm
    label_tfm.grid(column=1, rowspan=20, row=1)
    qual_tfm = tk.Label(master=janela, text='TFM-' + num_tfm, font='Arial 24 bold')
    qual_tfm.grid(column=2, row=1)
    ceva = tk.Label(master=janela, text='Cerveja: ', font='Arial 20 bold')
    ceva.grid(column=2, row=2, sticky='W')
    ceva_selecionada = 'Ceva selecionada'
    opcao_ceva = ttk.Combobox(master=janela, values=cervs_factory, state='readonly', textvariable=ceva_selecionada)
    opcao_ceva.grid(column=3, row=2)
    opcao_ceva.bind("<<ComboboxSelected>>", manter_selecao_ceva)
    status = tk.Label(master=janela, text='Status: ', font='Arial 20 bold')
    status.grid(column=2, row=3, sticky='W')
    status_selecionado = 'Status selecionado'
    opcao_status = ttk.Combobox(master=janela, values=('Fermentando', 'Maturando'), state='readonly', textvariable=status_selecionado)
    opcao_status.grid(column=3, row=3)
    opcao_status.bind("<<ComboboxSelected>>", manter_selecao_status)
    botao_salvar_alteracoes = tk.Button(master=janela, text="Salvar alterações no TFM", command=salvar_alteracoes)
    botao_salvar_alteracoes.grid(column=2, columnspan=2, row=4)

# creates main window and tabs (there are 22 smaller tanks to be added later on second tab)
gui = tk.Tk()
gui.configure(background="white")
gui.title("Acompanhamento de adegas")
abas = tk.ttk.Notebook(gui)
adega_grande = tk.Frame(abas)
adega_pequena = tk.Frame(abas)
abas.add(adega_grande, text='Adega Grande')
abas.add(adega_pequena, text='Adega pequena')
abas.grid()

# list of all kinds of beer produced in the factory
cervs_factory = ('VAZIO', 'Weiss', 'Vienna Lager')

# list of images to show on the tanks
img_tqs = ["",
           "tq cheio Beer 1.png",    # TFM-01
           "tq cheio Beer 2.png",       # TFM-02
           ]              # TFM-12

# list of which beer is currently on each tank
ceva_tqs = ["",
            cervs_factory[1],         # TFM-01
            cervs_factory[2]]          # TFM-02

# list of tank current status Fermenting/Maturing
status_tqs = ["",
              'Fermentando',    # TFM-01
              'Maturando',      # TFM-02
              ]              # TFM-12

# ~~~~  TFM's Adega Grande  ~~~~ #
font_titulo_tfm = 'Arial 14 bold'  # altera fonte e tamanho dos títulos dos TFM's
font_cerv_e_status = 'Arial 12 bold'  # altera fonte e tamanho do tipo de cerveja e status dos TFM's
tamanho_img_tqs = (250, 250)  # altera o tamanho das imagens dos TFM's, só considera o menor valor

tfm01 = Image.open(img_tqs[1])
tfm01.thumbnail(tamanho_img_tqs, Image.ANTIALIAS)
photo_tfm01 = ImageTk.PhotoImage(tfm01)
label_tfm01 = tk.Label(adega_grande, image=photo_tfm01, borderwidth=0, highlightthickness=0)
label_tfm01.grid(column=1, row=0)
legenda_tfm01 = tk.Label(adega_grande, text='TFM-01', font=font_titulo_tfm)
legenda_tfm01.grid(column=1, row=1)
ceva01 = tk.Label(adega_grande, text=ceva_tqs[1], font=font_cerv_e_status)
ceva01.grid(column=1, row=2)
status01 = tk.Label(adega_grande, text=status_tqs[1], font=font_cerv_e_status, fg='green')
status01.grid(column=1, row=3)
label_tfm01.bind('<Double-Button-1>', click_duplo_tfm)
label_tfm01.extra = "Widget TFM01"

tfm02 = Image.open(img_tqs[2])
tfm02.thumbnail(tamanho_img_tqs, Image.ANTIALIAS)
photo_tfm02 = ImageTk.PhotoImage(tfm02)
label_tfm02 = tk.Label(adega_grande, image=photo_tfm02, borderwidth=0, highlightthickness=0)
label_tfm02.grid(column=2, row=0)
legenda_tfm02 = tk.Label(adega_grande, text='TFM-02', font=font_titulo_tfm)
legenda_tfm02.grid(column=2, row=1)
ceva02 = tk.Label(adega_grande, text=ceva_tqs[2], font=font_cerv_e_status)
ceva02.grid(column=2, row=2)
status02 = tk.Label(adega_grande, text=status_tqs[2], font=font_cerv_e_status, fg='blue')
status02.grid(column=2, row=3)
label_tfm02.bind('<Double-Button-1>', click_duplo_tfm)
label_tfm02.extra = "Widget TFM02"

abas.mainloop()

I hope to be forgiven if my question/code got too long, I'm very new to coding and this is my first time asking for help. Also not very fluent in English, but I think you guys get the point of my problem here. Thank in advance for any insight.

A: It is indeed a lot easier if you use classes, but it is still doable with your current approach.
Basically you need to first store your brand/status labels to a container (like a list), and then when you spawn a Toplevel widget, pass a index so you know which labels you need to modify. Below is a minimum sample:
import tkinter as tk
from tkinter import ttk
from itertools import cycle

root = tk.Tk()
brands = ('VAZIO', 'Weiss', 'Vienna Lager')
status = ("Fermenting","Maturing")
beer_factory = cycle(brands)
beer_status = cycle(status)
beer = []

for i in range(6):
    a = tk.Label(root,text=f"TFM-0{i+1}",width=20)
    a.grid(row=0,column=i)
    b = tk.Label(root, text=next(beer_factory))
    b.grid(row=1, column=i)
    c = tk.Label(root, text=next(beer_status))
    c.grid(row=2, column=i)
    a.bind('<Double-Button-1>', lambda e, i=i: toplevel(e,i))
    beer.append([a,b,c])

def toplevel(event, i):
    top = tk.Toplevel()
    tk.Label(top,text="Beer factory").grid(row=0,column=0)
    tk.Label(top, text="Status").grid(row=1, column=0)
    com1 = ttk.Combobox(top,values=brands,state="readonly")
    com1.set(beer[i][1]["text"])
    com1.grid(row=0,column=1)
    com2 = ttk.Combobox(top,values=status,state="readonly")
    com2.set(beer[i][2]["text"])
    com2.grid(row=1,column=1)
    def finish():
        beer[i][1].config(text=com1.get())
        beer[i][2].config(text=com2.get())
        top.destroy()
    tk.Button(top,text="Finish",command=finish).grid(row=3,column=0,columnspan=2)

root.mainloop()

The <Double-Button-1> event is bound to the labels TFM-0X.


text:
Q: 401 unauthorized response when trying to use GET method using Bearer token in react (Postman) I am trying to show users (by GET request) from mongodb using and Bearer access token in Postman, but it says unauthorized and data is not retrieved from mongodb.
I am working on MERN, I have created a private route for login. I have mongodb in cloud and want to access protected route by providing access token ('Bearer + token') in POSTMAN, but it says unauthorized and does not show me the result. (status code is 401).
//FInd the user by email
  User.findOne({ email: email }).then(user => {
    //Check for user
    if (!user) {
      errors.email = "User not found";
      return res.status(404).json({ email: errors });
    }

    //Check for password
    bcrypt.compare(password, user.password).then(isMatch => {
      if (isMatch) {
        //User matched
        const payload = { id: user.id, name: user.name, avatar: user.avatar }; // create JWT payload

        //Sign the token
        jwt.sign(
          payload,
          keys.secretOrKey,
          { expiresIn: 3600 },
          (err, token) => {
            res.json({ success: true, token: "Bearer " + token });
          }
        );
      } else {
        errors.password = "Password incorrect";
        return res.status(400).json({ password: errors });
      }
    });
  });
});

I expect the output should be user object with fields which come from mongodb in cloud. But unauthorized is coming. Literally, I am trying to create an a DEVConnector social site which holds profiles of developers. For this I have created Register and Login pages, Register user is working fine, when I try to login to get a Bearer token, it also works. The problem is that when i copy the Token and paste in other page to access protected routes it responds me with 401 unauthorized code.


text:
Q: Angular 5 router - how to replace a string in the url without changing the state? I have an Angular 5 application,
I use the angular router, most of my entry route components placed under a context id which represents a name in the app store (and some more data relevant for that context), I use the id for proper fetching,
despite that the name is in most cases unique, I rather use an id.
So currently my url contains an id and I want it to contain a name instead without changing the state,
From: 'www.somesite/5/things'
To: 'www.somesite/five/things'

I want to keep the param as id, meaning when I'll subscribe to that route params I would get the id and I wont have to modify the router confoguration to be: name instead of id?
Can I achieve such scenario?

A: Create a Guard that checks for the variable parameter, if it's string search the id based on the name and redirect to the same url with the found id parameter.
Check this example enter link description here