text:
Q: C++ Getting compilation error while insert string into a map I used get() and getline() to read the file then input to my map(). Then insert from map class to AVLTree and AVLNode class. What should I do to fix the const string error and where the exactly problem is? Thank you for all your time and help. Here is the whole code.
https://github.com/RichardHung/AVL-BST-Tree.git

60 13  SequenceMap.cpp [Error] passing 'const std::basic_string' as 'this' argument of 'std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char; _Traits = std::char_traits; _Alloc = std::allocator]' discards qualifiers [-fpermissive]
  [Note] void std::basic_string<_CharT, _Traits, _Alloc>::push_back(_CharT) [with _CharT = char; _Traits = std::char_traits; _Alloc = std::allocator]
  [Note] no known conversion for argument 1 from 'const std::basic_string' to 'char'

template <typename Comparable_1, typename Comparable_2>
class AvlNode
{
  Comparable_1 element1; // sequence
  vector<Comparable_2> element2; // enzy
  AvlNode *left;
  AvlNode *right;
  int height;
  bool exist;
  AvlNode( const Comparable_1 & theElement1, const Comparable_2 & theElement2, AvlNode *lt, AvlNode *rt, int h = 0, bool ex = false):
  element1( theElement1 ),element2( theElement2 ), left( lt ), right( rt ), height( h ), exist( ex ) { }
  friend class AvlTree<Comparable_1, Comparable_2>;
};

template <typename Comparable_1, typename Comparable_2>
void AvlTree<Comparable_1, Comparable_2>::insert( const Comparable_1 & x, const Comparable_2 y, AvlNode<Comparable_1, Comparable_2> * & t )
{
 if( t == NULL )
     t = new AvlNode<Comparable_1, Comparable_2>( x, y, NULL, NULL, true );
 else if( x < t->element1 )
 {
      insert( x, y, t->left );
      if( height( t->left ) - height( t->right ) == 2 )
          if( x < t->left->element1 )
              rotateWithLeftChild( t );
          else
              doubleWithLeftChild( t );
 }
 else if( x > t->element1 )
 {
      insert( x, y, t->right );
      if( height( t->right ) - height( t->left ) == 2 )
          if( x < t->right->element1 )
              rotateWithRightChild( t );
          else
              doubleWithRightChild( t );
 }
 else // ( x == t->element1 )
 {
     t->element2 = y ;
 }
 t->height = max( height( t->left ), height( t->right ) ) + 1;
 }

template <typename Comparable_1, typename Comparable_2>
class SequenceMap
{
  public:
         Comparable_1 key;
         Comparable_2 value;
         AvlTree < Comparable_1, Comparable_2 > avl;
         BinarySearchTree < Comparable_1, Comparable_2 > bst;
         SequenceMap(){};
         ~SequenceMap();
         }
template <typename Comparable_1, typename Comparable_2>
void SequenceMap<Comparable_1, Comparable_2>::AVLinsert( const Comparable_1 & str, const Comparable_2 & set )
{
if ( avl.isEmpty( ) )
{
    key = str;
    value = set;
    avl.insert( key, value );
}
else                        // check the enzy is duplicated or not
{
    for( int i=0; i<set.size( ); i++ )
    {
        if ( avl.findEnzyme( key, set ) ) // if cannot find the enzy in the node
        {
                merge( set );
                avl.insert( key, value );
        }
    }
    // if find the same enzy in the node, do nothing to avoid duplicated.
}
}

main.cpp
while ( ! fin.eof( ) )
{
    if ( fin.peek( ) == '/' )
    {
        fin.get();      // skip "/" and move ptr to next sequence
        while ( fin.peek() != '\n' )
        {
            getline(fin, sequence, '/');
            cout << "enzyme: " << enzyme << endl;
            cout << "sequence: " << sequence << endl;
            map.insert(tree, sequence, enzyme);
            sequence.clear();
            fin.get();  // skip "/" and move ptr to next sequence
            if(fin.peek() == '/')
                fin.get();
        }
        fin.get();
        enzyme.clear();
    }
    else // if( enz != '/' )
    {
        enzyme += fin.get( );
    }

}

A: You need to pay attention to your compiler warnings.
In a couple of your classes you had std::vector<Comparable_2> members where I think you meant to have just plain old Comparable_2 members. I couldn't get your code to compile without changing that. As far as I can tell, that was your main issue. You can't just assign an object of type T to a container of type vector<T>. Not only are they different types with no implicit conversions according to the compiler, but such an assignment makes no logical sense.
You may have meant to use a std::vector<Comparable_2>. In that case your syntax is wrong in numerous places; you will need to do things like element2.push_back(y) instead of element2 = y. You'll also need to change your comparisons like element2 == y to something like std::find(element2.begin(), element2.end(), y) != element2.end(), because just like you can't assign a T to a vector<T>, you also won't be able to compare a T to a vector<T>.
However, you had quite a few significant compiler warnings: ambiguous if/else blocks, many functions not always returning a value, other functions never ever returning a value, etc. If changing your element2 members from std::vectors to std::strings still doesn't let your code compile, I'd have a look at fixing some of those warnings--several of them will probably lead to your app doing things you don't expect.
Here is a link to coliru compiling and running your app. I loaded the input file into this other coliru instance here.
As a side note, you really shouldn't do using namespace std;.


text:
Q: Difference between "subsequently" and "consequently"? When studying and reading course material in "softer" sciences that are descriptive the word "subsequently" appears in a way like "and subsequently" ...what does it mean, disctinct from "consequently" ?
Is the difference that "subsequently" doesn't imply a causality and the word "consequently" does? For instance A ⇒ B should read "A and consequently B" and in that case using the word "subsequently" is not false but it's not right since the word subsequently doesn't imply a causality which A ⇒ B does, so when talking about causality the we should use is "consequently"?

A: You're correct: subsequently doesn't imply causation.

subsequent: Following in order or succession; coming or placed after, esp. immediately after.
consequent: Following as an effect or result; resulting.

(Both definitions are from the Oxford English Dictionary.)
You might use subsequently to avoid the post hoc, ergo propter hoc fallacy.

A: Think of it this way: consequent requires there to be a consequence or a cause that the writer is trying to address. While subsequent is used to show the different parts of a particular event in smaller increments or successions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: scrollTo TweenMax Doesn't stop exactly on the hash I have a problem with plugin scrollTo (tweenMax), When I click on and the menu link the website slide to the section ID that I chose on menu. But the website doesn't stop on begin of the section, and I need to show the h2 (Title).
My Code

$(function(){
  var wrapper = $("#wrapper"),
  $menu = $("#menu");

  $menu.on("click","li", function(){
    var $this = $(this),
        href = $(this).find("a").attr("href"),
        topY = $(href).offset().top;

      TweenLite.to(window, 2, {scrollTo:{y:topY, x:0}, ease:Cubic.easeIn});

    return false;
  });

});
section{
  margin-top: 200px;
}

Home

Link 2

Link 3

Link 3

Link 4

Title 1

Title 2

Title 3

Title 4

Title 5

In this example above, it's OK. But in my site the same code not working well. In my website there is a menu fixed on the top, it has a height = 75px, I put {scrollTo:{y:topY -75, x:0} but not worked.
Update 1
Project

A: var extraOffset = $menu.hasClass('fixar') ? 75 : 0;

TweenLite.to(window, 2, { scrollTo: { y: topY - extraOffset, x: 0 }, ease: Cubic.easeIn });

It appears that the issue is whether or not the $menu is fixed when the click event occurs. When you're scrolled all the way to the top, the $menu is not fixed, but after you scroll down a bit, the $menu becomes fixed. The reason for this behavior is because the "fixed" $menu is removed from general flow of the webpage, and the calculated offset is thrown off.
With my solution, I've created a new variable extraOffset that checks if the $menu is fixed. If it is, the value is set to 75, otherwise 0. Let me know if you'd like further clarification!
Edit: If you want to add support for smooth scrolling on page load when the URL has the #hashtag), you can follow this example: Smooth scroll to anchor after loading new page. Note: You will probably want to always have the extra offset added since the $menu is expected to be fixed when scrolled to content.


text:
Q: How can I stream a local screen capture remotely ( I own a web server )? I have a VPS Debian server and I would like to stream my screen capture I have locally, so friends could watch what I'm viewing basically. How can I do this? I suspect I would need to have VLC sort of feed my web server, where my web server is setup so there's a streaming server installed.

A: I would try using either RecordMyDesktop or xvidcap as they both have live encoding features, and pair that up with VLC for streaming.
I haven't tried that yet myself, so let me know how well that works.


text:
Q: How to read user input from Radio Button in JavaFX into xml file I made application for selling internet packages in JavaFX that looks like this.

So when user click save button this application is saving all of his data in XML file so I did marshalling
@FXML
private void saveInternetPaketxml() throws JAXBException{
    if(internetPaket.isValid()){

        ObjectFactory objectFactory = new ObjectFactory();
        internetPaket.InternetPaket internetPaket = objectFactory.createInternetPaket();

        internetPaket.setFirstName(firstName.getText());
        internetPaket.setLastName(lastName.getText());
        internetPaket.setAddress(address.getText());
        internetPaket.setBrzina(brzina.getSelectedToggle().toString());
        internetPaket.setProtok(protok.getSelectedToggle().toString());
        internetPaket.setTrajanjeUgovora(trajanjeUgovora.getToggles().toString());

        JAXBContext jaxbc =JAXBContext.newInstance("internetPaket");
        Marshaller marshaller = jaxbc.createMarshaller();
        marshaller.marshal(internetPaket, new File("out.xml"));

but my output in XML file looks like this

and i need it to look like this:
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<internetPaket>
    <firstName>john</firstName>
    <lastName>mayers</lastName>
    <address>ddd</address>
    <brzina>5Mbt</brzina>
    <protok>10GB</protok>
    <trajanjeUgovora>1 Godina</trajanjeUgovora>
</internetPaket>

I need help because I'm very new to this. I don't know what to write instead of this:
internetPaket.setBrzina(brzina.getSelectedToggle().toString());
        internetPaket.setProtok(protok.getSelectedToggle().toString());
        internetPaket.setTrajanjeUgovora(trajanjeUgovora.getToggles().toString());

to get from my Radio Button and Toggle Button right output also I need advice how to keep every "sale" in my XML file because now every time i insert new user only his data is in XML file? Thanks.

A: getSelectedToggle returns you an instance of toggled radio button. Do not call toString! Call getText instead and there you go.
Sidenote:
1) You always want to name your variables, classes, methods in english.
2) I don't see a point of using ToggleButton's in "Izaberi trajanje ugovora". You can use RadioButton's there too.


text:
Q: LaTeX conflict between biblatex and draftmark? I need to use biblatex for a draft of a report. I'd like to use draftmark to create a water mark as well. However, the document fails to compile even with just the usepackage statements. Here is a MWE:
\documentclass[11pt,letter]{report}
\usepackage{biblatex}
\usepackage{draftmark}

\begin{document}
  Lorem ipsum dolor sit amet.
\end{document}

And I get the following error:
\file \blx@list@req@stat \advance \lrq@indent \m@ne \xappto \lrq@hook@data \ETC
Latex Error: ./untitled.tex:14 Paragraph ended before \ettl@forloop was complete.

Latex Error: ./untitled.tex:14 Extra }, or forgotten \endgroup.

pdfTeX warning: pdflatex: \pdfmatch: repetition-operator operand invalid

! Emergency stop.

! ==> Fatal error occurred, no output PDF file produced!

Any idea what's going on here or if there's a work around?
EDIT
Additionally, I would like to add a draft watermark to the bottom of the page, in the footer area (so that it's easier to others to read).
[I am running pdfTeX (TeX Live 2012) through TextMate on Mac OS X]

A: Since draftmark uses etextools and biblatex applies macros from etoolbox, the usage of both packages in the same document is hopeless -- they do not match.
A similar watermark for content can be achieved with Gonzalo Medina's background package, which is quite easy to configure, however, there's no draft feature. Please note, that the package usage requires two compilation runs to get the underlying tikz anchors correct, but this is no issue, since most documents need two runs.
\documentclass[11pt]{report}
\usepackage{biblatex}

\usepackage{background}
\usepackage{blindtext}

\backgroundsetup{contents=DRAFT,color=blue}

\begin{document}
  \blindtext[5]
\end{document}

Edit A small 'hack' to use the draft option of the report.cls
\documentclass[11pt,draft]{report}
\usepackage{biblatex}

\usepackage{blindtext}

\newif\ifdraftmode  % Define the `\ifdraftmode` conditional
\draftmodefalse     % Set it to false --> not the draft mode

\DeclareOption{draft}{\draftmodetrue\setlength\overfullrule{5pt}} % set draft mode to true if specified
\ProcessOptions*  % Reprocess options

\ifdraftmode                   % Check for draftmode
\usepackage{background}        % Within the check, because the package automatically sets a pink coloured 'Draft' in the background
\backgroundsetup{angle=0,scale=3,placement=bottom,vshift=0.5cm,contents=DRAFT,color=blue}
\fi

\begin{document}
\blindtext[5]
\end{document}


text:
Q: Systray how to track status of a menu when clicked? I have a systray and I want to track a menu when it's clicked. For example I use InsertMenu(hPopMenu,0xFFFFFFFF,uFlag,IDM_AUTO,_T("Auto")); when the right mouse button is clicked over the systray but it always overide my changes? How can I track which menu the user has clicked? This is my callback function:
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int wmId, wmEvent;
    POINT lpClickPoint;
    HMENU hMenu;    // handle to main menu
    MENUITEMINFO mii = {sizeof(MENUITEMINFO) };
    BOOL status;

    switch (message)
    {
        case WM_USER_SHELLICON:

            // systray msg callback
            switch(LOWORD(lParam))
            {
                case WM_RBUTTONDOWN:

                    UINT uFlag = MF_BYPOSITION|MF_UNCHECKED|MF_STRING;
                    GetCursorPos(&lpClickPoint);
                    hPopMenu = CreatePopupMenu();

                                InsertMenu(hPopMenu,0xFFFFFFFF,uFlag,IDM_AUTO,_T("Auto")); InsertMenu(hPopMenu,0xFFFFFFFF,MF_SEPARATOR,IDM_SEP,_T("SEP"));
InsertMenu(hPopMenu,0xFFFFFFFF,MF_BYPOSITION|MF_STRING,IDM_EXIT,_T("Exit"));

                    SetForegroundWindow(hWnd);
                    TrackPopupMenu(hPopMenu,TPM_LEFTALIGN|TPM_LEFTBUTTON|TPM_BOTTOMALIGN,lpClickPoint.x, lpClickPoint.y,0,hWnd,NULL);
                    return TRUE;
            }
            break;

    case WM_COMMAND:

        wmId    = LOWORD(wParam);
        wmEvent = HIWORD(wParam);

        // Parse the menu selections:

               ...
               ...

    }
    break;

    case WM_DESTROY:
        PostQuitMessage(0);
        break;

    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

A: You're re-creating every mouse click.  So, you have to initialize based on current state.
UINT uFlag = MF_BYPOSITION|MF_UNCHECKED|MF_STRING;

becomes:
UINT uFlag;
if( bCheckboxShouldBeCheckedAccordingToYourApplication )
    uFlag = MF_BYPOSITION|MF_CHECKED|MF_STRING;
else
    uFlag = MF_BYPOSITION|MF_UNCHECKED|MF_STRING;

Here, now it's shorter but still actually matches the posed question:
UINT uFlag = MF_BYPOSITION  | (b?8:0) | MF_STRING;

Of course, it's a bit less readable.

A: It works :). Like in the comment I used a variable to store the state and then after the InsertMenu I change the menu state.
MENUITEMINFO mii = {sizeof(MENUITEMINFO) };
mii.fMask = MIIM_STATE;
status = GetMenuItemInfo(hPopMenu, oldmenu, FALSE, &mii);
mii.fState ^= MFS_CHECKED;
status = SetMenuItemInfo(hPopMenu, oldmenu, FALSE, &mii);


text:
Q: c++ output of an array using void display(ostream&)
Possible Duplicate:
singly linked chain printing c++

How can I get my void display function to display the array found in my Set function; also how would I reference that display function in my driver file?
Thanks.
Relevant files are below
header file
#ifndef SET_
#define SET_

using namespace std;

#include <iostream>

class Set
{
  private:

    unsigned Cap;    // Current capacity of the set
    unsigned Num;    // Current count of items in the set
    int * Pool;      // Pointer to array holding the items

  public:

    // Return information about the set
    //
    bool is_empty() const { return Num == 0; }
    unsigned size() const { return Num; }
    unsigned capacity() const { return Cap; }

    // Initialize the set to empty
    //
    Set()
    {
      Cap = Num = 0;
      Pool = NULL;
    }

    // De-initialize the set
    //
    ~Set();

    // Initialize the set using an existing set
    //
    Set( const Set& );

    // Assign into the set from another set
    //
    Set& operator=( const Set& );

    // Test for presence of a specified item in the set
    //
    bool is_present( int ) const;

    // Remove a specified item from the set, if possible
    //
    bool remove( int );

    // Insert a specified item into the set, if possible
    //
    bool insert( int );

    // Display the set
    //
    void display( ostream& ) const;

    // Produce the union of two sets
    //
    friend Set operator+( const Set&, const Set& );

    // Produce the intersection of two sets
    //
    friend Set operator^( const Set&, const Set& );
};

#endif

my implementation file
using namespace std;

#include <iostream>
#include "/user/cse232/Projects/project07.set.h"

void bubbleSort(int arr[], int n)
{
        bool swapped = true;
        int j = 0;
        int tmp;

        while(swapped)
        {
                j++;
                for(int i = 0; i < n-j; i++)
                {
                        if(arr[i] > arr[i+1])
                        {
                                tmp = arr[i];
                                arr[i] = arr[i+1];
                                arr[i+1] = tmp;
                                swapped = true;
                        }
                }
        }
}

Set::~Set()
{
        Cap = 0;
        Num = 0;
        delete [] Pool;
        Pool = NULL;
}

/*bool Set::is_present(int X) const
{
        bool Flag = false;

        while(unsigned Z=0;Z<=Num;Z++)
        {
                if(Pool[Z] = X)
                {
                        Flag = true;
                }
        }
        return Flag;
}*/
bool Set::insert(int X)
{
        bool Flag = false;

        if(Num == Cap)
        {
                //reallocate memory
                const unsigned Inc = 3;

                try
                {
                        int * temp = new int[Cap+Inc];

                        for(unsigned J=0; J<Num; J++)
                        {
                                temp[J] = Pool[J];
                        }
                        delete [] Pool;
                        Pool = temp;
                }
                catch(std::bad_alloc)
                {
                        cerr << "\n*** UNABLE TO INCREASE CAPACITY ***\n\n";
                }
        }
        if(Num < Cap)
        {
                //insert stuff
                Pool[Num+1] = X;
                Num++;

                bubbleSort(Pool,Num);

                Flag = true;
        }

        return Flag;
}
void display(ostream &out) const
{
        //print the array
}


text:
Q: In the Rayleigh–Jeans Law, why polarization is two? When we count mode of wave in  cavity radiator, why the "2" is multiplied by polarization?
Polarization has two base, but the number of polarization state maybe infinity and continues.
Linear polarization, Circularly polarization, Elliptically polarization,...
It is countless.
Why the two is multiplied?

A: Polarized light on a plane is a superposition of independent components $E_x$ and $E_y$. Considering circular polarization, there are again two independent components, since two distinct rotations are conceivable.
On the whole, we pay attention to the number of independent polarization states -which is 2- while counting independent modes, thus $N(v)dv=\frac{4*π*\rho^{2}d\rho}{8}$ is multiplied by 2.


text:
Q: Evaluating Gaussian Mixture model using a score metric? I have 1D data (on column data). I used Gaussian Mixture Model (GMM) as a density estimation, using this implementation in Python: https://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html. By relying on AIC/BIC criteron i was able to determine number of components. After i fit the GMM, i plotted kernel density estimation of original observation + that of sampled data drawn from GMM. the plot of original and sampled desnities are quiet similar( that is good). But, i would like some metrics to report how good is the fitted model.
g = GaussianMixture(n_components = 35)

data= df['x'].values.reshape(-1,1) # data taken from data frame (10,000 data pints)
clf= g.fit(data)# fit model

samples= clf.sample(10000)[0] # generate sample data points (same # as original data points)

I found score in the implementation, but not sure how to implememnt. Am i doing it wrong? or is there any better way to show how accuracy is the fitted model, apart from histogram or kernel densities plots?.
print(clf.score(data))
print(clf.score(samples))

A: You can use normalized_mutual_info_score, adjusted_rand_score or silhouette score to evaluate your clusters. All of these metrics are implemented under sklearn.metrics section.
EDIT: You can check this link for more detail explanations.
In a summary:

*

*Adjusted Rand Index: measures the similarity of the two assignments.

*Normalized Mutual Information: measures the agreement of the two assignments.

*Silhouette Coefficient: measures how well-assigned each individual point is.

gmm.fit(x_vec)

pred = gmm.predict(x_vec)

print ("gmm: silhouttte: ", silhouette_score(x_vec, pred))

A: I would better use cross-validation and try to see the accuracy of the trained model.
Use the predict method of the fitted model to predict the labels of unseen data (use cross-validation and report the acurracy): https://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html#sklearn.mixture.GaussianMixture.predict
Toy example:
g = GaussianMixture(n_components = 35)
g.fit(train_data)# fit model
y_pred = g.predict(test_data)

EDIT:
There are several options to measure the performance of your unsupervised case. For GMM, which base on real probabilities, the most common are BIC and AIC. They are immediatly included in the scikit GMM class.


text:
Q: SQL Server Write Permission but not delete I'm pretty sure the answer is that once I grant write/alter access it explicitly gives the person access to delete.

A: Pretty straight forward to do this AND to test it which you really should do before you post a question.
GRANT INSERT TO YourUser
GRANT SELECT TO YourUser
GRANT UPDATE TO YourUser
DENY DELETE TO YourUser

A: For data; Insert, Update & Delete are all separate permissions.  Granting db_datawriter  is a role that grants all three, but you can grant them individually if you choose.
Select is also a distinct permission.  You can technically grant someone the ability to only insert data, without the ability to select/update/delete.
For objects; Create, Alter, Drop are the separate permissions.


text:
Q: Is there a JDK method for changing a double to the nearest larger int, even if it's already an integer value? I want to be able to 'round' up any double value to the closest higher integer, even if the value itself is already an integer value.
Math.ceil(2) returns 2, since 2 is already equal to an integer value. I need a function that would return 3 in this case.
I can easily code this myself but am curious whether this already exists in the JDK.
EDIT: In the likely case that I will just code this myself given how trivial I think this is, please tell me if the following code looks okay to you:
public static double convertToNearestLargerIntValue(double value){
    return Math.floor(value + 1.0);
}

A: It's so simple, there doesn't need to be a JDK method.
Math.floor(value) + 1


text:
Q: Why Does Map Marker Lurch Around The Map I'm in Android Studio and I have a map fragment (com.google.android.gms.maps.SupportMapFragment) that has two markers. One is static and called Target. The other tracks my movements and is called Hunter. It works but the problem is that the Hunter marker lurches about. I have the update interval set at 15 milliseconds, but at walking speed it only updates about once every block.
So, how do I properly add a marker to track my location and have it be reasonably accurate and update in real-time? Or what am I doing wrong here?
Greg
onCreate()
    setUpMapIfNeeded();

    if (mMap != null) {
        LatLng Target = new LatLng(TargetLat, TargetLong);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Target, 15));
    }

    LocationManager locationManager = (LocationManager) this.getSystemService(this.LOCATION_SERVICE);

    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            makeUseOfNewLocation(location);
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {}

        public void onProviderEnabled(String provider) {
            registerForUpdates();
        }

        public void onProviderDisabled(String provider) {
            deregisterForUpdates();
        }
    };

    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

private void registerForUpdates() {
    _locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, GPS_FREQUENCY_MILLIS, 0, _locationListener);
}

Update marker when location changes. When we get close to the target, vibrate and change the text.
    private void makeUseOfNewLocation(Location loc) {
    HunterLat = loc.getLatitude();
    HunterLong = loc.getLongitude();

    if (Hunter != null) {
        LatLng NewLoc = new LatLng(HunterLat, HunterLong);
        Hunter.setPosition(NewLoc);

        TextView txtItem = (TextView) findViewById(R.id.ItemName);

        if (HunterLong > TargetLong - .0007 && HunterLong < TargetLong + .0007 && HunterLat > TargetLat - .0007 && HunterLat < TargetLat + .0007) {
            txtItem.setTextColor(Color.MAGENTA);
            txtItem.setText(ItemName);
            if (!Vibrated){
                Vibrated = true;
                Vibrator v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
                v.vibrate(500);
            }
        }
        else {
            txtItem.setTextColor(Color.BLACK);
            txtItem.setText(getResources().getString(R.string.hunt_item));
        }
    }
    else {
        Hunter = mMap.addMarker(new MarkerOptions().position(new LatLng(HunterLat, HunterLong)).title("You"));
        BitmapDescriptor icon2 = BitmapDescriptorFactory.fromResource(R.drawable.ic_map_person);
        Hunter.setIcon(icon2);

    }
}

Set up the map and add the static target marker
   private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}

private void setUpMap() {
    Marker Target = mMap.addMarker(new MarkerOptions().position(new LatLng(TargetLat, TargetLong)).title(Location));
    BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.ic_target);
    Target.setIcon(icon);
}

A: After seeing your other question, it looks like the non-map Activity is getting the onProviderEnabled() callback, but your map Activity is not getting it (unless the GPS radio is enabled during use of the map Activity).
Instead of only calling registerForUpdates() in the onProviderEnabled() callback, call it in onCreate() if the GPS radio is enabled, and fall-back to Network Location if GPS is disabled and Network Location is enabled.
Something like this:
    LocationManager locationManager = (LocationManager) this.getSystemService(this.LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        registerForUpdates();
    }
    else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    }

Another thing to note is that you should unregister from all location callbacks in the onPause() override for your Activities that request location updates, so that you don't have unnecessary battery drain caused by your app.

A: I was using network instead of GPS.
Changed
 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

To
 locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

It now tracks my movements smoothly. Thanks to Daniel Nugent for pointing this out to me an another post.
Greg


text:
Q: Adding rows to DataGridView in VB.NET I have a DataGridView set up with the following columns:
Teacher, Subject, Date, Period.
After a lot of Googleing I can see there are a few ways to add data to the grid programmatically, with each one differing to another quite extensively.
I wanted your opinion on how I should go about this, considering I am going to be adding data from a text file line-by-line (using ":" as a delimiter) and I want each line to have its own row, so it's going to be in a loop.
Thanks.

A: Since the data in the text file is delimited then one way to do this is to use the Split function to create an array of cell strings and then just add these directly to the grid.
Dim CellData() As String
Dim LineText As String = ""

' open the data file
Dim objReader As New System.IO.StreamReader("c:\temp\file.dat")

Do While objReader.Peek() <> -1
    LineText = objReader.ReadLine()
    ' split the line of text into cells
    CellData = Split(LineText, ":")
    Me.DataGridView1.Rows.Add(CellData)
Loop


text:
Q: Access root document map in the $filter aggregation (MongoDb) I apologize for the vague question description, but I have quite a complex question regarding filtration in MongoDB aggregations. Please, see my data schema to understand the question better:
Company {
  _id: ObjectId
 name: string
}

License {
  _id: ObjectId
  companyId: ObjectId
  userId: ObjectId
}

User {
  _id: ObjectId
  companyId: ObjectId
  email: string
}

The goal:
I would like to query all non-licensed users. In order to do this, you would need these plain MongoDB queries:
const licenses = db.licenses.find({ companyId }); // Get all licenses for specific company
const userIds = licenses.toArray().map(l => l.userId); // Collect all licensed user ids

const nonLicensedUsers = db.users.find({ _id: { $nin: userIds } }); // Query all users that don't hold a license

The problem:
The code above works perfectly fine. However, in our system, companies may have hundreds of thousands of users. Therefore, the first and the last step become exceptionally expensive. I'll elaborate on this. First things first, you need to fetch a big number of documents from DB and transmit them via the network, which is fairly expensive. Then, we need to pass a huge $nin query to MongoDB over the network again, which doubles overhead costs.
So, I would like to perform all the mentioned operations on the MongoDB end and return a small slice of non-licensed users to avoid network transmission costs. Are there ideas on how to achieve this?
I was able to come pretty close using the following aggregation (pseudo-code):
db.company.aggregate([
  { $match: { _id: id } }, // Step 1. Find the company entity by id
  { $lookup: {...} }, // Step 2. Joins 'users' collection by `companyId` field
  { $lookup: {...} }, // Step 3. Joins 'licenses' collection by `companyId` field
  {
    $project: {
      licensesMap: // Step 4. Convert 'licenses' array to the map with the shape { 'user-id': true }. Could be done with $arrayToObject operator
    }
  },
  {
    $project: {
       unlicensedUsers: {
             $filter: {...} // And this is the place, where I stopped
          }
     }
  }
]);

Let's have a closer look at the final stage of the above aggregation. I tried to utilize the $filter aggregation in the following manner:
{
    $filter: {
     input: "$users"
     as: "user",
     cond: {
       $neq: ["$licensesMap[$$user._id]", true]
     }
  }
}

But, unfortunately, that didn't work. It seemed like MongoDB didn't apply interpolation and just tried to compare a raw "$licensesMap[$$user._id]" string with true boolean value.
Note #1:
Unfortunately, we're not in a position to change the current data schema. It would be costly for us.
Note #2:
I didn't include this in the aggregation example above, but I did convert Mongo object ids to strings to be able to create the licensesMap. And also, I stringified the ids of the users list to be able to access licensesMap properly.
Sample data:
Companies collection:
[
  { _id: "1", name: "Acme" }
]

Licenses collection
[
  { _id: "1", companyId: "1", userId: "1" },
  { _id: "2", companyId: "1", userId: "2" }
]

Users collection:
[
  { _id: "1", companyId: "1" },
  { _id: "2", companyId: "1" },
  { _id: "3", companyId: "1" },
  { _id: "4", companyId: "1" },
]

The expected result is:
[
  _id: "1", // company id
  name: "Acme",
  unlicensedUsers: [
    { _id: "3", companyId: "1" },
    { _id: "4", companyId: "1" },
  ]
]

Explanation: unlicensedUsers list contains the third and the fourth users because they don't have corresponding entries in the licenses collection.

A: How about something simple like:
db.usersCollection.aggregate([
  {
    $lookup: {
      from: "licensesCollection",
      localField: "_id",
      foreignField: "userId",
      as: "licensedUsers"
    }
  },
  {$match: {"licensedUsers.0": {$exists: false}}},
  {
    $group: {
      _id: "$companyId",
      unlicensedUsers: {$push: {_id: "$_id", companyId: "$companyId"}}
    }
  },
  {
    $lookup: {
      from: "companiesCollection",
      localField: "_id",
      foreignField: "_id",
      as: "company"
    }
  },
  {$project: {unlicensedUsers: 1, company: {$arrayElemAt: ["$company", 0]}}},
  {$project: {unlicensedUsers: 1, name: "$company.name"}}
])

playground example
users collection and licenses collection, both have anything you need on the users so after the first $lookup that "merges" them, and a simple $match to keep only the unlicensed users, all that left is just formatting to the format you request.
Bonus: This solution can work with any type of id. For example playground

A: If you're facing a similar situation. Bear in mind that the above solution will work fast only with the hashed index.


text:
Q: What is the most portable way to open the default Java truststore? I am programmatically manipulating the default Java TrustStore. In order to do that, I need its path.
I tried reading javax.net.ssl.keyStore and javax.net.ssl.trustStore and they're both undefined.
I came up with System.getenv("JAVA_HOME") + "/jre/lib/security/cacerts", is it the right approach?
It works but I'd like the code to be as portable and future-proof as possible.
Edits:

*

*This is for an app running in AWS Lambda, Lamda does not allow to customize or provide your own JRE.

*This question was originally asking for the default keystore. I changed it to truststore since keystores are app-specific.

A: No.  You probably won't have permission to modify files in an installed JRE.  And that path does not exist, starting with Java 9.
Furthermore, as of Java 11, there is no JRE.  The only way to distribute an application is to use jlink to create an image containing a subset of Java SE containing only the modules required by the application.
In summary, you can't rely on a Java installation, and even if you find one, you can't rely on the presence of a default keystore file.
You shouldn't be changing a user's Java installation anyway.  Your code should include a custom keystore file as an application resource, which you should pass to Keystore.load:
InputStream embeddedKeystore =
    MyApplication.class.getResourceAsStream("custom-keystore.pkcs");

assert embeddedKeystore != null : "Application was not properly built."
    + " Keystore is missing!";

KeyStore keystore = KeyStore.getInstance("pkcs12");
keystore.load(embeddedKeystore,
    new char[] { 's', 'w', 'o', 'r', 'd', 'f', 'i', 's', 'h' });

embeddedKeystore.close();

A: Posting my solution so far.
In my question, I was reading from System.getenv("JAVA_HOME") + "/jre/lib/security/cacerts" but that is the path of the JDK (which isn't installed on AWS Lambda) and is the root of the /jre folder.
String trustStoreLocation = Optional.ofNullable(System.getProperty("javax.net.ssl.trustStore"))
    .orElseGet(() -> System.getProperty("java.home") + "/lib/security/cacerts");

File trustStoreFile = new File(trustStoreLocation);
if (!trustStoreFile.exists()) {
    throw new RuntimeException("Unable to locate the Java TrustStore: the system property javax.net.ssl.trustStore is undefined or " + trustStoreLocation + " does not exist.");
}

KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
try (FileInputStream fis = new FileInputStream(trustStoreFile)) {
    keyStore.load(fis, new char[] { 't','h','e',' ','p','a','s','s','w','o','r','d' });
}

A: You can use your own path for the trustsotre and the keystore using passing system property option to the JVM
-Djavax.net.ssl.keyStore=your_custom_path
-Djavax.net.ssl.trustStore=your_custom_path


text:
Q: vlc does not display via vlc-wrapper but cvlc works after 22.10 upgrade After upgrading from 22.04 to 22.10, vlc-wrapper no longer displays dvd video content (sound works).  However, and oddly enough, running cvlc works.
I am under x11 rather than wayland because of another software requirement. I am using the 470 driver set of NVidia (unchanged from 22.04) using a Geforce 1030.
The upgrade from 22.04 to 22.10 was uneventful, everything else works (including basic opengl checks).  I poked around online but no suggestion, apart from one that suggested cvlc may work.
The error message suggests I am lacking
$ vlc-wrapper Videos/some_mp4_file_recorded_on_my_phone.mp4
VLC media player 3.0.17.4 Vetinari (revision 3.0.13-8-g41878ff4f2)
[000055c362a95550] main libvlc: Running vlc with the default interface. Use 'cvlc' to use vlc without interface.
[00007fe8bc0049c0] gl gl: Initialized libplacebo v4.192.1 (API v192)
libva info: VA-API version 1.15.0
libva info: Trying to open /usr/lib/x86_64-linux-gnu/dri/nvidia_drv_video.so
libva info: va_openDriver() returns -1
[00007fe8bc0049c0] glconv_vaapi_x11 gl error: vaInitialize: unknown libva error
libva info: VA-API version 1.15.0
libva info: Trying to open /usr/lib/x86_64-linux-gnu/dri/iHD_drv_video.so
libva info: Found init function __vaDriverInit_1_14
libva info: va_openDriver() returns 0
[00007fe8b8098690] main video output error: video output creation failed
[00007fe8ccc7a220] main decoder error: failed to create video output
[00007fe8bc0049c0] gl gl: Initialized libplacebo v4.192.1 (API v192)
[00007fe8ccc7a220] avcodec decoder: Using NVIDIA VDPAU Driver Shared Library  470.161.03  Wed Oct 19 00:03:46 UTC 2022 for hardware decoding

With cvlc  I get
$ cvlc Videos/some_mp4_file_recorded_on_my_phone.mp4
VLC media player 3.0.17.4 Vetinari (revision 3.0.13-8-g41878ff4f2)
[0000561a244132c0] dummy interface: using the dummy interface module...
[00007f4170004b10] gl gl: Initialized libplacebo v4.192.1 (API v192)
libva info: VA-API version 1.15.0
libva info: Trying to open /usr/lib/x86_64-linux-gnu/dri/nvidia_drv_video.so
libva info: va_openDriver() returns -1
[00007f4170004b10] glconv_vaapi_x11 gl error: vaInitialize: unknown libva error
libva info: VA-API version 1.15.0
libva info: Trying to open /usr/lib/x86_64-linux-gnu/dri/iHD_drv_video.so
libva info: Found init function __vaDriverInit_1_14
libva info: va_openDriver() returns 0
[00007f4180001b40] main video output error: video output creation failed
[00007f4188c79d80] main decoder error: failed to create video output
[00007f4174001720] gl gl: Initialized libplacebo v4.192.1 (API v192)
[00007f4188c79d80] avcodec decoder: Using NVIDIA VDPAU Driver Shared Library  470.161.03  Wed Oct 19 00:03:46 UTC 2022 for hardware decoding

I am reasonably familiar with package.ubuntu.com to search, but at a loss about /usr/lib/x86_64-linux-gnu/dri/nvidia_drv_video.so -- which package would provide this?


text:
Q: Easy to state high-dimensional consequences of Bezout theorem A classical consequence of Bezout's theorem for plane curves is Pascal's theorem.
I am curious if there are some other statements that you find pretty that can be formulated (almost) as elementarily as Pascal's theorem and proven using higher dimensional Bezout's theorem? For example, is there some statement that involves quadrics, planes and lines (cubics?...)?
I ask this question since I want to finish to teach my (introductory) course in algebraic geometry by higher-dimensional Bezout theorem (using Hilbert polynomials, ect), and I would be extremely happy to give some pretty application :)
(to give you an idea of the level of the course, the course is very close to some bits of Harris book "algebraic geometry first course", and covers some bits of it)

A: The Fundamental Theorem of Algebra is generalized by Bezout. (Doesn't appear to be mentioned in the Wikipedia entry).
"The roots of $f(x)$ correspond to the points at which the zero set of the polynomial $y-  f(x)$ and the zero set of the polynomial $y$ intersect." -- Stephanie Fitchett "Bezout's theorem: a taste of algebraic geometry"
She goes on to write: "Based on our experience with the fundamental theorem of algebra, we would like to replace the inequality with an equality, and in fact, this is exactly what Bezout's Theorem claims..."
The curves $f(x)$ and $y=0$ are replaced by arbitrary curves in projective space.


text:
Q: SwiftSpinner in initial load is not working Upon calling SwiftSpinner, on viewDidLoad , Swift spinner is not working
Please find below the code i am using,
override func viewDidLoad() {
        super.viewDidLoad()
            DispatchQueue.global(qos: .background).async {
                self.basicSync {(isSynced) in
                     DispatchQueue.main.async {
                         SwiftSpinner.hide()
                     }
                }
            }
            DispatchQueue.main.async {
                SwiftSpinner.show("Syncing")
            }
}

public func basicSync(completion: @escaping (Bool) -> ()) {
        //Sync related work
        completion("true")
}

I am not able to find a way to call Swift spinner on initial load
Some of the methods i tried with SwiftSpinner.Show from above code

*

*To call,
SwiftSpinner.show("Syncing")

*To call it main inside main thread
 DispatchQueue.main.async {
          DispatchQueue.main.async {
                SwiftSpinner.show("Syncing")
            }
          }

*I was able to achieve it when it is written like this,

DispatchQueue.main.async {
                DispatchQueue.main.async {
                    DispatchQueue.main.async {
                        SwiftSpinner.show("Syncing")
                    }
                }
            }

But I dont think it is the correct coding standard, new to Swift and coding technology

A: Try adding it in

viewdidappear

A: I have this issue before, you need to do the following
func delay(seconds: Double, completion: @escaping () -> ()) {
    let popTime = DispatchTime.now() + Double(Int64( Double(NSEC_PER_SEC) * seconds )) / Double(NSEC_PER_SEC)
    DispatchQueue.main.asyncAfter(deadline: popTime) {
        completion()
    }
}

then in view did load
override func viewDidLoad() {
    super.viewDidLoad()
    delay(seconds: 0.5) {
       SwiftSpinner.show("Syncing")
    }
}

That's it :D


text:
Q: Power grid distribution and recipient bias First of all, sorry for the vague nature of this question. I have a strong feeling that this problem I'm trying to solve has already been done by someone much smarter than me at one point and I'm more looking at where I can research a topic further rather than asking for an outright solution.
Essentially, I'm looking for a method on how to evenly distribute resources between providers and recipients, not entirely unlike a power grid in real life.
A example provider/recipient graph
In this example, all the recipients require 100 units of a resource and each provider has 350 units to be handed out. The ideal outcome would be for all recipients except D to receive 100 units from providers 1 and 2, with D receiving an equal 50 units from both provider 1 and 2.
Hopefully I've managed to communicate my problem reasonably well, again I'm mainly hoping for someone to point me in the right direction so I can research the topic further. Thanks for reading.


text:
Q: UnicodeEncodeError [Python3/Gunicorn/Nginx/Django] Solved
This error happened when I follow the instruction in here.
I set Unit file. I understood that LAN env valuable doens't transfer properly and it used default ascii. You can fix this problem with adding one line in unit file. It was a really long journey to find out....
[service]
Environment="LANG=en_US.UTF-8"

I didn't have any problem when I set my environment with mod_wsgi and Apache2. I just had to add "export LANG='en_US.UTF-8' export LC_ALL='en_US.UTF-8'" in /etc/apache2/envars path to upload file with non-ASCII filename.
This time, I set my env with Nginx and Gunicorn. But It occurs UnicodeEncoderError in every part where shows non-ASCII characters.
'ascii' codec can't encode characters in position 57-59: ordinal not in range(128)

I don't understand why 'ascii' codec is used to encode in Python3 and Django environment.
I searched and searched and searched. I checked and tried like below.

*

*PostgreSQL check : Encoding UTF8

*Django default encoding : utf-8

*Ubuntu locale check : en_US.UTF-8 (I also tried 'ko_KR.UTF-8', because it has an error with Korean)

*checked python 3 sys.getdefaultencoding, sys.stdout.encoding, sys.stdin.encoding : utf-8

*adding charset utf-8; in /etc/nginx/sites-available/myproject

*checked if Gunicorn call python2 instead of python3 : installing gunicorn with pip3 virtualenv and checked '#!/home/username/venv/bin/python3' in gunicorn file.

*write import sys reload(sys) sys.setdefaultencoding('utf-8') in views.py : I understood it can apply to python2 and it is not recommended way.

I was suspicous that Gunicorn call python2 instead of python3 because python2 is also installed in my Ubuntu. If I check python -c 'import sys; print(sys.getdefaultencoding());', I can see 'ascii'. Python 2 has str and unicode. I concluded that Gunicorn doesn't have problem with it at the end.
I am still suspicious of python 2.7 which was preinstalled in Ubuntu16.04. Can you explain that What i am missing or misunderstanding?? I understood that ascii codec encode error could happen with Python2, not Python3.
Env
Python 3.5
Django 1.11.1
Gunicorn 19.7.1
Nginx 1.10.3
Ubuntu 16.04 LTS

A: For people who are having the encoding problem with gunicorn but not using it as a daemon (for example if you run gunicorn in docker you just launch the command), and therefore, not using this configuration files:
I'm using the openpyxl library to generate a spreadsheet, and I got this error when testing it in the server in which I have the service dockerized with gunicorn. After confirming that every other encoding requirement was fine (python, system locales, etc.) it was clear that the problem was gunicorn.
Everything else in the app works fine, it's only the spreadsheet exportation that throws this.
I was about to try replacing gunicorn with something else but then I realized that the problem is with file names and not with the process of generating the contents of the file.
I was naming the generated file "exportació", and just replacing it with "exportacio" made it work like a charm.
Given that I really don't need non-ascii characters in the file name, that works enough for me.


text:
Q: Algorithm to get maximum number of n rectangles with given same width and height that fit into a rectangle with a given width and height I am looking for an algorithm that can return the maximum number of rectangles in the same size with given width and height that fit in to a rectangle with given height and width.
For an example let's say I have a small rectangle with height of 50mm and width of 70mm and a bigger rectangle with height of 1200mm and width of 1000mm. I want to arrange the small rectangles inside the bigger rectangle in a fully utilize way. The small rectangles can be arrange in anyway (Small rectangle can rotated as well), I just want the number of small rectangles that I can put in the bigger rectangle in a maximum utilize way.
Thank you for your help!

A: In your example, you can form a rectangle of 1,000 x 1,050 leaving 1,000 x 150, then a rectangle of size 150 x 980, leaving 150 x 20, which is less than a small rectangle, and therefore cannot be improved.
In general, this will be hard and involve systematically trying out various combinations.

A: If you want to take only positive integer sides into consideration, you can take a value that yields the highest possible quotient with a non-zero remainder. The best thing to do here (I am not that sure, but let it be so :D)is to take the remainder as $1$ , subtract it from the longer side of the larger rectangle and find the remaining number's smallest proper divisor. If the side minus one yields a length that has a prime number as its magnitude, subtract another $1$ from the value you have at hand and do the above steps.
But please take care not to end up in a place where the next dividend you take can be divided by the remainder at hand - that's where you can put a decision point whether to abort that iteration or not.
Another thing is that the smaller side must either be divisible or leave a small remainder when divided by the remainder.
I am not sure if this helps, but I felt this would work. Please do notify me if I did the wrong thing.


text:
Q: BeautifulSoup - Amazon and Google identify me as a robot; how can i fix it? when i do scraping on amazon and google shopping with BeautifulSoup after a while (after about 100/200 products analyzed) it identifies me as a robot, how do i prevent this from happening?
By changing the ip I am able to restart, but after a while they block me again.
Here is my code:
from bs4 import BeautifulSoup
import requests

cookies_goo = {
    "NID": "511=ktkACo_ZFBfZiD_DvYTKQFmYYX7R3Esh1ZtJ6A3F87KG_YzkbqlHc0NmQsGPyc78KIOXyCtVuYE9QmX-ixl-HzpbE9N9K67sGQCTZ2CFZ1oZAhe-iSFKtCcsUCsY8CHmbDu9YtxaEs7prgZqRID19DI6bqN2lxQZjog8HY6ur_M",
    "1P_JAR": "2021-11-05-13",
    "CONSENT": "YES+cb.20211102-08-p0.it+FX+548"
}

header = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36",
    "Accept-Language": "it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7"
}

response = requests.get(url, headers=header, cookies=cookies_goo)
soup = BeautifulSoup(response.content, "lxml")

A: You are a robot, so their algorithm is entirely correct. Try using their API instead.

A: *

*Rotating proxies

*Delays

*Avoid the same pattern

*IP rate limit (probably your issue)

IP rate limit. It's a basic security system that can ban or block incoming requests from the same IP. It means that a regular user would not make 100 requests to the same domain in a few seconds with the exact same pattern (scroll, click, scroll, click, open. As an example).
How to reduce the chance of being blocked while web scraping search engines.

Alternatively, you can use Google Shopping Results API from SerpApi. It's a paid API with a free plan.
The difference in your case is that you don't have to spend time figuring out how to bypass blocks from Google since it's already done for the end-user.
Example code to integrate to parse data from Google Shopping and example in the online IDE:
import os
from serpapi import GoogleSearch

params = {
    "api_key": os.getenv("API_KEY"),
    "engine": "google_product",
    "product_id": "14506091995175728218", # can be iterated over multiple product ids
    "gl": "us",                           # country to search from
    "hl": "en"                            # language
}

search = GoogleSearch(params)
results = search.get_dict()

title = results['product_results']['title']
prices = results['product_results']['prices']
reviews = results['product_results']['reviews']
rating = results['product_results']['rating']
extensions = results['product_results']['extensions']
description = results['product_results']['description']
user_reviews = results['product_results']['reviews']
reviews_results = results['reviews_results']['ratings']

print(f'{title}\n'
    f'{prices}\n'
    f'{reviews}\n'
    f'{rating}\n'
    f'{extensions}\n'
    f'{description}\n'
    f'{user_reviews}\n'
    f'{reviews_results}')

'''
Google Pixel 4 White 64 GB, Unlocked
['$247.79', '$245.00', '$439.00']
526
3.7
['October 2019', 'Google', 'Pixel Family', 'Pixel 4', 'Android', '5.7″', 'Facial Recognition', '8 MP front camera', 'Smartphone', 'With Wireless Charging']
Point and shoot for the perfect photo. Capture brilliant color and control the exposure balance of different parts of your photos. Get the shot without the flash. Night Sight is now faster and easier to use it can even take photos of the Milky Way. Get more done with your voice. The new Google Assistant is the easiest way to send texts, share photos, and more. A new way to control your phone. Quick Gestures let you skip songs and silence calls – just by waving your hand above the screen. End the robocalls. With Call Screen, the Google Assistant helps you proactively filter our spam before your phone ever rings.
526
[{'stars': 1, 'amount': 101}, {'stars': 2, 'amount': 43}, {'stars': 3, 'amount': 39}, {'stars': 4, 'amount': 73}, {'stars': 5, 'amount': 270}]
'''

Example to iterate over multiple item ID's:
# import os
# from serpapi import GoogleSearch

# random numbers except the first one
products = ['14506091995175728218', '1450609199517512118', '145129895175728218']

for product in products:
    params = {
        "api_key": os.getenv("API_KEY"),
        "engine": "google_product",
        "product_id": product,
        "gl": "us",
        "hl": "en"
    }

    search = GoogleSearch(params)
    results = search.get_dict()

    title = results['product_results']['title']

    print(title, sep='\n')  # prints 3 titles from 3 different products

Disclaimer, I work for SerpApi.


text:
Q: s6: service not logging anything I'm trying to get s6-log to work on a service file I've written. The service file looks something like this:
#!/usr/local/bin/execlineb -P

/usr/local/bin/s6-setuidgid [username]

/usr/bin/[actual_service]

and I also created [servicedir]/log/run, which is just
#!/usr/local/bin/execlineb -P

/usr/local/bin/s6-log T /var/log/[servicename]

After starting it, s6-logger is running, /var/log/[servicename]/current is nicely created, and yet, it's empty. I even checked whether the service is writing things out with strace -p [supervisor pid] -f to catch even startup messages... and it works, writing things to file descriptor 2, which is stderr.
Why isn't this written to the log file?

A: Note the ... to file descriptor 2, which is stderr part.
s6-supervise will only pick up logs written to stdout. It will ignore stderr, unless it's explicitly redirected to stdout explicitly, for example by adding
fdmove -c 2 1
to the service run script.


text:
Q: Android, запрос и проверка необходимых разрешений При запуске приложения мне нужно проверять что у него есть все необходимые для работы разрешения.
Это я делаю в onStart Activity следующим образом
try {
        val info = packageManager.getPackageInfo(this.packageName, PackageManager.GET_PERMISSIONS)
        Log.d(TAG, "SDK " + Build.VERSION.SDK_INT + " App Permissions:")
        if (info.requestedPermissions != null) {
            for (p in info.requestedPermissions) {
                val grantResult = this.checkPermission(p, android.os.Process.myPid(), android.os.Process.myUid())
                if (grantResult == PackageManager.PERMISSION_GRANTED) {
                    Log.d(TAG, "$p PERMISSION_GRANTED")
                } else {
                    Log.d(TAG, "$p PERMISSION_DENIED: $grantResult")
                    val permissions = arrayOf(p)

                    ActivityCompat.requestPermissions(this, permissions,0)
                }
            }
        }

В LogCat я вижу что практически все разрешения есть, за исключением
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,

По логике у меня должно в случае если нет разрешения, то должно появиться окно с запросом его. Однако окно не появляется.
В чем может быть проблема?

A: Код из вопроса действительно работает некорректно. Насколько я понимаю, не стоит запрашивать более одного разрешения одновременно. Во всяком случае, не таким образом.
На коленке написал код, на моем эмуляторе сработал:
companion object {
    private const val MY_PERMISSIONS_REQUEST_CODE = 1
}

private var listOfNonGrantedPermissions: MutableList<String> = mutableListOf()

override fun onStart() {
    super.onStart()
    val info = packageManager.getPackageInfo(this.packageName, PackageManager.GET_PERMISSIONS)
    Log.d(TAG, "SDK " + Build.VERSION.SDK_INT + " App Permissions:")
    info.requestedPermissions?.forEach {
        if (checkPermission(it, android.os.Process.myPid(), android.os.Process.myUid()) == PackageManager.PERMISSION_GRANTED) {
            Log.d(TAG,"$it PERMISSION_GRANTED")
        } else {
            Log.d(TAG,"$it PERMISSION_DENIED")
            listOfNonGrantedPermissions.add(it)
        }
    }
    makeRequestForNotGrantedPermissions()
}

private fun makeRequestForNotGrantedPermissions(){
    if (listOfNonGrantedPermissions.isNotEmpty()){
        val nextPermission = arrayOf(listOfNonGrantedPermissions.first())
        listOfNonGrantedPermissions.removeAt(0)
        ActivityCompat.requestPermissions(
            this,
            nextPermission,
            MY_PERMISSIONS_REQUEST_CODE
        )
    }
}

override fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<out String>,
    grantResults: IntArray
) {
    when (requestCode) {
        MY_PERMISSIONS_REQUEST_CODE -> {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG,"Granted")
            } else {
                Log.d(TAG,"NOT Granted")
            }
            return makeRequestForNotGrantedPermissions()
        }
    }
}

Суть кода:

*

*Создаем список всех разрешений, которые не выданы.

*Вызываем функцию запроса разрешения.

*Функция запрашивает одно разрешение, если есть еще не полученные.

*Получив ответ от пользователя, снова вызываем функцию запроса разрешения.

*Если для всех разрешения ответ пользователя получен - процесс прекращается.

Код приведен для примера и с целью натолкнуть на действительное решение, использовать его в конечном варианте приложения не советую!


text:
Q: How to build WSO2 WSF/PHP 2.1.0 for FreeBSD 8.1? I have a problem with building WSO2 WSF/PHP on my FreeBSD 8.1. It seems that something broken in the source.
I check all prerequisites then run ./configure && make and receive next error:

Making all in platforms/unix
/usr/local/bin/bash ../../../libtool --tag=CC    --mode=compile gcc -DHAVE_CONFIG_H -I. -I../../.. -I../../../include  -I../../../include/platforms  -I../../../include/platforms/unix     -g -O2 -D_LARGEFILE64_SOURCE -ansi -Wall -Wno-implicit-function-declaration -D_GNU_SOURCE -MT uuid_gen_unix.lo -MD -MP -MF .deps/uuid_gen_unix.Tpo -c -o uuid_gen_unix.lo uuid_gen_unix.c
mkdir .libs
 gcc -DHAVE_CONFIG_H -I. -I../../.. -I../../../include -I../../../include/platforms -I../../../include/platforms/unix -g -O2 -D_LARGEFILE64_SOURCE -ansi -Wall -Wno-implicit-function-declaration -D_GNU_SOURCE -MT uuid_gen_unix.lo -MD -MP -MF .deps/uuid_gen_unix.Tpo -c uuid_gen_unix.c  -fPIC -DPIC -o .libs/uuid_gen_unix.o
uuid_gen_unix.c: In function 'axutil_uuid_get_mac_addr':
uuid_gen_unix.c:332: error: 'SIOCGARP' undeclared (first use in this function)

After googling I found an advice to configure with ./configure 'CPPFLAGS=-DHAVE_GETIFADDRS'. After that make command almost finished but die at the end with following information:
gcc -g -O2 -D_LARGEFILE64_SOURCE -ansi -Wall -Wno-implicit-function-declaration -o .libs/test test.o  ../../axiom/src/om/.libs/libaxis2_axiom.so ../../util/src/.libs/libaxutil.so ../src/.libs/libneethi.so /usr/home/alisachenko/src/wso2-wsf-php-src-2.1.0/wsf_c/axis2c/axiom/src/om/.libs/libaxis2_axiom.so /usr/home/alisachenko/src/wso2-wsf-php-src-2.1.0/wsf_c/axis2c/axiom/src/parser/guththila/.libs/libaxis2_parser.so /usr/home/alisachenko/src/wso2-wsf-php-src-2.1.0/wsf_c/axis2c/guththila/src/.libs/libguththila.so /usr/home/alisachenko/src/wso2-wsf-php-src-2.1.0/wsf_c/axis2c/util/src/.libs/libaxutil.so -lpthread -lz  -Wl,--rpath -Wl,/usr/local/wsf_c/lib
../../util/src/.libs/libaxutil.so: undefined reference to `ftime'

What should I do to completely build WSO2 on my FreeBSD?
UPD1
Building after ./configure 'CPPFLAGS=-DHAVE_GETIFADDRS' 'LDFLAGS=-lcompat'

gcc -shared   -Wl,--whole-archive ../src/platforms/unix/.libs/libaxis2_unix.a -Wl,--no-whole-archive  -lcompat -lpthread -lz  -Wl,-soname -Wl,libaxutil.so.4 -o .libs/libaxutil.so.4
/usr/bin/ld: /usr/lib/libcompat.a(ftime.o): relocation R_X86_64_32 can not be used when making a shared object; recompile with -fPIC
/usr/lib/libcompat.a: could not read symbols: Bad value

UPD2
Building after ./configure CPPFLAGS='-fPIC -DHAVE_GETIFADDRS' 'LDFLAGS=-lcompat'

gcc -shared  .libs/hash.o .libs/allocator.o .libs/env.o .libs/error.o .libs/stream.o .libs/log.o .libs/string.o .libs/string_util.o .libs/qname.o .libs/array_list.o .libs/linked_list.o .libs/utils.o .libs/dir_handler.o .libs/file_handler.o .libs/class_loader.o .libs/network_handler.o .libs/file.o .libs/uuid_gen.o .libs/thread_pool.o .libs/property.o .libs/types.o .libs/param.o .libs/param_container.o .libs/dll_desc.o .libs/url.o .libs/stack.o .libs/generic_obj.o .libs/base64.o .libs/uri.o .libs/date_time.o .libs/base64_binary.o .libs/properties.o .libs/http_chunked_stream.o .libs/rand.o .libs/date_time_util.o .libs/version.o .libs/duration.o .libs/frame.o .libs/stomp.o .libs/md5.o .libs/digest_calc.o -Wl,--whole-archive ../src/platforms/unix/.libs/libaxis2_unix.a -Wl,--no-whole-archive  -lcompat -lpthread -lz  -Wl,-soname -Wl,libaxutil.so.4 -o .libs/libaxutil.so.4
/usr/bin/ld: /usr/lib/libcompat.a(ftime.o): relocation R_X86_64_32 can not be used when making a shared object; recompile with -fPIC
/usr/lib/libcompat.a: could not read symbols: Bad value
*** Error code 1

Stop in /usr/src/wso2-wsf-php-src-2.1.0/wsf_c/axis2c/util/src.

A: ./configure 'CPPFLAGS=-DHAVE_GETIFADDRS LDFLAGS==-lcompat'

A:
I am also trying to run WSO2 on various FreeBSD AMD64 without success.
I am compiling WSO2 in jail built on top of ezjail.
Since recompilation of libcompat is required I did it in "main" system. All the rest is done in the jail.

*

*In main system (without jail) I recompiled libcompat (/usr/src/lib/libcompat) with -fPIC in makefile, so now the line looks like that:
CFLAGS+=-fPIC -DLIBC_SCCS -DSYSLIBC_SCCS -I${.CURDIR}/../libc/locale
[root@system /usr/src/lib/libcompat]# make install
install -C -o root -g wheel -m 444   libcompat.a /usr/lib
install -C -o root -g wheel -m 444   libcompat_p.a /usr/lib

*Then
I copied  libcompat.a and libcompat_p.a into basejail and switched to jail where I made a compilation
I found this: http://bsd.dischaos.com/2008/05/14/wso-web-services-framework-on-freebsd/
which inspired me.
I modified wsf_c/axis2c/util/src/platforms/unix/uuid_gen_unix.c and added
    #include < sys/param.h>
(I put      ^^^^ space here because I it was wrongly parsed by stackoverflow portal)
3 . Then I modified configure.m4 and I put the following path
        PHP_ADD_INCLUDE(/usr/local/include/libxml2/libxml) replacing the original one
4 . Then still having problems with compilation I added these environment variables
    export CPATH=/usr/local/include:/usr/local/include/libxml2:/usr/local/ssl/include/openssl::/usr/local/ssl/include
    export LD_LIBRARY_PATH=/usr/local/lib
5 . And finally I managed to compile without errors
./configure "CPPFLAGS=-fPIC -DHAVE_GETIFADDRS" "LDFLAGS=-lcompat"
 make
 make install
My test jail on remote server doesnt have the web interface available yet and thus I couldn't test this installation on samples provided, but I am pretty sure that I would succeed since there were no errors during make nor during make install.
Php -m shows wsf module without any segfaults.
Samples are also working fine. I can't get wsdls yet, but it is rather matter of time.
The important problem you may face is openssl. It must be in ver 0.9.8 at least if I recall correctly. I am using 1.x. though
Although this setup is working fine on Freebsd 8.x I was unable to have it working on FreeBSD 6.x. On 6.x I finally built WSO2 successfully, but got segfaults when included wsf.so in php configuration ... then I gave up on 6.x and focused on freebsd 8.x where it seems to work fine ... just starting to do some programming with this module.


text:
Q: Mysql query is producing duplicate data I have a database set up with one table containing customers, and a second containing calls. When a customer calls in it is logged and saved as a text file to the calls database with the date time and the customer ID that called in.
Customer ID is a foreign key that links to ID in the calls table, one customer can have many calls.
I use the following to get the data from the database
        $result = mysql_query(" SELECT * FROM customer LEFT JOIN calllog ON calllog.customID = customer.ID INNER JOIN address ON customer.ID = address.customer_ID   WHERE CallStatus= 'Open' ")or die(mysql_error());

A for loop then echoes out all of the results like so:
 for ($i = $start; $i < $end; $i++)
    {

            if ($i == $total_results) { break; }

            echo "
";
            echo '' . mysql_result($result, $i, 'First_Name') . '	';
            echo '' . mysql_result($result, $i, 'Surname') . '	';
            echo '' . mysql_result($result, $i, 'Company_Name') . '	';
            echo '
' .  nl2br(mysql_result($result, $i,'line_1')) . '
	';
            echo '' . mysql_result($result, $i, 'town') . '	';
            echo '' . mysql_result($result, $i, 'customer.ID') . '	';

            echo '' . mysql_result($result, $i, 'Telephone') . '	';

            echo '	';
    echo '<button class= "Call" id="Calllog' . mysql_result($result, $i, 'id') . '"></></ />	';

            echo "
";

            echo "
";
             echo '
' .  nl2br(mysql_result($result, $i, 'CallNotes')) . '
	'; //Display notes
            echo '' . mysql_result($result, $i, 'CallTime') . '	';
            echo "
";

    }
    echo "
";

multiple call notes are attached to a single customer however I am getting duplicate customers when they have multiple calls. It will echo out:
Tom
Call log1

Jim
Call log1

Tom
call log 2

I was expecting it to go
Tom
Call Log1
Call log2

Jim
Call log 1.

A: Add group by clause to your SQL statement
SELECT *
FROM customer
LEFT JOIN calllog ON calllog.customID = customer.ID
INNER JOIN address ON customer.ID = address.customer_ID
WHERE CallStatus= 'Open'
GROUP BY customer.ID

A: I think your INNER JOIN is the culprit change that to an LEFT JOIN.


text:
Q: How can temperature be defined as it is if entropy isn't a function of energy? I've been taught that for large systems, the temperature of a system is defined as $$\frac{1}{T} \equiv \left(\frac{\partial S}{\partial U}\right)_{N, V}.$$ I have a problem with this definition, namely, that the entropy of a system isn't a function of the energy of the system because the entropy of the system is $$S = k\ln\Omega,$$ where $\Omega$ is the multiplicity of the system's current macrostate, and for a given amount of energy, the system may have several macrostates. How (precisely) is this problem resolved?
P.S. I don't remember what my past self is talking about in this question: Definition of temperature ambiguity. He has knowledge or a notion that I don't have.

A: You are correct in saying that the multiplicity is not a function of just the energy, it depends on other things as well. This is why the definition of temperature includes the additional requirement that the partial derivative involves holding the system at a constant volume and number of particles.
So it is not true in general that $\Omega=\Omega(U)$ (i.e. just a function of energy), but it is true that $\Omega=\Omega(U,V,N)$ for the definition you give.
I suppose there could be other relevant variables as well, but they would just appear as extra terms in your thermodynamic identity which would then be set to $0$ by holding things constant in order to use the above definition.

A: Your question goes directly to the problem of identifying all the variables which uniquely identify a macrostate. With the exception of the usual textbook examples, it could be a non trivial problem.
It is a fingerprint of thermodynamics that the energy of the system is one of the relevant variables. In addition to energy, the other variables may vary  from a system to another.
For fluid systems confined in a volume $V$ and  made by $N$  particles, these two additional parameters may identify a macrostate. However, both, the choice of the two additional variables (in addition to energy) and the fact that two are enough should be looked as an experimentally verifiable fact.
Indeed, for a solid system, $V$ is not enough, as the shape matters to identify the macrostate, in addition to the volume. Thus, the strain tensor would be required. If each molecule carries an electric dipole, a macroscopic polarization vector would be required to select a macrostate.
However, since energy remains one of the variables identifying the macrostate, the condition of equilibrium with respect to the exchange of energy between two arbitrary systems in thermal contact remains the equality of the partial derivatives of the entropy of each system with respect to energy by keeping fixed all remaining variables (whatever they are).

A: So as we saw earlier the principle of maximum entropy is simply a principle that if we are looking at a sufficiently isolated system then our uncertainties multiply until we are effectively choosing one possibility uniformly at random from some "phase space" of possibilities. The meaning of "uniformly at random" is slightly suspect, as it requires us to specify what coördinates we use to describe phase space, but in general we take every Cartesian position-and-momentum coördinate pair and parcel it up into chunks of some size $h$, where once we start doing quantum mechanics we get rigorous about $h$ being Planck's constant due to the uncertainty principle, but in classical mechanics it is just some normalization constant.
The "phase space of possibilities" then is constrained by any conservation laws that we have, e.g. conservation of energy, and by other constraints like a fixed volume, or a fixed number of particles. Finally, other observables can identify one macroscopic state as distinct from some other macroscopic state: for example if we are watching two gases of different colors (say red and blue) mixing together into one homogeneous color, we might have some sort of observable "mixing length" (the length of the purple segment between them) which identifies a class of macroscopic states distinct from each other. One often needs to be careful to include some form of experimental uncertainty to get an authentic count of microstates in a macrostate, but one can also take limits as this uncertainty goes to zero. The principle of maximum entropy then dictates a "spontaneous" transition of our observables to a configuration which has the largest phase-space volume.
The sort of reasoning we are pursuing
Suppose that like our two-gases-of-different-colors mixing example, we have a bigger system that is comprised of two subsystems with variable energies. We then have an internal degree of freedom, $E_1$, with the total energy $E$ conserved and $E_2 = E - E_1.$ This is some observable degree of freedom. Now if these subsystems are otherwise isolated, then we can come up with their subsystem entropies $S_{1,2}$ if we were to disable their ability to share energy with each other, and we would find due to the multiplicative nature of multiplicity and the logarithm that the overall entropy is $$S(E, E_1) = S_1(E_1) + S_2(E - E_1).$$Now if we were to change $E_1$ we would find a change in the entropy, $$S(E, E_1 + \epsilon) = S_1(E_1) + S_1'(E_1)\epsilon + S_2(E - E_1) - S_2'(E - E_1) \epsilon.$$The total change from an increase of $E_1$ is thus given by multiplying that change by $S_1' - S_2',$ and this change will be positive and therefore entropically favored if $S_1' > S_2'.$ So $S_{1,2}'$ measure a sort of coldness, where energy spontaneously flows into a subsystem with larger $S'$ from a subsystem with smaller $S'$. Moreover thermal equilibrium will then happen when they both have the same $S'$ at which point entropy will not favor one or the other at all.
A subtlety
If you were to now combine two of those systems into a homogeneous whole, would $\left(\frac{\partial S}{\partial E}\right)_{E_1}$ be a correct definition of temperature?
It is probably eventually correct, since it is $S_2'$, but it is probably not instantaneously correct. In fact a system which is not in thermal equilibrium cannot be assigned just one authoritative temperature value. So for example let us couple the four subsystems linearly with temperatures (in some arbitrary units):
+--------+   +--------+   +--------+   +--------+
|   10   |---|   70   |===|   40   |---|   60   |
+--------+   +--------+   +--------+   +--------+

Here we see four boxes thermally connected in a line, the first subsystem is two boxes with temperatures 10 and 70, the second subsystem is two boxes with temperatures 40 and 60.
The left subsystem has in some sense temperature "40" since that is what it would come to if allowed to come to equilibrium, (10 + 70)/2. The right subsystem has in some sense temperature "50" as that would be (40 + 60)/2. So if we were to define temperature coherently in this fashion, surely energy would flow from hotter to colder, from right to left, correct?
Well, that is eventually correct but it is not immediately correct. Since the 70 is in thermal contact with the 40, heat will first flow from the left to the right. Only after some time will the heat flow back from the right to the left.
So you are correct to suspect some shenanigans. Temperature does not have an additive property where we can easily define the temperature of a whole if its parts have different temperatures.
This can be very easily seen by the equipartition theorem, which states that the world can be decomposed into various "degrees of freedom" and then measures the temperature of any degree of freedom as the average energy in that degree of freedom. If you have a bunch of degrees of freedom, you can only define the temperature if they all have the same average.
So let's suppose you want to analyze a harmonic oscillator that dissipates into a many other degrees of freedom: probably what you want to do is to model this as a system with two non-equilibrium degrees of freedom $x, p$, and those two do not have a well-defined temperature, in some sort of contact with a multitude of degrees of freedom which we collectively combine into one thermal "bath" at some well-specified temperature. And this combined system can then show you a dissipation from the energy sloshing back and forth from $x$ into $p$ and back into the bath, plus it can show you that $x$ and $p$ come to a nonzero equilibrium energy state where they have the same energy as the bath.


text:
Q: How to Handle Unknown Data Type in one Table I have a situation where I need to store a general piece of data (could be an int, float, or string) in my database, but I don't know ahead of time which it will be. I need a table (or less preferably tables) to store this unknown typed data.
What I think I am going to do is have a column for each data type, only use one for each record and leave the others NULL. This requires some logic above the database, but this is not too much of a problem because I will be representing these records in models anyway.
Basically, is there a best practice way to do something like this? I have not come up with anything that is less of a hack than this, but it seems like this is a somewhat common problem. Thanks in advance.
EDIT: Also, is this considered 3NF?

A: If your application can reliably convert datatypes, you might consider a single column solution based on a variable-length binary column, with a second column to track original data type.  (I did a very small routine based on this once before, and it worked well enough.)  Testing would show if conversion is more efficiently handled on the application or database side.

A: You could easily do that if you used SQLite as a database backend :

Any column in a version 3 database, except an INTEGER PRIMARY KEY column, may be used to store any type of value.

For other RDBMS systems, I would go with Philip's solution.
Note that in my line of software (business applications), I cannot think of any situation where this kind of requirement would be needed (a value with an unknown datatype). Unless the domain model was flawed, of course... I can imagine that other lines of software may incur different practices, but I suggest that you consider rethinking your overall design.

A: If I were to do this I would choose either your method, or I would cast everything to string and use only one column. Of course there would be another column with the type (which would probably be useful for the first method too).
For faster code I would probably go with your method.


text:
Q: Getting error while connecting to MySQL in Golang My code looks like this
connStr := fmt.Sprintf("%s:%s@%s(%s:%d)/%s", USERNAME, PASSWORD, NETWORK, SERVER, PORT, DATABASE)

conn, err := sql.Open("mymysql", connStr)
checkErr(err)
dbl.Conn = conn

When I run it, thrown error code:
2020/09/06 15:16:01 [Recovery] 2020/09/06 - 15:16:01 panic recovered:
POST /signin HTTP/1.1
Host: localhost:8080
Accept: */*
Accept-Encoding: gzip, deflate, br
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 0
Password: ccc
Postman-Token: ff5f3d30-925e-40bc-9016-305b488e9476
User-Agent: PostmanRuntime/7.26.2
Username: ggg

Wrong database part of URI
/Users/liuda/IdeaProjects/go_workspace/dehm/main/dbLinker.go:57 (0x1656393)
        checkErr: panic(err)
/Users/liuda/IdeaProjects/go_workspace/dehm/main/dbLinker.go:43 (0x165635f)
        DbLinker.Signin: checkErr(err)
/Users/liuda/IdeaProjects/go_workspace/dehm/main/signin.go:26 (0x16569a6)
        Signin: linker.Signin(sd)
/Users/liuda/IdeaProjects/go_test/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x154ab1a)
        (*Context).Next: c.handlers[c.index](c)
/Users/liuda/IdeaProjects/go_test/pkg/mod/github.com/gin-gonic/gin@v1.6.3/recovery.go:83 (0x155eb04)
        RecoveryWithWriter.func1: c.Next()
/Users/liuda/IdeaProjects/go_test/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x154ab1a)
        (*Context).Next: c.handlers[c.index](c)
/Users/liuda/IdeaProjects/go_test/pkg/mod/github.com/gin-gonic/gin@v1.6.3/logger.go:241 (0x155dc04)
        LoggerWithConfig.func1: c.Next()
/Users/liuda/IdeaProjects/go_test/pkg/mod/github.com/gin-gonic/gin@v1.6.3/context.go:161 (0x154ab1a)
        (*Context).Next: c.handlers[c.index](c)
/Users/liuda/IdeaProjects/go_test/pkg/mod/github.com/gin-gonic/gin@v1.6.3/gin.go:409 (0x1554e59)
        (*Engine).handleHTTPRequest: c.Next()
/Users/liuda/IdeaProjects/go_test/pkg/mod/github.com/gin-gonic/gin@v1.6.3/gin.go:367 (0x155454c)
        (*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/usr/local/go/src/net/http/server.go:2843 (0x1328562)
        serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/usr/local/go/src/net/http/server.go:1925 (0x1323c6c)
        (*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
/usr/local/go/src/runtime/asm_amd64.s:1374 (0x106bd80)
        goexit: BYTE    $0x90   // NOP

Can anyone help me, how to fix this issue?

A: If I had to guess, your PORT variable is a string not a int and silently producing an invalid DSN e.g.
fmt.Printf("%s:%s@%s(%s:%d)/%s", `user`, `secr3t`, `tcp`, `mydbsrv`, `3306`, `mydb`)
// `user:secr3t@tcp(mydbsrv:%!d(string=3306))/mydb` - invalid DSN

Log the DSN prior to sql.Open to verify - and if that is indeed the issue: I'd encourage you to use mysql's Config.FormatDSN instead, to ensure safely encoded DSN addresses:
c := mysql.Config{
    User:                    "user",
    Passwd:                  "secr3t",
    Net:                     "tcp",
    Addr:                    "mydbsrv:3306",
    DBName:                  "mydb",
    Params:                  map[string]string{"charset": "utf8"}, // optional
    ParseTime:               true,                                 // optional
}
fmt.Println(c.FormatDSN())

https://play.golang.org/p/kOvruaWiwsp


text:
Q: Chaining a Get request from a Post request then sending to client, using Express and Google oauth I am servicing a Post request, where I retrieve user token id in this request, I further verify the token using OAuth2Client library. When verified, I want  to issue a Get request to get user info. I am not sure of the way I am chaining requests.
Code is like:
var userid;
app.post( '/oauth/google/redirect', (req, res) => {
  const token = req.body.idtoken;
  verify().catch(console.error);
  req.get(`https://oauth2.googleapis.com/tokeninfo?id_token=${token}`, (req, res) => {
    var body = "";

      res.on('data', function(chunk) {
        body += chunk;
      });

      res.on('end', function() {
        res.send(body)
      });
  })

  });
const {OAuth2Client} = require('google-auth-library');

const client = new OAuth2Client(google.clientID);
async function verify() {
  const ticket = await client.verifyIdToken({
      idToken: token,
      audience: google.clientID,  // Specify the CLIENT_ID of the app that accesses the backend
      // Or, if multiple clients access the backend:
      //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
  });
  const payload = ticket.getPayload();
  userid = payload['sub'];
  // If request specified a G Suite domain:
  //const domain = payload['hd'];
}

On client side, browser says it failed on post request as it took too much time returning:

POST http://mywebapp.com/oauth/google/redirect 504 (Gateway Time-out)

Signed in as:
504 Gateway Time-out

The server didn't respond in time.

A: For now, I used request as a library, something like:
app.post( '/oauth/google/redirect', (req, res) => {
  const token = req.body.idtoken;
  verify().catch(console.error);
  request(`https://oauth2.googleapis.com/tokeninfo?id_token=${token}`, function (error, response, body) {
        var data={
          body:body
        };
        res.send(data);
      });
  });

Still accepting a native Express solution as a better answer.


text:
Q: How do I use tf serving with transforming methods? I have a problem. I have a free text, for example: "Today the weather is good" and this free text I would like to predict which class it is. For this I would like to use tf serving. I don't put free text directly into the model, but I first clean the sentence and then connect it to a vector.
However, how can I incorporate these steps within the tf serving process. My x_ready that goes into model.predict(x_ready) looks like this:
[[
  0 0 0 0
  0 0 0 0
  1 5 987 54
]]

How can I call my methods and then pass tf serving my x?
In addition, I would like to get the probability. How can I get the class and probability with tf serving?
That is how I predict a single class
def predict_single(x):
    # lower the text
    x = x.lower()
    x = remove_URL(x)
    x = remove_punct(x)
    x = remove_stopwords(x)

    x = tokenizer.texts_to_sequences([x])
    # pad
    x_ready = pad_sequences(x, maxlen=maxlen)
    print(x)
    pred = model.predict(x_ready)
    print("Probability", pred.max(axis=1))
    pred = pred.argmax(axis=1)
    pred = le.classes_[pred]

    return pred[0]

    # Clean the text
    return x

[OUT]
Probability [0.7528353]
Class 3

How I installed tf-serving
docker pull tensorflow/serving

docker run -it -v C:\Code\tensorflow\demo:/demo-p 8601:8601 --entrypoint /bin/bash tensorflow/serving

tensorflow_model_server --rest_api_port=8601 --model_name=model --model_base_path=/demo/models/

How I saved the model
model.fit(...)
model.save("models/1")
model.save("models/2")

A: TF Serving is mainly used to deploy a trained model to production environment with high performance. TF Serving doesn't support with data cleaning and data preprocessing. So if you want to preprocess your inputs and then do inference, you can take a look at the Tensorflow Transform component in TFX . You can refer the documentation of TF Transorm here.
For getting the probability values, Can you take a look at Serving saved model with Tensorflow Serving section of this blog, which explains on the same.
Let us know if you have any questions. Thank you!


text:
Q: Angular UI-Router - Returning rejected promise in resolve is not stopping state transition I am trying to assure that a user is authenticated before allowing them to transition to specific states. As I understand it (after review other posts), a state transition should not occur if the state's resolve returns a rejected promise and the '$stateChangeError' event should be raised. However this is not what I am experiencing.
Stepping throught the following code, I can see that the deferred promise is rejected but the state transition still occurs and '$stateChangeError' is not triggered. In my module's config I have the following state:
 .state('accounts', {
            url: '/Accounts',
            controller: 'AccountsController',
            templateUrl: 'Scripts/angular/accounts/templates/accounts.tpl.html',
            resolve: {
                authenticated: ['$q', 'AccountService', function ($q, accountService) {
                    var deferred = $q.defer();
                    accountService.userLoggedIn().then(function (loggedIn) {
                        if (loggedIn) {
                            deferred.resolve();
                        } else {
                            deferred.reject('Not logged in'); <-- This happens
                        }
                        return deferred.promise;
                    });
                }]
            }
        })

In the same module, in the run function I have:
 $rootScope.$on('$stateChangeError',
    function (event, toState, toParams, fromState, fromParams, error) {
        $log.debug(error); <-- This is never called
        $state.go('login');
    });

What am I missing?

A: You dont need to create new deferred since you already get promise from userLoggedIn():
resolve: {
    authenticated: ['$q', 'AccountService', function ($q, accountService) {

        return accountService.userLoggedIn().then(function (loggedIn) {
              if (loggedIn) {
                   return loggedIn;
              } else {
                   return $q.reject('Not logged in');
              }
        });

     }]
}

A: You're returning the promise in the wrong place. Authenticated needs to be a function that returns a promise but you're just returning the promise in the the .then() function and then authenticated is returning undefined:
        resolve: {
            authenticated: ['$q', 'AccountService', function ($q, accountService) {
                var deferred = $q.defer();
                accountService.userLoggedIn().then(function (loggedIn) {
                    if (loggedIn) {
                        deferred.resolve();
                    } else {
                        deferred.reject('Not logged in'); <-- This happens
                    }
                });

                return deferred.promise;

            }]
        }


text:
Q: String encryption in RubyMotion I'm trying to encrypt strings in RubyMotion - ideally AES but weaker/older cyphers such as Blowfish should do just fine.
So far I have failed at compiling a couple of pods: RNCrypto and CommonCrypto.
Suggestions? Anyone else tried these pods?
Thank you,
Adrian

A: If you're having trouble compiling CocoaPods, make sure you run a rake clean. CocoaPods should work fine with RubyMotion as far as I know.
EDIT: Since the OP hasn't posted his solution as the answer, I'll post it here:

RNCryptor doesn't build for iOS6, and there's a pull for ARC compatibility but not yet integrated in the pod.
As for CommonCrypto, it has an example.m file showcasing its capabilities. This example.m includes a main function which clashes with the one created by RubyMotion. By deleting it, I've managed to make it compile successfully.

A: Here's the necessary process if you currently want to use CommonCrypto pod:

*

*make sure to include the pod in your Rakefile or perform the equivalent Bundler ritual

*don't forget to include app.frameworks << 'Security' in the Rakefile as well

*then go to vendor/Pods/CommonCrypto and delete the file example.m

Congratulations, you're all set!
Here's a quick (and dirty) sample:
iv = 'init_vector_here'
key = 'key_here'
plainText = 'This is plain text'

plainData = plainText.dataUsingEncoding(NSUTF8StringEncoding)
ivData = iv.dataUsingEncoding(NSUTF8StringEncoding)
keyData = key.dataUsingEncoding(NSUTF8StringEncoding)

status = NIL
result = plainData.dataEncryptedUsingAlgorithm(0, key: keyData, initializationVector: ivData, options: 0, error: status) # 0 = AES128
p result.base64EncodedString

For Base64 encoding you have to include the 'NSData+Base64' pod.
Thank you @AwDogsGo2Heaven and @Jamon Holmgren for your helpful suggestions!


text:
Q: php reading and plotting large datasets I have 5 second data for a year in an ascii file
each line is a reading...
timestamp, value
for 6 million lines
I want to display this data in a chart or multiple charts in a web browser
I considered a choice of 3 charts
1 - last 500 data points at maximum (5 second resolution)
2 - last 500 points at 15 min resolution
3 - all data at various resolutions
etc
being wary of a) time to read file b) processing time c) amount and time to download data to browser for javascript plotting
Can php do direct access read from a file?
More to the point, these big dataset plotting problems must be quite common, bhoiw do people get around it?

A: Yes, PHP can read files on the filesystem. Databases may be very helpful along with reading data from file with PHP.
What would you like to do with the data - as in, what are you really looking for? Are you looking for peaks, averages, values greater than average etc.?
Generic analysis
Perhaps the answer is - I don't know; I want to look at the data and see what comes glaring out. Fair enough. In that case you could have a web page that uses something like a stock chart. Show the last 1000 records.
To get the last 1000 records, you could use a combination of commands such as top or head (on Linux-y systems) or powershell on Windows to get last 1000 rows and then parse them with PHP, shove them into an array or object and show them on screen using Javascript or PHP charting tools.
When the user changes selection, do a read of the file and display relevant records. This can be taxing because the file is constantly processed.
Non-PHP method
A faster non-PHP alternate would be to use something like an in-memory business intelligence tool like QlikView (free download for personal use, I think). The learning curve is not steep, ... and I have no affiliation with QlikView. Tableau and Spotfire are other tools that can be easy to use and can make analysis of large datasets relatively easy.
Specific analysis
If your interest is to find out number of days each month with sales of $1 million or above, you could do a single pass on the file and extract all lines with sales >= 1MM and store it in an array of date and sales. Pass through the array and output a file with Year, Month, Sales. That would be pre-processing of the data.
Then, the web application or your presentation layer can pull this data and show information in bar charts or whatever else. Javascript charting libraries like amcharts, d3, highcharts etc. can be used, or PHP charting libraries like jpGraph and such can be used to read pre-processed data on the fly and show them.
If data has to be looked from multiple angles such as - table showing top 10 products that are sold, scatter plot of # of orders vs. $ ordered etc., all this data could be shoved into a database and then pulled on the screen. As Mark Baker commented, appropriate indexes will be necessary to pull data efficiently.
Prepare specific datasets in batch
Some climate research centers in the US run programs that churn through millions of records, like you have, at night to create graphs, charts, maps etc. and then use web applications to display them. For example High Plains Regional Climate Center and Iowa Mesonet do that regularly. You could do something similar with PHP.
Databases are my favorite. I prefer massaging textual data, eliminate what I don't want and push the objective matter in databases. PHP can then utilize rollup, top n, group by etc. methods within dbs to extract data and present it on screen - primarily through a web interface.
If you have specific questions about toolset or so relevant to this question, feel free to comment. If a new question crops up in your mind, feel free to add a new question altogether to solicit diverse answers.


text:
Q: How to store a Hashmap(Integer keys, hashmap values) in a txt file in java? I want to store the meteosemana hashmap(meteoSemana has integer keys and a hashmap has values) in a txt file... but  the compiler just jumps to the end of the method and nothing is stored.
public void storeEmpresa(String f)
{
    try {
        FileOutputStream fos = new FileOutputStream(f);
        ObjectOutputStream oos = new ObjectOutputStream(fos);

        oos.writeObject(this.meteoSemana);

        oos.writeObject(this.mapaUAV);
        oos.writeObject(this.mapaArmazem);
        oos.writeObject(Servicos.cod);
        oos.close();
        fos.close();
        System.out.println("Ficheiro guardado com sucesso \n");
    }
    catch(FileNotFoundException e)
    {System.out.println("Falha na gravação do ficheiro! Tem permissões de administrador?");System.exit(0);}
    catch(IOException e)
    { System.out.println("Falha na gravação de ficheiro!"); System.exit(0);}
}

public void loadEmpresa(String f) {
    try {
        FileInputStream fis = new FileInputStream(f);
        ObjectInputStream ois = new ObjectInputStream(fis);

        this.meteoSemana = (HashMap<Integer,HashMap<Integer,meteoPeriodo>>)ois.readObject();

        this.mapaUAV = (HashMap<Integer,UAV>)ois.readObject();
        this.mapaArmazem = (HashMap<Integer,Armazem>)ois.readObject();
        Servicos.cod = (Integer)ois.readObject();
        ois.close();
        fis.close();
    }
    catch (IOException e)
    {}
    catch (ClassNotFoundException e)
    {}
}


text:
Q: ArrayIndexOutOfBoundsException while converting linkedList to array list Im trying to convert a linkedList into an ArrayList as shown below.
private LinkedList<myData> myLinkedList= new LinkedList<myData>();
public Collection<myData> getData()
 {
  return new ArrayList<myData>(myLinkedList);
 }

The linkedList might be updated by multiple threads. While testing in production I get the below error. The error is not consistant. So i get it may be once in a week, month or so.
java.lang.ArrayIndexOutOfBoundsException: 15
at java.util.LinkedList.toArray(LinkedList.java:866)
at java.util.ArrayList.<init>(ArrayList.java:131)
at org.xxx.yyy.zzz.getData(Data.java:291)

Is there any way it could be related to concurrent modification of the linkedList. Appreciate any help on this.

A: toArray failing is only one symptom of you doing something fundamentally dangerous.
From the documentation of LinkedList:

If multiple threads access a linked list concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.

You'll either need to add synchronization (not just for toArray, but basically all uses of the list) or use one of the concurrent collections which is designed to be thread-safe.

A: LinkedList#toArray() is implemented as such (Oracle JDK 7)
public Object[] toArray() {
    Object[] result = new Object[size];
    int i = 0;
    for (Node<E> x = first; x != null; x = x.next)
        result[i++] = x.item;
    return result;
}

If you add to the LinkedList after the result array is constructed but before the for loop, then the array access expression inside the for loop will cause an ArrayIndexOutOfBoundsException when trying to access an index larger than the original size.
You should really put some synchronization barriers so that doesn't happen.