text:
Q: stopSerivce gives null object reference I am trying to stop my service but it gives null object reference. this is my code ......
PendingUpdatesService.java
NetworkStateReceiver networkStateReceiver;
MarkAttendance attendance ;
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    networkStateReceiver = new NetworkStateReceiver(this);
    networkStateReceiver.addListener(this);
    this.registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
   }

@Override
public void onNetworkAvailable() {
    Toast.makeText(this, "NW available", Toast.LENGTH_LONG).show();
    SharedPreferenceSingleton.getInstance().init(getApplication());
    if (SharedPreferenceSingleton.getInstance().getIntPreference(StudentsAttendanceContracts.IF_ATTENDANCE_FAILED) == 1) {
        attendance = new MarkAttendance();
        attendance.updateAttendance(getApplicationContext());
    }
}

@Override
public void onNetworkUnavailable() {
    Toast.makeText(this, "NW not available", Toast.LENGTH_LONG).show();
}

this is a class where i am trying to stop service......
MarkAttendance.java
String mClassId, mStaffId ;

String date, classAttendanceDate;
Context mContext;
SQLiteDatabase mDB;

public void updateAttendance(Context context) {
    this.mContext = context;
    mDB = context.openOrCreateDatabase(DatabaseContracts.BLUEWINGS_STAFF_DB_NAME, Context.MODE_PRIVATE, null);
    SharedPreferenceSingleton.getInstance().init(context);
    mStaffId = String.valueOf(SharedPreferenceSingleton.getInstance().getIntPreference(SharedContracts.TEACHER_STAFF_ID));
    String[] parameter = {"Attendance"} ;
    String query = " SELECT * FROM " + DatabaseContracts.Tables.CheckingDataOnServer.TABLE + " WHERE " + DatabaseContracts.Tables.CheckingDataOnServer.MODULE_NAME + " =? ";
    Cursor cursor = mDB.rawQuery(query, parameter);
    cursor.moveToFirst();
    while(!cursor.isAfterLast()){
        if (cursor.getString(cursor.getColumnIndex(DatabaseContracts.Tables.CheckingDataOnServer.IS_ATTENDANCE_SAVED)).equals("false")){
            mClassId = cursor.getString(cursor.getColumnIndex(DatabaseContracts.Tables.CheckingDataOnServer.CLASS_ID));
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
            classAttendanceDate = cursor.getString(cursor.getColumnIndex(DatabaseContracts.Tables.CheckingDataOnServer.DATE));
            Date attendancedate = null;
            try {
                attendancedate = dateFormat.parse(classAttendanceDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            date = format.format(attendancedate);

            String[] parameters = {mClassId ,date + "%"};
            Cursor studentInfo = mDB.rawQuery(" SELECT * FROM " + DatabaseContracts.Tables.AttendanceTable.TABLE +
                    " WHERE " + DatabaseContracts.Tables.AttendanceTable.CLASS_ID + " =? " +
                    " AND " + DatabaseContracts.Tables.AttendanceTable.ATTENDANCE_DATE + " LIKE ? ", parameters);
            JSONObject attObj = new JSONObject();
            try {
                attObj.put(StudentsAttendanceContracts.FK_STAFF_ID, mStaffId);
                attObj.put(StudentsAttendanceContracts.CLASS_ID, mClassId);
                attObj.put(StudentsAttendanceContracts.ATTENDANCE_DATE, classAttendanceDate);
                JSONArray studentArray = new JSONArray();
                studentInfo.moveToFirst();
                while (!studentInfo.isAfterLast())
                {
                    JSONObject stuObj = new JSONObject();
                    stuObj.put(StudentsAttendanceContracts.STUDENT_ID, studentInfo.getString(studentInfo.getColumnIndex(DatabaseContracts.Tables.AttendanceTable.STUDENT_ID)));
                    stuObj.put(StudentsAttendanceContracts.ATTENDENCE_STATUS, studentInfo.getString(studentInfo.getColumnIndex(DatabaseContracts.Tables.AttendanceTable.ATTENDANCE_STATUS)));
                    studentArray.put(stuObj);
                    studentInfo.moveToNext();
                }
                attObj.put(StudentsAttendanceContracts.ATTENDANCE_KEY, studentArray);
                AsyncWorkerEncrypted mAsyncWorker = new AsyncWorkerEncrypted(context,false);
                mAsyncWorker.delegate = this;
                mAsyncWorker.execute(ServerConnector.MARK_ATTENDANCE, attObj.toString(), RequestConstants.POST_REQUEST, RequestConstants.HEADER_YES, RequestConstants.MARK_ATTENDANCE);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        cursor.moveToNext();
    }
}

@Override
public void onRefresh() {

}

@Override
public void ReceivedResponseFromServer(String output, String REQUEST_NUMBER) {
    switch (REQUEST_NUMBER) {
        case RequestConstants.MARK_ATTENDANCE :
            Boolean response = false  ;
            try {
                JSONObject obj = new JSONObject(output);
                response = obj.getBoolean(StudentsAttendanceContracts.RESPONSE_STATUS);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if(response){
                String[] updateparameterOfCheckingPendingUpdatesTable = {"true", "Attendance", mClassId, date+"%"};
                String Updatequery = " UPDATE " + DatabaseContracts.Tables.CheckingDataOnServer.TABLE + " SET " +
                        "" + DatabaseContracts.Tables.CheckingDataOnServer.IS_ATTENDANCE_SAVED + " =? " +
                        " WHERE " + DatabaseContracts.Tables.CheckingDataOnServer.MODULE_NAME + " =? " +
                        " AND " + DatabaseContracts.Tables.CheckingDataOnServer.CLASS_ID + " =? " +
                        " AND " + DatabaseContracts.Tables.CheckingDataOnServer.DATE + " LIKE ? " ;
                mDB.execSQL(Updatequery, updateparameterOfCheckingPendingUpdatesTable);
                stopService(new Intent(mContext, PendingUpdatesService.class)) ;
                SharedPreferenceSingleton.getInstance().init(mContext);
                SharedPreferenceSingleton.getInstance().writeIntPreference(StudentsAttendanceContracts.IF_ATTENDANCE_FAILED, 0);
            }
            break;
    }
}

enter code here
stopService(new Intent(mContext, PendingUpdatesService.class)) ;
for this line i am getting null object reference for context ....
this is my stacktrace
06-03 12:55:43.051 7714-7714/com.synclovis.bluewingsstaff E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: com.synclovis.bluewingsstaff, PID: 7714
                                                                        java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.content.Context.stopService(android.content.Intent)' on a null object reference
                                                                            at android.content.ContextWrapper.stopService(ContextWrapper.java:539)
                                                                            at com.synclovis.bluewingsstaff.util.MarkAttendance.ReceivedResponseFromServer(MarkAttendance.java:119)
                                                                            at com.synclovis.bluewingsstaff.networkEngine.AsyncWorkerEncrypted.onPostExecute(AsyncWorkerEncrypted.java:178)
                                                                            at com.synclovis.bluewingsstaff.networkEngine.AsyncWorkerEncrypted.onPostExecute(AsyncWorkerEncrypted.java:26)
                                                                            at android.os.AsyncTask.finish(AsyncTask.java:636)
                                                                            at android.os.AsyncTask.access$500(AsyncTask.java:177)
                                                                            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:145)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:6946)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

A: Try replacing getApplicationContext() with this.
Please provide the stacktrace which appears in your logcat when the exception occurs.

A: *

*You are calling the ReceivedResponseFromServer method from the Async task.

*It looks like updateAttendance() is where you would prefer to set the context.

It's hard to tell if it's a threading issue or something else, but a quick fix should be just passing in the context from the async task if you have access to it. That way you need not set the context in updateAttendance() as you're not using it in that method anyway (unless you're using it elsewhere in the class).


text:
Q: How to fix "urllib.error.URLError: " I'm using "urilib.request",but faild,here are error message:
C:\ProgramData\Anaconda3\python.exe "E:/python project/practice.py"
Traceback (most recent call last):
  File "E:/python project/practice.py", line 2, in <module>
    urlrequest.urlopen('https://www.baidu.com')
  File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 525, in open
    response = self._open(req, data)
  File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 548, in _open
    'unknown_open', req)
  File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 503, in _call_chain
    result = func(*args)
  File "C:\ProgramData\Anaconda3\lib\urllib\request.py", line 1387, in unknown_open
    raise URLError('unknown url type: %s' % type)
urllib.error.URLError: <urlopen error unknown url type: https>

see the following code
import urllib.request as urlrequest
urlrequest.urlopen('https://www.baidu.com')

I try to install pyopenssl
pip install pyopenssl

But system remind me:it's already exist

*

*My os is Window

*Python edition:3.7

*IDE:Pycharm

redpajama_set_name: RedPajamaStackExchange


text:
Q: is it possible to generate data model class or structure dynamically ?? in entity framework? currently my WPF application is using entity framework (code first) and i got stuck on a new feature in my project. in this new feature, i need to create tables in MS SQL Server DB  on runtime. these tables will contain random number of columns and they can updated later too.

i am confused on how the data model class will be generated on runtime
(of new tables created in DB)?
and how will i use them in my code too
?

one solution comes up in my mind (i haven't implemented yet)
i should create a new table name "TableNamesandFields" and it will contain new table and column names in it. by using "TableNamesandFields" table i will maintain new table structure.
by using data from "TableNamesandFields" i could create temporary data model of new tables (currently i don't know any way of doing it) and use them in my views
if anyone implemented and handled situation like this please help me out in it

A: WPF4.0 provided ability to databind to dynamic (runtime generated) properties using the DynamicObject,basically, you should inherit DynamicObject (maybe impl INotifyPropertyChanged Interface also), override TryGetMember and TrySetMember method.
I am not familiar with this stuff, so i recommend you take a look at this post(http://miteshsureja.blogspot.com/2011/05/data-binding-improvements-in-wpf-40.html)
or use key word "WPF DynamicObject DataBinding" and ask google.
**just one thing,for your case, you may need a dictionary to maintain dynamic properties(above post use public filed "MyName").


text:
Q: why is thlis list phenomenon in python? n = int(input())
chess =[[]]*n

for i in range(n) :
    for j in range(n):
        chess[i].append(0)

print(chess)

I want to make list as N x N. but this cord make list as N x (N^2). why is thlis list phenomenon?


text:
Q: What function is passed to cb here? So I have a small project containing both frontend (html) and backend (express: server, routers) parts. The project isn't that clean, so the its main operationality is launched directly in html  section. And not much is clear to me here, especially what function is passed to cb (callback) here?
I have the following code in  part of my html page within js project:
            const $ = document.getElementById.bind(document)

            const request = (path, cb) =>
                fetch(path)
                    .then((res) => {
                        if (res.ok) return res.json()
                        throw Error('HTTP error: ' + res.status)
                    })
                    .then(cb)
                    .catch((err) => ($('result').innerHTML = err))

            const main = async () => {
                const pinRequired = new URLSearchParams(document.location.search).get('pin')
                const id = await request(`./qrcode?pin=${pinRequired}`, (json) => {
                    const { qrbase64, deeplink, pin, id } = json
                    $('qrcode').innerHTML = `<img src="${qrbase64}" alt="Red dot" />`
                    $('deeplink').innerHTML = `<a href=${deeplink} target="_blank"> ${deeplink.slice(0, 90)}...</a>`
                    $('pin').innerHTML = pin ? pin : 'Not requested'
                    return id
                })

                setInterval(() => request(`./status?id=${id}`, ({ status }) => ($('result').innerHTML = status)), 1000)
            }

            main().catch(console.log)

Is this (json)? I also don't know why it is in () round brackets, however, it is an object, it cannot be passed as a callback, right?
And I also have a code in another file, which contains /qrcode route of my website. There is a function (quite big, so i'm not posting it, just pointing that it doesn't return function that may be passed as a callback).
If this callback 100% is in another part of the code, as you think, please let me know.

A: If what you're asking about is this callback (json) => { ... } in the code below:
               request(`./qrcode?pin=${pinRequired}`, (json) => {
                    const { qrbase64, deeplink, pin, id } = json
                    $('qrcode').innerHTML = `<img src="${qrbase64}" alt="Red dot" />`
                    $('deeplink').innerHTML = `<a href=${deeplink} target="_blank"> ${deeplink.slice(0, 90)}...</a>`
                    $('pin').innerHTML = pin ? pin : 'Not requested'
                    return id
                });

Then this is what is known as an arrow function.  You can read about them here on MDN.  They are a shortcut syntax for declaring a function that also has a number of implementation differences.
Note, there are some other issues in your code as request() does not return a promise so it does no good to use await on it and you won't get the id back from return id either.
Also note that the request library has been deprecated and generally shouldn't be used for new code.  There is a list of alternatives here, all of which support promises natively.  My favorite in that list is the got() library.


text:
Q: When using Dexterity, can I combine model-driven types with schema-driven types? How do I create a hybrid type (i.e. a type that keeps the convenience of model-driven types but takes advantage of schema-driven types on an as-needed basis)?
My most recent explorations have led me to model-driven dexterity types as the most convenient approach for dexterity development. I've been following this article: http://developer.plone.org/reference_manuals/external/plone.app.dexterity/model-driven-types.html in contrast to schema driven types documented here: http://developer.plone.org/reference_manuals/external/plone.app.dexterity/schema-driven-types.html.
The hybrid approach arose from a problem I've come upon with references, which so far do not behave predictably using model-driven types. I expect that schema-driven definitions will give me more fine-grained control in situations like this.

A: You can create a schema based on a model:
from plone.supermodel import model

class IMySchema(model.Schema):
    model.load('path/to/model.xml')

Any fields defined in the Python schema will take precedence over those with the same name defined in the model.
The model is loaded at the end of the ZCML configuration phase. This means there's a caveat:
 You can't refer to a field from the model at module scope anywhere. For example, registering a default value using the @form.default_value(IMySchema['foo']) decorator will not work, because the field hasn't been loaded yet at the time when the decorator executes at  import time.


text:
Q: Using Magic mock to test Github Api I am basically using magic mock and context manager to test my code, I was successfully able to mock my get_urls function, But I am having trouble mocking out my access_all_repos_pr(): function which contains data of PR newer than 7 days, can anyone help me out on how to mock that data.
Here is the test code for my get_urls():
import unittest
from mock import MagicMock, patch
from contextlib2 import ExitStack
from GithubAPIpackage.GithubAPI import get_urls

class Test_GithubApi(unittest.TestCase):
    def test_get_urls_returns_valid_urls(self):
        with ExitStack() as stack:

            mock_get_urls = stack.enter_context(
                patch("GithubAPIpackage.GithubAPI._fetch_url")
            )
            fake_data = {"current_user_repositories_url": "http://FAKEURL.com"}
            mock_get_urls.return_value = fake_data
            print(type(fake_data))

            result = get_urls()
            self.assertEqual(result, "http://FAKEURL.com")

I want to mock out the response for the function access_all_repo_pr, can anyone help me out in what I need to do exactly to create a mock for my access_all_repo_pr function. Do I need to refactor my code in some way? (relatively new to python)
what I am trying is:
class Test_GithubApi_newer_than_7_days(unittest.TestCase):
    def test_access_all_repo_pr_returns_valid_response(self):
        with ExitStack() as stack:

            mock_access_all_repo_pr = stack.enter_context(
                patch("GithubAPIpackage.GithubAPI._fetch_url")
            )
            fake_data = {"current_user_repositories_url": "http://myfakeurl.com"}
            mock_access_all_repo_pr.return_value = fake_data

            result = access_all_repo_pr()

            self.assertEqual(result, "")

A: Since you are using requests under the hood, may I suggest using responses for your testing? Not trying to skirt the question, but in my experience, I have found this to be the path of least resistance when it comes to writing tests that deal with the requests module. The tests end up being a lot cleaner, safer, and easier to write.


text:
Q: How to send mail after api endpoint is invoked, Django? My application is using React for frontend and Django & Django RestFramework. I am trying to send email. It is not possible from React Side. So what I thought is to create a Model Mail here in django with
class Mail(models.Model):
    MAIL_SENT= (
        ('Y', 'Yes'),
        ('N', 'No'),
    )
    send_to= models.CharField(max_length=120)
    reply_to= models.CharField(max_length=120)
    message= models.TextField()
    subject= models.TextField()
    mail_sent= models.CharField(max_length=1, default="Y", choices=MAIL_SENT)

    def __self__(self):
        return self.send_to

What I want to do is create an API endpoint for Mail and send method at the time of post method.
Can anyone please help me with this?

A: Django provide send_mail function like this:
from django.core.mail import send_mail

send_mail(
    'Subject here',
    'Here is the message.',
    'from@example.com',
    ['to@example.com'],
    fail_silently=False,
)

the docs link:https://docs.djangoproject.com/en/2.2/topics/email/

A: You can use django send_mail function
example:
from django.core.mail import send_mail

send_mail(
    'Subject here',
    'Here is the message.',
    'from@example.com',
    ['to@example.com'],
    fail_silently=False,
)

you must use your mail_port, default from_email and password.
reference: https://docs.djangoproject.com/en/2.2/topics/email/
================================
so you can create your endpoint same like this
from django.core.mail import send_mail
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

class MailSender(APIView):

    def post(self, request, format=None):
        to_email = request.data.get("to_email")
        send_mail(
            'Subject here',
            'Here is the message.',
            'from@example.com',
            ['to_email'],
            fail_silently=False,
        )
        return Response({"message": "e-mail has been sent successfully"},
                        status=status.HTTP_200_OK)

you can also send mail using threading and then return the response.


text:
Q: Get None instead of a string slice if an index range is not valid I want to check if a string starts with "|<any char><any char>TD". I have already verified that the string only contains 0..9, a-z, A-Z, space, ',' and '*'.
Including the regex crate for such a task is too much overhead, instead I think I need something like
fn get_slice(s: &str, range: Range<usize>) -> Option<&str> {
    unimplemented!();
}

It can be used like:
let is_good_string: bool =
  get_slice(s, (0..5)).map_or(false, |v: &str| &v[0..1] == "|" && &v[3..5] == "TD");

Are there any functions in the standard library similar to my get_slice? Is it possible to solve my task with the help of standard library  functions in some other way?

A:
get None instead of slice if index range not valid

There is no function for that in the standard, that I know of.

I want to check if string starts with "|<any char><any char>TD",

But for that goal, I propose a solution that is (in my opinion) more elegant than slicing:
fn is_good(s: &str) -> bool {
    if !s.starts_with('|') {
        return false;
    }
    let mut td_iter = s.chars().skip(3);
    (td_iter.next(), td_iter.next()) == (Some('T'), Some('D'))
}

Playground. It is compatible with any UTF-8 string and will ensure that no panics occur from reading code points outside of string/character boundaries.

A: I agree with E_net4's answer, but for posterity, the literal answer to your question is straight-forward:
use std::ops::Range;

fn get_slice(s: &str, range: Range<usize>) -> Option<&str> {
    if s.len() > range.start && s.len() >= range.end {
        Some(&s[range])
    } else {
        None
    }
}

fn main() {
    assert_eq!(get_slice("", 0..5), None);
    assert_eq!(get_slice("abc", 0..2), Some("ab"));
    assert_eq!(get_slice("abc", 2..5), None);
    assert_eq!(get_slice("abc", 1..2), Some("b"));
    assert_eq!(get_slice("abc", 2..3), Some("c"));
}

Although I'd avoid using this for string slices and use it only on regular slices, due to the UTF-8 nature of strings.


text:
Q: Prototyping a flight path over a Google Map Pretend that you're in an airplane. You can access a Google Map that shows what you're flying over. The map moves with the plane.
I'd like to prototype this. How can I go about doing this?
My thoughts are to take a very high res picture of the flight path. Using some unknown method, I could "zoom in" on part of the image. Every time a new frame is drawn, the map picture should move x pixels to the left... or something like that.

A: What you need is not an image, it's a polyline which defines the route.
You'll be able to "walk" this line by using the defined waypoints and a little bit calculation.
The moving of the map may be achieved by using map.setCenter(currentPosition)
Docs: http://code.google.com/intl/en/apis/maps/documentation/javascript/overlays.html#Polylines


text:
Q: Create a mock Request object in Loopback 4 I've got a Loopback 4 controller, and I want to unit test it.  How do I mock the request parameter?  Here's the constructor to my controller:
  constructor(@inject(RestBindings.Http.REQUEST) private req: Request,
              @service(HttpService) private httpService: HttpService,
              @service(LocalRequestService) private localRequestService: LocalRequestService) {}

I tried mocking it with createStubInstance(Request), but that gave me this error:
Argument of type 'StubbedInstanceWithSinonAccessor<Request>' is not assignable to parameter of type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
  Type 'StubbedInstanceWithSinonAccessor<Request>' is missing the following properties from type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>': get, header, accepts, acceptsCharsets, and 68 more.ts(2345)

A: stubExpressContext can be used.
const context = stubExpressContext();
const controller = new MyController(context.request);

Options can be passed to stubExpressContext.
More..


text:
Q: Basis for the annihilator Let the field $F$ be given by $F=\mathbb{Z}/5\mathbb{Z}$ and let $V=F^3$. Let $S$ be a subspace of $V$ spanned by $v_1=(1,2,3),v_2=(2,1,2)$. I'm now asked to find a basis for $S^0.$
I've tried solving this and I get $(-1/3,-4/3,1)$. Is it right that the $S^0$ has dimension $1$?

A: Since $(v_1,v_2)$ are linearly independent vectors, we have $\dim S = 2$ and indeed
$$ \dim S^{0} = \dim V - \dim S = 3 - 2 = 1. $$
To check your answer, note that we indeed have
$$ \left( -\frac{1}{3}, -\frac{4}{3}, 1 \right) \begin{pmatrix} 1 \\ 2 \\ 3 \end{pmatrix} = -\frac{1}{3} - \frac{8}{3} + 3 = 0, \\
\left( -\frac{1}{3}, -\frac{4}{3}, 1 \right) \begin{pmatrix} 2 \\ 1 \\ 2 \end{pmatrix} = -\frac{2}{3} -\frac{4}{3} + 2 = 0 $$
and so your vector belongs to $S^0$ and spans it by dimensional reasons.
BTW, since you work over $\mathbb{Z}/5\mathbb{Z}$, the $\frac{1}{3}$ stands for the multiplicative inverse of $3$ which is (or, more precisely, can be identified with the equivalence class of) $2$ and so $-\frac{1}{3}$ is identified with $3$. Thus, your spanning vector of $S^0$ can also be written as
$$ (3, 2, 1). $$


text:
Q: Handling questions that have been edited to include answer
Possible Duplicate:
How to handle posts in "Unanswered" lists containing self-answers within question only?

I think we all agree that questions should not be edited to include the correct answer — that just duplicates the information. But what do you recommend doing when it happens anyway? I often see questions like this one where the OP asked a fine question and then later edited it to include the answer he found. Further answers are thus redundant and the question will never get out of the "Unanswered" tab.
Would it be appropriate to cut his answer out of the question and paste it into an answer of my own? On one hand, it feels bad to "steal" his text like that, but it's also feel more "correct" than leaving the question unanswered.

A: First add comment asking the OP to post the solution as separate answer and accepting it.
If the OP is not responding after several days then yes, in my opinion it would be proper to copy the solution, post it as your own answer and removing it from the question maybe leaving some comment to notify what you've done.
Order is important and having the answer as standalone post is vital part of the order, let alone the correct answer resolving the question.

A: Wouldn't it be best for moderators or others to contact the person and tell them to post the answer as an answer and then accept it?
That's what I tend to do. I use a comment to notify the commenter and/or author about posting it as an answer and then accepting it.
I'm thinking gentle education for end users is best.


text:
Q: Java CSV writer fails but data is there I am trying to write the output of a query to a CSV file. I issue three queries to a table with three companies (CompanyA, CompanyB, CompanyC) and output the result of each query to a csv file (A.csv, B.csv, C.csv).
The queries are valid and System.out.println (below) produces correct names.
However, when I check the output files only CompanyC is populated. CompanyA and B are blank. I thought it was only processing the last query so I removed C from the query and still A.csv and B.csv are blank. There's no formatting difference between these names and no nulls or anything that could throw off the output. I just can't figure out why ONE of them always works?
Just to reiterate: the query is valid and the console output is correct and what I'm trying to write to those files:
while (rsGroups.next()) {

    String groupcode = rsGroups.getString("GroupCode");
    String groupname = rsGroups.getString("groupname");
    String sqlGetComms = "Select companyname from companies where groupcode ='" + groupcode + "'";
    System.out.println(sqlGetComms);
    ResultSet rs2 = st.executeQuery(sqlGetComms);
    FileWriter fstream = new FileWriter("C:\\temp\\" + groupname + "comms.csv");
    BufferedWriter out = new BufferedWriter(fstream);

    while (rs2.next()) {
        out.write(rs2.getString("CompanyName") );
        System.out.println(rs2.getString("companyname"));
        out.newLine();
    }
    rs2.close();

    fstream.close();
   // fstream.flush();
}
System.out.println("done");

A: You need out.close(); instead of fstream.close();. This will write, flush, the buffer of the BufferedWriter and close the fstream.
It is a good idea to use the try-with-resources syntax instead of closing oneself. Less messy.
Also use the Files utility class. For instance File Writer is an old convenience class that uses the default operating system encoding. One might prefer full Unicode with UTF-8.


text:
Q: Compute screen location based on initial coords and angle of movement Given initial coordinates (the left and top css properties) of an absolutely positioned element on screen, and an angle of movement, how can I find out the values I should feed to transform: translate to animate the element? (The element would eventually fall off-screen, so one of the final coords will be 0 or window.innerWidth or window.innerHeight.)
For example, starting from left: 0 and top: 0, and given an angle of 90°, the destination point would be at left equal to window.innerWidth and top equal to 0. If the angle is 135°, the element would end up in the bottom right corner, etc. How can I calculate this for any angle?
(transform: translate takes deltas as parameters, not absolute positions; either is fine)

A: It is actually fairly simple trig. Based on the example you have given:

*

*Your known quantities are initial coords { x: 0, y: 0 } and { angle: 90 /* in degrees*/ }

*Find x-distance between initial x-coord and { window.innerWidth if angle is between 90-270 or 0 if angle between 0-90 & 270-360 }

*Find the cosine of angle and multiply it with x-distance

*Find y-distance between initial y-coord and { window.innerHeight if angle between 180-360 or 0 if angle between 0-180 }

*Find the sine of angle and multiply it with y-distance

*Add the initial x-coord with result of cosine * x-distance. This gives new x-coordinate

*Add the initial y-coord with result of sine * y-distance. This gives new y-coordinate

*Add some buffer to xnew and ynew so they fall off screen

For moving the element, you no longer require transform. You can simply add a transition CSS property and define new coords with new class added to that element. JSFiddle Demo
HTH


text:
Q: SQL Server Date Logic - Finding the next reminder date Given the following database table:
StartDate DATETIME  -- day that the reminder period starts
LastReminderDate DATETIME -- the last time the reminder triggered
DayOfMonth INT -- the day of the month to remind the user
Interval INT   -- how often in months to remind the user

How can I figure out the next reminder date based on these values? For example:
StartDate = '6/1/2011'
LastReminderDate = '6/5/2011'
DayOfMonth = 5 -- remind on the 5th of the month
Interval = 2 -- remind every other month

For this particular example, the next reminder date should be 8/5/2011 because it reminds on the 5th of the month every two months. How would I write a function to figure this out?
If LastReminderDate is NULL, then LastReminderDate should be equal to StartDate
UPDATE:
StartDate = '6/1/2011'
LastReminderDate = NULL
DayOfMonth = 5
Interval = 2

In this case, there was no last reminder date. The first time the reminder would occur would be 6/5/2011. The solutions below seem to be returning 8/5 in this case.
Here are some specific rules:

*

*The Reminder should always occur on whatever DayOfMonth is. If DayOfMonth would be illegal for the given month then it should be the last day of that month. For example....if DayOfMonth is 31 and the next reminder date would fall on June 31, then it should be June 30th instead.

*The next reminder date should always be based off of the Last Reminder Date plus the Interval. If Last Reminder Date does not match the Day of Month, then it could potentially be more than what the interval was. For example...if Last Reminder was 6/1/2011 and the interval is 2 months, but the reminder is for the 20th of the month, then the next reminder will be 8/20/2011.

*If there is no last reminder date, then use the Start Date instead of last reminder date...but this will use the earliest date in the future. If start date was 6/1/2011 and day of month is 5, then this will be 7/5/2011 since today is 6/22/2011. If Day of Month was 25 then it would be 6/25/2011

A: DECLARE
@StartDate AS datetime,  -- day that the reminder period starts
@LastReminderDate AS datetime, -- the last time the reminder triggered
@DayOfMonth AS integer, -- the day of the month to remind the user
@Interval AS integer   -- how often in months to remind the user

SET @StartDate = '6/1/2011'
SET @LastReminderDate = '6/5/2011'
SET @DayOfMonth = 5 -- remind on the 5th of the month
SET @Interval = 2 -- remind every other month

SELECT
CASE
   WHEN @LastReminderDate IS NULL
   THEN
     CASE WHEN Day(@StartDate) <= @DayOfMonth
       THEN DateAdd( month, ((Year( @StartDate ) - 1900) * 12) + Month( @StartDate ) - 1, @DayOfMonth - 1 )
       ELSE DateAdd( month, ((Year( @StartDate ) - 1900) * 12) + Month( @StartDate ) - 0, @DayOfMonth - 1 )
     END
  ELSE DateAdd( month, @Interval, @LastReminderDate )
END

The meat of this is the last four lines, the SELECT CASE ... END statement. I provided a whole script that lets you plug in different values, and see how the SELECT CASE ... END behaves for those test values.
But to just use this on your table, use only the last four lines (and remove the @ from the front of the names so they match the table's column names).
You could also generalize this so that Interval doesn't have to be months. If your table had an IntervalType column, you could supply that as the first argument to DateAdd().  See the docs but some common intervals are days, months, years, and so on.
EDIT2: Respect DayOfMonth.

A: Since you want to use the StartDate if there is no LastReminderDate, then you'll want to use COALESCE for that bit of logic: COALESCE(LastReminderDate, StartDate)
Now, get to the last of the previous month: DATEADD(DAY, -DAY(COALESCE(LastReminderDate, StartDate)), COALESCE(LastReminderDate, StartDate))
Finally, add the months and then get to the date that we need:
DATEADD(MONTH, Interval, DATEADD(DAY, -DAY(COALESCE(LastReminderDate, StartDate)) + DayOfMonth, COALESCE(LastReminderDate, StartDate)))

This will potentially go forward less than two months if the date of the last reminder was on a day of the month after the "DayOfMonth" that's configured for the reminder. You should be able to tweak that depending on what your business logic is in that situation.


text:
Q: Prove that $S^{-1}M\otimes_{S^{-1}R} S^{-1}N=S^{-1}M\otimes_R S^{-1}N$ Problem: Let $R$ be a commutative ring, $S\subset R$ multiplicative and $M,N$ $R$-modules. Show that
$$S^{-1}M \otimes_R N=S^{-1}M\otimes_{S^{-1}R} S^{-1}N=S^{-1}M\otimes_R S^{-1}N,$$
where $S^{-1}(\cdot)$ is the localization.
My attempt: Using the cancellation law, and the fact that the functors $S^{-1}(\cdot)$ and $S^{-1}R\otimes_R\cdot$ are isomorphic, I get
\begin{align*}
S^{-1}M \otimes_R N &= S^{-1}M\otimes_{S^{-1}R}(S^{-1}R\otimes_R N)\\
&= S^{-1}M\otimes_{S^{-1}R}S^{-1}N
\end{align*}
Now, how would I go around to prove the second isomorphism? Many thanks in advance!

A: More generally, if $R \to T$ is an epimorphism in the category of commutative rings (for example, every localization $R \to S^{-1} R$) and $M,N$ are two $T$-modules, then the canonical map of $R$-modules
$$M \otimes_R N \to M \otimes_T N$$
is an isomorphism. Since both sides are cocontinuous functors in $M$ and $N$, and $M,N$ are colimits of copies of $T$, it suffices to prove that the canonical map
$$T \otimes_R T \to T$$
is an isomorphism. But this is one of the characterizations of an epimorphism $f : X \to Y$ in a category, namely that the codiagonal $Y \sqcup_X Y \to Y$ is an isomorphism.
Of course, you can also fiddle around with elements to prove the result for localizations. You only need to argue that a $R$-bilinear map $\beta$ between $S^{-1} R$-modules is also $S^{-1} R$-bilinear (and conversely, but the converse is trivial). But $\beta(s^{-1} x,y) = s^{-1} \beta(x,y)$ is equivalent to $s \beta(s^{-1} x,y) = \beta(x,y)$, and the left side is, in fact, equal to $\beta(s s^{-1} x,y)=\beta(x,y)$.


text:
Q: API Gateway custom authorizer I'm new to API Gateway. I try to use the "custom authorizer". I followed below document and used sample code that website provided.
https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html
The "Lambda Authorizer of the TOKEN type" is work.
curl -v -H 'x-custom-auth: xxxxx" https://xxxxx.execute-api.us-west-1.amazonaws.com/Prod/

For the "Lambda Authorizer of the REQUEST type", I can input header, queryValue1, stageValue1 and accountId for testing via aws console.
But...
I'm confused about the "request type" and did not know how to pass the queryValue1, stageValue1 and accountId to API Gateway.
Can anyone help me to figure it out?

A: Regardless of which type of Authorizer you use, API Gateway will receive the same headers and parameters that you originally sent.
Your Authorizer cannot modify the original request details (but it include an auth context which API Gateway can also read).
In the example you're referencing:
if (headers.HeaderAuth1 === "headerValue1"
    && queryStringParameters.QueryString1 === "queryValue1"
    && stageVariables.StageVar1 === "stageValue1"
    && requestContext.accountId === "123456789012") {
    callback(null, generateAllow('me', event.methodArn));
}  else {
    callback("Unauthorized");
}

What they're saying is that the REQUEST authorizer is expecting specific values in the request object:

*

*If all the values match, the authorizer will Allow the request to continue. API Gateway will receive the same request object (with all the same parameters).

*If not all the values match, the authorizer will Deny the request returning 403 Unauthorized; API Gateway will not receive the request.
Each of the properties in the example are sourced in the following ways:

*

*AccountId is set automatically by AWS

*StageVar1 comes from the deployed API's stage settings (API Name > Stages > Stage Name > Stage Variables)

*HeaderAuth and QueryString1 are sent by the HTTP client (e.g. curl)


text:
Q: mysql: Remove records until How can I delete all record, until some conditions happen? For example ordered by date. For example if conditions is non zero val, then first 2 records must be removed:
 val date
 0   10.10.2011
 0   11.10.2011
 3   12.10.2011
 0   13.10.2011
 1   14.10.2011

It can be done with 2 request, but I ask is there better solution.

A: You can use DELETE with a WHERE clause:
DELETE FROM `your_table`
WHERE (val = 0 OR date < '2011-01-31')


text:
Q: flutter PropertyChangeNotifier ignore: mixin_inherits_from_not_object Working with flutter I'm struggling with notifying a model class parameters about changes coming from the Firestore DB.
I'm trying to use plugin property_change_notifier
Using the example:
// ignore: mixin_inherits_from_not_object
class MyModel with PropertyChangeNotifier<String> {
  int _foo = 0;
  int _bar = 0;

  int get foo => _foo;
  int get bar => _bar;

  set foo(int value) {
    _foo = value;
    notifyListeners('foo');
  }

  set bar(int value) {
    _bar = value;
    notifyListeners('bar');
  }
}

I've added the ignore remark and even tried to set the analysis_option.yaml with this rule, but I still get the message:
The class 'PropertyChangeNotifier' can't be used as a mixin because it extends a class other than Object.dart(mixin_inherits_from_not_object)

When I try to build the project it then shows the following error:
 - 'BuildContext' is from 'package:flutter/src/widgets/framework.dart' ('/C:/ngplayground/flutter/packages/flutter/lib/src/widgets/framework.dart').
Try correcting the name to the name of an existing method, or defining a method named 'ancestorWidgetOfExactType'.

      return nullCheck(context.ancestorWidgetOfExactType(type) as PropertyChangeModel);
                               ^^^^^^^^^^^^^^^^^^^^^^^^^
2

FAILURE: Build failed with an exception.

* Where:
Script 'C:\ngplayground\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 991

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.

What is wrong here?

A: you just need to change
class MyModel with PropertyChangeNotifier<String>

to
class MyModel extends PropertyChangeNotifier<String>

and it should work

A: This is the official solution the author introduced on the main page of PropertyChangeNotifier.
https://pub.dev/packages/property_change_notifier#mixin-compilation-error
It is recommended to add // ignore: mixin_inherits_from_not_object over your class.
add ignore comment
Or just extend your class with PropertyChangeNotifier.


text:
Q: MAX(value) with TWO COLUMN I have this value for exemple
 VAL1 VAL2
    04   ZZ
    06   TT
    05   XX
    03   XX
    04   ZZ
    09   TT

I want query that show me the max (last record) of each value of column val2
For exemple , for TT = 09 , XX = 03 , ZZ = 04 .
Can you please provide ? with HANA query if possible ?

A: I don't know hana but SQL looks like this
select val2, max(val1) as maxVal
from myTable
group by val2

FROM SAP -
"The generated SQL ANSI code is compliant and should work on most databases which are not yet supported by the application."
The code ^^ I provided above is pretty much ANSI SQL, which should work in most SQL databases.
More from SAP [ANSI SUPPORT] - "E051-02 -- GROUP BY clause  -- Full Support.....E091-03 -- MAX -- Full Support"


text:
Q: Can't git pull because of unmerged files I'm still very new to git and trying to figure out how everything works. So here's my situation: I've been working on a java project on my laptop. Pushed onto git repository and pulled it on a different machine. Made some changes and pushed onto the repository. Now I want to pull my current work onto my laptop but it's saying I can't because I have unmerged files.
Pull is not possible because you have unmerged files.
Please, fix them up in the work tree, and then use 'git add/rm <file>'

Please help on correcting this issue. Thank you.
$ git status
on branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

You have unmerged paths.
  (fix conflicts and run "git commit")

A: You have two choices: finish the current merge or abort it.

*

*To finish the merge, you first need to check what files are being merged. You can do this with
git status

Now edit the files to resolve all merge conflicts. When you are satisfied that you have restored your code to a working state, you should run
git add .
git commit

*On the other hand, if you want to abort the current merge and remove all local changes, you can do
git reset --hard HEAD

WARNING Be very careful with this command. It will delete all of your local changes and you will not be able to restore them.
Finally, when you have finished either of these actions, you can go ahead with your pull.


text:
Q: LINQ Where clause throws casting exception from string to Guid even though comparison only contains Guids I get the following error when executing a LINQ to SQL statement: The specified cast from a materialized 'System.String' type to the 'System.Guid' type is not valid.
The exception occurs on this line:
IList<DocumentData> dds = hcDbContext.DocumentDatas.Where(d => fileDataSyncIds.Contains(d.FileDataSyncId)).ToList();

d.FileDataSyncId is a Guid and fileDataSyncIds is type IList<Guid>.
There's no string so I don't understand where the error is coming from.
This is the code:
DocumentData zipFile = new DocumentData();
IList<Guid> fileDataSyncIds = hcDbContext.Documents.Where(d => d.EventId == eventId && d.DocumentOwnerTeamId == teamId).Select(d => d.FileDataSyncId).ToList();
//Exception on next line
IList<DocumentData> dds = hcDbContext.DocumentDatas.Where(d => fileDataSyncIds.Contains(d.FileDataSyncId)).ToList();
using (var memoryStream = new MemoryStream()) {
    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) {

        foreach (var dd in dds) {
            var docFile = archive.CreateEntry(dd.Filename);

            using (var entryStream = docFile.Open())
            using (var streamWriter = new StreamWriter(entryStream)) {
                streamWriter.Write(dd.FileData);
            }
        }
    }
    zipFile.Filename = "Event" + eventId.ToString() + "_Team" + teamId + "_Documents.zip";
    zipFile.FileData = memoryStream.ToArray();
}

return zipFile;

A: The problem is most likely in the mapping of the FileDataSyncId field of the DocumentDatas table. In order for the Contains to succeed, the field must be uniqueidentifier in the database, and Guid on the .NET side. The error message suggests that .NET side sees the field as a String, causing the problem.


text:
Q: Unable to capture request and response values into csv by using sample variables Could some one please advise me where am i doing wrong.
When i tried to capture request and response values into csv using sample variables  by adding in the next line to user.properties file: sample_variables=request,response
it's throwing null in the request and response columns in the csv file.
Is there is any another work around to achieve this?

Thanks,
Rajani

A: Please follow the below steps to capture the request URL and response. Alternatively, you can extract the request/response using Bean Shell sampler.

*

*Open JMeter.Properties and configure the sample variables. Restart JMeter.

*In your test plan, create two Regular Expression Extractors for your HTTP request, one is to capture 'request' and another is to capture the 'response'. Use (?s)(^.*) regular expression to extract everything.

To capture the request, configure as shown below. If you want to capture the request headers, select Request Headers radio button.

To capture the response, configure as shown below.

*In the Aggregate report, make sure you checked the options as shown below and provide a name in Filename e.g. google.csv.

*Here is my JMeter test plan for Google.com

*Here is the expected output. Check in the JMETER_HOME\bin\google.csv.


text:
Q: "Error: invalid input syntax for integer:" when inserting NULL values for an SMALLINT column in a Redshift table? I have this locally defined python function that works fine when inserting data into a redshift table:
def _insert_data(table_name, values_list):
    insert_base_sql = f"INSERT INTO {table_name} VALUES"
    insert_sql = insert_base_sql + ','.join([str(row) for row in values_list])
    <run_local_python_code_to_execute_insert_sql>

The values_list is a list of tuples, each with the same number of elements as columns in table_name (even though I don't explicitly assert/check that in this function). However, I'm failing to find a way to insert a NULL value for a smallint column. Here's the schema for the table in question (no DEFAULT values were assigned to columns at table creation):
 schemaname |      tablename      |    column    |         type          | encoding | distkey | sortkey | notnull
------------+---------------------+--------------+-----------------------+----------+---------+---------+---------
 public     | table               | col1         | bigint                | lzo      | t       |       1 | f
 public     | table               | col2         | date                  | lzo      | f       |       2 | f
 public     | table               | col3         | smallint              | lzo      | f       |       3 | f
 public     | table               | col4         | smallint              | lzo      | f       |       4 | f
 public     | table               | col5         | double precision      | none     | f       |       0 | f
 public     | table               | col6         | bigint                | lzo      | f       |       0 | f
 public     | table               | col7         | character varying(48) | bytedict | f       |       0 | f

I'm specifically trying to insert NULL values for col3 and col4; I've tried creating tuples with '' and 'NULL' but run into this error: Error: invalid input syntax for integer: "NULL".
For what it's worth, here's what a scrubbed row ends up looking like in the INSERT statement: ('bigint_value', 'dt_value', 'NULL', 'NULL', 'double_value', 'bigint_value', 'string_name')

A: The approach you are taking is quite dangerous by itself. Constructing queries using string concatenation and formatting is error-prone and not secure - you are making your query vulnerable to SQL injection attacks.
Instead, properly parameterize your query, passing a list of parameters as a separate argument to the cursor.executemany(). Here is one, not quite pretty, way to generate placeholders:
placeholders = ", ".join(["%s"] * len(values_list))
query = f"""
    INSERT INTO
        {table_name}
    VALUES
        ({placeholders})
"""
cursor.executemany(query, values_list)

(note that table name cannot be parameterized - sanitize and validate it separately)
Note the use of executemany() - it would execute a prepared query statement for every tuple in the values_list.
But, if you are using psycopg2, there is an even better way to insert multiple records into the table - execute_values() - take a look at this answer.
And, coming back to your initial question - if you take this approach, None placeholder values would be automatically converted to 'NULL' strings by the database driver.


text:
Q: How do I get a value from a dynamic control? I've got a form with a picturecontrol (default to black bg) and I have a flowlayoutpanel underneath. On the form's load it cycles through a folder of images and creates a thumbnail (picturecontrol) inside the flowlayoutpanel. What I want to do is dynamically add a click event to let the user change the main picturecontrol image with one of the thumbnails.
Private Sub TabImageLoad()
    Dim apppath As String = Application.StartupPath()
    Dim strFileSize As String = ""
    Dim di As New IO.DirectoryInfo(apppath + "\images")
    Dim aryFi As IO.FileInfo() = di.GetFiles("*.*")
    Dim fi As IO.FileInfo

    For Each fi In aryFi
        If fi.Extension = ".jpg" Or fi.Extension = ".jpeg" Or fi.Extension = ".gif" Or fi.Extension = ".bmp" Then
            Dim temp As New PictureBox
            temp.Image = Image.FromFile(di.ToString + "\" + fi.ToString)
            temp.Width = 100
            temp.Height = 75
            temp.Name = fi.ToString
            temp.Visible = True
            temp.SizeMode = PictureBoxSizeMode.StretchImage
            AddHandler temp.Click, AddressOf Me.temp_click
            FlowLayoutPanel1.Controls.Add(temp)
        End If
    Next
End Sub
Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    PictureBox1.Image = temp.Image
End Sub

This is my code for the sub that gets the images (note the addhandler attempt) and the sub that links to the addhandler. As you've probably guessed the addhandler doesn't work because "temp" is not declared in the temp_click sub.
Any suggestions?

A: The sender argument is always the control that triggered the event, in this case a PictureBox:
Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim pb As PictureBox = DirectCast(sender, PictureBox)
    PictureBox1.Image = pb.Image
End Sub

A: I suggest you to use:
Private Sub temp_click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim pbDynamic as PictureBox = trycast(sender,Picturebox)

Then validate with
if pbDynamic IsNot Nothing Then
    PictureBox1.Image = pbDynamic.image
end if

This way you avoid runtime errors and null pointer exceptions


text:
Q: sql having get only the first recorded row in table and i want all Somebody already helped me with this query but I made an adaptation and I get a problem :
    SELECT
        AVG(tyd.price) AS avg_price, COUNT(tyd.id_product) AS cnt,
        tyd.id_marchand, tyd.id_product,
        catalog.price AS c_price, tyd.price AS t_price,
        tyd.amount AS t_am, pro_tyd.amount AS p_am,
        pro_tyd.price AS p_price, catalog.img_src,
        tyd.step, tyd.login AS tyd_l
    FROM catalog
    INNER JOIN tyd ON catalog.id_marchand = tyd.id_marchand
                   AND catalog.id_product =   tyd.id_product
                   AND tyd.step = "1"
    INNER JOIN pro_tyd  ON tyd.id_marchand = pro_tyd.id_marchand
                        AND tyd.id_product = pro_tyd.id_product
    GROUP BY
         catalog.id_product, catalog.id_marchand
    HAVING
         tyd.login = "user1@tyd.fr"

and it only works when tyd.login = "user3@tyd.fr" which is the lower id. doesn't work with user1 or user2...I just can't figure why...! Also it work if i group by tyd.login but in this case the AVG and COUNT function work only on a single line...
Here is the table :
id  id_marchand  id_product   login       price  amount  delay  step    time
29      1           1       user3@tyd.fr   344     1       0      1   1343297500
120     1           1       user1@tyd.fr   54      1       0      1   1343297504
109     1           1       user10@tyd.fr  34      1       0      1   1343298598

When HAVING tyd.login = "user3@tyd.fr" it works perfectly. When user1 or user2 i got 0 lines.
thanks for your help
First subject : Sql, get the average on a group while escaping the where condition

A: The problem is that your query is non deterministic. You are selecting more columns that you are grouping by where the additional columns are not determined by the columns you are grouping by. If the latter had been true, then this would fall into the ANSII standards of SQL, since it is not it is (in my opinion) a failure of MySQL that it allows the statement to run at all. Other DBMS have gone the opposite way, since they cannot determine if certain columns are functions of other columns not contained in the group by, they will now allow any statement with columns in the select list that are not contained within the group by.
To try and simplify the problem take the following dataset (Table T)
ID    Col1    Col2
1     1       1
2     1       3

Running this:
SELECT Col1, MAX(Col2) AS MaxCol2, MIN(Col2) AS MinCol2, AVG(Col2) AS AvgCol2
FROM T
GROUP BY Col1

Will always return
Col1    MaxCol2    MinCol2    AvgCol2
1       3          1          2

However, if you throw ID into the mix
SELECT ID, Col1, MAX(Col2) AS MaxCol2, MIN(Col2) AS MinCol2, AVG(Col2) AS AvgCol2
FROM T
GROUP BY Col1

There is no way of determining which ID will be returned, 1 or 2, the most likely result is
ID    Col1    MaxCol2    MinCol2    AvgCol2
1    1       3          1          2

However there is nothing defined in the SQL to state that the result could not be:
ID    Col1    MaxCol2    MinCol2    AvgCol2
2     1       3          1          2

So if if the above was the result set, and you added HAVING ID = 1 to the query, you would get no results due to the point at which the HAVING clause is applied to the data. If you were to Add ID to the GROUP BY you would end up with 2 rows, which as I understand it is not what you want, and if you were to add it to the WHERE your MIN, MAX and AVG functions would be affected. So you need to use a subquery. So in this example I would use
SELECT  T.ID, T.Col1, MaxCol2, MinCol2, AvgCol2
FROM    T
        INNER JOIN
        (   SELECT Col1, MAX(Col2) AS MaxCol2, MIN(Col2) AS MinCol2, AVG(Col2) AS AvgCol2
            FROM T
            GROUP BY Col1
        ) T2
            ON T.Col1 = T2.Col1
WHERE   ID = 1 -- OR ID = 2 DEPENDING ON REQUIREMENTS

To apply this to your situation, the database engine has deteremined that the row that will be returned for the columns not in the group by is the row containing ID = 29. So your HAVING Clause is only being applied to this row, the rows with user1@tyd.fr, and user10@tyd.fr in have already been removed from the results by the time your HAVING clause is applied. You need to perform the aggregate functions separately to the filtering.
Now I haven't fully got my head around your schema, but I am hoping I have explained the issue of the non deterministic statement well enough that you can make any ammendments required to my attempt at rewriting your query
SELECT  Avg_Price,
        Cnt,
        tyd.id_marchand,
        tyd.id_product,
        catalog.price AS c_price,
        tyd.price AS t_price,
        tyd.amount AS t_am,
        pro_tyd.amount AS p_am,
        pro_tyd.price AS p_price,
        catalog.img_src,
        tyd.step,
        tyd.login AS tyd_l
FROM    Catalog
        INNER JOIN tyd
            ON catalog.id_marchand = tyd.id_marchand
            AND catalog.id_product = tyd.id_product
        INNER JOIN Pro_tyd
            ON tyd.id_marchand = pro_tyd.id_marchand
            AND tyd.id_product = pro_tyd.id_product
        INNER JOIN
        (   SELECT  ID_Marchand, ID_Product, Step, AVG(tyd.price) AS avg_price, COUNT(tyd.id_product) AS cnt
            FROM    Tyd
            WHERE   Step = '1'
            GROUP BY ID_Marchand, ID_Product, Step
        ) Agg
            ON Agg.id_marchand = pro_tyd.id_marchand
            AND Agg.id_product = pro_tyd.id_product
            AND Agg.Step = tyd.Step
WHERE   tyd.Login = 'user1@tyd.fr'

A: i just want to add that this query :
SELECT * FROM  tyd WHERE step = "1"
GROUP BY tyd.id_product, tyd.id_marchand
HAVING tyd.login = "user1@tyd.fr"

Has the same problem. Works when tyd.login = "user3" but not when an other user is ask...


text:
Q: Build failed after adding new main file in NetBeans I am new to NetBeans (switched from Dev) and added a new main file to a project to try to test a few things out (clearly this is not acceptable in NetBeans). Now, even though I've deleted the extra main file, my builds keep failing and I am seeing "No rule to make target newmain.cpp', needed bybuild/Debug/MinGW-Windows/newmain.o'.  Stop" ... so it seems like it's still looking for the extra main file even though I've deleted it. How do I stop this from happening?
UPDATE: found the file and removed it from the project correctly, but deleted the Makefile in the process. How do I recreate the Makefile?


text:
Q: capture String and store it in mongoDB I'm trying to capture a text-generated string (client / session based) for when a user is uploading an image.
Output when doing db.collection.find(); from console when uploading:
"_id" : ObjectId("590c67f472667e031fe80a9d"),
"path" : "uploads/bicycle.jpg",
"originalname" : "bicycle.jpg",
"__v" : 0

Here I want to have "imagelocation" : "N/A" also.
The string is based on a users location when uploading the image.
I want to connect that specific strings value to the image-objects ID as displayed above.
App.js:
/image UPLOAD TO MONGODB

 var bodyParser = require('body-parser');
 var mongoose = require('mongoose');
 var path = require('path');
 app.use(bodyParser.json());

 //To get the access for the functions defined in imagefile.js class
 var routes = require('./imagefile');

 // connect to mongo,
 mongoose.connect('mongodb://localhost:27017/gps');

 app.use('/', routes);

 // To get all the images/files stored in MongoDB
 app.get('/images', function(req, res) {
   routes.getImages(function(err, genres) {
      if (err) {
         throw err;
      }
 res.json(genres);

 });
 });

 app.get('/images/:id', function(req, res) {
    routes.getImageById(req.params.id, function(err, genres) {
    if (err) {
       throw err;
    }

 res.send(genres.path)
 });
 });

path and originalname are declared as follows in my imagefile.js:
var imageSchema = mongoose.Schema({
 path: {
    type: String,
    required: true,
    trim: true
 },
 originalname: {
    type: String,
    required: true
 },
 imagelocation:{ // format for storing
   type: String,
   required: true
 }

});
module.exports = mongoose.model('Image', stringClass);
var Image = module.exports = mongoose.model('files', stringClass);

router.getImages = function(callback, limit) {

 Image.find(callback).limit(limit);
}

router.getImageById = function(id, callback) {

 Image.findById(id, callback);

}

router.addImage = function(image, callback) {
 Image.create(image, callback);
}
//multer
var storage = multer.diskStorage({
 destination: function(req, file, cb) {
 cb(null, 'uploads/')
 },
 filename: function(req, file, cb) {
 cb(null, file.originalname);
 },
 imagelocation: function(req,file,cb){
   cb(null, $('#coordinates').innerHTML);
 }
});

var upload = multer({
 storage: storage
});

router.get('/', function(req, res, next) {
 res.render('layouts/main.handlebars');
});

router.post('/', upload.any(), function(req, res, next) {

 res.send(req.files);

 var path = req.files[0].path;
 var imageName = req.files[0].originalname;
 var imagepath = {};
 imagepath['path'] = path;
 imagepath['originalname'] = imageName;

 router.addImage(imagepath, function(err) {

 });

});

module.exports = router;

HTML:

String is generated here

TL;DR - how would i capture a string and send that along with the image when uploading it to my MongoDB?

A: To send a string a long with your image file, you just send it along with your form on submission. For instance in a hidden input field.
Then, on submission, you can access it as part of the req.body object
Here's an example (from an API, but you get the idea):
app.post('/api/file', function(req, res){
    var upload = multer({
        storage: storage
    }).single('imageFile')
    upload(req, res, function(err){
        if(err){
            // handle any errors here ...
        }
        console.log(req.body)// <-- here you can access your text string as 'req.body.yourStringIdentifier'
        res.json({success: true, msg: 'File uploaded'});
    })
})

If you have any questions feel free to ask :)

Edit: Full example
server.js:
const express = require('express');
const multer = require('multer');
const path = require('path');
const ejs = require('ejs');
var app = express();
app.set('view engine','ejs');

app.get('/', function(req, res){
    res.render('index');
})

var storage = multer.diskStorage({
    destination: function(req, file, callback){
        callback(null, './uploads');
    },
    filename: function(req, file, callback){
        callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
})

app.post('/', function(req, res){
    var upload = multer({
        storage: storage
    }).single('imageFile')
    upload(req, res, function(err){
        console.log(req.body.textInput);
        res.end('File is uploaded');
    })
})

var port = process.env.PORT || 7850
app.listen(port, function(){
    console.log('Listening on port ' + port);
})

index.ejs:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>INDEX</title>

        <form id="uploadForm" enctype="multipart/form-data" method="post">
            <input type="file" name="imageFile">
            <input type="text" name="textInput">
            <input type="submit" value="Upload file" name="submit">
        </form>

This code works when I run it from the terminal with nodemon server.js. When the form is submitted, the contents of the text field is printed to the console.

A: Joel,
     As per the Multer documentation, the Disk Storage
var storage = multer.diskStorage({.....})
engine gives you full control on storing files to disk and it has only two options available, destination and filename. They are both functions that determine where the file should be stored.

*

*Destination is used to determine within which folder the uploaded files should be stored

*Filename is used to determine what the file should be named inside the folder.

Hence your way of defining the multer.diskStorage is wrong.
If you are trying to upload it into MongoDB refer the following link:
https://ciphertrick.com/2017/02/28/file-upload-with-nodejs-and-gridfs-mongodb/
If you want to store the file in disk storage and then upload some information about the file that is stored using your schema
var imageSchema = mongoose.Schema({
   path: {
          type: String,
          required: true,
          trim: true
         },
   originalname: {
          type: String,
          required: true
      },
   imagelocation:{ // format for storing
          type: String,
          required: true
      }

      });

Then make changes in
 var imagepath = {};
 imagepath['path'] = path;
 imagepath['originalname'] = imageName;
  /* provide logic here as mentioned by  David Stenstrøm to read it
     from request.body and move it to the image schema object */

 router.addImage(imagepath, function(err) {

 });

Hope I clarified your query :) :)


text:
Q: Filtering a 2D array with objects in Swift I have create the following struct to display a tableview:
struct Section {
    var heading : String
    var items : [MusicModel]
    init(category: String, objects : [MusicModel]) {
       heading = category
       items = objects
   }
}

Then I have the following function to add objects to the array:
var sectionsArray = [Section]()

func getSectionsFromData() -> [Section] {
    let basicStrokes = Section(category: "Basic Strokes",
    objects: [MusicModel(title: Title.EightOnAHand, author: .None, snare: true, tenor: true)])

    sectionsArray.append(basicStrokes)
    return sectionsArray
}

So the tableview loads just fine with section header and rows for the data. I want to be able to filter the table cells but am having a tough time figuring out the proper syntax to filter an array of objects based on a user selected instrument that is sent to a filtering function. Here is what I have:
func getMusic(instrument: MusicData.Instrument) -> [Section] {
    if instrument == .Tenor {
        let filtered = sections.filter {$0.items.filter {$0.tenor == true}}
        return filtered
    } else {
        let filtered = sections.filter {$0.items.filter {$0.snare == true}}
        return filtered
    }
}

The object is returned only if snare or tenor is true. The error that I am getting is:
Cannot invoke 'filter' with an argument list of type '(@noescape (MusicModel) throws -> Bool)'
Any idea? If you have a suggestion on better way to do this I would greatly appreciate it. Thanks!

A: Use this updated getMusic method,
func getMusic(instrument: MusicData.Instrument) -> [Section] {
    if instrument == .Tenor {
        var filtered = sections.filter {$0.items.filter {$0.tenor == true}.count > 0}
        filtered = filtered.map({ (var section: Section) -> Section in
            section.items = section.items.filter {$0.tenor == true}
            return section
        })
        return filtered
    } else {
        let filtered = sections.filter {$0.items.filter {$0.snare == true}.count > 0}
        filtered = filtered.map({ (var section: Section) -> Section in
            section.items = section.items.filter {$0.snare == true}
            return section
        })
        return filtered
    }
}

A: Or the following one. (Be warned that your Section is struct, which means it'll be copied around.)
func getMusic(instrument: MusicData.Instrument) -> [Section] {
        return sections.map { (var s: Section) -> Section in
            s.items = s.items.filter { instrument == .Tenor ? $0.tenor : $0.snare }
            return s
        }
    }


text:
Q: ActiveRecord where included record's attribute is compared to original record's attribute If I have models like AModel, BModel, and CModel, I want to do an ActiveRecord query something like
AModel.includes(:b_model).where.not('b_model.c_model_id = ?', AModel.c_model.id)

The only trouble that I'm having with that query is that last part
AModel.c_model_id

which is trying to refer to the current AModel record. Is it possible to refer back to AModel's c_model_id attribute using that query?

A:
Is it possible to refer back to AModel's c_model_id attribute using that query?

No, this isn't possible. This is a smell of circular referencing database models, which should be avoided. Re-evaluate your database schema, or post a more specific use case to work through the problem with a better data structure.


text:
Q: If $u,v\in H_0^1(\Lambda,\mathbb R^d)$ are divergence-free, does $(u\cdot\nabla)v$ belong to $L^2(\Lambda,\mathbb R^d)$? Let

*

*$\Lambda\subseteq\mathbb R^d$ be open

*$\mathcal V:=\left\{v\in C_c^\infty(\Lambda)^d:\nabla\cdot v=0\right\}$, $$V:=\overline{\mathcal V}^{\left\|\;\cdot\;\right\|_{H^1(\Lambda,\:\mathbb R^d)}}$$ and $$H:=\overline{\mathcal V}^{\left\|\;\cdot\;\right\|_{L^2(\Lambda,\:\mathbb R^d)}}=\overline V^{\left\|\;\cdot\;\right\|_{L^2(\Lambda,\:\mathbb R^d)}}\tag 1$$

Note that $H$ is a closed subspace of $L^2(\Lambda,\mathbb R^d)$ and hence there is a unique orthogonal projection $\operatorname P_H$ from $L^2(\Lambda,\mathbb R^d)$ onto $H$. Moreover, if $\Lambda$ is bounded and $\partial\Lambda$ is Lipschitz, then $$V=\left\{u\in H_0^1(\Lambda,\mathbb R^d):\nabla\cdot u=0\right\}\;.\tag 2$$

Now, I've seen some authors claiming that $$B(u,v):=\operatorname P_H\left[(u\cdot\nabla)v\right]\;\;\;\text{for }u,v\in V$$ is a well-defined bounded bilinear operator from $V\times V$ to $H$ (see page 2). However, I don't think that $B$ is well-defined, since I doubt that $(u\cdot\nabla)v\in L^2(\Lambda,\mathbb R^d)$ for all $u,v\in V$.

We would need to show that $$u_j\frac{\partial v_i}{\partial x_j}\in L^2(\Lambda)\tag 3$$ for all $i,j\in\left\{1,\ldots,d\right\}$, but while the Sobolev inequalities yield $$W_0^{1,\:p}(\Lambda)\subseteq L^q(\Lambda)\;\;\;\text{for all }q\in[1,p^\ast]\;.\tag 4$$ for all $p\in[1,d)$ and $p^\ast:=dp/(d-p)$, we only know that the weak partial derivatives of $w\in W_0^{1,\:p}(\Lambda)$ are in $L^p(\Lambda)$.

So, what am I missing?


text:
Q: Does the ternary operator work in constant definition? Why do I get a compiler error when using a ternary operator in the assignment of a CGSize const like this?
CGSize const ksizeSmall = SOME_BOOLEAN_VARIABLE ? {187, 187} : {206, 206};

it does work like this...
CGSize const ksizeSmall = {187, 187};

however, I want to add a boolean expression to evaluate whether I should use one size vs. the other size. I don't want to use if / else because I have a long list of CGSize to set specifically for different purposes.

A: {187, 187} and {206, 206} aggregates are valid as an initialization expressions, but not as a general-purpose expressions*. That is why a ternary operator does not allow it.
If you are making an initializer for a local constant, you could use CGSizeMake:
CGSize const ksizeSmall = SOME_BOOLEAN_VARIABLE ? CGSizeMake(187, 187) : CGSizeMake(206, 206);

If SOME_BOOLEAN_VARIABLE is a compile-time constant expression, you could use conditional compilation instead:
#if SOME_BOOLEAN_VARIABLE
CGSize const ksizeSmall = {187, 187};
#else
CGSize const ksizeSmall = {206, 206};
#endif

* gcc compiler has a C language extension that offers a special syntax for doing this. It was available in Objective-C as well. However, this extension is not part of the language.


text:
Q: Which version of Ubuntu should I use? I just bought a laptop (Sony Vaio fit 15), is a touch laptop with 8GB RAM, i7 processor (2.00 - 3.10ghz). I have installed Windows 8.1, and I would like to know which exact version of Ubuntu should I buy or download to get the maximum performance.
I'm not an Ubuntu user and I do not know much about Ubuntu, but I want to get started in this.

A: I think you would like to be using the latest features in Ubuntu and start playing with it and your not worried about 5 year extended support because you will be upgrading to Ubuntu 14.04 if you start using it soon so my recommendation is to install the latest stable Ubuntu version:
http://www.ubuntu.com/download/desktop/thank-you?release=latest&bits=64&distro=desktop&status=zeroc
If you like a nice interface and very simple to use:
https://wiki.ubuntu.com/UbuntuGNOME/GetUbuntuGNOME
There are more if you wish to look arround but my favourite is Gnome Ubuntu.
PS: Remember to use the 64 bit version of Ubuntu to use all your RAM and get the best performance.
I think Gnome Ubuntu is much better for touch screens :)

A: I'd recommend that you use the LTS version.  The support will be better.
http://www.howtogeek.com/162768/should-you-use-ubuntu-lts-or-upgrade-to-the-latest-release/


text:
Q: Get rid of default text I am trying to parse a user's event descriptions after obtaining access to their google calendar through the google calendar API. When I input the description into my program, I want to get rid of default (and useless) text such as Zoom meeting invitations. If the following below is the description string

Hi, please keep this text.

Bob is inviting you to a scheduled Zoom meeting.

Topic: Bob\'s Personal Meeting Room

Join Zoom Meeting

https://us04web.zoom.us/j/4487518794?pwd=SkdaTE9nV3E1M3FSaWplOHYvNGlndz09

Meeting ID: 448 751 8#94

Password: 1F9W2P

Also not Zoom default text.

How can I parse it so that only "Hi, please keep this test. Also not Zoom default text" remains?

A: Methodology
I think this would be a good use for Regular Expressions or RegEx. This is essentially a pattern-matching standard that allows for generalizing a certain structure in a string. While use in HTML and XML is not a good idea as it is not designed to extract any information you may be looking for, it should work if all you want to do is discard certain sections.
Explanation
If I understand correctly, you would like to be left with

Hi, please keep this text.

Also not Zoom default text.

Which means we need to come up with a pattern to match the following portion(the brackets indicating the information that will swap every time):

[Name] is inviting you to a scheduled Zoom meeting.

Topic: [Name]\'s Personal Meeting Room

Join Zoom Meeting

[Link]

Meeting ID: [ID]

Password: [Password]

Important Pieces:

*

*The beginning: [Name] will be some string of at least one character. To make sure you don't match
Hi, please keep this text.
, the part we want to match any characters that aren't "
" (this is represented in regex with [^(?:
)]), where "character" means anything other than a line break. The rest of the sentence should be matched word for word, so we're not just matching anything.

*The end: [Password], like [Name], is just [^(?:
)] for the same reason.

*This string starts and ends with "
". This should be reflected in the regex

*Everything between that first sentence and the password portion, even
though they have a format, they are wildcards, some mix of at least
one character or linebreak (represented in regex with
(.|\n)+)
Replacing all of the appropriate portions in the text, you get the following:

[^(?:
)]+? is inviting you to a scheduled Zoom meeting.+?Password: [^(?:
)]+?

Code
As for the Python, the re module will come in handy here as your regex aid:
We want to save the above pattern into a variable, and use the information to cut the appropriate portion out of the string.
To "save" the pattern, the re module allows you to compile the regex into an object (the r before the string indicates that it contains regex)
import re
zoom_pattern = re.compile(r"
[^(?:
)]+? is inviting you to a scheduled Zoom meeting.+?Password: [^(?:
)]+?
")

The module also provides the ability to split replace regex matches within strings, and we can replace our match with nothing to cut it out of the string:
import re
s = " - string with zoom meeting stuff - "
zoom_pattern = re.compile(r"
[^(?:
)]+? is inviting you to a scheduled Zoom meeting.+?Password: [^(?:
)]+?
")

clean_string = zoom_pattern.sub("", s)

Since we compiled the pattern, you now have a reusable way to clean up your string!
If you'd like to change your regex to match each individual thing, just adjust the "Important points" from earlier to match your goal. If you want to test your ideas, this is a wonderful resource!


text:
Q: Unable to summarize the minimum and maximum while using for loop Below is random data.
drop    drop1   drop2   ch
15  14  40  1
20  15  45  1
35  16  90  1
40  17  70  0
25  18  80  0
30  18  90  0
11  20  100 0
13  36  11  0
16  70  220 0
19  40  440 1
25  45  1   1
35  30  70  1
40  40  230 1
17  11  170 1
30  2   160 1

I am using code below for variable profiling for continuous variable in R.
library(dplyr)
dt %>% mutate(dec=ntile(drop, n=2)) %>%
  count(ch, dec) %>%
  filter(ch == 1) -> datcbld

datcbld$N <- unclass(dt %>%
                       mutate(dec=ntile(drop, n=2)) %>%
                       count(dec) %>%
                       unname())[[2]]
datcbld$ch_perc <- datcbld$n / datcbld$N
datcbld$GreaterThan <- unclass(dt %>% mutate(dec=ntile(drop, n=2)) %>%
                                 group_by(dec) %>%
                                 summarise(min(drop)))[[2]]
datcbld$LessThan <- unclass(dt %>%
                              mutate(dec=ntile(drop, n=2)) %>%
                              group_by(dec) %>%
                              summarise(max(drop)))[[2]]
datcbld$Varname <- rep("dt", nrow(datcbld))

And below is output of the code.
ch  dec n   N   ch_perc GreaterThan LessThan    Varname
1   1   4   8   0.5 11  25  drop
1   2   5   7   0.714285714 25  40  drop

This code works perfectly fine when I am using it for a single variable.
When I am trying to run it for each column using a for loop it is unable to summarise with min and max for each decile.
Below is my code using for running for loop.
finaldata <- data.frame()

for(i in 1:(ncol(dt) - 1)){
  dt %>%
    mutate(dec=ntile(dt[, colnames(dt[i])], n = 2)) %>%
    count(ch,dec) %>%
    filter(ch == 1) -> dat
  dat$N <- unclass(dt %>%
                     mutate(dec=ntile(dt[, colnames(dt[i])], n=2)) %>%
                     count(dec) %>%
                     unname())[[2]]
  dat$ch_perc <- dat$n / dat$N
  dat$GreaterThan <- unclass(dt %>%
                               mutate(dec=ntile(dt[, colnames(dt[i])], n=2)) %>%
                               group_by(dec) %>%
                               summarise(min(dt[, colnames(dt[i])])))[[2]]
  dat$LessThan <- unclass(dt %>%
                            mutate(dec=ntile(dt[, colnames(dt[i])], n=2)) %>%
                            group_by(dec) %>%
                            summarise(max(dt[, colnames(dt[i])])))[[2]]
  dat$Varname <- rep(colnames(dt[i]), nrow(dat))
  finaldata <- rbind(finaldata, dat)
}

But I'm unable to get same result.

A: We could do this with map by looping over the names and this can be done without breaking off the chain (%>%)
library(tidyverse)
names(dt)[1:3] %>%
     map_df(~
           dt %>%
            select(.x, ch) %>%
            mutate(dec = ntile(!! rlang::sym(.x), n = 2)) %>%
            group_by(dec) %>%
            mutate(N = n(),
                   GreaterThan = max(!!rlang::sym(.x)),
                   LessThan = min(!!rlang::sym(.x))) %>%
            select(-1) %>%
            count(!!! rlang::syms(names(.))) %>%
            filter(ch == 1)%>%
            mutate(ch_perc = n/N,
                   Varname = .x))
# A tibble: 6 x 8
# Groups:   dec [2]
#    dec    ch     N GreaterThan LessThan     n ch_perc Varname
#  <int> <int> <int>       <dbl>    <dbl> <int>   <dbl> <chr>
#1     1     1     8          25       11     4   0.5   drop
#2     2     1     7          40       25     5   0.714 drop
#3     1     1     8          18        2     5   0.625 drop1
#4     2     1     7          70       20     4   0.571 drop1
#5     1     1     8          90        1     5   0.625 drop2
#6     2     1     7         440       90     4   0.571 drop2

The issue in the OP's for loop is the use of
dt[, colnames(dt[i])]

within summarise.  It will apply the min or max on the full column value instead of applying the function on the column respecting the group by structure
We could convert the column names to symbols as showed above (sym) and do an evaluation or use summarise_at
finaldata <- data.frame()
 for(i in 1:(ncol(dt) - 1)){
  dt %>%
    mutate(dec=ntile(dt[, colnames(dt[i])], n = 2)) %>%
    count(ch,dec) %>%
    filter(ch == 1) -> dat
  dat$N <- unclass(dt %>%
                     mutate(dec=ntile(dt[, colnames(dt[i])], n=2)) %>%
                     count(dec) %>%
                     unname())[[2]]
  dat$ch_perc <- dat$n / dat$N
  dat$GreaterThan <- unclass(dt %>%
                               mutate(dec=ntile(dt[, colnames(dt[i])], n=2)) %>%
                               group_by(dec) %>%
                               summarise(max(!! rlang::sym(names(dt)[i]))))[[2]]

  dat$LessThan <- unclass(dt %>%
                            mutate(dec=ntile(dt[, colnames(dt[i])], n=2)) %>%
                            group_by(dec) %>%
                            summarise(min(!! rlang::sym(names(dt)[i]))))[[2]]

  dat$Varname <- rep(colnames(dt[i]), nrow(dat))
  finaldata <- rbind(finaldata, dat)
}

finaldata
# A tibble: 6 x 8
#     ch   dec     n     N ch_perc GreaterThan LessThan Varname
#  <int> <int> <int> <int>   <dbl>       <dbl>    <dbl> <chr>
#1     1     1     4     8   0.5            25       11 drop
#2     1     2     5     7   0.714          40       25 drop
#3     1     1     5     8   0.625          18        2 drop1
#4     1     2     4     7   0.571          70       20 drop1
#5     1     1     5     8   0.625          90        1 drop2
#6     1     2     4     7   0.571         440       90 drop2

data
dt <- structure(list(drop = c(15L, 20L, 35L, 40L, 25L, 30L, 11L, 13L,
16L, 19L, 25L, 35L, 40L, 17L, 30L), drop1 = c(14L, 15L, 16L,
17L, 18L, 18L, 20L, 36L, 70L, 40L, 45L, 30L, 40L, 11L, 2L), drop2 = c(40L,
45L, 90L, 70L, 80L, 90L, 100L, 11L, 220L, 440L, 1L, 70L, 230L,
170L, 160L), ch = c(1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L,
1L, 1L, 1L, 1L)), .Names = c("drop", "drop1", "drop2", "ch"),
 class = "data.frame", row.names = c(NA,
-15L))


text:
Q: EDISMAX - 0 weight for QF field I came across an example EDISMAX query with 0 weight assigned to a field in qf.
Example:
Fields in index: title, body, keywords
qf = title^100 body^0 keywords
I understand providing no boost indicates default boost of 1. I however do not understand what it means to assign a boost factor of 0.
Thank you.


text:
Q: How to attach a JSON web token in axios In React i send the data and Headers like below:
 axios.post("http://localhost:3000/stockdata",{
                    // data
                    },{headers: {
                        'authorization': "Bearer "+LocalStorage.get('token'),
                        'Accept' : 'application/json',
                        'Content-Type': 'application/json'
                    }
                })

In Index.js
//required all the modules
    var stockDataRouter = require('./Routers/stockDataRouter')
    app.use('/stockdata', authenticateToken, stockDataRouter)

    app.route('/login')
    .options(cors.corsWithOptions, (req,res)=>{ res.sendStatus(200)})
    .post(cors.cors, (req, res, next) => {

    console.log(req.header)
    if(req.body.username==='admin' && req.body.password==='password'){
        const user = {
            username: req.body.username,
        }
        jwt.sign({user:user}, 'secretkey',(err, token)=>{
        res.json({
                token: token
            })
        })
          }
          else{
              res.sendStatus(403)
          }
      })

    function authenticateToken(req,res,next){
        const bearerHeader = req.headers['authorization']
        console.log(req.headers)
        if(typeof bearerHeader !== 'undefined'){
            const bearer = bearerHeader.split(' ');
            const bearerToken = bearer[1];
            req.token = bearerToken;
            next();
        }
        else{
            console.log('hihihi')
            res.sendStatus(403);
        }
    }

if the request have the token then it wont go into the else part ,i can access the stockdata endpoint. but even though am passing the token properly as you can see it in chrome dev tools. Why its not getting reflected in the backend.
req.headers is not having authorization in it.

In chrome dev tools We can clearly see the Token

how to solve this?

A: Check in Request Headers in chrome DevTools or etc. Is authorization presented there?

What is on BE side, may be you should check it?

A: You need to change your client side code to
//Try like this
axios.interceptors.request.use(function (config) {
    config.headers.Authorization =  "Bearer " + LocalStorage.get('token');
    return config;
});

axios.post("http://localhost:3000/post",{
                    // data
                    },{headers: {
                       // 'authorization': "Bearer " + LocalStorage.get('token'),
                        'Accept' : 'application/json',
                        'Content-Type': 'application/json'
                    }
                })

as you are splitting the authorization string at the backend


text:
Q: Синхронизация баз MySql У меня есть сервер. На нем крутится сайт с базой (глобальный). Есть 2 локальных сервера, в каждого своя БД, но она точно такая как на глобальном. В каждой базе в таблицах есть понятие server_id. Например, в первого локального он равен 1, во второго - 2.
Суть задачи: если что то изменилось на глобальном (вставка, удаление, редактирование), надо что бы данных передались на нужный локальный сервер. И наоборот: если на локальном что то изменилось - глобальный должен получить эти изменения.
Можно что бы это происходило не моментально, а по крону (на локальном может быть обрыв интернета).
Все сайты написаны на php (фреймворк Yii2)


text:
Q: How to link python3 to a specific version of opencv? I successfully compiled and installed OpenCV 4.5.0, but when I use python3 to import cv2, I find that the version of cv2 is 4.5.1. Like the following output:
Python 3.6.9 (default, Oct  8 2020, 12:12:24)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> print(cv2.getBuildInformation())

General configuration for OpenCV 4.5.1 =====================================
  Version control:               4.5.1-dirty

  Platform:
    Timestamp:                   2021-01-02T12:47:39Z
    Host:                        Linux 5.4.0-54-generic aarch64
    CMake:                       3.18.4
    CMake generator:             Unix Makefiles
    CMake build tool:            /bin/gmake
    Configuration:               Release

 .........

  Python 3:
    Interpreter:                 /opt/python/cp36-cp36m/bin/python (ver 3.6.12)
    Libraries:                   libpython3.6m.a (ver 3.6.12)
    numpy:                       /tmp/pip-build-env-c03ewnak/overlay/lib/python3.6/site-packages/numpy/core/include (ver 1.19.3)
    install path:                python

  Python (for build):            /bin/python2.7

  Install to:                    /tmp/pip-req-build-zuuo394f/_skbuild/linux-aarch64-3.6/cmake-install
-----------------------------------------------------------------

When I open /tmp, I can't find folder /pip-req-build-zuuo394f.
But when I use python(2.7.17), I get the right version of opencv:
Python 2.7.17 (default, Sep 30 2020, 13:38:04)
[GCC 7.5.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> print(cv2.getBuildInformation())

General configuration for OpenCV 4.5.0 =====================================
  Version control:               unknown

  Extra modules:
    Location (extra):            /home/xana/opencv_contrib/modules
    Version control (extra):     unknown

  Platform:
    Timestamp:                   2021-04-07T04:04:29Z
    Host:                        Linux 4.9.140-tegra aarch64
    CMake:                       3.10.2
    CMake generator:             Unix Makefiles
    CMake build tool:            /usr/bin/make
    Configuration:               RELEASE

.......

  cuDNN:                         YES (ver 8.0.0)

  Python 2:
    Interpreter:                 /usr/bin/python2.7 (ver 2.7.17)
    Libraries:                   /usr/lib/aarch64-linux-gnu/libpython2.7.so (ver 2.7.17)
    numpy:                       /usr/lib/python2.7/dist-packages/numpy/core/include (ver 1.13.3)
    install path:                lib/python2.7/dist-packages/cv2/python-2.7

  Python 3:
    Interpreter:                 /usr/bin/python3 (ver 3.6.9)
    Libraries:                   /usr/lib/aarch64-linux-gnu/libpython3.6m.so (ver 3.6.9)
    numpy:                       /usr/lib/python3/dist-packages/numpy/core/include (ver 1.13.3)
    install path:                lib/python3.6/dist-packages/cv2/python-3.6

  Python (for build):            /usr/bin/python2.7

  Install to:                    /usr
-----------------------------------------------------------------

And in python2's cv2, all functions in cv2 worked.
So how can I change the cv2 version in python3? Thanks a lot!

A: I follow @Peter's suggestion print(cv2). I find a cv2.so in /home/.local/lib/python3.6/site-packages/cv2 folder, but my OpenCV 4.5.0 was installed in usr/lib/python3.6/dist-packages/cv2.
Then, I removed the cv2 folder in /home/..., and I import cv2 again, and cv2.__version__ now is 4.5.0 and all functions worked.


text:
Q: convert a list of strings to list of type dynamic Im trying to use a MultiSelectFormField to create a drop down list with multiple choices.The datasource for the MultiSelectFormField is required in the below format,
                 dataSource:[
                              {
                                "display": "Running",
                                "value": "Running",
                              },
                              {
                                "display": "Climbing",
                                "value": "Climbing",
                              },
                              {
                                "display": "Walking",
                                "value": "Walking",
                              },
                            ],

but what I have is a list of type string containing the value sthat should be displayed in the drop down.My question is how can I convert
list<String> dropDownValues=["Running","Climbing","Walking"]

to the format required

A: Please use the map operator
final dropDownValues=["Running","Climbing","Walking"];

final data = dropDownValues.map((el) => {"display": el,"value" el,}).toList();


text:
Q: Secure Web API with token c# I created a mobile app with Cordova, with 2 Login methods Facebook and Google. I after I authenticate the token (FB or Google) I want to use one of them to secure my Web API 2 and communicate with my APP, but I don't know where to store it in the web API, I saved it to Thread.CurrentPrincipal but it returns null later.
This is my code:
    public bool UserExist(Credentials credentials,ISQLDB socialDB,IEncrypt encrypt)
    {
        bool exist = false;
        //IPrincipal principal;

        if (credentials.fb_access_Token != "")
            exist =CheckFB(credentials.fb_access_Token);
        else if (credentials.Google_token != "")
            exist= CheckGoogle(credentials.Google_token);

        if(exist==true)
        {
            var identity = new GenericIdentity(credentials.Token);
            SetPrincipal(new GenericPrincipal(identity, null));
            return true;
        }
        else
            return false;
    }

    private void SetPrincipal(IPrincipal principal)
    {
        Thread.CurrentPrincipal = principal;
        if (HttpContext.Current != null)
        {
            HttpContext.Current.User = principal;
        }

    }

Web API secure is a complicated thing to me, I don't know why, so I appreciate your help.

A: I use custom middlewares for tokens something like this:
   public class TokenAuthenticationOptions : AuthenticationSchemeOptions
{

}

public class TokenAuthentication : AuthenticationHandler<TokenAuthenticationOptions>
{

    public const string SchemeName = "TokenAuth";

    public TokenAuthentication(IOptionsMonitor<TokenAuthenticationOptions> options,
        ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
            : base(options, logger, encoder, clock)
    {
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        return Task.Run(() => Authenticate());
    }

    private AuthenticateResult Authenticate()
    {
        string token = Context.Request.Query["token"];
        if (token == null) return AuthenticateResult.Fail("No JWT token provided");
        try
        {
            var principal = LoginControl.Validate(token);
            return AuthenticateResult.Success(new AuthenticationTicket(principal, SchemeName));
        }
        catch (Exception)
        {
            return AuthenticateResult.Fail("Failed to validate token");
        }

    }
}

It makes it easier for modifications. You can then have this in your startup:
services.AddAuthentication(TokenAuthentication.SchemeName)
    .AddScheme<TokenAuthenticationOptions, TokenAuthentication>
                (TokenAuthentication.SchemeName, o => { });

A: You cannot "save the token", since the API is stateless, this meaning (among other things) that should not keep track of the clients that are calling and their corresponding auth tokens (sessions).
That said, you need to pass the token every time, and have an authorization middleware defined in your OWIN pipeline, to validate the token sent. This is an example using IdentityServer
public void Configuration(IAppBuilder app)
        {
            // accept access tokens from identityserver and require a scope of 'api1'
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
                {
                    Authority = "http://localhost:5000",
                    ValidationMode = ValidationMode.ValidationEndpoint,
                RequiredScopes = new[] { "api1" }
            });

        // configure web api
        var config = new HttpConfiguration();
        config.MapHttpAttributeRoutes();

        // require authentication for all controllers
        config.Filters.Add(new AuthorizeAttribute());

        app.UseWebApi(config);
    }

Additional example from MS Docs
public void ConfigureAuth(IAppBuilder app)
    {
        // Enable the application to use cookies to authenticate users
        app.UseCookieAuthentication(CookieOptions);

        // Enable the application to use a cookie to store temporary information about a user logging in with a third party login provider
        app.UseExternalSignInCookie(ExternalCookieAuthenticationType);

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions, ExternalOAuthAuthenticationType);

        // Uncomment the following lines to enable logging in with third party login providers
        //app.UseMicrosoftAccountAuthentication(
        //    clientId: "",
        //    clientSecret: "");

        //app.UseTwitterAuthentication(
        //    consumerKey: "",
        //    consumerSecret: "");

        //app.UseFacebookAuthentication(
        //    appId: "",
        //    appSecret: "");

        //app.UseGoogleAuthentication();
    }


text:
Q: svn add * --force does not add recursive svn add * --force

I am on window and using Tortoise SVN. I want to add all new files with single task.
I tried all solutions which I found, but that does not add recursively.
I only see add icon on files/directories in current directory only. How can I do this for all sub files/ recursively.
After this command I can not see add (+) icon on subdirectories/files.
I also tried
svn add <directory>

But this also add only current directory, not its all child.

A: I was surprised why the svn add * command is not adding its files recursively. Because recursive adding is default property. You can see in SVN book.
Issue was in properties of my Tortoise-SVN.
I got solution google issue tracker.

*

*Right click in your repo in window. Select TortoiseSVN > Properties.

*See if you don't have a property svn:global-ignores with a value of *

*If you have property with star(*) then it will ignore recursive adding. So remove this property.

This guy also explained why this property added in my project.
The most like way that it got there is that someone right-clicked a file without any extension and selected TortoiseSVN -> SVN Ignore -> * (recursively), and then committed this.

You can check the log to see who committed that property change, find
  out what they were actually trying to do, and ask them to be more
  careful in future. :)