Q: Is there any way to get a warning in eg. GCC or Clang about this strict aliasing violation? The rationale for this being a strict aliasing violation is that
the buffer has declared type char array and is being aliased by
a pointer to struct
#include<string.h>
#include<stdalign.h>
#include<stdio.h>

struct thing {
  int a;
  char x;
};

int main() {
  char alignas(struct thing) buffer[128];

  struct thing s = {10,'a'};

  struct thing *ptr = memcpy(buffer,&s,sizeof(struct thing));

  // violation at ptr->a
  printf("%d\n",ptr->a);

  return 0;
}

A: A compiler that warned about all constructs that violate the constraints in N1570 6.5p7 as written would generate a lot of warnings about constructs which all quality implementations would support without difficulty.  The only way those parts of the Standard would make any sense would be if the authors expected quality implementations to extend the semantics of the language to support use cases which, even if they're not mandated by the Standard, they should have no reason not to support.  The use case illustrated in the presented code is an example of this.
Although the Standard would not forbid implementations from using N1570 6.5p7 as an excuse to behave nonsensically even in situations where an object is only ever used as a single type of storage, the stated purpose of the rules is to describe situations where implementations would or would not be required to allow for the possibility of pointer aliasing.  Forbidding the particular construct at issue even in cases where storage is only used as a single type would do nothing to further that aim.  If code were to use the subscripting operator on buffer, in addition to accessing the storage via a struct thing*, a compiler might legitimately fail to recognize the possibility that accesses using the latter lvalue might interact with those using the former.  In the presented code, however, the storage is only used as type struct thing or via memcpy, usage cases that there would have been no reason to prohibit.  Writing the rules in such a way as to only forbid use of a char[] to hold data of some other type in situations where it was also subscripted would definitely add complexity, but would not have been expected to make compilers support any constructs they wouldn't have supported anyway.
If the Standard had been intended to characterize programs into those that were correct or incorrect, it would need to have been worthwhile to write more detailed rules.  Since it made no attempt to distinguish constructs which are erroneous from those which are correct but "non-portable" (in the sense that there might exist some implementations which don't process them meaningfully), however, there was no need to try to explicitly identify and provide for all of the constructs which compilers would have no reason not to process meaningfully.


Q: Overriding an external style sheet without access to  I have a Ecommerce Host that does not allow access to the Header Tag or the External .CSS file.
I have to override using inline styles.
Problem is, I have to override Pseudo Class :active
Is there way to link an external style sheet from within an inline style so that I can style the pseudo classes?
Any simple alternatives? Without  access?

A: You don't need to put your <link rel="stylesheet" href="blah-blah.css"> tag into head to make it work, but it's a bad practice, because it works slower and looks a bit bad, but I understand your situation :) Just put <link> at the end of the  and it'll work fine! For example:
File styles.css
p {
    color: blue;
}

File index.html
<!DOCTYPE html>

I am blue, da ba dee da ba dai!

  <link rel="stylesheet" href="styles.css"/>


Q: C#: RunWorkerAsync() doesn't trigger DoWork() I am writing a small forms based application to connect to an LDAP server, and I wanted the "connect" button to work in the background.  So I was following the information and discussion
here
but for whatever reason my code doesn't appear to be working right:  I set a breakpoint at 'worker.RunWorkerAsync();'  And it just steps right through it.
What am I doing wrong?  I am working in Visual Studio 2010, in case it matters.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices;
using System.Threading;

namespace ldapconnect
{

public partial class Form1 : Form
{
    private void Form1_Load(object sender, EventArgs e)
    {

    }

    public Form1()
    {
        InitializeComponent();
    }

    //server
    public string lds;
    //naming context
    public string root;

    public string username;
    public string password;

    BackgroundWorker worker = new BackgroundWorker();

    private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        worker = sender as BackgroundWorker;
        foreach (string s in connect(worker, e, lds + "/" + root, txt_user.Text.ToString(), txt_pass.Text.ToString()))
        {
            rtb_results.Text += s + "\r\n";
        }
    }

    private List<string> connect(BackgroundWorker worker, DoWorkEventArgs e, String serv, string usr, string pass)
    {
        //Directory search code taking server path and creds passed in from form
        DirectoryEntry conn = new DirectoryEntry(serv, usr, pass);
        DirectorySearcher ds = new DirectorySearcher(conn);

        //I only want users
        ds.Filter = "objectClass=user";

        List<string> sendBack = new List<string>();

        try
        {
            SearchResultCollection results = ds.FindAll();

            foreach (SearchResult result in results)
            {
                sendBack.Add(result.ToString());
            }
        }
        catch (Exception ex)
        {
            sendBack.Clear();
            sendBack.Add(ex.ToString());
        }

        return sendBack;
    }

    //connect button start background worker
    private void btn_connect_Click(object sender, EventArgs e)
    {
        worker.RunWorkerAsync();
    }

    //Exit Button
    private void btn_close_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    //set server path
    private void btn_server_Click(object sender, EventArgs e)
    {
        string serv = inputBox("ldap://", "IP or DNS Name of LDS Server", "");
        lds = serv;
        lbl_server.Text = lds;
    }

    //set default context
    private void btn_context_Click(object sender, EventArgs e)
    {
        string cntx = inputBox("In CN=,DC=,DC= Form:", "Default Naming Context", "");
        root = cntx;
        lbl_cntx.Text = root;
    }

    //VB interaction box
    private string inputBox(string a,string b,string c)
    {
        return Microsoft.VisualBasic.Interaction.InputBox(a, b, c);
    }

    private void btn_Defaults_Click(object sender, EventArgs e)
    {
        lds = "LDAP://127.0.0.1";
        root = "DC=USERS,DC=TEST,DC=LOCAL";
        txt_user.Text = "reader";
        txt_pass.Text = "password";
        lbl_server.Text = lds;
        lbl_cntx.Text = root;
    }
}
}

A: You have not set
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
before calling worker.RunAsync()

A: You are never wiring up the event.
   public Form1()
    {
        InitializeComponent();
        worker.DoWork += new DoWorkEventHandler(worker_DoWork);
    }

A: RunWorkerAsync() starts the worker thread and immediately returns thus the debugger seems to  "step through it". Set a breakpoint in the worker_DoWork() method.

A: If u still have event and is not working, try the following
Just call

System.Windows.Forms.Application.DoEvents();

before calling RunWorkerAsync()


Q: Qt QInputDialog parameter list I am starting a Qt course this semester. Having looked at the official documentation as well as some on line examples I am confused by the parameter lists of the QInputDialog and QMessagebox classes.
Is there anywhere where one could find some decent info as to what to pass when creating the class / form?
Right now I have this by trial error
tempC = QInputDialog::getDouble(0, "Temperature Converter",
                                "Enter the temperature in Celsius to convert to Fahrenheit:", 1);

Looking at the official docs doesn't help a lot either (at least not for me yet) as it says this:
double d = QInputDialog::getDouble(this, tr("QInputDialog::getDouble()"),
                                   tr("Amount:"), 37.56, -10000, 10000, 2, &ok);

as an example.
Any links will be much appreciated.

A: double d = QInputDialog::getDouble(this, tr("QInputDialog::getDouble()"),
                                   tr("Amount:"), 37.56, -10000, 10000, 2, &ok);

*

*A dialog will popup with parent the widget in which you are using this function. (this)

*The dialog's title will be  QInputDialog::getDouble() (tr is used in order to translate this string if you want using QtLinguist)

*Inside the dialog will be a double spibox and a label

*The label's string will be Amount:

*The default value of the spinbox (what you see when the dialog popups) will be 37.56

*The minimum value will be -10000 (you will not be able to set a value less than this)

*The maximum value will be 10000 (you will not be able to set a value greater than this)

*Two decimal point will be displayed, eg 3.478 will be displayed as 3.48.

*If the user presses the Ok button then the ok argument will be set to true, otherwise it will be set to false
Check the documentation which includes an example for more details.


Q: Object of type Period is not JSON serializable in plotly I am trying to plot a line chart. Below is my code
CODE :
import plotly.offline as pyo
import plotly.graph_objects as go
flag = determineFlag('2020-03-01','2020-03-30')

df_r = getDataForTrend(df,'2020-03-01','2020-03-30','d')

colors = {
    'background': '#111111',
    'text': '#7FDBFF'
}

data = [go.Scatter(x = df_r[df_r['S2PName-Category']==category]['S2BillDate'],
                    y = df_r[df_r['S2PName-Category']==category]['totSale'],
                    mode = 'lines',
                    name = category) for category in df_r['S2PName-Category'].unique()]

layout = {'title':'Category Trend',
         'xaxis':{'title':'Time Frame'},
         'yaxis':{'title':'Total Sales Amount','tickformat' : '.2f'}}

fig = go.Figure(data=data,layout=layout)

pyo.iplot(fig)

when I run the above code I get the below error:
ERROR:
TypeError: Object of type Period is not JSON serializable

While tying to debug, I try to execute the below code
DEBUG CODE :
df_r[df_r['S2PName-Category']==category]['S2BillDate']

OP :
3     2020-03-01
11    2020-03-02
21    2020-03-03
26    2020-03-04
41    2020-03-06
42    2020-03-05
46    2020-03-07
Name: S2BillDate, dtype: period[D]

How can I fix the type error ? Is there any tweaks to this ? Any help is much appreciated! Thanks !

A: AFAIK this is still an issue and plotly will fail in such situation. There is still an open issue at github: Support for Pandas Time spans as index col.
As proposed in the comments one of the solution is to use to_timestatmp conversion, see this.

*

*Create MWE (this is just for reproducibility since there is no data provided in the question)

import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.offline as pyo

df = pd.DataFrame({"one": np.random.random(10)}, index=pd.period_range("2020-03-01", freq="M", periods=10))
# Out:
#               one
# 2020-03  0.302359
# 2020-04  0.919923
# 2020-05  0.673808
# 2020-06  0.718974
# 2020-07  0.754675
# 2020-08  0.731673
# 2020-09  0.772382
# 2020-10  0.654555
# 2020-11  0.549314
# 2020-12  0.101696

data = [
    go.Scatter(
        x=df.index,
        y=df["one"],
    )
]
fig = go.Figure(data=data)
pyo.iplot(fig)
# -> will fail ("TypeError: Object of type Period is not JSON serializable")

*Use to_timestamp conversion (-> df.index.to_timestamp())

data = [
    go.Scatter(
        x=df.index.to_timestamp(), # period to datetime conversion
        y=df["one"],
    )
]
fig = go.Figure(data=data)
pyo.iplot(fig)

Or, if you do not need datetime format you can convert this to string as well:
data = [
    go.Scatter(
        x=df.index.strftime("%Y-%m"),  # You can define your own format
        y=df["one"],
    )
]
fig = go.Figure(data=data)
pyo.iplot(fig)

You can of course do this conversion right on the original dataframe (so you do not need to do it iteratively inside go.Scatter), but this is just minor stuff. There might be also a way of using custom encoder instead of the default one, but I think it's not worthy of trying and afaik there is no better solution than using one of possible conversion from Period to datetime or string.


Q: Start Activity while Countdown is running I have a problem with my Android app at the moment. I use the Google Client Message Service to send messages to my Android App. If the user opens the app, he starts on the HomeActivity.
When the user now receives my message from the server and press on the push message, the app starts a new intent with the AlertActivity.
At this point, I pass the time (saved in the message) with putExtra to the new activity, where i use it for a CownDownTimer. Till this point everything is ok and the countdown works perfect.
The problem is now, when the user minimizes the app and open it again.
At this Point the user is not redirected to my AlertActivity again but to my HomeActivity.
After the CountDownTimer Ends the AlertSound is played, but he can't cancel it, because he can't show the activity again.
How can I redirect the User to the AlertActivity if he starts the app while the CountDown is running?
My AlertActivity
package com.prgguru.example;

public class AlertActivity extends Activity {

    String str;
    Boolean running;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alert);

        final TextView txttime = (TextView) findViewById(R.id.txtalert);
        str = getIntent().getStringExtra("msg");
        Integer time = Integer.parseInt(str);

        time = time; //*60000;

        txttime.setText(time+"");

        CountDownTimer Count = new CountDownTimer(time, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                running = true;
                txttime.setText(String.format("%02d:%02d:%02d",
                        TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
                        TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) -
                                TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
                                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
                //txttime.setText(""+millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                txttime.setText("Finished");

                final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.alarm);
                mp.start();
            }
        };

        Count.start();
    }

    public boolean getRunning(){
        return false;
    }
}

GCMIntentService
public class GCMIntentService extends IntentService {
    // Sets an ID for the notification, so it can be updated
    public static final int notifyID = 9001;
    NotificationCompat.Builder builder;

    public GCMIntentService() {
        super("GcmIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) {
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
                    .equals(messageType)) {
                sendNotification("Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
                    .equals(messageType)) {
                sendNotification("Deleted messages on server: "
                        + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
                    .equals(messageType)) {
                sendNotification(extras.get(ApplicationConstants.MSG_KEY)+"");
            }
        }
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

    private void sendNotification(String msg) {
            Intent resultIntent = new Intent(this, AlertActivity.class);
            resultIntent.putExtra("msg", msg);
            PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
                    resultIntent, PendingIntent.FLAG_ONE_SHOT);

            NotificationCompat.Builder mNotifyBuilder;
            NotificationManager mNotificationManager;

            mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

            mNotifyBuilder = new NotificationCompat.Builder(this)
                    .setContentTitle("Alert")
                    .setContentText("You've received new message.")
                    .setSmallIcon(R.drawable.ic_launcher);
            // Set pending intent
            mNotifyBuilder.setContentIntent(resultPendingIntent);

            // Set Vibrate, Sound and Light
            int defaults = 0;
            //defaults = defaults | Notification.DEFAULT_LIGHTS;
            //defaults = defaults | Notification.DEFAULT_VIBRATE;
            // defaults = defaults | Notification.DEFAULT_SOUND;

            Notification notification = mNotifyBuilder.build();

            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.alarm);
            notification.defaults |= Notification.DEFAULT_VIBRATE;

            mNotifyBuilder.setDefaults(defaults);
            // Set the content for Notification
            mNotifyBuilder.setContentText("New message from Server");
            // Set autocancel
            mNotifyBuilder.setAutoCancel(true);
            // Post a notification
            mNotificationManager.notify(notifyID, notification);
    }
}


Q: Handle multiple login page for different type of user in asp.net core mvc 6 In asp.net core i need to manage two different types of user (administrator and normal user).
When user session is expired i want administrater to be redirected to baseurl/admistrator/login  and for normal user redirect to baseurl/login
   services.AddIdentity<User, Role>(op =>
                {
                    op.SecurityStampValidationInterval = TimeSpan.FromSeconds(0);
                    op.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromMinutes(30);
                    op.Cookies.ApplicationCookie.SlidingExpiration = true;

//here how can i set multiple login path
                    //op.Cookies.ApplicationCookie.LoginPath = new Microsoft.AspNetCore.Http.PathString("/administrator/account/login");
                    //op.Cookies.ApplicationCookie.LoginPath = new Microsoft.AspNetCore.Http.PathString("/login");

Does anyone have idea how to do it ?
Thanks


Q: Google Drive API with Python from server(Backend) without browser autentication I'd like to save the files of my Saas Appication to my Google Drive Account, all the examples I've seen was with oauth2 autentication and needs the end user autenticate openning the browser, I need to upload files from my server without any user interation, sending files direct to my account!
I have try many tutorials I found on internet with no success, mainly the oficial
Google Drive API with Python
How can I autenticate programatically from my server and upload files and use API features such as share folders and others?
I'm using Python, the lib PyDrive uses the same aproach to autenticate

A: To add to andyhasit's answer, using a service account is the correct and easiest way to do this.
The problem with using the JSON key file is it becomes hard to deploy code anywhere else, because you don't want the file in version control. An easier solution is to use an environment variable like so:
https://benjames.io/2020/09/13/authorise-your-python-google-drive-api-the-easy-way/

A: You can do this, but need to use a Service Account, which is (or rather can be used as) an account for an application, and doesn't require a browser to open.
The documentation is here: https://developers.google.com/api-client-library/python/auth/service-accounts
And an example (without PyDrive, which is just a wrapper around all this, but makes service account a bit trickier):
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http

scopes = ['https://www.googleapis.com/auth/drive.readonly']

credentials = ServiceAccountCredentials.from_json_keyfile_name('YourDownloadedFile-5ahjaosi2df2d.json', scopes)

http_auth = credentials.authorize(Http())
drive = build('drive', 'v3', http=http_auth)

request = drive.files().list().execute()
files = request.get('items', [])
for f in files:
    print(f)

A: I know it's quite late for answer but this worked for me:
Use the same API you were using, this time in your computer, it will generate a Storage.json which  using it along with your scripts will solve the issue (specially in read-ony platforms like heroku)

A: Checkout the Using OAuth 2.0 for Web Server Applications. It seems that's what you're looking for.

Any application that uses OAuth 2.0 to access Google APIs must have
  authorization credentials that identify the application to Google's
  OAuth 2.0 server. The following steps explain how to create
  credentials for your project. Your applications can then use the
  credentials to access APIs that you have enabled for that project.
Open the Credentials page in the API Console. Click Create credentials
   OAuth client ID. Complete the form. Set the application type to Web application. Applications that use languages and frameworks like PHP,
  Java, Python, Ruby, and .NET must specify authorized redirect URIs.
  The redirect URIs are the endpoints to which the OAuth 2.0 server can
  send responses. For testing, you can specify URIs that refer to the
  local machine, such as http://localhost:8080.
We recommend that you design your app's auth endpoints so that your
  application does not expose authorization codes to other resources on
  the page.

A: Might be a bit late but I've been working with gdrive over python, js and .net and here's one proposed solution (REST API) once you get the authorization code on authorization code
How to refresh token in .net google api v3?
Please let me know if you have any questions


Q: How can I delete the selected messages (with checkboxes) in jQuery? I'm making a messaging system and it has a lot of AJAX. I'm trying to add a bulk actions feature with check boxes. I've added the checkboxes, but my problem is that I don't know how to make something happen to the selected messages.
Here's my function that happens whenever a checkbox is clicked:
function checkIt(id) {
    if ($('#checkbox_' + id).is(':checked')) {
        $('#' + id).addClass("selected");
    }
    else {
        $('#' + id).removeClass("selected");
    }
}

But, I don't know where to go from there.

Here is some example markup for one of the lines [generated by PHP] of the list of messages:

<input type="checkbox" name="checkbox_33" onclick="checkIt(33)" id="checkbox_33" class="inbox_check" />

Nathan
Test
[Time sent]

As you can see, each line has the id attribute set to the actual message ID.
In my function above you can see how I check it. But, now what I need to do is when the "Delete" button is clicked, send an AJAX request to delete all of the selected messages.
Here is what I currently have for the delete button:
$('#delete').click(function() {
if($('.inbox_check').is(':checked')) {

}
else {
alertBox('No messages selected.'); //this is a custom function
}
});

I will also be making bulk Mark as Read, Mark as Unread, Remove Star, and Add Star buttons so once I know how to make this bulk Delete work, I can use that same method to do these other things.
And for the PHP part, how would I delete all them that get sent in the AJAX request with a mysql_query? I know it would have to have something to do with an array, but I just don't know the code to do this.
Thanks in advance!

A: How about this
$('#delete').click(function() {
    var checked = $('.inbox_check:checked');
    var ids = checked.map(function() {
        return this.value;  // why not store the message id in the value?
    }).get().join(",");
    if (ids) {
        $.post(deleteUrl, {idsToDelete:ids}, function() {
            checked.closest(".line").remove();
        });
    }
    else {
        alertBox('No messages selected.'); // this is a custom function
    }
});

Edit: Just as a side comment, you don't need to be generating those incremental ids.  You can eliminate a lot of that string parsing and leverage jQuery instead.  First, store the message id in the value of the checkbox.  Then, in any click handler for a given line:
var line = $(this).closest(".line");  // the current line
var isSelected = line.has(":checked");  // true if the checkbox is checked
var msgId = line.find(":checkbox").val();  // the message id
var starImg = line.find(".star_clicker img");  // the star image

A: Assuming each checkbox has a parent div or td:
function removeDatabaseEntry(reference_id)
{
    var result = null;
    var scriptUrl = './databaseDelete.php';
    $.ajax({
        url: scriptUrl,
        type: 'post',
        async: false,
        data: {id: reference_id},
        success: function(response)
        {
            result = response;
        }
    )};
    return result;
}
$('.inbox_check').each(function(){
    if ($(this).is(':checked')){
        var row = $(this).parent().parent();
        var id = row.attr('id');
        if (id == null)
        {
            alert('My selector needs updating');
            return false;
        }
        var debug = 'Deleting ' + id + ' now...';
        if (console) console.log(debug);
        else alert(debug);
        row.remove();
        var response = removeDatabaseEntry(id);

        // Tell the user something happened
        $('#response_div').html(response);
    }
});


Q: Getting Error after implementing ROOM database in kotlin Gradle (Module) :
def room_ver = "2.2.5"

dependencies {
  implementation "androidx.room:room-ktx:" + room_ver
    kapt "androidx.room:room-compiler:" + room_ver
    androidTestImplementation "androidx.room:room-testing:" + room_ver
}

Error :

Tried adding :
gradle (app level)
dependencies {
   classpath "com.android.tools.build:gradle:3.1.3"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.51"
}

gradle : Module
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'kotlin-kapt'

Dashboard.kt
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver.OnScrollChangedListener
import android.view.inputmethod.EditorInfo
import android.widget.TextView.GONE
import android.widget.TextView.OnEditorActionListener
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.ddnsoftech.mrenvois.R
import com.ddnsoftech.mrenvois.common.APIService.Const
import com.ddnsoftech.mrenvois.common.APIService.IntentKeys
import com.ddnsoftech.mrenvois.common.`interface`.BackButtonClickIntefrace
import com.ddnsoftech.mrenvois.common.helpers.UserSession
import com.ddnsoftech.mrenvois.common.util.SnackNotify
import com.ddnsoftech.mrenvois.common.util.hideKeyboard
import com.ddnsoftech.mrenvois.model.Restaurant
import com.ddnsoftech.mrenvois.view.Activities.RestaurantsDetails.ResturantsDetailsActivity
import com.ddnsoftech.mrenvois.view.Adapter.CategoryAdapter
import com.ddnsoftech.mrenvois.view.Adapter.ResturantAdapter
import com.ddnsoftech.mrenvois.view.BaseActivity.BaseActivity
import com.ddnsoftech.mrenvois.view.ServiceNotAvailable.ServiceNotAvailableActivity
import kotlinx.android.synthetic.main.filer_search_view.*
import kotlinx.android.synthetic.main.fragment_dashboard.*

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [DashboardFragment.newInstance] factory method to
 * create an instance of this fragment.
 */

private enum class DashboardListType {
    FILTER_VIEW,HOME_VIEW
}

enum class FilterType {
    popular,promo,location
}

class DashboardFragment : Fragment(), BackButtonClickIntefrace {

    val viewModel = DashboardFragmentVM()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
//            param1 = it.getString(ARG_PARAM1)
//            param2 = it.getString(ARG_PARAM2)
        }
        hideKeyboard()
    }

    lateinit var popularRestaurantAdapter: ResturantAdapter
    lateinit var nearRestaurantAdapter: ResturantAdapter
    lateinit var categoryAdapter: CategoryAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_dashboard, container, false)
    }

    override fun onStart() {
        super.onStart()
        txtDeliveringTo.text =  "${getString(R.string.delivering_to)} ${UserSession.shared.currentAddress?.address ?: ""}"
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initialSetup()
        getHomePageData()
    }

    companion object {

        @JvmStatic
        fun newInstance() =
            DashboardFragment().apply {
//                arguments = Bundle().apply {
//                    putString(ARG_PARAM1, param1)
//                    putString(ARG_PARAM2, param2)
//                }
            }
    }

    @SuppressLint("ClickableViewAccessibility")
    fun initialSetup() {
        viewModel.clearFilter()
        popularRestaurantAdapter = ResturantAdapter(viewModel.popular_restaurant,requireActivity())
        nearRestaurantAdapter = ResturantAdapter(viewModel.near_restaurants,requireActivity(), GridLayoutManager.HORIZONTAL)
        categoryAdapter = CategoryAdapter(viewModel.categories,requireContext())

        popularRestaurantAdapter.onItemSelect = { restaurant ->
            redirectToRestaurantDetails(restaurant)
        }

        nearRestaurantAdapter.onItemSelect = { restaurant ->
            redirectToRestaurantDetails(restaurant)
        }

        categoryAdapter.onItemSelect = { index,value ->
            viewModel.restaurants.clear()
            viewModel.categories[index] = value
            getHomePageData()
        }

        val manager1 =  GridLayoutManager(requireActivity(), 1, GridLayoutManager.HORIZONTAL, false)
        recyclerViewMostPopular.layoutManager = manager1

        val manager2 =   GridLayoutManager(requireActivity(), 1, GridLayoutManager.HORIZONTAL, false)
        recyclerViewNearBy.layoutManager = manager2

        val manager3 =  LinearLayoutManager(requireActivity(),LinearLayoutManager.HORIZONTAL,false)

          //  GridLayoutManager(requireActivity(), 4, GridLayoutManager.HORIZONTAL, false)
        recyclerViewCategory.layoutManager = manager3

        recyclerViewMostPopular.adapter = popularRestaurantAdapter
        recyclerViewNearBy.adapter = nearRestaurantAdapter
        recyclerViewCategory.adapter = categoryAdapter

        scrollView.viewTreeObserver
            .addOnScrollChangedListener(OnScrollChangedListener {

                if (scrollView != null) {
                    val bottom: Int =
                        scrollView.getChildAt(scrollView.childCount - 1)
                            .height - scrollView.height - scrollView.scrollY
//                if (scrollView.scrollY === 0) {
//                    //top detected
//                    SnackNotify.showMessage("Reached to top",relyMain,SnackNotify.MSGType.SUCCESS)
//                }

                    if (scrollView.scrollY == 120) {
                        hideKeyboard()
                    }

                    if (bottom == 0) {
                        //bottom detected
                        if (viewModel.isFilterApplied()) {
                            getHomePageData()
                        }
                        //SnackNotify.showMessage("Reached to Bottom",relyMain,SnackNotify.MSGType.SUCCESS)
                    }
                }
            })

        swipeRefreshLayout.setOnRefreshListener {
            viewModel.restaurants.clear()
            getHomePageData()
        }

        /// Ser view handler
//        etSearchView.

        setupSearchView()
        setUpFilerView()
        reloadList()
    }

    fun redirectToRestaurantDetails(restaurant: Restaurant) {
       var intent = Intent(requireActivity(),  ResturantsDetailsActivity::class.java)
        intent.putExtra(IntentKeys.RESTAURANT,restaurant)
        activity?.startActivity(intent)
    }

    fun setUpFilerView() {
        lnrPopular.setOnClickListener { view ->
            onFilterButtonClick(view)
        }

        lnrPromos.setOnClickListener { view ->
           onFilterButtonClick(view)
        }

        lnrLocation.setOnClickListener { view ->
            onFilterButtonClick(view)
        }

        txtNearByViewAll.setOnClickListener {
            onFilterButtonClick(lnrLocation)
        }

        txtPopularViewAll.setOnClickListener {
            onFilterButtonClick(lnrPopular)
        }

        txtDeliveringTo.setOnClickListener {
            (requireActivity() as? BaseActivity)?.openSetLocation()
        }
    }

    fun setupSearchView() {
        etSearchView.setOnTouchListener(View.OnTouchListener { _ , event ->
            val DRAWABLE_RIGHT = 2
            if (event.action == MotionEvent.ACTION_UP) {
                if (event.rawX >= etSearchView.right - etSearchView.compoundDrawables[DRAWABLE_RIGHT].bounds.width()
                ) {
                    viewModel.restaurants.clear()
                    getHomePageData()
                    true
                }
            }
            false
        })

        etSearchView.setOnEditorActionListener(OnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                viewModel.restaurants.clear()
                getHomePageData()
                true
            } else false
        })
//        etSearchView.doOnTextChanged { text, start, before, count ->
//        }
    }

    fun getHomePageData() {
        hideKeyboard()
        viewModel.search = etSearchView.text?.toString()
        swipeRefreshLayout.isRefreshing = true
        viewModel.getHomeData {  success,errMsg ->
            swipeRefreshLayout.isRefreshing = false
            if (success) {
                reloadList()
            }else {
                SnackNotify.showMessage(errMsg,relyMain, SnackNotify.MSGType.ERROR)
                reloadList()
            }
        }
    }

    fun getSearchData() {

    }

    fun reloadList() {
        if (viewModel.isFilterApplied()) {

            if (nearRestaurantAdapter.scrollDirection != GridLayoutManager.VERTICAL) {
                val handler = nearRestaurantAdapter.onItemSelect
                nearRestaurantAdapter = ResturantAdapter(viewModel.restaurants,requireActivity(), GridLayoutManager.VERTICAL)
                nearRestaurantAdapter.onItemSelect = handler
                val manager2 =   GridLayoutManager(requireActivity(), 1, GridLayoutManager.VERTICAL, false)
                recyclerViewNearBy.layoutManager = manager2
                recyclerViewNearBy.adapter = nearRestaurantAdapter
          }

            lnrMostPopularContainer.visibility = View.GONE
            lnrTopCategoryContainer.visibility =
                if (viewModel.categories.count() == 0) View.GONE else View.VISIBLE

            lnrNearByContainer.visibility =
                if (viewModel.restaurants.count() == 0) View.GONE else View.VISIBLE

            viewNoRecordFound.visibility =
                if (viewModel.restaurants.count() != 0) View.GONE else View.VISIBLE

            //popularRestaurantAdapter.updateList(viewModel.popular_restaurant)
            nearRestaurantAdapter.updateList(viewModel.restaurants)
            categoryAdapter.updateList(viewModel.categories)

            txtNearByTitle.text =  getString(R.string.restaurants)
            txtNearByViewAll.visibility = View.GONE
            reloadFilterTab(true)
        }else{

            if (nearRestaurantAdapter.scrollDirection != GridLayoutManager.HORIZONTAL) {
                nearRestaurantAdapter = ResturantAdapter(viewModel.near_restaurants,requireActivity(), GridLayoutManager.HORIZONTAL)
                val manager2 =   GridLayoutManager(requireActivity(), 1, GridLayoutManager.HORIZONTAL, false)
                recyclerViewNearBy.layoutManager = manager2
                recyclerViewNearBy.adapter = nearRestaurantAdapter
            }

            txtNearByTitle.text =  getString(R.string.near_by)
            txtNearByViewAll.visibility = View.VISIBLE

            viewNoRecordFound.visibility =  if (viewModel.near_restaurants.count() == 0 && viewModel.popular_restaurant.count() == 0)  View.VISIBLE else  View.GONE

            lnrMostPopularContainer.visibility =
                if (viewModel.popular_restaurant.count() == 0) View.GONE else View.VISIBLE
            lnrNearByContainer.visibility =
                if (viewModel.near_restaurants.count() == 0) View.GONE else View.VISIBLE
            lnrTopCategoryContainer.visibility =
                if (viewModel.categories.count() == 0) View.GONE else View.VISIBLE
            popularRestaurantAdapter.updateList(viewModel.popular_restaurant)
            nearRestaurantAdapter.updateList(viewModel.near_restaurants)
            categoryAdapter.updateList(viewModel.categories)
            reloadFilterTab(false)
        }
    }

    fun reloadFilterTab(filterApplied:Boolean) {
        if (filterApplied && viewModel.filterType != null)
        {
             when (viewModel.filterType!!) {

                 FilterType.popular -> {
                     lnrPopular.background = resources.getDrawable(R.drawable.filter_active_border)
                     lnrPromos.background = resources.getDrawable(R.drawable.rounded_border_tab)
                     lnrLocation.background = resources.getDrawable(R.drawable.rounded_border_tab)
                 }

                 FilterType.promo -> {
                     lnrPopular.background = resources.getDrawable(R.drawable.rounded_border_tab)
                     lnrPromos.background = resources.getDrawable(R.drawable.filter_active_border)
                     lnrLocation.background = resources.getDrawable(R.drawable.rounded_border_tab)
                 }

                 FilterType.location -> {
                     lnrPopular.background = resources.getDrawable(R.drawable.rounded_border_tab)
                     lnrPromos.background = resources.getDrawable(R.drawable.rounded_border_tab)
                     lnrLocation.background = resources.getDrawable(R.drawable.filter_active_border)
                 }

             }
        }else{
            lnrPopular.background = resources.getDrawable(R.drawable.rounded_border_tab)
            lnrPromos.background = resources.getDrawable(R.drawable.rounded_border_tab)
            lnrLocation.background = resources.getDrawable(R.drawable.rounded_border_tab)
        }

    }

    override fun onBackClicked(): Boolean{
//        TODO("Not yet implemented")
        if (viewModel.isFilterApplied())
        {
            viewModel.clearFilter()
            getHomePageData()
            return true
        }

        return false
    }

    fun onFilterButtonClick(v: View) {
       when (v) {
           lnrPopular -> {
               viewModel.filterType = if( viewModel.filterType == FilterType.popular ) null else FilterType.popular
           }

           lnrPromos -> {
               viewModel.filterType = if( viewModel.filterType == FilterType.promo ) null else FilterType.promo
           }

           lnrLocation -> {
               viewModel.filterType = if( viewModel.filterType == FilterType.location ) null else FilterType.location
           }
       }

        reloadFilterTab(viewModel.filterType != null)
        viewModel.restaurants.clear()
        getHomePageData()
    }
}


Q: modal does not load form data I have the data form and the data update views, when I'm not using the modal, it works perfectly, however when using modal, it loads the empty forms, and if I load without the modal, the data saved in the database appear .
I do not know where I'm going wrong.
I can change the user name and save, the problem is that let's say user1 and I want to change to the user2 name, when I click to change the name, the form field does not come with user1 filled in.
and if I do not use the modal, it comes with the user1 already filled in
views.py
class UserNameUpdate(LoginRequiredMixin, UpdateView):
    model= User
    fields = ['username']
    template_name=' /change-username.html'

    def get_object(self, queryset=None):
        if queryset is None:
            queryset = self.get_queryset()   # This should help to get current user

        # Next, try looking up by primary key of Usario model.
        queryset = queryset.filter(pk=self.request.user.usuario.pk)

        try:
            # Get the single item from the filtered queryset
            obj = queryset.get()
        except queryset.model.DoesNotExist:
            raise Http404("No user matching this query")
        return obj

    def get_success_url(self):
        return reverse('sistema_perfil')

change-username.html
{% load static %}
{% load bootstrap %}
{% load widget_tweaks %}
{% load crispy_forms_tags %}
{% block main %}

          Home /
          Perfil /
          Usúario

 Alterar Nome do Usúario

<form method="post" action="{% url 'sistema_change_username' %}" class="form-signin" enctype="multipart/form-data" id="form" name="form" validate>
{% csrf_token %}

        {{ form.username| as_crispy_field}}

<input type="submit" class="btn btn-primary " >

</form>

Voltar

{% endblock %}

menu_perfil.html
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
            Launch demo modal
        </button>

Modal title

                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                ×
                            </button>

    {% include 'profile/change-username.html' %}

A: Am I right that the with-modal and without-modal templates load from two different views? If so, the problem is how you are using Django's {% include %} template tag. Here are the docs:
https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#include
Key line: "An included template is rendered within the context of the template that includes it."
It looks like menu_perfil.html is rendered from a different view, which doesn't pass the form object into its context. So menu_perfil.html doesn't know what {{ form }} is. Whereas change-username.html is rendered with your UsernameUpdate view with the form object.  Try moving your modal HTML into change-username.html, around your form code, instead of including a separate snippet, and see if that solves the problem.
In general, inheriting from base templates using {% extends %} is preferable to using includes unless you really have to, because of limitations like this.


Q: printing BST IN order I am trying to print out tree nodes IN order however all that it is coming out are the noes of the lowest depth! I'm not sure what is wrong with my logic so I was wondering if another set of eyes would help me or give me a hint thanks!!
Expected output:
1
2
3
4
6
8
10

my code:
class Node:
    def __init__(self,value):
        self.right = None
        self.left = None
        self.value = value

def BST_Insert(root, node):     # root --> root of tree or subtree!
    if root.value is None:
        root = node             # beginning of tree
    else:
        if root.value > node.value:     # go to left
            if root.left is None:
                root.left = node
            else:
                BST_Insert(root.left, node)

        if root.value < node.value:    # go to right
            if root.right is None:
                root.right = node
            else:
                BST_Insert(root.right, node)

def inorder_print(root):
    if root.left is not None:
        inorder_print(root.left)
    else:
        print root.value
    if root.right is not None:
        inorder_print(root.right)

r = Node(4)
# left
a = Node(2)
b = Node(1)
c = Node(3)
# right
d = Node(8)
e = Node(6)
f = Node(10)

BST_Insert(r, a)
BST_Insert(r, b)
BST_Insert(r, c)
BST_Insert(r, d)
BST_Insert(r, e)
BST_Insert(r, f)

print "in order:"
inorder_print(r)

A: I don't think you need the else after the the first if statement.
Something like the following might work,
if left!=null:
    inorder(left)
print(current_node.val)
if (right!=null):
    inorder(right)


Q: htaccess [L] flag didn't work I have .htaccess file like this inside searchEngine folder inside htdocs of xampps
    RewriteEngine On
    RewriteRule ^\/?test$ view/index.php [NC,L]
    RewriteRule ^(.*)$   http://google.com [NC,L]

then I type this in the address bar:

*

*localhost/searchEngine/test

Why this redirect to

*

*http://google.com
not

*

*view/index.php?

I thought this must be redirected to

*

*view/index.php

not

*

*http://google.com

A: It is because mod_rewrite runs in a loop. First rule is doing this:
Starting URL:
/searchEngine/test

Ending URL:
/searchEngine/view/index.php

Now L flag causes mod_rewrite to loop again. So now your starting URL becomes:
Starting URL:
/searchEngine/view/index.php

Now 1st rule' pattern ^test doesn't match but your 2nd rule is using .* as matching pattern hence redirects to google.
You can have your rules as follows to prevent this behavior:
RewriteEngine On

RewriteRule ^/?test$ view/index.php [NC,L]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^ http://google.com [R,L]

2nd rule has this additional condition:
RewriteCond %{ENV:REDIRECT_STATUS} ^$

REDIRECT_STATUS is set to 200 after first rule's execution. So 2nd rule will redirect only if first rule hasn't executed first hence it will skip /test.
If you're using Apache 2.4+ then you can use END instead of L to end the execution:
RewriteEngine On

RewriteRule ^/?test$ view/index.php [NC,END]

RewriteRule ^ http://google.com [R,L]

A: This is happening because of the internal redirection, You can use the END flag instead of L to stop this behaviour :
    RewriteEngine On
    RewriteRule ^\/?test$ view/index.php [NC,END]
    RewriteRule ^(.*)$   http://google.com [NC,L]


Q: Is there a way to reduce duplication here? I am creating a prisoner's dilemma simulation and I have two functions that are counting cooperations and defections done by the two players and outputting them as a tuple. I see a lot of similarities and would like some guidance on how to consolidate the two functions into another function that the two can call upon so I am not reusing code. I am very new in OCaml so I am struggling to find a way to do this!
Here is the necessary information:
type action = bool ;;
type play = action * action ;;
type history = play list

let rec count_defections (history : history) : (int * int) =
  match history with
  | [] -> (0, 0)
  | play :: rest ->
    match play with
    | (player1, player2) ->
      match count_defections rest with
      | (d1, d2) ->
        if (player1, player2) = (false, false) then (d1 + 1, d2 + 1)
        else if (player1, player2) = (false, true) then (d1 + 1, d2)
        else if (player1, player2) = (true, false) then (d1, d2 + 1)
        else (d1, d2) ;;

let rec count_cooperations (history : history) : (int * int) =
  match history with
  | [] -> (0, 0)
  | play :: rest ->
    match play with
    | (player1, player2) ->
      match count_cooperations rest with
      | (d1, d2) ->
        if (player1, player2) = (true, true) then (d1 + 1, d2 + 1)
        else if (player1, player2) = (true, false) then (d1 + 1, d2)
        else if (player1, player2) = (false, true) then (d1, d2 + 1)
        else (d1, d2) ;;

My first thoughts were:
let count_common (history : history) : (int * int) =
  match history with
  | [] -> (0, 0)
  | play :: rest ->
    match play with
    | (player1, player2) ->
      match .....

But I don't really understand  how to do the rest.

A: Here's a function that counts the two parts of a pair separately, counting elements that equal a given value.
let count_val_in_pairs value pairs =
    List.fold_left
        (fun (cta, ctb) (a, b) ->
            ((if a = value then cta + 1 else cta),
             (if b = value then ctb + 1 else ctb)))
        (0, 0)
        pairs

Your count_defections is this:
let count_defections history =
    count_val_in_pairs false history

Your count_cooperations is this:
let count_cooperations history =
    count_val_in_pairs true history


Q: taking input from file using scanner class in java I am trying store a list of cities in a class using two co-ordinates(x,y) in java
My class is as follows:
public class City {
    int x;
    int y;

    // Constructs a city at chosen x, y location
    public City(int x, int y){
        this.x = x;
        this.y = y;
    }
}

I have made another class to store the cities in an ArrayList:
public class TourManager {

    // Holds our cities
    private static ArrayList destinationCities = new ArrayList<City>();

    // Adds a destination city
    public static void addCity(City city) {
        destinationCities.add(city);
    }
}

My main class is as follows:
public class Final {
    public static void main(String[] args) {
        // Create and add our cities
        City city = new City(60, 200);
        TourManager.addCity(city);
        City city2 = new City(180, 200);
        TourManager.addCity(city2);
        City city3 = new City(80, 180);
        TourManager.addCity(city3);
    }
}

Here, I have stored three cities in the ArrayList inside the main function. But now I want to take the input from a file in the following format. I just want to take the co-ordinates ignoring all other lines.

NAME: sample.tsp
TYPE: TSP
COMMENT: Odyssey of Ulysses (Groetschel/Padberg)
DIMENSION: 3
EDGE_WEIGHT_TYPE: GEO
NODE_COORD_SECTION
1 60 200
2 180 200
3 80  180

I want to use the scanner class to take the input but getting confused in using it. i have made a partial code fragment to take input but it isn't working:
Scanner in = new Scanner(new File("sample.tsp"));
String line = "";
int n;
in.nextLine();
in.nextLine();
in.nextLine();
line = in.nextLine();
line = line.substring(11).trim();
n = Integer.parseInt(line);
in.nextLine();
in.nextLine();

But how will I take the coordinates using the City class object as I have done before from this file?

A: You need to skip the first few lines, which you don't need.
Then split the lines to get the various numbers. Index 0 contains the serial no., 1 and 2 contain the coordinates. Then parse them to int. eg:
in.nextLine();// multiple times.
//...
String cs = in.nextLine(); // get the line
City city = new City(Integer.parseInt(cs.split(" ")[1]), Integer.parseInt(cs.split(" ")[2]));
TourManager.addCity(city);

String cs2 = in.nextLine();
City city2 = new City(Integer.parseInt(cs2.split(" ")[1]), Integer.parseInt(cs2.split(" ")[2]));
TourManager.addCity(city2);

String cs3 = in.nextLine();
City city3 = new City(Integer.parseInt(cs3.split(" ")[1]), Integer.parseInt(cs3.split(" ")[2]));
TourManager.addCity(city3);

A: Whenever you use in.nextLine(), actually it takes the string that you entered. So try to assign it to some string variable. For example:
String s =in.nextLine();

Also, just using in.nextLine(); which you did in 2nd,3rd 4th,8th and 9th line is not needed.


Q: sql query to fetch the third highest sale grouped by sales Fetch the third highest sale amount from the table (group by sale amount) in MySQL
 select Top 3 * from t1 group by sale_Amnt

|Id|product_name|product_group    |sale_Amnt(INR)
------------------------------------------------
 1|  p1       |   Cosmetic       |4485
 2|  p2       |   Cosmetic       |8525
 3|  p3       |   Health         |12589
 4|  p4       |   Health         |8525
 5|  p5       |   Home Appliances|9858
 6|  p6       |   Home Appliances|12589

Expected output
|Id|product_name|product_group    |sale_Amnt(INR)
------------------------------------------------
 2|  p2       |   Cosmetic       |8525
 4|  p4       |   Health         |8525`

A: The proposed duplicate is a misunderstanding of the question.  This question appears to be looking for the third highest value overall, but taking duplicates into account.
You can get the third row using offset/fetch in SQL Server:
select t.*
from t
where t.sale_amount = (select t2.sale_amount
                       from t t2
                       group by t2.sale_amount
                       order by t2.sale_amount desc
                       offset 2 fetch first 1 row only
                      );

In MySQL, that would be:
select t.*
from t
where t.sale_amount = (select t2.sale_amount
                       from t t2
                       group by t2.sale_amount
                       order by t2.sale_amount desc
                       limit 1 offset 2
                      );

A:

SELECT * FROM `sale_amnt` ORDER BY `sale_Amnt` DESC LIMIT 2,1


Q: SQL divide by shifted value of other field I have a table that looks like this:

Where RETENTION is the division of N_CUSTOMERS by CUSTOMER_WHEN_0 for each PERIOD_NUMBER.
Now I need to get another new field that is the result of dividing each retention value of thar PERIOD_NUMBER by the retetion value of the previous PERIOUD_NUMBER. In the example of the image it's not appreciated, but I have all the consecutive values for PERIOD_NUMBER. When the PERIOD_NUMBER is 0, it doesn't matter that the division by its shifter value is NAN or similar, I will replace it later.
So, summarizing, my desired output is a ner field that shows the result of dividing the RETENTION value of the PERIOD_NUMBER of that row by the RETENTION value of the previous PERIOD_NUMBER. I'm using DBT and in case is useful I have the querys I used to get these fields and I have the code to do that process in Python, but I need to do it in SQL
first purchase of the user, ORDER_MONTH is the date  of that purchase, and PERIOD_NUMBER is the date difference in months between COHORT and ORDER_MONTH. N_CUSTOMERS is the number of customers in each PERIOD_NUMBER in each COHORT, and CUSTOMER_WHEN_0 is the number of users in each cohort when the PERIOD_NUMBER is 0.
I had to use a window function in order to achive this last field.

A: Here is an example of how you can get the previous RETENTION using a subquery, assuming that the period numbers are all consecutive:
SELECT
    N_CUSTOMERS,
    PERIOD_NUMBER,
    CUSTOMER_WHEN_0,
    RETENTION,
    (SELECT st_inner.RETENTION
        FROM sourcetable st_inner
        WHERE st_inner.PERIOD_NUMBER = st_outer.PERIOD_NUMBER - 1
    ) as PREVIOUS_RETENTION
FROM sourcetable st_outer

I left out the calculation for readability's sake, but I think it should be clear how to do this.


Q: AngularJS. Displaying custom popup on user's attempt to leave the page Is it possible to synchronously display bootstrap modal (instead of native confirm) when user tries:

*

*change route

*leave the page

(AngularJS)

A: You must separate your code into two different functions.
If you have this:
var txt;
var r = confirm("Press a button!");
if (r == true) {
    // Put this in a function ...
    txt = "You pressed OK!";
} else {
    // ... and this in another function
    txt = "You pressed Cancel!";
}

Would like this:
var onOkClick = function(){
  txt = "You pressed OK!";
};

var onCancelClick = function(){
  txt = "You pressed Cancel!";
};

And in the buttons of your modal:
<button type='button' class='btn btn-success' onclick="onOkClick()">OK</button>
<button type='button' class='btn btn-default' onclick="onCancelClick()">Cancel</button>


Q: This is a number guessing game the num_check function works just fine the first time but won't run any second attempts. Does anyone know why? import random

# Define function - Number Generator
def num_gen():

    num = random.randrange(1, 101)
    return num

# Define function - Number Check
def num_check(x, y):

    result = ''
    if x > y:
        result = 'high'
    elif x < y:
        result = 'low'
    else:
        result = 'correct'
    return result

# Call - Number Generator
num = num_gen()

# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))

att = 1

# Process - Guess and Display Result
result = num_check(guess, num)

if result == 'high':

    guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
    att += 1
    result = num_check(guess, num)

elif result == 'low':

    guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
    att += 1
    result = num_check(guess, num)

else:

    print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')

A: After getting input from console, you should create a loop which breaks when guessed number equal to input. For example:
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))

att = 1

# Process - Guess and Display Result
result = num_check(guess, num)

while result != guess:

    if result == 'high':

        guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
        att += 1
        result = num_check(guess, num)

    elif result == 'low':

        guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
        att += 1
        result = num_check(guess, num)

    else:
        break

print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')

After revision, code seems like:
import random

# Define function - Number Generator
def num_gen():

    num = random.randrange(1, 101)
    return num

# Define function - Number Check
def num_check(x, y):

    result = ''
    if x > y:
        result = 'high'
    elif x < y:
        result = 'low'
    else:
        result = 'correct'
    return result

# Call - Number Generator
num = num_gen()

# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))

att = 1

# Process - Guess and Display Result
result = num_check(guess, num)

while result != guess:

    if result == 'high':

        guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
        att += 1
        result = num_check(guess, num)

    elif result == 'low':

        guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
        att += 1
        result = num_check(guess, num)

    else:
        break

print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')

A: You should use while True:, because your guessing code runs only once without it
import random

# Define function - Number Generator
def num_gen():

    num = random.randrange(1, 10)
    return num

# Define function - Number Check
def num_check(x, y):

    result = ''
    if x > y:
        result = 'high'
    elif x < y:
        result = 'low'
    else:
        result = 'correct'
    return result

# Call - Number Generator
att = 1
num = num_gen()
while True:
    # Input - Guess
    guess = int(input('Please guess a number between 1 and 100: '))
    # Process - Guess and Display Result
    result = num_check(guess, num)

    if result == 'high':
        print('Your guess was HIGH! Please guess another number between 1 and 100: ')
        att += 1

    elif result == 'low':
        print('Your guess was LOW! Please guess another number between 1 and 100: ')
        att += 1

    else:
        print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
        break

A: It's because python programs runs from top to bottom, and when it reaches the bottom it's done and stops running. To stop this order we have multiple different ways:
We can call a function, as you do in you're program.
Selection Control Structures: As if statements
Iteration Control Structures: As loops
The last one is the one you need in this solution. Wrap code in a while loop, with the correct condition, in you're example, this would be
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))

att = 1

# Process - Guess and Display Result
result = num_check(guess, num)

if result == 'high':

    guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
    att += 1
    result = num_check(guess, num)

elif result == 'low':

    guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
    att += 1
    result = num_check(guess, num)

else:

    print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')

The best way woul be to use a will loop as follow:
while guess != num:

A: how can you expect it to run more than 1 time if you have not used any loop in the program. For example in this case you should use a while loop, then only it will prompt the user again and again and will check for the conditions, set a game variable to be True. When the number is matched then simply set the game variable to be False and it will end the loop.
import random

# Set the game variable initially to be True
game = True

# Define function - Number Generator
def num_gen():

    num = random.randrange(1, 101)
    return num

# Define function - Number Check
def num_check(x, y):

    result = ''
    if x > y:
        result = 'high'
    elif x < y:
        result = 'low'
    else:
        result = 'correct'
    return result

# Call - Number Generator
num = num_gen()

# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))

att = 1

# Process - Guess and Display Result
result = num_check(guess, num)

while game:

    if result == 'high':

        guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
        att += 1
        result = num_check(guess, num)

    elif result == 'low':

        guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
        att += 1
        result = num_check(guess, num)

    else:

        print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
        game = False


Q: How to use query string to find requesting page in ASP.NET? I have a page signup.aspx where user can register, how this page will find from which page request came from and how it will redirect user after registration to the requesting page. I want to do this using query string but don't know how

A: On any links to the register page put
<a href="Signup.aspx?ReturnUrl=<%=Request.Url.AbsolutePath%>">Register Here

then on your register form when they have registered add:
if (!String.IsNullOrEmpty(Request["ReturnUrl"]))
     Response.Redirect(Request["ReturnUrl"]);
else
     Response.Redirect("~/Default.aspx");

A: if(Request.QueryString["foo"] == "bar"){
    Response.Redirect("page.php", true);
}

This would get the information from http://www.example.com/registered.aspx?foo=bar
So Request.QueryString["QueryString"] is the value of anything after the ? and each variable after the &. so if you had http://www.example.com/registered.aspx?foo=bar&abc=def
Then you would have 2 querystrings, foo and abc.


Q: How Can I Implement Realtime Notification On My Php Page This Is My Home.Php ,I Need To Display Realtime Notification From Database
<html>
<body>
<label>Notifications <?php echo "(".$notification.")"; ?>)</label>
//$notification Contain no. of Notifications From Database
</body>
</html>

A: You need to use web socket for real time notification. You can try Ratchet or socket.io.


Q: How to sum the values of all the textboxes with same class which are generated using ajax? I want to sum of all the values of textboxes generated using ajax. I have the textboxes with classname adminhoursand these textboxes are generated using ajax. The sum should be displayed in another textbox on the change event of the textbox with class adminhours. The sum should be multiplied with the admin rate textbox. Please help me. Thanks in advance.
HTML
<form action="" method="post">

                Name
                Email2(payment)
                Class Rate
                Admin Rate
                Week
                Status
                Comment

                    <select name="txtuser" id="txtuser">
                    <option>--select--</option>
                                        <option value="2">nitinjohnson2000</option>

                    </select>

                <input type="text" name="txtemail2" style="width:100%;" readonly="">
                <input type="text" name="txtclassrate" style="width:80px;" readonly="">
                <input type="text" name="txtadminrate" style="width:80px;" readonly="">

                    <select name="txtweek" id="txtweek">
                        <option>--select--</option>
                                                <option>08-31-2015</option>
                                                <option>09-07-2015</option>
                                                <option>09-14-2015</option>
                                                <option>09-21-2015</option>
                                                <option>09-28-2015</option>
                                                <option>10-05-2015</option>
                                                <option>10-12-2015</option>
                                                <option>10-19-2015</option>
                                            </select>

                Not Saved
                <textarea name="txtcomment"></textarea>

                    Session
                    Day of week
                    Date
                    Pre-Assigned
                    Start Date
                    End Date
                    Present
                    Late Arrival
                    Expense
                    Admin Hours
                    Comments

                    Fall 2015 - Bethany Elementary Chess Program - Plano ISD
                    Wed
                    09-02-2015
                    Y
                    2015-09-09
                    2015-12-12
                    <input type="checkbox" name="presentdays[]">
                    <input type="checkbox" name="latedays[]">
                    5
                    <input type="text" name="admin_hours[]" class="adminhours" value="0" style="width:50px;">
                    <input type="text" name="item_comment" style="width:80px;">

                        Fall 2015 - Ashley Elementary Chess Program - Frisco ISD
                        Mon
                        08-31-2015
                        Y
                        2015-09-14
                        2015-12-12
                        <input type="checkbox" name="presentdays[]">
                        <input type="checkbox" name="latedays[]">
                        15	<input type="text" name="admin_hours[]" class="adminhours" value="0" style="width:50px;">
                        <input type="text" name="item_comment" style="width:80px;">

                        Fall 2015 - Bledsoe Elementary Chess Program - Frisco ISD
                        Wed
                        09-02-2015
                        Y
                        2015-09-16
                        2015-12-12
                        <input type="checkbox" name="presentdays[]">
                        <input type="checkbox" name="latedays[]">
                        15
                        <input type="text" name="admin_hours[]" class="adminhours" value="0" style="width:50px;">
                        <input type="text" name="item_comment" style="width:80px;">

                        Fall 2015 - Anderson Elementary Chess Program - Frisco ISD
                        Mon
                        08-31-2015
                        Y
                        2015-09-21
                        2015-12-12
                        <input type="checkbox" name="presentdays[]">
                        <input type="checkbox" name="latedays[]">
                        5
                        <input type="text" name="admin_hours[]" class="adminhours" value="0" style="width:50px;">
                        <input type="text" name="item_comment" style="width:80px;">

                    Day
                    Classes $
                    Late $
                    Expense
                    Admin
                    Approved Adjustment
                    Approved Comment

                    <input type="text" name="number_of_classes" value="4" style="width:50px;" readonly="">
                    <input type="text" name="totalclasses" value="40" readonly="">
                    <input type="text" value="" id="latecharges" readonly="">
                    <input type="text" name="totalexpense" value="40" readonly="">
                    <input type="text" name="totaladminrate" value="0" readonly="">
                    <input type="text" name="approved_adjustment" id="approved_adjustment" style="width:50px;">
                    <textarea name="approver_comment"></textarea>

                Total
                <input type="text" name="finaltotal" id="finaltotal" readonly="">
                Approved Total
                <input type="text" name="approvedtotal" id="approvedtotal" readonly="">

    <input type="hidden" name="alldata" id="alldata" value="16,15,17,14">

                <input type="submit" name="addtimecard" value="Save" class="button button-primary button-large">

</form>

Javascript

A: The logic to get all elements with class .adminhours should not check with val in selector if(jQuery(".adminhours").val().length > 0). I have updated your code below :
var totalAdminhours = 0;
if(jQuery(".adminhours").length > 0){
        jQuery(".adminhours").each(function () {
            totalAdminhours += totalAdminhours + jQuery(this).val();
        });
    } else {
        totalAdminhours = 0;
    }


Q: Overloading == operator A derives directly from Object class and neither A or Object overload == operator, so why doesn't next code cause an error:
class Program
{
    static void Main(string[] args)
    {
        A a1 = new A();
        A a2 = new A();

        if (a1 == a2) ... ;
    }
}

class A { }

thanx

A:
A derives directly from Object class and neither A or Object overload == operator, so why doesn't next code cause an error?

As with your other question, you seem to have some strange belief that whether an overloaded operator exists has any bearing on whether an operator can be meaningfully chosen. It does not.
Again, to resolve this situation overload resolution first attempts to determine if there is a user-defined operator defined on either of the operands. As you note, there is not.
Overload resolution then falls back on the built-in operators. As I mentioned in your other question, the built-in operators are the equality operators on int, uint, long, ulong, bool, char, float, double, decimal, object, string, all delegate types and all enum types, plus the lifted-to-nullable versions of all the value types.
Given those operators we must now determine the applicable ones. There is no implicit conversion from "A" to any of the value types, to any of the nullable value types, to string, or to any delegate type.
The only remaining applicable candidate is object.
If overload resolution chooses the equality operator that compares two objects, additional constraints must be met. In particular, both operands must either be null or a reference type, or a type parameter not constrained to be a value type.  That constraint is met.  Also, if the two sides have types then the operand types must have some sort of compatibility relationship; you can't do "myString == myException" because there is no relationship between string and Exception. There is a relationship between "A" and "A", namely, they are identical.
Therefore the reference equality operator is chosen, and the == means "compare these two object expressions by reference".
I am mystified as to why you believe having a user-defined == operator has anything to do with this, either in this question or your other question. The absence of such a method does not prevent the compiler from generating whatever code it likes for this expression. Can you explain?

A: Because by default, the == operator compares the references (memory locations) of the objects a1 and a2. And because they're different instances of class A, the expression a1 == a2 always evaluates to false in your example.

A: Objects have a default implementation of the == operator that checks if they refer to the same object (reference comparison). So there's no reason for it to be an error. The operator does have a meaning.

A: Because Object has a default implementation comparing references.

A: The base's == operator is called that why its not giving any error.

A:
By default, the operator == tests for
  reference equality by determining if
  two references indicate the same
  object, so reference types do not need
  to implement operator == in order to
  gain this functionality.

From: http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx
The important bit concerning your question being:

reference types do not need to
  implement operator == in order to gain
  this functionality


Q: Are the UTC datetime formats acknowledged by W3C identical to those of ISO 8601? The W3C Date and Time note suggests that date and time 'official' formats are identical to, or a subset of ISO 8601. The note says "This document defines a profile of ISO 8601", and also "To reduce the scope for error and the complexity of software, it is useful to restrict the supported formats to a small number."
Is it safe to assume, that all W3C datetimes (such as those used in server logs) are therefore compatible with ISO 8601?


Q: How can I change the Universal Login logo on auth0 dashboard? I'm currently stuck on the auth0 Universal Login page.
I want to change the logo by given an url but it keep telling me that the url is not valid.
I don't know what to do anymore because the exact same url is valid for the Application logo.
Screenshot of the error

A: it seems that you might get that error if you have an whitespace before or after the link too. Can you check whether or not you have that white space in there? maybe that's it


Q: Positive lookahead assertion and .* sign in python I have the following regular expression:
passw = re.compile(r'^(?=.*\d)(?=.*[A-Z])(?=.*[\$|\?\!])[A-Za-z\d$!&]{8}$')

which I can interpret as string of length 8, which must contain at least one number, one big letter and one of characters($?!). And also consists only of numbers, letters and $?!.
?= - this symbol is known as lookahead assertion:  For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.
But how can we interpret .* sign? What does it mean in regex?
Can we avoid it in this situation?

A: In fact .* means zero or more occurrences of any character, and when it follows with a special pattern in a lookahead it means that the regex engine will assert that the regex can be matched. And when you use .* before your pattern you are telling the regex engine to match my pattern that precede by zero or more characters this means you want to be sure that your pattern is present in your string (from leading to trailing).
Here is an example with diagram:
(?=.*\d)[a-z]+

Debuggex Demo


Q: Google Maps kml files If I use an embeded google map in my website, will the data contained in an kml displayed be publicly viewable?
Will it be possible for the user to access just the data displayed (i.e., not the user interface) or would I have to provide that separately?

A: If you load your KML through the API, with GGeoXml(), (V2), or KmlLayer(), (V3), then your data needs to be in a public server because it is parsed by Google's servers and they need to be able to get to it. If you load it with a third party extension then you can keep it private.
Third party extensions that can load and parse KML data are EGeoXml() by Mike Williams
http://econym.org.uk/gmap/extensions.htm#EGeoXml
and GeoXml() by Lance Dyas
http://www.dyasdesigns.com/geoxml/
but I believe that both of those are only available for the API V2 for now.

A: I just upgraded my Google Maps JavaScript API Application from v2 to v3, following these instructions.
My v2 application was using the EGeoXml extension referred to by @Marcelo in the accepted answer to locally parse KML data.
A substitution of geoxml3 in its place, as suggested by @geocodezip (a contributor to the project) in a comment, functioned immediately in my v3 application.

A: No, the data will not be public. I'm not sure about your other question though.


Q: remove duplicate rows where one column equals a different column I have a df like this:
d = {'label':['A','B','G','O']
    ,'label2':['C','D','O','Z']}
df = pd.DataFrame(d)
print(df)

  label label2
0   A    C
1   B    D
2   G    O
3   O    Z

What i want to do is to get rid of the duplicate rows that have label = label2 (keep only the first)
So i want to get something like this from the above df:
  label label2
0   A    C
1   B    D
2   G    O

I do this below, but it doesn't do the trick
df[~df[['label', 'label2']].apply(frozenset, axis=1).duplicated()]

Any idea on how to tackle this?

A: Try this, using .isin method for Seires:
mask = ~df['label'].isin(df['label2'])
df_output = df[mask]
print(df_output)

Output:
  label label2
0   A    C
1   B    D
2   G    O

A: You can use drop to remove duplicate label between 2 columns:
df.drop(df[df['label'].isin(df['label2'])].index, inplace=True)
print(df)

# Output:
  label label2
0     A      C
1     B      D
2     G      O


Q: .Net Garbage Collection on LoH When the memory dump is being analyzed, it shows that this particular string variable which is holding the xml content is causing memory leak. I read on some of the articles that LoH goes to Gen 2. So,

*

*Will garbage collector gets invoked if Gen 0 and Gen 1 is not under pressure and Gen 2 is under pressure due to LoH ?

*Will it go to Gen 2 when it has released Gen 0 or Gen 1 memory ?

*If so what’s the better way to handle this ?

A: *

*No, it will not

*Only if there's enough memory pressure

However, if your application is doing allocations, it's pretty unlikely the string will survive for too long. And if there's not enough memory pressure, the GC has little reason to release the memory.
Do make sure the string is not referenced anymore, though. Count the references, check that it's not interned.
You can force a garbage collection, but it's great way to damage GC performance. It might be the best solution for your case if your application does the odd "allocate a huge string and then forget it" operation, and you care about memory available to the rest of the system (there's no benefit to your application). There's no point in trying that if you're doing a lot of allocations anyway, though - in that case, look for memory leaks on your side. WinDbg can help.

A: 1. Will garbage collector gets invoked if Gen 0 and Gen 1 is not under pressure ?
If there is enough space in Generation0 and Generation2, then Garbage Collector will not be invoked.
If there is enough space in Generation0 and Generation2, then it means that that there is enough space to create new objects and there is no reason to run Garabage Collection.
2. Will it go to Gen 2 when it has released Gen 0 or Gen 1 memory ?
If the object is survived after Garbage Collection in Generation1 and in the Generation1, then the object will be moved to Generation2.
3. If so what’s the better way to handle this ?

*

*To destroy an object from heap, you should just delete references of this string. Your string variable which has xml values should not be static to be garbage collected.(read more about roots)

*Try to use compact GCSettings.LargeObjectHeapCompactionMode:
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();
This will compact the Large Object Heap when the next Full Garbage Collection is executed. With GC.Collect() call after the settings been applied, the GC gets compacted immediately.

*

*Try to use WeakReference:
WeakReference w = new WeakReference(MyLargeObject);
 MyLargeObject = w.Target as MyLargeClass;
MyLargeClass MyLargeObject;
if ( (w == null) || ( (MyLargeObject=w.Target as MyLargeClass) == null) )
{
    MyLargeObject = new MyLargeClass();
    w = new WeakReference(MyLargeObject);
}
This article gives is very useful to you about Garbage Collection and the article is written in plain English.


Q: How to Drawable Rotating around its Top Android I am getting strange results with the following code:
  Animation a = new RotateAnimation(0.0f, 360.0f,
                Animation.ZORDER_TOP, 0.5f, Animation.ZORDER_TOP,
                0.5f);
        a.setRepeatCount(-1);
        a.setDuration(1000);
        img.startAnimation(a);

Whats the right way to specify the axis point (top of the drawable)?

A: Try this one it will work "rotationY" means it will rotate Y Direction, "rotationX" means it will rotate X Direction
    ObjectAnimator animation = ObjectAnimator.ofFloat(view, "rotationY", 0.0f, 360f);
    animation.setDuration(600);
    animation.setRepeatCount(ObjectAnimator.INFINITE);
    animation.setInterpolator(new AccelerateDecelerateInterpolator());
    animation.start();


Q: ^M characters when using Tramp (on Windows) to connect to Ubuntu Server I've set up Tramp on Emacs on my Windows 7 box (64 bit). For this test, this is the only thing in my emacs-config:
(setq tramp-default-method "plink")
Then I connect to my Ubuntu Server 9.10 running in a VM on my local network.
Connection goes fine, i can use dired to browse folders and open files. Yay!
However, git status shows up as:
Git:master^M
An when i open speedbar all folders and files ends with ^M, ie:
<+> conf/^M
Does anyone know how to prevent this line-ending collision from occurring?

A: don't know if this is it but I had a similar issue that I fixed with this.
(setq default-buffer-file-coding-system 'utf-8-unix)

there's a few people who have asked how to get tramp working on windows(I actually gave up) so if you felt like documenting how you did it, there would likely be legions of thankful windows users out there.

A: (prefer-coding-system 'utf-8) did the trick!
Thanks Tom for the clue... Getting Tramp to work on my windows machine was no trouble at all. I'm using this version of Emacs:
GNU Emacs 23.1.50.1 (i386-mingw-nt6.1.7600)
of 2009-10-15 on LENNART-69DE564

With this in my init.el:
(setq tramp-default-method "plink")
(prefer-coding-system 'utf-8)

Putty directory with plink-app is in my system path.
Then: C-X C-F /username@192.168.0.2: and Tab brings up password prompt then autocompletion on servers-files.


Q: Hiding filter input box instead of disabling + tablesorter 2 I need a little assistance.  I am using a fork of JQuery TableSorter 2 (http://mottie.github.com/tablesorter/) to work and filter my tables.  If i dont want certain columns to be used as filter, I simply need to add "filter-false" as a class to the selected column header.
My main question is whether there is a way I can actually hide the filter boxes on the selected columns instead of just disabling them...
Thanks
Emmanuel

A: Here is the default css:
/* optional disabled input styling */
table.tablesorter thead tr.tablesorter-filter-row input.disabled {
    opacity: 0.5;
    filter: alpha(opacity=50);
}

As seen, a disabled class is applied to those disabled filters, so you can use css to either apply display:none or visibility:hidden to it:
tr.tablesorter-filter-row input.disabled {
    display: none;
}

A: I recommend simply sticking with:
/* optional disabled input styling */
table.tablesorter thead tr.tablesorter-filter-row input.disabled {
   opacity: 0.0;
    filter: alpha(opacity=0);
}

As having that one hidden, removes also the table's inner border thus creating unpleasant visual effect.


Q: AlertDialog not showing when not onCreate I have an Activity that have to show an AlertDialog with a ListView for the user to choose one of the options. When I put the code of the AlertDialog in the onCreate method, it works. But when somewhere else, it doesn't. There are no errors on the console.
Here is where it's called (in the Activity):
@Override
public void onStateChanged(IntegratorState state) {
    switch (state.getState()) {
    case AWAITING_MENU_OPTION:
        IntegratorHelper.showOptionsMenu(state, SitefMenuActivity.this).show();
        break;
    default:
        Toast.makeText(getApplicationContext(), state.getState().name(),
                Toast.LENGTH_LONG).show();
    }
}

And here is where I create the Dialog (in another class):
public static AlertDialog showOptionsMenu(IntegratorState state, Context context) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(state.getGatewayMessageExtra());
    String[] strings;
    strings = state.getGatewayMessage().split(";");

    final List<String> options = Arrays.asList(strings);

    builder.setAdapter(new MenuSaleAdapter(context,
            android.R.layout.simple_list_item_1, options),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == options.size()-1) {
                        // Do a thing
                    } else {
                        // Do other thing
                    }
                }
            });
    return builder.create();
}

private static class MenuSaleAdapter extends ArrayAdapter<String> {

    public MenuSaleAdapter(Context context, int textViewResourceId,
            List<String> objects) {
        super(context, textViewResourceId, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView view = (TextView) super.getView(position, convertView,
                parent);
        view.setTextColor(Color.BLACK);
        return view;
    }
}

I tried to put all the code in the same Activity, but it still doesn't work. The application doesn't freeze or anything, it just don't show the Dialog. Any ideas? Thanks

A: Try changing first part to:
    @Override
    public void onStateChanged(IntegratorState state) {
    switch (state.getState()) {
    case AWAITING_MENU_OPTION:
        IntegratorHelper.showOptionsMenu(state, SitefMenuActivity.this);
        break;
    default:
        Toast.makeText(getApplicationContext(), state.getState().name(),
                Toast.LENGTH_LONG).show();
    }
}

and second part:
public static void showOptionsMenu(IntegratorState state, Activity activity) {
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setTitle(state.getGatewayMessageExtra());
    String[] strings;
    strings = state.getGatewayMessage().split(";");

    final List<String> options = Arrays.asList(strings);

    builder.setAdapter(new MenuSaleAdapter(activity,
            android.R.layout.simple_list_item_1, options),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == options.size()-1) {
                        // Do a thing
                    } else {
                        // Do other thing
                    }
                }
            });
    builder.create().show();
}


Q: How to use cronjobs to run a python script on a webserver thats on the cloud? I am currently trying to create a Discord bot (with Discord.py) that is able to search through Reddit every few hours to see if there is anything new that has been posted in a specific subreddit. Currently, I have a way to scrape Reddit for this information but it is activated through a Discord command. Ideally, I would like for the script to run automatically after a certain time interval instead of being activated through a command.
I am using asyncpraw and discord.py for my code, so it is all in Python.
Additionally, I am using Flask to create a webserver for the bot, and then using Repl.it to host the server for free. I also use cron-job.org to submit a request every five minutes to the webserver in order to keep it running.
I have my files set up as main.py, which contains all information for the Discord bot, commands, and code that activates when the command is entered into the chat, and then a keep_alive.py file that contains the starting of the web server and the thread (I'm not super knowledgeable about Flask so I'm not super clear on what everything does). At the end of main.py, before I enter the discord bot's token, I call a function from keep_alive.py.
So far, I have tried to use cron-job.org to set up a cronjob, but it hasn't worked thus far as I am not super clear on how to go about it. I have also tried using schedule.py or sched.py, but neither has worked.
To my understanding, I need to use a cronjob for the functionality that I want, but I would love some guidance on actually implementing it, especially as far as the organization of files goes and where to call functions for them to activate. Additionally, I would like to find out if there is a way to use cronjobs within Repl.it, because I don't think you can use them from within their console.
Please let me know if you need any more information or code or anything else!
I appreciate any and all help! Thanks!

A: I don't know if this helps you but the way I was able to automate python scripts on my web server was by using a windows 2016 server.
Then creating a .bat file that would run the script like this. Just make sure your file location is set correctly.
python C:\inetpub\wwwroot\top_10_week.py %*

Then use windows task scheduler to schedule the script to run after a certain time, I set mine to 3 hours but I'm sure you can do it every 5 minutes.
https://www.windowscentral.com/how-create-automated-task-using-task-scheduler-windows-10


Q: Incorrect prettier file pattern I'm using prettier to format an angular project but I'm having a little trouble figuring out the correct file pattern.
Using prettier --check src/**/* includes *.pdf files which causes errors.

Using prettier --check src/**/*.ts ignores *.component.ts files.
I could use prettier --check src/**/*(.component.ts|.service.ts|...) an so on but this pattern would be gigantic. I also have to do this for .html en .scss


Q: Missing Method when include require 'test_helper' i'm trying to test using minitest but when running this file with

bin/rails test test/controllers/api/v1/blogs_api_controller_test.rb

But it gives this error

.rvm/gems/ruby-2.3.1/gems/railties-5.1.1/lib/rails/railtie/configuration.rb:95:in
  method_missing': undefined methodweb_console' for
 (NoMethodError) Did you mean?  console

require 'test_helper'

class BlogsApiControllerTest < ActiveSupport::TestCase
  test 'Get all Blogs' do
    assert false
  end
end

Rails version 5.1.1 Ruby 2.3.1
Gem File
source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.1.1'
# Use Puma as the app server
gem 'puma', '~> 3.8.2'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 3.2.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails', '~> 4.1.1'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.6'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'

gem 'kaminari', '~> 0.17.0'
gem 'bootsy', '~> 2.4'
gem 'searchkick', '~> 3.0.2'
gem 'devise', '~> 4.3.0'
gem 'omniauth-facebook', '~> 3.0.0'
gem 'omniauth-google-oauth2', '~> 0.4.1'

gem 'cancancan', '~> 1.15.0'
gem 'paperclip', '~> 5.0.0'
gem 'sitemap_generator', '~> 5.1.0'
gem 'jwt'
gem 'simple_command'

gem 'rack-cors', require: 'rack/cors'

# For admin panel ----------------
gem 'activeadmin', '~> 1.0.0'
# Below are for rails 5
# gem 'inherited_resources', github: 'activeadmin/inherited_resources'
# gem 'ransack',             github: 'activerecord-hackery/ransack'
gem 'draper',              '~> 3.0.1'
# ---------------------

group :development, :test do
  gem 'pry'

  # Use mysql as the database for Active Record
  gem 'mysql2', '~> 0.4.6'
end

group :development do
  gem 'wdm', '>= 0.1.0' if Gem.win_platform?
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console'
  gem 'listen', '~> 3.0.8'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.1'
end

group :production do
  gem 'pg', '~> 0.18.4'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

A: Please put gem 'web-console' into your Gemfile's test section. You can change the following lines
group :development, :test do
  gem 'pry'

  # Use mysql as the database for Active Record
  gem 'mysql2', '~> 0.4.6'
end

with following
group :development, :test do
  gem 'pry'
  gem 'web-console'
  # Use mysql as the database for Active Record
  gem 'mysql2', '~> 0.4.6'
end

And remove web-console from following lines
group :development do
  gem 'wdm', '>= 0.1.0' if Gem.win_platform?
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console' # remove this

Now run following command to update bundles
bundle install