text:
Q: insert html into string at several positions at the same time So I have a Peptide, which is a string of letters, corresponding to aminoacids
Say the peptide is
peptide_sequence = "VEILANDQGNR"

And it has a modification on L at position 4 and R at position 11,
I would like to insert a " and  before and after those positions at the same time.
Here is what I tried:
My modifications are stored in an array pep_mods of objects modification containing an attribute location with the position, in this case 4 and 11
pep_mods.each do |m|
  peptide_sequence.gsub(peptide_sequence[m.position.to_i-1], "#{@peptide_sequence[m.location.to_i-1]}" )
end

But since there are two modifications after the first insert of the html span tag the positions in the string become all different
How could I achieve what I intend to do? I hope it was clear

A: You should work backwards- make the modification starting with the last one. That way the index of earlier modifications is unchanged.
You might need to sort the array of indices in reverse order - then you can use the code you currently have.

A: Floris's answer is correct, but if you want to do it the hard way (O(n^2) instead of O(nlgn)) here is the basic idea.
Instead of relying on gsub you can iterate over the characters checking if each has an index corresponding to one of the modifications. If the index matches, perform the modification. Otherwise, keep the original character.
modified = peptide_sequence.each_with_index
                           .to_a
                           .map do |c, i|
                              pep_mods.each do |m|
                                if m.location.to_i = i
                                  %Q{#{c}}
                                else
                                  c
                                end
                              end
                          end.join('')

A: Ok, just in case this is helpful for anyone else, this is how I finally did it:
I first converted the peptide sequence to an array :
pep_seq_arr = peptide_sequence.split("")

then used each_with_index as Casey mentioned
pep_seq_arr.each_with_index do |aa, i|
  pep_mods.each do |m|
    pep_seq_arr[i] = "#{aa}" if i == m.location.to_i-1
  end
end

and finally joined the array:
pep_seq_arr.join

It was easier than I first thought


text:
Q: Is there a way to make a for loop with two parallel iterators in Scala? I am trying to do a for loop on a HashMap in Scala, but I also need a count of my iteration, like an index of sorts. Here is what I want the functionality to be:
    val map = HashMap()
    val i = 0;

    for ((k, v) <- map) {
        // do something
        i += 1
    }

But I want it to look something like this, where i is updated inside the for loop syntax. But, this seems to act as a nested loop rather than a parallel iterator.
    for ((k, v) <- map; i <- 0 until map.size) {
        // do something
    }

A: The zipWithIndex method is designed specifically for this purpose:
for {((k, v), i) <- map.zipWithIndex} yield {???}

or
map.zipWithIndex.collect { case ((k, v), i) => ??? }

Personally I would use the second version in this case and only use the for syntax when iterating over multiple collections.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Updating a column in excel I have two excel sheets with one column common for both. I need to match the column value and update the next column by following the excel 2.
for example:
I have excel1 as
   A                 B        C          D
fruits              22     f.market
vegetables          50     v.market
flowers             60     l.market

excel2
  A          B
fruits      1000
flowers     2000

So, I need to update column D in excel 1 as 1000 where column A is fruits

A: You can use VLOOKUP() for fetching the respective value. Considering your data value 'fruits' is in cell A1 try to use following function
=VLOOKUP(A1,$A1$B2,2,false)


text:
Q: creating models with foreingn keys using django Rest framework I have the following models
class Parent(models.Model):
    address = models.CharField(max_length=30, blank=True, null=True)
    address_no = models.CharField(max_length=4, blank=True, null=True, verbose_name="No")
    phone = models.CharField(max_length=15, blank=True, null=True, verbose_name="Phone Number")
    user = models.OneToOneField(User)

    class Meta:
        verbose_name_plural = "Parents"
        verbose_name = "Parent"

    def __unicode__(self):
        return "%s %s" % (self.user.first_name, self.user.last_name)

class Child(models.Model):
    age = models.IntegerField(blank=True, null=True)
    grade = models.IntegerField(blank=True, null=True)
    user = models.OneToOneField(User)
    parent = models.ForeignKey(Parent, related_name="children")

    class Meta:
        verbose_name = "Child"
        verbose_name_plural = "Children"

    def __unicode__(self):
        return "%s %s" % (self.user.first_name, self.user.last_name)

So I have different types of users on my system (parents and children). I am implementing them using a relation to the User model because Parents have different fields from Children. (extra: is there a better way to do it?)
I also implemented the serializes for those models in my rest api
serializers.py
class UserSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'url', 'username', 'email', 'groups')

class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ('url', 'name')

class ParentSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Parent

class ChildSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Child

and used the viewsets to generate the views for the api and the functionality
views.py
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_fields = ('username', 'email', 'first_name', 'last_name')

class GroupViewSet(viewsets.ModelViewSet):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

class ParentViewSet(viewsets.ModelViewSet):
    queryset = Parent.objects.all()
    serializer_class = ParentSerializer

class ChildViewSet(viewsets.ModelViewSet):
    queryset = Child.objects.all()
    serializer_class = ChildSerializer

and set up the urls
urls.py
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
router.register(r'parents', views.ParentViewSet)
router.register(r'children', views.ChildViewSet)

urlpatterns = patterns('',
    # Examples:
    url(r'^api/', include(router.urls)),
    url(r'api-auth/', include('rest_framework.urls', namespace='rest_framework')),
)

So a post in /api/parents would create a new Parent object.But it wont create a user object which is necessary for the Parent model. One way is to do 2 api calls one to /api/users/ a post and create new user and then get the new user's id and use it to post to /api/parents. I would like to avoid this. Is there a way to do this when creating a new parent from within the api. How can I also return the first_name and last_name of the user in the parents list view (api/parents/). Now it only returns the url of the related user but none of its fields

A:
So I have different types of users on my system (parents and
  children). I am implementing them using a relation to the User model
  because Parents have different fields from Children. (extra: is there
  a better way to do it?)

I'd rather use an inverse approach.
Person
   Profile
   Contact
   Graduation

ParentChildRelationship
   Parent (Person)
   Child (Person)

But I guess that is a matter of taste.

So a post in /api/parents would create a new Parent object.But it wont
  create a user object which is necessary for the Parent model. One way
  is to do 2 api calls one to /api/users/ a post and create new user and
  then get the new user's id and use it to post to /api/parents. I would
  like to avoid this. Is there a way to do this when creating a new
  parent from within the api.

By REST you can always create a new resource for whatever purpose you want. So for example if you want to create resources A and B at once, then you can define a resource called C which can create both at once. It's just the same by reading.
In your current case you don't have to define a new resource. The user is an embedded resource of the parent and the child. So you have to send a representation which contains that embedded resource as well. Typically {user: {}} in plain JSON. You probably cannot solve these problems with your current tools. Since I have not a clue about django and python, I cannot help more.


text:
Q: Tkinter get rid of the python icon in messagebox tkinter How can I get rid of the Python (or matplotlib) icon when running this code? Even when I add icon='info', I still get the rocket with the python logo. Please check the photo in reference.
from tkinter import * import tkinter as tk from tkinter import messagebox as tm
        root=Tk() root.geometry("1200x1200") canvas1 = tk.Canvas(root, width = 300, height = 300) canvas1.pack() def ExitApplication():

    text=text= ' Our team thank you for your visit ! '

    MsgBox=tk.messagebox.askquestion('Exit the platform' , text, icon='info')
    if MsgBox=='yes':
        root.destroy()
    else:
        tk.messagebox.showinfo('Return', 'You will now return to the application screen ', icon='info')

exit_button = Button(root, text="Exit ", command=ExitApplication) canvas1.create_window(200, 200, window=exit_button)

root.mainloop()

A: icon=info is used for changing the icon inside message box.
Answered here nicely.

Referring to this question and its comments, one solution could be to create your own custom messagebox using tk.Toplevel():
Here is an example of how you would be coding it. (You can further make it more efficient for multiple messageboxes):
from tkinter import *
import tkinter as tk
#from tkinter import messagebox as tm

root=Tk()
root.geometry("1200x1200")
canvas1 = tk.Canvas(root, width = 300, height = 300)
canvas1.pack()
def ExitApplication():
    text = ' Our team thank you for your visit ! '

    MsgBox=Toplevel(root)
    MsgBox.title("Exit the platform")
    MsgBox.geometry(f"300x100+{root.winfo_x()}+{root.winfo_y()}")
    icon = PhotoImage(file="Any image file")#provide here the image file location
    MsgBox.iconphoto(True, icon)

    l1=Label(MsgBox, image="::tk::icons::question")
    l1.grid(row=0, column=0, pady=(7, 0), padx=(10, 30), sticky="e")
    l2=Label(MsgBox,text=text)
    l2.grid(row=0, column=1, columnspan=3, pady=(7, 10), sticky="w")

    b1=Button(MsgBox,text="Yes",command=root.destroy,width = 10)
    b1.grid(row=1, column=1, padx=(2, 35), sticky="e")
    b2=Button(MsgBox,text="No",command=lambda:[MsgBox.destroy(), returnBack()],width = 10)
    b2.grid(row=1, column=2, padx=(2, 35), sticky="e")

def returnBack():
    pass
    #Similarly, create a custom messagebox using Toplevel() for showing the following info:
    #tk.messagebox.showinfo('Return', 'You will now return to the application screen ', icon='info')

exit_button = Button(root, text="Exit ", command=ExitApplication)
canvas1.create_window(200, 200, window=exit_button)

root.mainloop()

But if you are looking for a solution to change the default icon with an .ico icon file, for entire Tkinter windows including MessageBox refer here, just use iconbitmap:
import tkinter as tk

win = tk.Tk()
win.title("example")
win.iconbitmap(".ico file location")

win.mainloop()


text:
Q: Want to build tex file but Recipe terminated with error error message :
The command name is D:\texlive\2021\bin\win32\mktexfmt
Latexmk: fls file doesn't appear to have been made.
Collected error summary (may duplicate other messages):
  pdflatex: Command for 'pdflatex' gave return code 1
      Refer to 'Latex_Text_Template1.log' for details
----------------------
This message may duplicate earlier message.
Latexmk: Failure in processing file 'd:/ys_/study/custom_setup/workplaces/issues-in-computer-programming-20210818/Latex_Text_Template1':
   *LaTeX didn't generate the expected log file 'Latex_Text_Template1.log'
----------------------
Latexmk: Errors, so I did not complete making targets
Latexmk: Use the -f option to force complete processing,
 unless error was exceeding maximum runs, or warnings treated as errors.
D:\texlive\2021\bin\win32\runscript.tlu:915: command failed with exit code 12:
perl.exe d:\texlive\2021\texmf-dist\scripts\latexmk\latexmk.pl -synctex=1 -interaction=nonstopmode -file-line-error -pdf -outdir={my path} {tex file path}

OS : windows 10
File was operated in vscode
I installed latex-workshop and installed texlive.
I don't know why building tex file failed.


text:
Q: Why is my JTable CellRenderer running all the time? //newbie question
I have a JTable with an almost basic cell renderer (it colors the line differently).
I've noticed my cell renderer is constantly running for the lines that are displayed on the screen, even when I don't do anything with the table.
Is that how it's supposed to be? Shouldn't it have rendered each cell once , and that's it?
How can I make it stop , and only recalculate on change?
public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {

   log.debug("Building cell : " + row + "," + column);

   Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

   Filter filter = (Filter)table.getModel().getValueAt(row, Column.CLASSIFICATION.getIndex());
   comp.setBackground(filter.getColor());
   return comp;

  }

A: Following @Steve McLeod's offer , I started building an example code with the same bug , and only then I realized that inside one of my CellRenderers
@Override
    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {

        log.debug("Building a list for " + row + "," + column);
        setListData(((Vector<String>)value).toArray());
        setToolTipText("This is a tool tip for " + row + "," + column);

        table.setRowHeight(row, Math.max(1, getPreferredSize().height));
        Filter filter = (Filter)table.getModel().getValueAt(row, Column.CLASSIFICATION_RESULT.getIndex());
        setBackground(filter.getColor());
        return this;
    }

I had the line :
table.setRowHeight(row, Math.max(1, getPreferredSize().height));

and it constantly changed the row line , while the other renderers in the same line did the same...
so they were constantly firing each other.

A: I've worked a lot with JTables containing a lot of data.  More than what 99.9% of Java programmers typically manipulate.  There's one thing you need to know: by default there's an insane amount of waste generated and an insane amount of typically needless operation done.
If you're after fast and efficient JTables, then there's the authoritative Sun article on the subject:
"Christmas Tree Applications, How to Create Frequently-Updated JTables that Perform Well"
Notice the "that Perform Well" in the title, because by default JTable perfs are really, really pathetically bad:
Original Link (Sun)
Current link (Oracle)
Archived Version:
After implementing two or three of the techniques adviced in that article, you'll notice amazing speedup in your JTable rendering and you'll notice that much less garbage is generated (and hence the GC needs to kick in way less often).

A: I notice you change the appearance of a cell based on the value of another cell. If this relationship goes both ways - cell 1 appearance is based on cell 2 and vice versa you could get such a problem. But really, we need a self-contained code example that reproduces the problem - otherwise we can only shoot in the dark.

A: the renderer already caches your rendered component, when nothing changes nothing gets rerendered
However when the table detects something MIGHT have changed it will request a re-rendering.
The event that triggers it the most is a mouse move.
So yes its normal behaviour for a JTable.


text:
Q: Creating rules efficiently for large forms I'm using the jQuery validate plugin to validate a form with a lot of fields:
<input name="first_name0">
<input name="last_name0">
<input name="age0">
<input name="first_name1">
<input name="last_name1">
<input name="age1">
<input name="first_name2">
<input name="last_name2">
<input name="age2">
...
<input name="first_name200">
<input name="last_name200">
<input name="age200">

What's the best way to add validation rules to all of the identical fields? Currently I'm adding rules like this, however it's very slow after 100 rows.
$("input[name*=age]").each(function(i) {
    $(this).rules("add", {
        digits: true
    });
});

$("input[name*=first_name], input[name*=last_name]").each(function(i) {
    $(this).rules("add", {
        digits: true
    });
});

A: There's no need to loop, it'll operate on a Query set, like this:
$("input").filter("[name*=age], [name*=first_name], [name*=last_name]")
          .rules("add", {
             digits: true
          });

Giving them a class would be a bit more maintainable, for example:
<input name="first_name0" class="digits">
<input name="last_name0" class="digits">
<input name="age0" class="digits">

Then you could do this:
$("input.digits").rules("add", {
  digits: true
});


text:
Q: Unit-testing javascript/jQuery events with Jasmine I have this code:
$(document).on('click', '#clear-button', clearCalculatedPrice)

clearCalculatedPrice = ->
    $('#price_rule').removeAttr('data-original-title')
    $('#calculated-price').removeAttr('data-original-title')
    $('#calculated-price').empty()

And such test for it
describe 'Call taker', ->
  it 'should clear calculated price', ->
    spyOn($.fn, 'removeAttr')
    spyOn($.fn, 'empty')
    clearCalculatedPrice()
    expect($.fn.removeAttr).toHaveBeenCalled()
    expect($.fn.empty).toHaveBeenCalled()

I need to create another test which will check that function was called when event was triggered, like this
     it 'should clear calculated price when "click" event is triggered', ->
      $('#destination-clear-button').trigger('click')
      spyOn($.fn, 'removeAttr')
      spyOn($.fn, 'empty')
      expect($.fn.removeAttr).toHaveBeenCalled()
      expect($.fn.empty).toHaveBeenCalled()

But this test do not work as I thought. So question is:
How should unit-test that tests event handler should be written

A: Probably order calls is bad
 it 'should clear calculated price when "click" event is triggered', ->
  # set spys
  spyOn($.fn, 'removeAttr')
  spyOn($.fn, 'empty')
  # trigger
  $('#destination-clear-button').trigger('click')
  # check
  expect($.fn.removeAttr).toHaveBeenCalled()
  expect($.fn.empty).toHaveBeenCalled()


text:
Q: Is it possible to make a Hash MD5 in Laravel Blade? In my form, i need to make a hash then submit it as POST.
<form action="{{ route('api') }}" method="POST">
    <input type="hidden" name="Hash" value="{{  md5('2019030428' . '54321' . 'Juan dela Cruz' }}">
    <button type="submit" value="API POST">Submit</button>
</form>

is this correct? The instruction says i need to pass it as HASH lowercase md5

A: You can also try with
{{strtolower(md5('STRING Is here'))}}


text:
Q: generate quadratic functions to evaluate membership of points How can I make a printable list with different quadratic functions and with points that belong or not to them so that a young person can check whether or not the point belongs to the parabola? my code is horrible
(I can't get it not to take the number zero)
something like the image
sig := 2*Random[Integer, {0, 1}] - 1;
a := Random[Integer, {-9, 9}];
b := Random[Integer, {-9, 9}];
c := Random[Integer, {-9, 9}]
nul := Random[Integer, {0, 1}] - 1;

For[i = 1, i <= 30, i++,
 Print[i, " f(x) = ", sig*a, "x^2", nul*sig*b, "x ", nul*sig*c]]

A: Here's an answer; there could be some cleanup done, and I need to explain why some of the auxiliary functions work. But here you go—I tried to explain how it works in inline comments along the way, so that you can simply copy-paste the whole code block and run it.
(* Given a list of coefficents {a, b, c}, make a polynomial
 function—this can be done with FromDigits. *)

makePolynomial[coeffs_List] := Evaluate[FromDigits[coeffs, #]] &

(* Example: makePolynomial[{1, 2, 3}] ==> 3 + 2 #1 + #1^2 & *)

(* Format polynomials as a function definition,
using fname and var for the lhs: *)

polynomialFormat[fname_, var_][f_] :=
 With[{poly = Reverse@Inactivate[f[var], Plus]},
  HoldForm[fname[var] = poly]]

(* Example: polynomialFormat[f, x][makePolynomial[{1, 2, 3}]] ==>
   f[x] = x^2 + 2 x + 3 *)
(* We expect to apply TraditionalForm to this to make it look nicer. *)

(* Format a 2D point as a tuple: *)

pointFormat[{x_, y_}] := Row[{"(", x, ", ", y, ")"}]

(* Again, we expect to apply TraditionalForm. *)

(* If the first argument is True, get a point from the
graph of the function; if false, get one definitely not from the graph. *)

ifGetPoint[xrange_ : {-9, 9}, yrange_ : {-25, 25}][bool_, f_] :=
 With[{x = RandomInteger[xrange]},
  If[bool,
   {x, f[x]},
   Block[{y = RandomInteger[yrange]},
    While[y == f[x], y = RandomInteger[yrange]]; {x, y}]
   ]
  ]

(* Ok, main function. We allow parameters for the range of
coefficients, the percentage of answers which should be
true, and the range in which to select a "false" point.
All but the number of rows requested can be omitted and
will take on default values.*)

ParabolaPointTableBasic[numrows_Integer?Positive,
  coefficientrange : (_Integer?Positive) : 9,
  truepercentage : (_?(0 <= # <= 1 &)) : 0.5,
  xrange : {_Integer, _Integer} : {-9, 9},
  yrange : {_Integer, _Integer} : {-25, 25}] :=
 (* First, make sure x is "fresh" for the duration of
    this evaluation, and that any external definition of x
    or f, e.g. x = 5, will not affect us. *)
 Block[{f, x},
  (* "With" is a way of saying that symbols explicitly used
     in the following expression should be repalced with
     some value (whatever we set in the following list. *)
  With[
   (* First, let's get a list with about truepercentage*
   numrows values of True, and the rest False.
   We'll do this by asking if each integer between 1 and numrows is \
below truepercentage*numrows,
   then mixing that list up with RandomSample. *)
   {truelist =
     RandomSample@Table[i <= truepercentage*numrows, {i, numrows}],
    (* Next, we'll get a list of polynomial functions.
    We generate a random list of three coefficient ranges,
    and if the leading coefficient is 0, we change it to 1,
    then apply makePolynomial. *)

    polys =
     Table[
      makePolynomial@
       Replace[{0, b_, c_} :> {1, b, c}]@
        RandomInteger[{-coefficientrange, coefficientrange},
         3], {numrows}]},
   (* We need a new "With", since we're going to now
      use the variables defined in the previous one. *)
   With[
    (* Get a point in the parabola if the corresponding
       element of truelist is True, and a point not in the
       parabola if it's false. *)
    {points =
      MapThread[ifGetPoint[xrange, yrange], {truelist, polys}]},
    (* store the "answer key" in global variable answerKey *)
    answerKey = Transpose[{polys, points, truelist}];
    (* Put it all together. We have two lists of equal length;
    that's three rows. We need a third list of just blank space.
    We need to flip it to turn those rows into columns,
    so we use Transpose.
    We also need to format the polynomials and points,
    and call them f,
    so we map those formatting functions over the lists.
    Also, prepend the headers.
    Wrap the whole thing in Grid and give it appropriate options. *)
    TraditionalForm@Grid[
      Prepend[
        Text /@ {"Quadratic Function", "Point",
          "Put T if the point belongs \n to the graph of the \n \
function and F if not."}]@
       Transpose[{polynomialFormat[f, x] /@ polys,
         pointFormat /@ points, Table["   ", {numrows}]}],
      Frame -> All,
      Alignment -> {{Left, Center, Center}, {Center,
       {Automatic}}, {1, 1} -> {Center, Center}}]
    ]
   ]
  ]

(* Test/example call: *)

ParabolaPointTableBasic[9]

(* Out: *)

Validate the answers that have been stored in answerKey:
validAnswer[{f_, {x_, y_}, answer : (True | False)}] :=
  (f[x] == y) == answer

AllTrue[answerKey, validAnswer]

(* Out (should be): True *)

Improvements we could make:

*

*Give the optional arguments as Options instead of default arguments

*Remove grid from around header elements

*✓ Align $f(x)=$ to the left of each cell [added Alignment -> {{Left, Center, Center}, {Center,{Automatic}}, {1, 1} -> {Center, Center}} to Grid]

*Generate values that are in the function range (considered over the xrange) instead of a predetermined range, so that they seem more realistic

*✓ Store the "answer key" as well as the computational content in a global variable somewhere for the instructor [declared variable answerKey]

*Make storing the answer key optional and controlled by an option

*✓ Include way of validating the answer key [via validAnswer for a single triple of {function, point, answer}, and then AllTrue[answerKey, validAnswer]]

*Make it interactive, so that someone could choose True or False in the actual mathematica notebook

*Provide an "Export" button for exporting it as a given filetype

*Provide manipulation options for individual elements/the ability to "refresh" individual rows

*Include optional numbering of rows along the side

Hope this helps; it was fun! Let me know if there's anything you'd like me to explain or change.


text:
Q: Enabling grouping in ng-table removes the pagination I'm working with ng-table and I've run into an issue with grouping. I have it so that grouping can be enabled or disabled by selecting options in a dropdown menu but enabling grouping always breaks pagination while it works fine when grouping is disabled.
Here's an example of what one of the objects in my columns array looks like:
{
  field: "payeeName",
  title: "Charity",
  sortable: "payeeName",
  filter: {
    payeeName: 'select'
  },
  classes: "td-width-150",
  show: true,
  hideOnExport: true,
  groupable: "payeeName",
  buildTemplate: function(donation, idx) {
    var str = donation.payeeName + '
';
    str += '';
    str += $filter('buildAddressLine')(donation) + '
';
    str += $filter('buildRegistrationId')(donation) + '
';
    if (donation.designation) {
      str += donation.designation;
    }
    str += '';
    return str;
  }
}

Here are the rows that appear when grouping is either turned on or off:

      {{ group.value }}

Lastly, here is the function that preps the data for the table. It should be known that below this code is an API call that sets $scope.donations equal to what the endpoint returns:
var prepData = function(checkFilter) {
  var orderFilter = params.filter();
  // add grid filters to the data we loaded in get data
  var filteredData = params.filter() ? $filter('filter')($scope.donations, params.filter()) : $scope.donations;
  // apply the global filter

  filteredData = $filter('filter')(filteredData, $scope.globalTableFilter);

  var orderedData = params.sorting() ?
    $filter('orderBy')(filteredData, params.orderBy()) :
    filteredData;

  orderedData = $filter('filter')(orderedData, $scope.filterDonation);

  // Prep data for export
  $scope.exportData = angular.copy(orderedData);
  $scope.exportData.forEach(function(e) {
    e.donationDate = $filter('date')(e.donationDate, 'dd/MM/yyyy');
    e.receiptAmount = $filter('currency')(e.receiptAmount);
  });
  // recalc the pagination - MUST PRECEED THE PAGE SLICE

  params.total(orderedData.length);
  $scope.$emit('gotDonations', $scope.orderedData);

  $scope.filterDonations = orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count());
  return $scope.filterDonations;

};

When grouping is enabled via the select input, it fires a function that looks like: $scope.tableDonationParams.group({payeeName: 'asc'})
When grouping is disabled via the select input, it fires this:
$scope.tableDonationParams.group({})
Like I said, pagination works fine whenever grouping is set to a blank object, but completely breaks when enabled.
Here is an image of my table just for clarity: http://imgur.com/f6WyksA
I integrated a plugin called angular-dragdrop to allow me to drag items from the sidebar into the table to be added to the columns object and also drag columns over each other to change their positioning on the table so don't let that confuse you.
Thank you for any and all help.

A: I've same problem, when paging on group data. So, i add these lines at the end on getGroups function [ng-table.js].
if (!settings.dataOptions.applyPaging) {
    return ngTableDefaultGetData(result, params);
}
return ngTableDefaultGetData.applyPaging(result, params);

The pagination working on either used default or custom.


text:
Q: Trouble to migrate some flavors from Firebase CrashReport to Firebase Crashlytics So we have an Android application which was monitored using Firebase Crash Report and we updated it a couple weeks ago to migrate to Firebase Crashlytics.
We followed the (pretty straightforward) official procedure and tested it on our development flavor. It took some time for the first test crash reports to pop up but it definitively worked.
But we tried it this week on another flavor of our application and it does not work in this case. Looking closer, we can see the following lines in Logcat :
com.ourapp.flavorb I/CrashlyticsCore: Initializing Crashlytics 2.6.3.25
com.ourapp.flavorb I/CrashlyticsInitProvider: CrashlyticsInitProvider initialization successful
com.ourapp.flavorb D/FirebaseApp: com.google.firebase.auth.FirebaseAuth is not linked. Skipping initialization.
    com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
com.ourapp.flavorb E/Fabric: Failed to retrieve settings from https://settings.crashlytics.com/spi/v2/platforms/android/apps/com.ourapp.flavorb/settings
com.ourapp.flavorb W/CrashlyticsCore: Received null settings, skipping report submission!

The working flavor has the following output :
com.laposte.tvfacteur.integration I/CrashlyticsCore: Initializing Crashlytics 2.6.3.25
com.ourapp.flavora I/CrashlyticsInitProvider: CrashlyticsInitProvider initialization successful
com.ourapp.flavora D/FirebaseApp: com.google.firebase.auth.FirebaseAuth is not linked. Skipping initialization.
    com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
com.ourapp.flavora I/CrashlyticsCore: Crashlytics report upload complete: [SOME-UID]

Is there something we're missing ? It seems we did nothing more for the first flavor…
I'm under the impression that Firebase creates at some point a settings entry in Crashlytics servers and, for some reason, it has not worked for the second flavor.
Does anyone saw something like that ? Any idea on things we could try ?
Any help will be welcomed !

A: So… It's kinda weird but it finally works for both flavors !
Seems that it took a looooooooooooooong time to process the new flavor. My guess is that some kind of account is automatically created on Crashlytics on first report. In my case, it took nearly a week !
I also uninstalled/reinstalled the application multiple times, maybe it helped…
Just for my archives, here is the situation before :

And after :


text:
Q: Momentum change in an inelastic collision Hello fellow stackexchangers, this is my first post, so sorry if this is too vague or violates guidelines.
I am studying Physics and this problem came up, I will type it verbatim

A small object collides with a large object and sticks. Which object experiences the larger magnitude of momentum change -the small object -the large object-both objects experience the same magnitude of momentum change

I posted this on the math site because I wish to see a proof for the general situation. Note that this situation occurs in one dimension, that conservation of momentum applies, and that the two objects become one after the collison. The collision is inelastic and kinetic energy is not conserved.
If this is more suitable for the Physics site, please tell me.

A: Since the initial momentum is $m_1v_1+m_2v_2$ and
and the final momentum is $(m_1+m_2)v_f$, we have:
$m_1v_1 + m_2v_2 = (m_1+m_2)v_f$
or
$v_f\to \frac{m_1 v_1+m_2 v_2}{m_1+m_2}$
To find the change in object 1's momentum, we compute
$m_1 \left(v_1-v_f\right)$
Substituting, we get:
$m_1 \left(v_1-\frac{m_1 v_1+m_2 v_2}{m_1+m_2}\right)$
which simplifies to:
$\frac{m_1 m_2 \left(v_1-v_2\right)}{m_1+m_2}$
Similarly, for object 2, we compute:
$m_2 \left(v_2-v_f\right)$
after substitution:
$m_2 \left(v_2-\frac{m_1 v_1+m_2 v_2}{m_1+m_2}\right)$
and simplifying:
$\frac{m_1 m_2 \left(v_2-v_1\right)}{m_1+m_2}$
which is the exact negative of the answer for object 1, so the
absolute changes in momentum are identical.


text:
Q: Why write modular javascript? The benefits of well-factored and modular code, in my understanding are re-usability and organization. Code written in a big chunk all in one file is difficult to read, and re-using small portions of the code requires careful copy-pasting, rather than include statements.
In particular, with regards to Javascript, I came across an example recently that got me thinking about this. A comment was made on SO to the effect that, if you are not including your javascripts conditionally on a page-by-page basis, this "represents a failure to modularize JS code properly". However, from a code re-use and organization point of view, there is no reason to consider what happens at page load time. The code will be just as readable if it is written in a bunch of separate files and then mashed together and minified before being served. The rails asset pipeline, for example, does just this.
When I first encountered the asset pipeline, my mind reeled and I started wondering "how do I make javascripts load only when needed?" I read a few SO questions and an article on the matter, and began to think that maybe I shouldn't worry about what happens to my code after it "compiles".
Is the purpose of writing modular code purely a human-level activity, should we stop worrying about modularity after the code starts running? In the case of Javascript, should we be concerned that our scripts are being mashed together before being included?

A: I think the one thing that you are not really talking about in this with regards to performance is actual HTML browser download behavior. I believe you have to walk a fine line between only displaying the javascript needed on a page by page basis and leveraging browser caching and download behavior.
For example, say you have 20 different javascript snippets that are going to be used on every page.  In this case it is a no-brainer to compile/minify them into a single file, as the fewer files your browser needs to download, the better. This single file would also be able to be cached, that is assuming it is a static file or appearing to be static (via headers sent) if it is dynamically compiled.
Now say of those 20 snippets, 15 are used on every page and the others are used intermittently.  Of course you put all 15 of the always used snippets into a single file. But what about the others?  In my opinion you need to consider the size and frequency of use of the files.  If they are small and used relatively frequently, I might consider putting them into the main file, with the thought that the extra size in the main file is outweighed by the need to have additional request to download the content later.  If the code is large, I would tend to only use it where necessary. Of course once it is used, it should remain in cache.
This approach might best be suited for a web application where users are expect to typically have multiple page loads per session.  Of course if you are designing an advertising landing pages or seomthing where the user only may see that single page, you might lean on keeping the initial javasciprt download as small as possible and only loading new javascript in as necessary based on user interaction.

A: Every aspect of this question boils down to "it depends".
Are you writing an enterprise-level application, which results in 80,000 lines of code, when you stuff it all together?
If so, then yes, compilation time is going to be huge, and if you stuff that in the <head> of your document, people are going to feel the wait time.
Even if it's already cached, compile time alone will be palpable.
Are you writing dozens of widgets which might never be seen by an end-user?
Especially on mobile?
If so, then you might want to save them the download/compile time, and instead load your core functionality, and then load extra functionality on-demand, as more studies are showing that the non-technical end-user expects their mobile-internet experience to be similar to their desktop experience, not only in terms of content, but in general wait-times.
Fewer and fewer people are willing to accept 5s-8s for a mobile experience (or a desktop experience on mobile) to get to the point of interactivity, just based on the "well, it's mobile, so it'll take longer" train of thought.
So again, if you've got an 80,000 line application, or a 300kB JS file, or are doing a whole lot of XML parsing, et cetera, prior to load, without offering a separate mobile experience, your stats on mobile are bound to hurt -- especially if you're a media site or a commercial/retail site.
So the correct answer to your question is to say that there is no correct answer to your question, excepting that there are good ideas and bad ideas, based on the target-devices, the intent of the site/application, the demographic, the code-base, the anticipation that users will frequent the site (and thus benefit from cached assets), the frequency of updates to the codebase (having one updated module, with 20 cached modules, versus a fully-invalid 21-module chunk, due to one updated line, with a client-base of 250,000 customers, is a consideration for several reasons)...
...and more...
Figure out what you're doing.
Figure out what you need to do to make that happen.
Figure out how to do it, while providing your customers a good experience.
Know how to combine files.
Know how to load on demand.
Know how to build a light bootstrap, which can intelligently load modules (and/or learn require/AMD).
Use these as tools to offer your users the best experience possible, given what you're trying to accomplish.


text:
Q: How to trigger a bash script from right click in Safari on a particular URL? is it possible when I'm in Safari and have link (URL) to trigger a bach script with an right mouse option?
The bach script should be run with this format:
bash scriptname.sh -parameter -parameter URL
Thanks!

A: No - Safari is designed to not run code like that.
Could you imagine the damage someone would do with a malicious script to delete all a user's photos if they get them to click a link that could say anything and link to a malicious script underneath?


text:
Q: How to Logout in Angular / Spring by POST I want to logout by Angular using POST method, here is my code:
  logout() {
    const url = 'http://localhost:8181/user/logout';
    const xToken = localStorage.getItem('xAuthToken');
    const basicHeader = 'Basic ' + localStorage.getItem('credentials');
    const headers = new Headers({
      'x-auth-token': xToken,
      'Authorization': basicHeader
    });
    // return this.http.get(url, { headers: headers }); // This will work
    return this.http.post(url, { headers: headers }); // This will generate error
  }

And this my backend:
@RequestMapping("/user/logout")
public ResponseEntity<String> logout(){
    SecurityContextHolder.clearContext();
    return new ResponseEntity<String>("Logout Successfully!", HttpStatus.OK);
}

The weird thing is the code above work with this.http.get but will generate below error with this.http.post. And here is error with this.http.post:
POST http://localhost:8181/user/logout 401

If I modify code using HttpClient, like this:
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class LoginService {

  constructor(private http: HttpClient) {
  }

  sendCredential(username: string, password: string) {
    let url = "http://localhost:8181/token";
    let encodedCredentials = btoa(username + ":" + password);// encode in base64 to send a token
    let basicHeader = "Basic " + encodedCredentials;
    let headers = new Headers({
      'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization': basicHeader
    })
    // send credential method when login component
    return this.http.get(url, { headers: headers }); // Error at this line
  }

  checkSession() {
    const url = 'http://localhost:8181/checkSession';
    const xToken = localStorage.getItem('xAuthToken');
    const basicHeader = 'Basic ' + localStorage.getItem('credentials');
    const headers = new Headers({
      'x-auth-token': xToken,
      'Authorization': basicHeader
    });
    return this.http.get(url, { headers: headers }); // Error at this line
  }

  logout() {
    const url = 'http://localhost:8181/user/logout';
    const xToken = localStorage.getItem('xAuthToken');
    const basicHeader = 'Basic ' + localStorage.getItem('credentials');
    const headers = new Headers({
      'x-auth-token': xToken,
      'Authorization': basicHeader
    });

    return this.http.get(url, { headers: headers }); // Error at this line
  }
}

Then I get error message:
(property) headers?: HttpHeaders | {
    [header: string]: string | string[];
}
Type 'Headers' is not assignable to type 'HttpHeaders | { [header: string]: string | string[]; }'.
  Type 'Headers' is not assignable to type '{ [header: string]: string | string[]; }'.
    Index signature is missing in type 'Headers'.ts(2322)
http.d.ts(1086, 9): The expected type comes from property 'headers' which is declared here on type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }'

at line return this.http.get(url, { headers: headers });
Anyone know how to fix it?

A: Try setting headers like this:
let headers = new HttpHeaders();
headers = headers.set('x-auth-token', xToken).set('Authorization', basicHeader);

and then,
return this.http.post(url, null, headers );

Pass null as it accepts body as in the second parameter.
Using HttpClient:
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) { }
in app.module.ts:
import { HttpClientModule } from '@angular/common/http';
and in @NgModule:
imports: [ HttpClientModule ]

A: It's normal, by default @RequestMapping("/user/logout") will accept only GET requests. You have to set the method explicitly
@RequestMapping("/user/logout", method = RequestMethod.POST)
public ResponseEntity<String> logout(){
    SecurityContextHolder.clearContext();
    return new ResponseEntity<String>("Logout Successfully!", HttpStatus.OK);
}

Or use @PostMapping

A: Try this:
constructor(private http:HttpClient){}
logout()
{
    const url = 'http://localhost:8181/user/logout';
    const headers = new HttpHeaders()
      .set('x-auth-token', localStorage.getItem('xAuthToken'));

    return this.http.post(url, '' ,{headers: headers, responseType: 'text'})};

In Spring, my recommendation would be to use @PostMapping or @DeleteMapping annotation instead of @RequestMapping. The reason for using ResponseType as 'text' is because you are providing ResponseEntity<> as of String type and by default Angular perceives the response as JSON.
Further, remember to use localStorage.removeItem('xAuthToken'); in the response when subscribing to that observable & also unsubscribe that observable in ngOnDestroy() lifecycle.


text:
Q: How to resume the last activity after the user closed Android kivy app? I created a calculator with memory function, Answer history and Other Functions that need to remain stored even if the user completely closed the.
Kivy has an on_pause and on_resume methods of the main app class that can be use to resume the app if suspended and not close.
Is there a way the user can resume to recent activities if the app is closed?
Please help me, thanks..

A: You can use Json file
from kivy.storage.jsonstore import JsonStore

store = JsonStore('file name.json')

# put some values
store.put('tito', name='Mathieu', org='kivy')
store.put('tshirtman', name='Gabriel', age=27)

# using the same index key erases all previously added key-value pairs
store.put('tito', name='Mathieu', age=30)

# get a value using a index key and key
print('tito is', store.get('tito')['age'])

# or guess the key/entry for a part of the key
for item in store.find(name='Gabriel'):
    print('tshirtmans index key is', item[0])
    print('his key value pairs are', str(item[1]))

More information


text:
Q: Non-Serializable data member with WCF I have a non-serialized object and I dont have access to source codes. What are options to make it serializable so that I can send it over the network using WCF?
There is no serious reasons that the object is not serializable. The class is not serializable because its author just did not mark it that way and I do not have access to class.

A: Check this out:
public class Base
{
    public string Name { get; set; }
    public List<int> Values { get; set; }
}

[Serializable]
public class Derived : Base
{
    public double X { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var d = new Derived() { X = 3.1415, Values = new List<int> { 3, 1, 4, 1, 5 }, Name = "Pi" };
        var stream = new MemoryStream();
        new XmlSerializer(typeof(Derived)).Serialize(stream, d);
        string result = Encoding.UTF8.GetString(stream.GetBuffer());
    }
}

Apparently you can make a derived class serializable. The resulting string contains the values for the base class properties as well.

A: If the class isn't written with serialization in mind from the start, I'd suggest that you make a simple DTO class that is your data contract and copy the data to that one. To ease up copying you could use Automapper if there are many properties.
It is always a good idea to separate the protocol contract (which a WCF data contract class is) into a separate class that you have tight control over when/how it changes as any changes will break clients of your service.

A: You have to create a "proxy" since you cannot alter the other code.
It can be a basic DTO/POCO object that contains the properties of interest.
Anders already said this.
Here is a link to the "pattern"
http://www.dofactory.com/Patterns/PatternProxy.aspx
It's not a direct to wcf concept.  The link is provided to provide some "food for thought".
You can write a basic "translator" between your [Serializable] object, and the original one.


text:
Q: Pass NEPTUNE_API_TOKEN environment variable via docker run command Using the docker run command, I'm trying to pass my NEPTUNE_API_TOKEN to my container.
My understanding is that I should use the -e flag as follows: -e ENV_VAR='env_var_value' and that might work.
I wish, however, to use the value existing in the already-running session, as follows:
docker run -e NEPTUNE_API_TOKEN=$(NEPTUNE_API_TOKEN) <my_image>

However, after doing so, NEPTUNE_API_TOKEN is set to empty when checking the value inside the container.
My question is whether I'm doing something wrong or if this is not possible and I must provide an explicit Neptune API token as a string.

A: $(NEPTUNE_API_TOKEN) is the syntax for running a command and grabbing the output. Use $NEPTUNE_API_TOKEN.

A: You can set up and pass NEPTUNE_API_TOKEN as a:

*

*Docker run command options environment variable
Example: docker run -e NEPTUNE_API_TOKEN="<YOUR_API_TOKEN>" <image-name>

*Dockerfile environment variable

*Docker secret
Neptune will work with any of the methods described above.
For your case, I believe using method 2 and 3 will work best as you will set the API token only once and all containers can reuse it. Additionally, they are more secure methods.
You can read this guide on how to use Neptune with Docker I created last year.
Docs: https://docs.neptune.ai/how-to-guides/automation-pipelines/how-to-use-neptune-with-docker


text:
Q: Find the total number of ways to select a non-empty subset of these people, such that no two adjacent people are selected. There are N people are sitting around a circular table. Let's call them P1, P2, . . . , PN ,
in order. P1 is sitting between P2 and PN . P2 is sitting between P1 and P3. P3 is
sitting between P2 and P4, and so on.
You need to select a non-empty subset of these people, such that no two adjacent
people are selected. Find the total number of ways in which you can do so.
For example, suppose N = 3, then we have P1, P2 and P3. If we select P1, then
neither P2 nor P3 can be selected. So, the only valid selections are {P1}, {P2}, {P3}.
So there are three possible ways, and hence the answer would be 3.
Suppose N = 4, then we have P1, P2, P3 and P4. The possible subsets are
{P1}, {P2}, {P3}, {P4}, {P1, P3}, {P2, P4}. So the answer would be 6.
Find the answer for the following values of N:
(a) N = 11
(b) N = 13
(c) N = 15
source:- Q.3 https://www.iarcs.org.in/inoi/2019/zio2019/zio2019-question-paper.pdf
ANS:- (a)198
(b) 520
(c) 1363
This question was from pen & paper test
My failed attempt:-
(a) For N = 11,
the possible subsets are {P1},{P2},....{P11} = 11 +
since P11,P2 are adjacent to P1, the next possible subsets are:- {P1,P3},{P1,P4},...,{P1,P10}
= 8 +
Similarly, P1,P3 are adjacent to P2, the next subsets are:-
{P2,P4},{P2,P5}.....,{P2,11} = 8 +
DOING SAME FOR P3,P4,P5,P6,P7,P8,P9,P10,P10, (each of the individual has 7 subsets)
total subsets of them are :- 7 x 9 + 8 + 8 + 11 = 90.
MY ANS:-90

A: Two comments:
First, your count for subsets of $2$ is off. When you choose $P_4$, you have already counted pairing that up with $P_1$ and $P_2$, and so you only have $6$ more options, rather than $7$. So, you get $8+8+7+6+5+4+3+2+1=44$ options.
However, an easier way to count this is to say that for *each * person we can pick $8$ others, giving $11\cdot 8 = 88$ options.  Of course, now you need to rule out double-counting: first picking $P_1$ and then picking $P_6$ gives you the same subset as first picking $P_6$ and then picking $P_1$. So, you need to divide by $2$. In other words, there are $\frac{88}{2}=44$ possible subsets of size $2$
Second: what about subsets of size $3$?  For example, you can pick $P_1$, $P_4$, and $P_8$.  You didn't count that subset, or any subset of size $3$. And you also didn't consider subsets of size $4$ or $5$. Now, any subset of size $6$ or larger will be impossible (do you see why?), but you will have to count the subsets of size $3$, $4$, and $5$.
OK, how many subsets of size $3$ are there?

 You can again start with $P_1$, pick $P_3$ as a second person, and then have a choice of $6$ ($P_5$ through $P_{10}$) as a third. So, that's $6$ options. Then, still staying with $P_1$, you can pick $P_4$ as your second person, but now you have only $5$ persons left ($P_6$ through $P_{10}$) for the third one. So, that's another $5$ options.  Choosing $P_5$ as the second gives $4$ options ... and continuing this, you get $6+5+4+3+2+1=21$ options with $P_1$ as the first person.  This, of course, repeats for all $11$ people, so you get $11\cdot 21=231$ options. But again, you are over-counting, because for any subset of $3$, you could have picked any of those $4$ as your 'first' person. As such, every triple got counted $3$ times, and so you have $\frac{231}{3}=77$ possible subsets of size $3$

For subsets of $4$:

 Again, start with $P_1$, add $P_3$, then $P_5$, and now you have $4$ options left ($P_7$ though $P_{10}$). Now we can make the third person $P_6$, and that gives you $3+2+1=6$ options. Likewise, you get $2+1=3$ and $1$ one more while having $P_1$ as the second person. So, there are $10+6+3+1=20$ subsets with $P_1$ as the first person. Again, multiply by $11$ ... and divide by $4$, since each subset gets counted $4$ times, since we could have started going around with each of the $4$ people in each subset. So: $\frac{11 \cdot 20}{4}=55$

Subsets of $5$:

 With $P_1$, $P_3$, $P_5$, and $P_7$ you have $2$ options left. You can also make $P_8$ the fourth person, and now there is $1$ option left. You can make the third $P_6$, and that also leads to $1$ options, and finally you can pick $P_4$ as the second, for a final option. Total: $5$ subsets with $P_1$. Again, multiply by $11$, and divide by size of subsets: $\frac{11 \cdot 5}{5}=11$ possibilities.

Total:

 $11+44+77+55+11=198$ subsets

A: Let $C_n$ be the number of ways to choose a group of people from a circle of $n$ people such that no two adjacent people are chosen, and let $L_n$ be the number of ways to choose a group of people from a line of $n$ people such that no two adjacent people are chosen.  For now, we will include the possibility that no one in the group is chosen -- remind me to rule that out at the end, okay?
Step 1: $C_n=L_{n-1}+L_{n-3}$
Proof: Let $n$ people numbered $p_1$ through $p_n$ be in a circle.  Either $p_n$ is in the group or not.  If $p_n$ is not in the group, then the remaining people could be selected for a group in $L_{n-1}$ ways.  If $p_n$ is in the group, then we know for certain that $p_{n-1}$ and $p_1$ cannot be in the group, so the remaining members of the group can be chosen in $L_{n-3}$ ways.
Step 2: $L_n=F_{n+2}$, where $F_n$ is the n'th Fibonacci number (i.e. $L_1=2$,$L_2=3$)
Proof: By inspection, $L_1=2$ and $L_2=3$, since we are still counting the possibility that no one is chosen. Let $n>2$ be given, and let $p_1$ through $p_n$ be our $n$ people in a line.  Again, either $p_n$ is in the group or not.  If not, then the remaining members of the group can be chosen in $L_{n-1}$ ways.  If so, then $p_{n-1}$ must not be in the group and the remaining members can be chosen in $L_{n-2}$ ways.  Therefore, $L_n=L_{n-1}+L_{n-2}$ and the sequence is a tail of the Fibonacci sequence starting at $2$.
Hmmm?  Oh, right, thank you.  Since there is 1 way to have nobody in the group and we're not supposed to count that, our final answer is $C_n-1=F_{n+1}+F_{n-1}-1$.


text:
Q: Jobeet for Symfony 2 error I try to set up jobeet using git and when i try to open localhost/jobeet/web I get class not found:
 Fatal error: Class 'Erlem\JobeetBundle\Repository\JobRepository' not found in
 D:\OpenServer\OpenServer\domains\joobet\vendor\doctrine\orm\lib\Doctrine\ORM\Repository\DefaultRepositoryFactory.php on line 75

A: If you say git, you didn't include the code with the composer right?
Have a look at

*

*https://getcomposer.org/doc/05-repositories.md how to include git repositories and then

*add it to your autoloader https://getcomposer.org/doc/01-basic-usage.md#autoloading


text:
Q: error : Connection Property has not been initialized using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        System.Data.OleDb.OleDbConnection con;
        DataSet ds1;
        System.Data.OleDb.OleDbDataAdapter da;

        int MaxRows = 0;
        int inc = 0;

        private void Form1_Load(object sender, EventArgs e)
        {
            con = new System.Data.OleDb.OleDbConnection();
            ds1 = new DataSet();

            con.ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/MyWorkers1.mdb";

            string sql = "SELECT * from tblWorkers";
            da = new System.Data.OleDb.OleDbDataAdapter(sql, con);

            con.Open();
            da.Fill(ds1, "MyWorkers1");
            NavigateRecords();
            MaxRows = ds1.Tables["MyWorkers1"].Rows.Count;
            //MaxRows = ds1.Tables["MyWorkers1"].Rows[inc];
            //MessageBox.Show("Database open");

            con.Close();
            //MessageBox.Show("Database close");

            con.Dispose();
        }

        private void NavigateRecords()
        {
            DataRow drow = ds1.Tables["MyWorkers1"].Rows[inc];
            textBox1.Text = drow.ItemArray.GetValue(0).ToString();
            textBox2.Text = drow.ItemArray.GetValue(1).ToString();
            textBox3.Text = drow.ItemArray.GetValue(2).ToString();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (inc != MaxRows - 1)
            {
                inc++;
                NavigateRecords();
            }
            else
            {
                MessageBox.Show("No More Records");
            }
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if (inc > 0)
            {
                inc--;
                NavigateRecords();
            }
            else
            {
                MessageBox.Show("First Record");
            }
        }

        private void btnFirst_Click(object sender, EventArgs e)
        {

            if (inc != 0)
            {
                inc = 0;
                NavigateRecords();
            }
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            if (inc != MaxRows - 1)
            {
                inc = MaxRows - 1;
                NavigateRecords();
            }
        }

        private void btnAddNew_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            System.Data.OleDb.OleDbCommandBuilder cb;
            cb = new System.Data.OleDb.OleDbCommandBuilder(da);

            DataRow drow = ds1.Tables["MyWorkers1"].NewRow();

            drow[0] = textBox1.Text;
            drow[1] = textBox2.Text;
            drow[2] = textBox3.Text;

            ds1.Tables["MyWorkers1"].Rows.Add(drow);

            MaxRows = MaxRows + 1;
            inc = MaxRows - 1;

            da.Update(ds1, "MyWorkers1");

            MessageBox.Show("Record / Entry Added");
        }

    }
}

When I run this it shows an error like  "Invalid Operation - Exception Unhandled connection property has not been initialized."
What is wrong?

A: I'm not an expert, but try
con = new System.Data.OleDb.OleDbConnection(you_connection_string);

A: You can check if your ConnectionString is valid or not here : http://www.connectionstrings.com/
Notice that the Provider is different, regarding the .mdb version you are using (2007, 2000...)
By the way, would you like to try Source=D:\MyWorkers1.mdb instead of Source=D:/MyWorkers1 ? With a "\" instead of a "/".

A: I was working on the same example and figured that con.Dispose(); that is in the Form Load is not allowing da.Update(ds1, "MyWorkers1"); to update the record. So for the time being i have removed it, but it should better be moved to the Destroy/ Unload etc (i really don't know which is the correct event before closing the form)

A: The exception is very clear. The ConnectionString property has not been 'properly' set,
when trying to call Open the SqlConnection object.
Have you tried creating one inside the web.config?


text:
Q: angular-cli do not bundle the style files in order when using AOT in my .angular-cli.json, the styles property like this:
"styles": [
    "styles.css",
    "../node_modules/bootstrap/dist/css/bootstrap.min.css",
    "adminlte.css",
    "../node_modules/admin-lte/dist/css/skins/skin-yellow-light.min.css"
  ],

I expect these files will bundle in that order, but I got the styles.bundle.css like this:
AdminLTE ...... styles ...... skin-yellow-light ...... bootstrap ......

This lead to my project's style are different from dev mode after I build it.
So I wonder why.

A: I solved this problem by @import all the style files into styles.css, so my angular-cli.json:
"styles": [
    "styles.css"
]

and styles.css:
/* import other style files */
@import "./styles/bootstrap.min.css";
@import './styles/adminlte.css';
@import './styles/skin-yellow-light.min.css';

/* some global styles */


text:
Q: .getElementByClassName is unreliable. How else can I point to an HTML element with no ID? I'm a JavaScript novice.
I'm currently trying to write a chrome extension for a website we use at work (to create customer quotes) that will take the "parts" value and the "tax" value as inputs and add them together and output a "deposit" value.
The only problem is that there are no ID's on the DIV elements that hold the values I need.
I can reference the "parts" value okay using
document.getElementsByClassName ("col-xs-7 text-right")[2].innerText

since the "parts" element seems to consistently be the 3rd element with that class, but the "tax" element isn't consistently in the same place. Sometimes it will be the 3rd element with that class, sometime's it'll be the 5th, etc... I know there has to be a better way. The "tax" element looks like:

    <button _ngcontent-c11="" class="_button _blank _tiny"></button>

    $0.00

(I don't think the edit button is relevant, but I figured I'd keep it just in case.)
and the "parts" element looks like:

$0.00

A: Thank you all for your help! I was able to traverse the DOM tree, starting with a parent element that was unique enough to reference, and just drilled down until I got to the element I needed.
document.getElementsByClassName('col-xs-12 col-md-6 grid-item')[1].childNodes[17].childNodes[5].innerText


text:
Q: Constructing types with related fields in Julia I would like to create a Julia type that contains fields which have a fixed relationship to each other.  For illustration, consider a Point type which represents a point in 2 dimensions, and which has fields representing both its Cartesian (x,y) and polar (r,theta) coordinates.  These fields must be related by r*cos(theta)=x and r*sin(theta)=y, and you should be able to construct a Point by specifying either set of coordinates.  The question is: What's a good way to make a constructor for this type?

A: If you're happy to introduce 'sub'types, then you can do something like:
type Cartesian
  x::Float64;  y::Float64
end

type Polar
  r::Float64;  t::Float64
end

type Point
  x::Float64;  y::Float64
  r::Float64;  t::Float64
end

# secondary external constructors
Point(c::Cartesian) = Point(c.x, c.y, sqrt(c.x^2+c.y^2), atan2(c.y, c.x))
Point(p::Polar) = Point(p.r * cos(p.t), p.r * sin(p.t), p.r, p.t)
Point(x::Float64, y::Float64) = Point(Cartesian(x,y))   # ... etc

Alternatively, and with regard to Chris' comment, one way to get the best of both worlds, is to create a closure-generating function, instead of a straightforward conversion function, such that once it has been initialised it retains state and can be used to return the conversion to polar at no cost.

A: Here is a possible implementation:
abstract CoordSys
abstract Cartesian <: CoordSys
abstract Polar <: CoordSys

transform(r, theta, ::Type{Polar}) = r*cos(theta), r*sin(theta)
transform(x, y, ::Type{Cartesian}) = sqrt(x^2+y^2), atan2(y, x)

immutable Point{T<:AbstractFloat}
    x::T
    y::T
    r::T
    theta::T
    function Point(x, y, r, theta)
        x_ctrl, y_ctrl = transform(r, theta, Polar)
        if isapprox(x_ctrl, x, atol = 1e-15) && isapprox(y_ctrl, y, atol = 1e-15)
            new(x, y, r, theta)
        else
            error("Coordinates are inconsistent")
        end
     end
 end

 # These constructors take the coordinate system as an additional argument
 Point{T<:AbstractFloat}(x::T, y::T, C::Type{Cartesian}) = Point{T}(x, y, transform(x,y,C)...)
 Point{T<:AbstractFloat}(r::T, theta::T, C::Type{Polar}) = Point{T}(transform(r,theta,C)..., r, theta)

 # Convenience methods
 Point{C<:CoordSys}(x::Real, y::Real, ::Type{C}) = Point(promote(float(x), float(y))..., C)
 Point(x, y) = Point(x, y, Cartesian)

It uses an inner constructor to enforce the relations on construction and an immutable type to enforce them also after construction.


text:
Q: Mysql find date range Given the following values YYYY-MM-DD
$start = 2012-03-21
$stop = 2012-07-15

and the following records in the DB, also YYYY-MM-DD
    DATE_FROM    DATE_TO       PRICE
    2012-01-01   2012-03-01    123
    2012-03-01   2012-04-08    123
    2012-04-09   2012-06-04    456
    2012-06-04   2012-07-02    789
    2012-07-02   2012-07-16    111
    2012-07-17   2012-08-17    222

How can I select all records that fall within the range of $start - $stop? This should include all except the last and first row
Attempt below, which gets records 2 - 4 but not 5.
    SELECT date_from, date_to, price
    FROM periods
    WHERE (date(date_from) <= '$start' OR date(date_to) <= '$stop')

A: You want logic something like this:
date_to >= $start AND date_from <= $stop

If this is what you are looking for:
Start-----Stop
       From-------------------To

           Start-----Stop
       From-------------------To

                      Start-----Stop
       From-------------------To

Notice that Start always has to come before To AND Stop always has to come after From for this overlap to occur.
Let me know if any of my assumptions are off of what you are looking for. But, either way, I always find something like this easier to write down so you can visualize and easily see the greater than/less than situations.

A: SELECT date_from, date_to, price
    FROM periods
    WHERE (date_from BETWEEN '$start' AND '$stop') AND (date_to BETWEEN '$start' AND '$stop')


text:
Q: How to get the link of a video from a facebook post (graph api) I want to embed videos on an external website so I need the link of the actual video. Is there a way to get that from the posts object?
I am currently looping some info from posts so it would be great if I could retrieve the videolink of a post somehow, I know how to get the image from a post, but there is nothing in their docs about videos. Only a different object called videos which just show all videos from a page. How can I combine the two so I can use the data from field embed_html in posts? Is that even possible?
Part of the posts object:
{
   "data": [
      {
         "created_time": "2017-09-12T20:58:21+0000",
         "message": "Vandaag bij Vivienne Westwood Boutique Amsterdam de lichtreclame gemonteerd. Mooi project om te mogen doen.\n\u2705  maatwerk\n\u2705  kwaliteit\n\u2705  betaalbaar\n\ud83d\udc4b  Benieuwd naar de kosten? We helpen je graag!\n- Reclame & Internet - #ontwerp > #productie > #montage",
         "id": "367712570004555_1287302444712225"
      },

Part of the video object:
{
   "data": [
      {
         "embed_html": "\u003Ciframe src=\"https://www.facebook.com/plugins/video.php?href=https\u00253A\u00252F\u00252Fwww.facebook.com\u00252Fwebsite\u00252Fvideos\u00252F1287302444712225\u00252F&width=1280\" width=\"1280\" height=\"720\" style=\"border:none;overflow:hidden\" scrolling=\"no\" frameborder=\"0\" allowTransparency=\"true\" allowFullScreen=\"true\">\u003C/iframe>",
         "permalink_url": "/website/videos/1287302444712225/",
         "id": "1287302444712225"
      },

They are both in different objects, how can I use them both in one looped element (a box with video/image and a description, that I already made so that is not my question)?
I see the post id and the video id are kinda similar, except I need to explode the post id on the underscore and compare the last part of the id (if I'm correct).
Am I overthinking this and is it way simpler or..?


text:
Q: PHP Get Javascript Variable Without Ajax Click div > popup > display everything from database (via php).
How can I get the javascript variable to be used in PHP for the WHERE clause in my sql statement?
Eg:
$(".divclass").click(function(){
     <php
          $sql = "select * from table where id = ".[the div id];
     ?>
});

is there anyway to get it besides using ajax and post via form method? also without the dom
Thanks!

A: No it's not possible in PHP.
PHP is a server side language, you can't pass him variables without a call to php script.
Javascript is a client-side language and it is NOT secure.
The best answer for your question is :

*

*Use JS on client-side to get the ID

*Call from JS (ajax for example) a PHP script and send it the ID in parameter (post/get).

*On server-side (php), you make the SQL request (and secure the ID : intval()) and you get the result.

*From php you send back the result (json for example).

*JS get the result and parse/use it !


text:
Q: Instagram search by area I'm starting with Instagram API and I notice that there is no way to search media for a certain area. API only lets me to search through lat/long. Is there anyway to get media from an area? For example Flickr's API lets to ask for regions/counties...
In other case, any idea to do this in a simple way?
Thanks in advance,
Regards

A: You have two ways of doing this with the Instagram api:
Use the get media/search endpoint to find media for an area defined by lat/lng and a radius. You can specify a radius up to 5000 meters to capture media for a large area.
api.instagram.com/v1/media/search?lat=48.858844&lng=2.294351&distance=5000

Use the /locations/location-id/media/recent endpoint to find media assigned to locations. Some cities, towns, regions, etc are set up as locations. These aren't very reliable and there are often duplicates. You would need to use the /locations/search endpoint to find the location id's first.
api.instagram.com/v1/locations/514276/media/recent


text:
Q: Get Date Products last updated in Opencart 3 I am trying to get the latest date from Opencart 3 Products field 'Date_available' and post it into the very top of the header page. I am currently doing it by manually adding the date in the settings/store page where I have placed a text box linked to the database variable - I use the code in cotroller Settings.php:
if (isset($this->request->post['config_updated'])) {
        $data['config_updated'] = $this->request->post['config_updated'];
    } else {
        $data['config_updated'] = $this->config->get('config_updated');
    }

and the code in sttings twig:

            {{ entry_updated }}

              <input type="text" name="config_updated" value="{{ config_updated}}" placeholder="{{ entry_updated}}" id="input-updated" class="form-updated" />

Here I can enter the date and it shows as image:
enter image description here Products last updated: 25/05/2020 : 21:12:32
How can I find the latest date in oc_products_date_available and show it in the place described above? Any help appreciated.

A: Here are all the steps.
First of all, backup your files.
Then,
go to folder:
catalog/model/catalog

Inside the folder common create a new file called
headerdate.php

Inside the headerdate.php add the following code:
    <?php
class ModelCatalogHeaderdate extends Model {
    public function getLastDate() {
        $query = $this->db->query("SELECT date_available FROM `" . DB_PREFIX . "product` ORDER BY `date_available` DESC LIMIT 1");
        return $query->row['date_available'];
    }

}

Save the changes.
Now open file:
catalog/controller/common/header.php

and before the line:
return $this->load->view('common/header', $data);

add the following code:
$this->load->model('catalog/headerdate');
$data['last_product_update'] = $this->model_catalog_headerdate->getLastDate();

Save settings and you've completed the hard part.
Now, the last and easiest part, is that you open your theme's header.twig file and you can show your date by using the variable we've set above like this:
{{ last_product_update }}

Don't forget to save your changes and upload them to your eshop.


text:
Q: Seaborn distplot works, but displot doesn't. Why? I created some data
my_array = np.random.uniform(low=0 , high = 15,size = (1000))
my_list = ['car','boat','place','ship','train']
my_categorical = np.random.choice(a=my_list,size =(1000))
df = pd.DataFrame(np.column_stack((my_array.T,my_categorical.T)),columns=['numbers','cat'])re

Then i runned this code:
sns.set_theme(style='whitegrid')
sns.distplot(x = df['numbers'],kde=False)
plt.show()

This worked, but it said that it was going to be deprecated. So i tried to use one of the new options, displot.
sns.displot(data= df, x='numbers')

And didn't work.
I'll copy the outputs.

Tried to get an output as the one with displot


text:
Q: Want to get data from rails api whenever mui's data grid is rendered per page
I'm facing a problem which user's table rendered super slowly.

Take a look at this code.

def index_all
    all_users = User.all.order('users.created_at DESC')

    render json: all_users,
           include: %i[inflow_souce job_area user_evaluations evaluations]
  end

I would get over 1,000 users and taking to react frontend.

That's why whenever reached user's table, the first rendering would be supper slow.

I execute it using useEffect.
useEffect(() => {
    axios
      .get(`${process.env.REACT_APP_ENDPOINT}/admin/working_users`, {
        headers: {
          "access-token": access_token!,
          client: client!,
          uid: uid!,
        },
      })
      .then((response) => {
        console.log(response.data.created_at);
        console.log(response.data);
        setUsers(response.data);
      })
      .catch(() => {
        Cookies.remove("_access_token");
        Cookies.remove("_client");
        Cookies.remove("_uid");
        dispatch(setSessionTimeout(true));
        dispatch(setLoggedIn(false));
        navigate("/");
      });
  }, [selectedTab]);

What I want to do is just calling api per page so that getting rendering faster.

So How can I do that..?.
This is whole programs.
AllUserListPage.tsx
import { Grid } from "@material-ui/core";
import React, { useEffect } from "react";
import { DataGrid, GridColDef } from "@mui/x-data-grid";
import { usersStyles } from "utils/styles/UsersStyle";
import axios from "axios";
import { useDispatch, useSelector } from "react-redux";
import { setSessionTimeout } from "slices/SessionTimeout";
import { setLoggedIn } from "slices/LoggedIn";
import { useNavigate } from "react-router-dom";
import Cookies from "js-cookie";

type AllUserListPageProps = {
  access_token: string | undefined;
  uid: string | undefined;
  client: string | undefined;
  changeUsers: (users: any) => void;
  rows: any;
  columns: GridColDef[];
};

export function AllUserListPage(props: AllUserListPageProps) {
  const classes = usersStyles();
  const [pageSize, setPageSize] = React.useState(15);
  const dispatch = useDispatch();
  const admin_name = useSelector(setSessionTimeout);
  const navigate = useNavigate();

  useEffect(() => {
    axios
      .get(`${process.env.REACT_APP_ENDPOINT}/admin/all_users`, {
        headers: {
          "access-token": props.access_token!,
          client: props.client!,
          uid: props.uid!,
        },
      })
      .then((response) => {
        console.log(response.data.created_at);
        console.log(response.data);
        props.changeUsers(response.data);
      })
      .catch(() => {
        Cookies.remove("_access_token");
        Cookies.remove("_client");
        Cookies.remove("_uid");
        dispatch(setSessionTimeout(true));
        dispatch(setLoggedIn(false));
        navigate("/");
      });
  }, []);

  return (
    <Grid item xs={12}>
      <div
        style={{
          height: "131vh",
          width: "100%",
          paddingTop: "10px",
        }}
      >
        <DataGrid
          rows={props.rows}
          columns={props.columns}
          checkboxSelection
          className={classes.data_grid_styles}
          pageSize={pageSize}
          rowsPerPageOptions={[15, 30, 50]}
          onPageSizeChange={(newPageSize) => setPageSize(newPageSize)}
          onPageChange={(page) => console.log(page)}
        />
      </div>
    </Grid>
  );
}

users_controller.rb
class Admin::UsersController < ApplicationController

def index_all
    all_users = User.all.order('users.created_at DESC')

    render json: all_users,
           include: %i[inflow_souce job_area user_evaluations evaluations]
  end
end

Thank you.


text:
Q: Strapi V3 to V4 database migration issue I am trying to migrate Strapi V3 to V4 using the migration scripts for Postgres
I have a backup V3 and an empty V4 database running on Heroku.
The problem is when I run Strapi migration Script: v3-sql-to-v4-sql, I get a following error:
(node:17788) UnhandledPromiseRejectionWarning: error: set session_replication_role to replica; - permission denied to set parameter "session_replication_role"
Does anyone have idea why this error is happening?

A: I was trying to do the database migration on HEROKU, where you can't set the replication role to 'replica'.
What you have to do is pull the database locally, spin up a server and from there run migration scripts. Once you are done - push the database back to HEROKU.


text:
Q: Pyspark GroupBy time span I have data with a start and end date e.g.
+---+----------+------------+
| id|     start|         end|
+---+----------+------------+
|  1|2021-05-01|  2022-02-01|
|  2|2021-10-01|  2021-12-01|
|  3|2021-11-01|  2022-01-01|
|  4|2021-06-01|  2021-10-01|
|  5|2022-01-01|  2022-02-01|
|  6|2021-08-01|  2021-12-01|
+---+----------+------------+

I want a count for each month on how many observations were "active" in order to display that in a plot. With active I mean I want a count on how many observations have a start and end date that includes the given month. The result for the example data should look like this:
Example of a plot for the active times
I have looked into the pyspark Window function, but I don't think that can help me with my problem. So far my only idea is to specify an extra column for each month in the data and indicate whether the observation is active in that month and work from there. But I feel like there must be a much more efficient way to do this.

A: You can use sequence SQL. sequence will create the date range with start, end and interval and return the list.
Then, you can use explode to flatten the list and then count.
from pyspark.sql import functions as F

# Make sure your spark session is set to UTC.
# This SQL won't work well with a month interval if timezone is set to a place that has a daylight saving.
spark = (SparkSession
         .builder
         .config('spark.sql.session.timeZone', 'UTC')
         ... # other config
         .getOrCreate())

df = (df.withColumn('range', F.expr('sequence(to_date(`start`), to_date(`end`), interval 1 month) as date'))
      .withColumn('observation', F.explode('range')))

df = df.groupby('observation').count()


text:
Q: ODBC Call Failed - Error 3151 We have an Access database migrated from Access 97 to Acces 2007 with some linked tables to an SQL Server 2008 database.
We are using a File DSN in the ODBC Administrator. Connection tests work fine there. In fact, we have a main form in the Access 2007 application that shows the data always correctly.
The problem appears when we execute a task that makes the following call:
Dim dbs As Database
 Dim rstAppend As Recordset
 Set dbs = CurrentDb
 Set rstAppend = dbs.OpenRecordset(strAccessTable, dbOpenDynaset, dbSeeChanges)
OpenRecordset throws the error number 3151 and occurs randomly but it appears quite frequently. It's sporadic. When we don't get the error, the task works fine.

*

*It not happens always, mostly we're fine.

*When it happens it happens for all subsequent tasks tried. We have to close and reopen the Access database and pray to the good Lord that it works.

*Sometimes, refreshing the tables in the Linked Table Manager solves the problem, but others don't.

*We receive sometimes an error "ODBC--Call Failed" when refreshing the Linked Table Manager. Deleting the File DSN and creating a new one solves the problem.

*We have tried with two different drivers (SQL Server and SQL Server Native Client 10) and in both cases the problem remains.

*Also we have tried to put the Access File in the same machine than the SQL Server and the problem remains.

*We have increased the ODBC Timeout for all the querys from 60 to 180 seconds,but the problem still remains.

*We don't have to wait to see the error, it appears in less than one second after executing the task.

We would be very happy if someone could help us to find a solution to this problem.

A: After two months of research, we found one solution, change from DAO to ADO. This is the answer MS gave me:
I'd like to make you aware that implementing the workaround (using ADO instead of DAO) could be less time consuming than trying to figure out why DAO doesn't seem to work.
Therefore it might be advisable using the workaround instead of trying to find the root cause of this issue, especially as it doesn't seem to be reproducible.
However; here is what I'd like to you do next:

*

*Please replace the file DSN by a system or User DSN.

*Use the 'normal' ODBC driver for SQL- Server instead of the native driver.

*After creating the user DSN re link all the tables.

*In VBA code use explicit type declarations only instead of implicit declarations. So please replace use DAO. In front of any database type declarations in order to explicitly create DAO objects. For example replace the following:
Dim dbs As Database
Dim rstAppend As Recordset
By
Dim dbs As DAO.Database
Dim rstAppend As DAO.Recordset

A: Switching from TCP/IP to Named Pipes in the Client Configuration for the SQL Server ODBC Driver did the trick for me.

A: One thing to look at is the DNS setup (DNS not DSN!) in the network configuration for the workstations.
I had a client a couple of years ago who was encountering sporadic ODBC disconnects like this with some users, and it turned out that the primary DNS was set to point to the Internet provider's DNS. That worked fine for Internet, but the ISP knew nothing about the client's SQL Server's internal IP address. Changing the primary DNS to point to the local domain controller (which was acting as local DNS) resolved the issue permanently.
It may not be the cause of your problem, but it's worth a look.

A: I was having this issue as well.  What i did was added the DSN to the SQL database in the User tab.  I noticed it was working on my dev system, and that's the only difference i could find.  After creating the DSN on the users PC, it worked.


text:
Q: Displaying blue with SDL2 and OpenGL The title of this question is a bit misleading because I know how to display color thanks to this tutorial. After getting it to work I decided to use it so I gutted one of my old bits of code that was a test of SDL2 when I first started using SDL2, and replaced all the renderer stuff and some other stuff, and replaced it with an OpenGL context and tried to get it to display blue, but with no luck it just displayed a black screen. Not sure what the exact issue is. here is a gist
P.S. if can think of a better title I'm all ears :)

A: There is hardcoded green in given code, not blue. Anyway, you never assign window to window_p pointer but use it to create context and swap. If you look at SDL_GetError, it will report "Invalid window".
Aside from that:

*

*please post code within question itself, not as an external link

*recursion in loop is not great at all

*you set context parameters after creating context

*function implementation in .h is likely to cause problems


text:
Q: If $(a_n)$ is bounded, show $\sum_{n=1}^{\infty}{a_{n+1}-a_n \over \sqrt{n}}$ converges I am trying to show that if a sequence of real numbers $(a_n)$ is bounded, then the series
$$\sum_{n=1}^{\infty}{a_{n+1}-a_n \over \sqrt{n}}$$
converges. I would appreciate any clues.

A: This directly follows from the Dirichlet test


text:
Q: What assembly language does gcc produce on my system? I'm trying to learn a bit about assembly. I decided to start by looking at the generated assembly files from simple source code. Of course, I get bombarded by instructions that I have no idea what they mean, and I start to search for their meaning on the internet. While searching, I realized that I have no idea what assembly language I'm looking for..
Is there a way to know which assembly language gcc generates? Does this question even make sense?
I am mainly interested in the assembly that my system accepts (or however I should phrase that..). See below for the generated code using gcc.
If you realize which knowledge gaps I have, please link the relevant documents to read/study.
System:
OS:        Windows 10 Pro
Processor: Intel(R) Core(TM) i5-5200U CPU @ 2.20GHz   2.20 GHz
Type:      64-bit operating system, x64-based processor
//test.c

int main(){

    int x = 2;

    return 0;
}

 //test.s
.file   "test.c"
    .text
    .def    __main; .scl    2;  .type   32; .endef
    .globl  main
    .def    main;   .scl    2;  .type   32; .endef
    .seh_proc   main
main:
    pushq   %rbp
    .seh_pushreg    %rbp
    movq    %rsp, %rbp
    .seh_setframe   %rbp, 0
    subq    $48, %rsp
   .seh_stackalloc  48
   .seh_endprologue
    call    __main
    movl    $2, -4(%rbp)
    movl    $0, %eax
    addq    $48, %rsp
    popq    %rbp
    ret
   .seh_endproc
   .ident   "GCC: (Rev10, Built by MSYS2 project) 10.2.0"

A:
Is there a way to know which assembly language gcc generates?

Yeah the one for your target port. Which appears to be x86. This assembler language in turn comes in various flavours and dialects, with tons of history: https://en.wikipedia.org/wiki/X86_assembly_language

Of course, I get bombarded by instructions that I have no idea what they mean

Reading C compiler-generated assembler is much harder than reading hand coded assembler. I'd recommend to start with some assembler tutorials with code examples written by humans instead.
x86 is also perhaps the hardest one of them all because of all the flavours, and because of the complexity of the core. It's generally recommended to learn some simple assembler first to get the hang of it.
8 bit microcontrollers is a good place to start.

A: GCC always produces asm output that the GNU assembler can assemble, on any platform.  (GAS / GNU as is part of GNU Binutils, along with tools like ld, a linker.)
In your case, the target is x86-64 Windows (prob. from x86_64-w64-mingw32-gcc),
and the instruction syntax is AT&T syntax (GCC and GAS default for x86 including x86-64).
The comment character is # in GAS for x86 (including x86-64).
Anything starting with a . is a directive; some, like .globl  main to export the symbol main as visible in the .o for linking, are universal to GAS in general; check the GAS manual.
SEH directives like .seh_setframe %rbp, 0 are Windows-specific stack-unwind metadata for Structured Exception Handling, specific to Windows object-file formats.  (Which you can 100% ignore, until/unless you want to learn how backtraces and exception handling work under the hood, without relying on a chain of legacy frame pointers.  AFAIK, it's basically equivalent to ELF/Linux .eh_frame metadata from .cfi directives.)
In fact you can ignore almost all the directives, with the only really important ones being sections like .text vs. .data, and somewhat important to make linking work being .globl.  That's why https://godbolt.org/ filters directives by default.

You can use gcc -masm=intel if you want Intel syntax / mnemonics which you can look up in Intel's manuals.  (https://software.intel.com/content/www/us/en/develop/articles/intel-sdm.html / https://www.felixcloutier.com/x86/).  See also How to remove "noise" from GCC/clang assembly output?.  (gcc -O1 -fverbose-asm might be interesting.)
If you want to learn AT&T syntax, see https://stackoverflow.com/tags/att/info.  The GAS manual also has a page about AT&T vs. Intel syntax, but it's not written as a tutorial, i.e. it assumes you know how x86 instructions work, and are looking for details on the syntax GAS uses to describe them:  https://sourceware.org/binutils/docs/as/i386_002dVariations.html
(Keep in mind that the CPU actually runs machine code, and it doesn't matter how the bytes get into memory, just that they do.  So different assemblers (like NASM vs. GAS) and different syntaxes (like .intel_syntax noprefix) ultimately have the same limitations on what the machine can do or not in one instruction.  All mainstream assemblers can let you express pretty much everything every instruction can do, it's just a matter of knowing the syntax for immediates, addressing modes, and so on.  Intel and AMD's manuals document exactly what the CPU can do, using Intel syntax but not nailing down the details of syntax or directives.)

Resources (including some linked above):

*

*Matt Godbolt's CppCon2017 talk "What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid"  and How to remove "noise" from GCC/clang assembly output?

*The x86 tag wiki

*https://stackoverflow.com/tags/att/info

*https://sourceware.org/binutils/docs/as/ GAS manual

*https://software.intel.com/content/www/us/en/develop/articles/intel-sdm.html Intel manuals

*https://support.amd.com/TechDocs/24594.pdf (AMD vol.3 manual: general purpose instructions)


text:
Q: How to add event to input in Angular 5 app using directive? I have the following directive groupingFormat which perform grouping to an input text
when user use the key up:
@Directive({
  selector: '[groupingFormat]'
})
export class GroupingFormatDirective {

  private el: HTMLInputElement;
  constructor(elRef: ElementRef) {
    this.el = elRef.nativeElement;
  }

  ngAfterViewInit(): void {
    let elem : HTMLInputElement = this.el;
     elem.addEventListener('keyup',() => {
      this.el.value = this.digitGrouping(this.el.value);
     });
   }
}

Example of usage:
<input type="text" #myValue="ngModel" name="my_value" [(ngModel)]="myObj.myValue" id="my_value" required groupingFormat>

This directive is working as expected but now I have new requirement: The input
text should use the directive also when the page is load and also if the a form
is open inside the page with the input becoming visible.
Is there an easy way to update the directive to support this functionality or
any alternative solution? Attach another directive ?
Thanks.

A: <input type="text" name="my_value" [appInputevent]="myValue" [(ngModel)]="myValue">

directive file
import { Directive,HostListener,ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[appInputevent]'
})
export class InputeventDirective {

  constructor(private el:ElementRef) { }

  @Input('appInputevent') params: string;

 @HostListener('keyup', ['$event'])
  onKeyUp(event: KeyboardEvent) {
    console.log('got parameters: '+this.params);
  }

  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }

}

change hostlistner event according to your need.
For demonstration-- https://stackblitz.com/edit/ionic2-test?file=app%2Finputevent.directive.ts


text:
Q: How to run a background process in Android repeatedly I am using AlarmManager for repeated background process. My app repeatedly requests data from server in 5 sec interval. But after some long time, when I open my app it crashes. I can't figure out why.
How should I execute a background process repeatedly? Should I use AlarmManager,Timer` or something else?
My background process should run always even when the app does not have focus or isn't active.

A:
My app repeatedly request server for data 5 sec interval.

Users with mobile devices, like phones and tablets, will not appreciate your behavior. They will not appreciate your consumption of battery life and your consumption of bandwidth. Device manufacturers and Google are continuing to take aggressive steps to prevent applications like yours from behaving this way, both automatically and by giving users the tools to find ill-behaving apps like yours and get rid of them.

But After some long time when i open my app its crash

Most likely, you have a bug in your app. You will need to fix the bug. Since you have provided no details of your crash, such as source code and a stack trace, nobody can really help you with that.

Which is the best for repeated background process, AlarmManager, Timer or something else?

Switch to a user-configurable and less-crazy polling period (e.g., every 15 minutes by default), then use AlarmManager in conjunction with an IntentService, so that your process can cleanly go away
Or, switch to having the server send messages to the device when the data of interest changes, such as via Google Cloud Messaging. This will allow you to drop the polling period to something infrequent (e.g., every hour by default), as a fallback mechanism in case you miss a push message for some reason.

My background process should run always though the app is not on focus or active

Your users will disagree with you. They do not want apps running all of the time, tying up system RAM. They really do not want apps that consume battery and bandwidth the way that you are proposing. The users will get rid of your background process, either by:

*

*swiping your app off the recent-tasks list

*using a third-party task manager

*force-stopping your app via its entry in the application list in Settings

*uninstalling your app