text:
Q: Can I use the claim device feature in the community edition of thingsboard The MQTT-API from thingsboard describes:

Claiming devices
Please see the corresponding article to get more information about the Claiming devices feature.
In order to initiate claiming device, send PUBLISH message to the following topic:
v1/devices/me/claim

The supported data format is:
{"secretKey":"value", "durationMs":60000}

Please note that the above fields are optional. In case the secretKey is not specified, the empty string as a default value is used. In case the durationMs is not specified, the system parameter device.claim.duration is used (in the file /etc/thingsboard/conf/thingsboard.yml).

But here are some problems. Devices must be authenticated with a access-token. But the claim process is for unknown devices.
Is it necessary to import the device to thingsboard before I can start the claim process?
What is the real procedure?

A: I think you are confusing claiming and provisioning.
Claiming it's when a customer becomes the owner of an already existing device in the tenant, in this state the device it's already provisioned and it's fully functional.
Provisioning it's the process of "authentication" of the device, we need it to tell apart an official device vs a random one created by a customer in the tenant.
So:

*

*You can't claim an unknown device. The device must be already created and you must know it's name and/or access token.

*To claim a device you need it to be provisioned.

*You should create the device on Thingsboard, provision it and then the customer should do the claim if he wants it.
Even though you don't really need any of this to use it by your self.

A: you should use function provisioning device before claim device. It will auto generate the access token for your device


text:
Q: store logout time in database using codeigniter I want to store logout time in the database while i click logout button . please help me how to fetch the date and time and store it in the database. I am not much familiar to codeigniter .
here is my logout controller
public function logout()
{
    $this->session->unset_userdata('SESS_ADMIN');

    redirect('test');
}

A: Create a function in model and call it from controller
Controller
public function logout() {
    $date = array(
        'date'=>date('d-m-y h:i:s')
    );
    $this->model_name->logout($date);
    $this->session->unset_userdata('SESS_ADMIN');
    redirect('test');
}

Model
    public function logout($date)
    {
        $this->db->insert(table_name, $date);
    }

A: public function logout()
{
    $dateTime = date("Y-m-d H:i:s");
    $this->userModel->updateLogoutTime($dateTime);
    $this->session->unset_userdata('SESS_ADMIN');

    redirect('test');
}

UserModel.php

public function updateLogoutTime($dateTime="") {
      $data = array(
             'logoutTime' => $dateTime,
      );
      $userId = $this->session->userdata('YOUR_USER_ID_VARIABLE_NAME');
      $this->db->where('id', $userId);
      $this->db->update('TABLENAME' ,$data);
      return $this->db->affected_rows();
}

A: First create your table.
create table tbl_user_logout(
 id int not null AUTO_INCREMENT,
 user_id int,
 logout_date varchar(100),
 logout_time varchar (100),
 PRIMARY key(id)
);

then go to application/config/database.php and provide your database details
then in your controller add this code
    public function logout()
    {
        $this->session->unset_userdata('SESS_ADMIN');

        $today_date=date('Y-m-d');
        $today_time=date('H:i:s');

        $post_data=array(
            "user_id"=>$user_id, // user_id you have to get from session data
            'logout_date'=>$today_date,
            'logout_time'=>$today_time,
        );
        $this->db->insert('tbl_user_logout',$post_data);

        redirect('test');
    }

A: For those using Codeigniter 4 (ci_4), here is my solution after the above of ci3 guided me.
My Controller
public function logout()
{

    $this->mysessionsModel      = new MySessionsModel();

    $id = session()->get('logged_user');
    $time = ['logged_out' =>  date("Y-m-d H:i:s")];

    if(!empty($id)){
    $this->mysessionsModel->logoutTime($id, $time);
    }
    $session = session();
    session()->remove('logged_user');
    session()->remove('loggedIn', true);

    $session->destroy();
    return redirect()->to('/');
}

MODEL
// updating User logout time in system.
public function logoutTime($id, $time)
{
    $builder = $this->db->table('table_name');
    $builder->where('code', $id);
    $builder->update(['logged_out' =>$time]);
    if($this->db->affectedRows()==1){
         return true;

     }else{
         return false;
     }
}

NOTE: Ensure your login time and logout time do not have  ATTRIBUTES "on update CURRENT_TIMESTAMP".
Because the above gave me run for money as every time i updated logout, login time could also change.

redpajama_set_name: RedPajamaStackExchange


text: Q: ANDROID: How to use outlinedbox as a background for linearlayout? I would like to ask how to implement as a background for my linear layout the functionality of outlinebox (textinputlayout) look like this,


text:
Q: Why my virtual machine mac os with KVM gives me this error : gtk initialization failed with ./basic.sh? I want to use Qemu-kvm to have a virtual machine with Mac OS on my Ubuntu Server installed on my pc.
I follow all the steps on the tutorial, but, I cannot use any graphic application, and Qemu used that. But I should use Ubuntu Server because I have only one GPU to use on my pc, and I cannot use the same graphic card for ubuntu and mac os.
Do you know how to solve this problem ?
Thanks a lot !


text:
Q: Disable input auto complete on React.js I know this has been asked a 1000 times, but all the answers say the same yet neither work for me at all.
Here'm my input field:
  <input
    className={
      required ? "input-field__input input-field__input--required" : "input-field__input"
    }
    id={placeHolder}
    type={type}
    placeholder={placeHolder}
    autoComplete="new-password"
    value={value || ""}
    onChange={e => handleChange(e.target.value)}
  />

I've tried autoComplete="new-password", autocomplete="new-password", autoComplete="none" & autocomplete="none" but chrome keeps showing me sugestions based on past inputs, no matter which one I've tried. Is there something else happening that might affect it?

A: Add autoComplete="off" in the form tag instead of the input tag.
Below is the code to follow :-
  <form autoComplete="off">
          <input id="input" type="text" placeholder="Enter Text" />
  </form>

{autoComplete} syntax i.e camelCase for React, html follow {autocomplete} in lowercase. JSX also convert it to lower case. You can see the rendered DOM.
Here is the demo :-
https://codepen.io/gahlotbaba/pen/JjdzmmB?editors=0111
Hope it helps.

A: you can add a dummy invisible input above your password
    <div style={{ height: 0px; overflow: hidden; background: transparent; }}>
        <input type="password"></input>
    </div>

A: autoComplete="new-password" should work for you.
this will remove the autocomplete
more on this here
https://github.com/react-toolbox/react-toolbox/issues/1795


text:
Q: Can I use shared preferences to create login sessions in android studio when I have two types of activities to intent depending on the type of user? I want that the user stays logged in the app until he/she logs out. I got to know that we can use shared preferences for creating such sessions. But I have two types of users and it depends on the type, which activity will intent.
How can I use shared preferences in such case? And also I am using intent.putExtras(), so how would the data be passed on to other activities if the app directly opens the mainactivity class.
public void loginHandler(View view){

        userId = useridTIET.getText().toString();
        password = passwordTIET.getText().toString();
        if(userId.isEmpty()||password.isEmpty()){
            Toast.makeText(this, "Empty fields!", Toast.LENGTH_SHORT).show();
        }
        else {
            Log.i("User Type",userType);
            if(userType.equals("resident")){
                residentLogin();
            }
            else {
                guardLogin();
            }
        }
    }

public void residentLogin(){
  if(condition){
     Intent intent = new Intent(getApplicationContext(),NavigationActivity.class);
     intent.putExtra("currentResident",currentResident);
     startActivity(intent);
  }
}

public void guardLogin(){
   if(condition){
     Intent intent = new Intent(getApplicationContext(),NavigationActivity2.class);
     intent.putExtra("userId",userId);
     startActivity(intent);
   }
}

How should I proceed to create sessions?
Thanks for your time :)

A: You can use like that
getSharedPreferences("guard",0)
getSharedPreferences("resident",0)


text:
Q: extjs documentation for declarative syntax I'm having a really hard time reading extjs documentation.  I've done a couple successful projects in extjs so far, but I still struggle reading through documentation.  It seems to be written in an imperative style, but all the examples expect a declarative syntax.
For example, if I were to add a tab to TabPanel, I would expect to see in the docs a function called addTab, which takes a tab name and panel like most other UI libraries I've used behave (like Qt or Swing).  Instead, I see a function like add which takes a dictionary of values, which don't seem to be documented in the docs themselves.
In an example in extjs 3 docs for TabPanel:
var tb = new Ext.Toolbar();
tb.render(document.body);  // toolbar is rendered
tb.add({text:'Button 1'}); // add multiple items (defaultType for Toolbar is 'button')
tb.add({text:'Button 2'});
tb.doLayout();             // refresh the layout

In this example, where is the text parameter documented?  I've seen examples for adding an items field, which I've used before, but what if I just want to add an existing panel?  I assume that's some other keyword, right?  Where are these kinds of things documented?

A: What you are providing via add() is a component config (or instance of a component if you have one).
"The defaultType is button" means, by default, it will treat your configs (what you pass to add between {}) as button configs unless you specify something else via xtype attribute.
So in this case tb.add({text:'Button 1'});, to know what text means, you need to look at button's documentation (config section)


text:
Q: koalas pip install fails on pyarrow dependency I tried installing Databricks' new koalas package using the recommended pip install koalas on but it failed on the pyarrow install.
I then installed pyarrow and retried koalas but it still failed on pyarrow. I visited the Github page which informed me:

If this fails to install the pyarrow dependency, you may want to try
  installing with Python 3.6.x, as pip install arrow does not work out
  of the box for 3.7 https://github.com/apache/arrow/issues/1125.

I searched through the discussions and could not make sense of the "solutions", perhaps because there aren't any. I am using Python 3.7.3. The error messages I get are:
  creating build/temp.macosx-10.7-x86_64-3.7
  -- Runnning cmake for pyarrow
  cmake -DPYTHON_EXECUTABLE=/anaconda3/bin/python  -DPYARROW_BOOST_USE_SHARED=on -DCMAKE_BUILD_TYPE=release /private/tmp/pip-install-uhdr9agf/pyarrow
  unable to execute 'cmake': No such file or directory
  error: command 'cmake' failed with exit status 1

  ----------------------------------------
  Failed building wheel for pyarrow
  Running setup.py clean for pyarrow
Failed to build pyarrow
Installing collected packages: pyarrow, koalas
  Found existing installation: pyarrow 0.13.0
    Uninstalling pyarrow-0.13.0:
      Successfully uninstalled pyarrow-0.13.0
  Running setup.py install for pyarrow ... error
    Complete output from command /anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/private/tmp/pip-install-uhdr9agf/pyarrow/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/tmp/pip-record-i7k4nwil/install-record.txt --single-version-externally-managed --compile:

...

    -- Runnning cmake for pyarrow
    cmake -DPYTHON_EXECUTABLE=/anaconda3/bin/python  -DPYARROW_BOOST_USE_SHARED=on -DCMAKE_BUILD_TYPE=release /private/tmp/pip-install-uhdr9agf/pyarrow
    unable to execute 'cmake': No such file or directory
    error: command 'cmake' failed with exit status 1

    ----------------------------------------
  Rolling back uninstall of pyarrow

...

Command "/anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/private/tmp/pip-install-uhdr9agf/pyarrow/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/tmp/pip-record-i7k4nwil/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/tmp/pip-install-uhdr9agf/pyarrow/

I have tried pip install koalas, sudo pip install koalas, and sudo -H pip install koalas and all have the same error message.
Has anyone found a solution to these errors? Or is koalas not (yet) compatible with 3.7?

A: you probably saw this but the github post you mentioned regarding arrow says "It does work for Python<3.7. For Python 3.7, you need to have installed the Arrow C++ packages via different means."
I was able to get koalas working on a single machine spark local mode with python 3.6 and ran the github sample script successfully ... it also specifies "pyspark>=2.4.0 is recommended"
I am sure if you try 3.6 it will work for you.
import sys
print(sys.version)
import pandas as pd
import databricks.koalas as ks
import pyarrow as pa

3.6.8

pdf = pd.DataFrame({'x':range(3), 'y':['a','b','b'], 'z':['a','b','b']})
print(pdf.head())

   x  y  z
0  0  a  a
1  1  b  b
2  2  b  b

df = ks.from_pandas(pdf)
df.columns = ['x', 'y', 'z1']
df['x2'] = df.x * df.x
df['x2']
0    0
1    1
2    4
Name: x2, dtype: int64


text:
Q: How to use glyphicon in HTML helpers? I have this anchor element that displays glyphicon and some style:

    REVEAL EXTRA LARGE

In my project I use HTML helper to create anchor elements.
I have this html helper  to create anchor element:
@Html.ActionLink(item.Name, "About", "Home", item, new { @class = "btn btn-3d btn-xlg btn-reveal btn-brown" })

But I don't know how to add    element to the HTML helper.
How can I define  inside HTML helper?

A: Use @Url.Action

  REVEAL EXTRA LARGE


text:
Q: Segmentation fault while matrix multiplication using openMp? My matrix multiplication code is
int matMul(int ld, double** matrix)
{

  //local variables initialize

  omp_set_num_threads(nthreads);

  \#pragma omp parallel private(tid,diag,ld) shared(i,j,k,matrix)

  {
    /* Obtain and print thread id */

    tid = omp_get_thread_num();

    for ( k=0; k<ld; k++)  {
    if (matrix[k][k] == 0.0) {
      error = 1;
      return error;
    }
    diag = 1.0 / matrix[k][k];
\#pragma omp for

    for ( i=k+1; i < ld; i++) {

      matrix[i][k] = diag * matrix[i][k];

    }
    for ( j=k+1; j<ld; j++) {

      for ( i=k+1; i<ld; i++) {

        matrix[i][j] = matrix[i][j] - matrix[i][k] * matrix[k][j];

      }

    }
  }

  }
  return error;

}

I assume that it is because of matrix object only but why will it be null even though it is passed as a parameter..

A: I ran into the same problem while compiling my code under Linux using GCC 4.2. The line that is causing the problem is:
omp_set_num_threads(nthreads);

You should try to set the number of threads by specifying it under pragma omp for:
#pragma omp for num_threads(nthreads)

Hope it helps!

A: I assume that your "matrix" is an array of pointers to the actual matrix' rows, something like:
double *matrix[NROWS];
for (i = 0; i < NROWS; ++i) {
    matrix[i] = malloc(sizeof(double)*NCOL);
}

But if "matrix" is defined this way
double matrix[NROWS][NCOL];

your program can't work.
If your matrix id defined properly, a possible reason of crash mey be an incorrect size ("ld").
Regards


text:
Q: Trig/Vector question I have no idea where to go from here. I only know how to compute dot product, cross product, cos(theta), magnitude, projection, and scalar components but I don't know how to do this

This is as far as I've gotten so far in trying to wrap my head around this after watching numerous videos on youtube:

A: Hint: Horizontal component of a vector $V$ is $|V| cos(\theta)$.
Hint 2: Take your horizontal direction to be parallel to inclined plane.
Note that angle of F with inclined plane is $34^\circ-16^\circ = 18^\circ$.

A: This was a lot easier than I expected.
$$|w|cos(16°)=2.8$$
will then be
$$|w|=\frac{2.8}{cos(16°)}$$
$$|w|=2.91$$


text:
Q: How to display Yes/No instead of True/False for bool? in c# I get the error "Cannot implicitly convert type 'string' to 'bool'.  How do I return 'Yes' or 'No' instead of true/false?
public bool? BuyerSampleSent
{
    get { bool result;
          Boolean.TryParse(this.repository.BuyerSampleSent.ToString(), out result);
        return result ? "Yes" : "No";
    }
    set { this.repository.BuyerSampleSent = value; }
}

A: You can't return a string if the return type is bool (or bool? in this case).  You return a bool:
return result;

Notice, however, that you ask...

How to display Yes/No...

This code isn't displaying anything.  This is a property on an object, not a UI component.  In the UI you can display whatever you like using this property as a flag:
someObject.BuyerSampleSent ? "Yes" : "No"

Conversely, if you want a display-friendly message on the object itself (perhaps it's a view model?) then you can add a property for that message:
public string BuyerSampleSentMessage
{
    get { return this.BuyerSampleSent ? "Yes" : "No"; }
}

A: Your method returns a bool as @Pierre-Luc points out.  You need to change that to a String.

A: You cannot return a bool value "Yes" or "No". In C#, bool is a keyword for Boolean Data Type.You cannot override this behavior of a keyword.
Read more about C# Boolean Data Type here.
In your case you can do the following:
public string BuyerSampleSent
{
    get
    {
        string result= "No";
        if (this.repository.BuyerSampleSent.Equals("true",StringComparisson.OrdinalIgnoreCase)) // <-- Performance here
            result = "Yes";
        return result;
    }
    set
    {
        this.repository.BuyerSampleSent = value;
    }
}


text:
Q: Not able to delete reminder in android studio I'm working on a pill reminder application using a database handler. The problem is that I'm not able to delete reminder and can't seem to find any errors. I'm very new to this still learning.
Here's my code for database handler:

 int deleteReminder(String name)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete(TABLE_REMINDERS,"medname" + "='" + name + "'",null);
    }

This is the java code:
 public void delete(View view) {

        DatabaseHandler dh = new DatabaseHandler(this);
        if (dh.deleteReminder(ar.get(0).toString()) > 0) {
            Toast.makeText(this, "Alarm Deleted Successfully", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, main.class);
            intent.putExtra("frag", "Med Reminder");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        }

    }

Xml:
  <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:tint="#ffffff"
            android:onClick="delete"
            android:src="@drawable/ic_delete_black_24dp"
            android:layout_marginRight="10dp"
            android:layout_gravity="right" />


text:
Q: PubSub REST subscription pull not returning with all messages We use the REST service API to pull messages from a PubSub subscription. Messages ready to be serviced are acknowledged, leaving other messages unacknowledged to be serviced during a later execution cycle.
During an execution cycle, we send a single reqeust to the pull service REST API with returnImmediately=true and maxMessages=100.
While testing we encountered a situation when only 3 "old" messages would be returned during each execution cycle. Newly published messages were never included in the request to pull. We verified new messages were successfully arriving at the subscription by monitoring the Undelivered messages in Stackdriver monitoring.

*

*Does the pull REST API not include all undelivered messages?

*Does it ignore the maxMessages parameter?

*How should all messages, up to the maximum specified, be read with the REST API?
Notes:
We worked around the problem by sending 2 parallel requests to the pull API and merging the results. We found the workaround (requiring parallel requests) discussed here.
Update Feb. 22, 2018
I wrote an article on our blog that explains why we forced to use the PubSub service REST API.

A: A single pull call will not necessarily return all undelivered messages, especially when returnImmediately is set to true. The pull promises to return at most maxMessages, it does not mean that it will always return maxMessages if there are that many messages available.
The pull API tries to balance returning more messages with keeping end-to-end latency low. It would rather return a few messages quickly than wait a long time to return more messages. Messages need to be retrieved from storage or from other servers and so sometimes all of those messages aren't immediately available to be delivered. A subsequent pull request would then receive other messages that were retrieved later.
If you want to maximize the chance of receiving more messages with a pull request, set returnImmediately to false. This still will not guarantee that messages will all be delivered in a single pull request, even if maxMessages is greater than the number of messages yet to be delivered. You should still send subsequent pull requests (or even more ideally, several pull requests at the same time) to retrieve all of the messages.
Alternatively, you should consider switching to the Google Cloud Pub/Sub client libraries, which handle all of this under the hood and deliver messages to a callback you specify as soon as they are available.


text:
Q: 500 internal server error deploying Django-Wagtail application on AWS Elastic Beanstalk I have tried everything I can think of and I have gone through the AWS and RealPython guides. I am honestly at a loss.
I have developed an application and it functions perfectly on my local machine, using a pipenv lockfile. Because of this there was no immediate need for a requirements.txt, however EB requires one and so, with the pipenv environment open I ran
pip freeze > requirements.txt

to create one. It now contains:
beautifulsoup4==4.6.0
certifi==2019.11.28
cffi==1.13.2
chardet==3.0.4
cryptography==2.8
defusedxml==0.6.0
Django==2.1.1
django-allauth==0.40.0
django-modelcluster==4.4.1
django-taggit==0.24.0
django-treebeard==4.3.1
djangorestframework==3.11.0
draftjs-exporter==2.1.7
html5lib==1.0.1
idna==2.8
oauthlib==3.1.0
Pillow==5.4.1
pycparser==2.19
python3-openid==3.1.0
pytz==2019.3
requests==2.22.0
requests-oauthlib==1.2.0
six==1.14.0
sqlparse==0.3.0
Unidecode==1.1.1
urllib3==1.25.7
wagtail==2.5.2
webencodings==0.5.1
Willow==1.1

I had to downgrade to Django 2.1.1 because someone said that there are versioning issues with EB at 2.2. I am using python 3.6.8.
I was receiving an error stating that "WSGIPath refers to a file that does not exist", I fixed this using
eb config

and searching for wsgi and changing the path to
application_name/wsgi.py

Now, upon running
eb create
eb deploy

I receive the output
Creating application version archive "app-60c1-200116_214620".
Uploading application_name/app-60c1-200116_214620.zip to S3. This may take a while.
Upload Complete.
2020-01-16 19:46:35    INFO    Environment update is starting.
2020-01-16 19:46:38    INFO    Deploying new version to instance(s).
2020-01-16 19:47:00    INFO    New application version was deployed to running EC2 instances.
2020-01-16 19:47:00    INFO    Environment update completed successfully.

I have also added the url into ALLOWED_HOSTS in base.py (wagtail version of settings.py).
The application works locally but when I run it on the server I receive a 500 internal service error. The following is some of the contents of the log file:
-------------------------------------
/var/log/httpd/error_log
-------------------------------------
[Thu Jan 16 19:40:47.104485 2020] [:error] [pid 4284] [remote 127.0.0.1:18388] mod_wsgi (pid=4284): Exception occurred processing WSGI script '/opt/python/current/app/educess/wsgi.py'.
[Thu Jan 16 19:40:47.104591 2020] [:error] [pid 4284] [remote 127.0.0.1:18388] Traceback (most recent call last):
[Thu Jan 16 19:40:47.104624 2020] [:error] [pid 4284] [remote 127.0.0.1:18388]   File "/opt/python/current/app/educess/wsgi.py", line 16, in <module>
[Thu Jan 16 19:40:47.104629 2020] [:error] [pid 4284] [remote 127.0.0.1:18388]     application = get_wsgi_application()
[Thu Jan 16 19:40:47.104636 2020] [:error] [pid 4284] [remote 127.0.0.1:18388]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application
[Thu Jan 16 19:40:47.104640 2020] [:error] [pid 4284] [remote 127.0.0.1:18388]     django.setup(set_prefix=False)
[Thu Jan 16 19:40:47.104645 2020] [:error] [pid 4284] [remote 127.0.0.1:18388]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
[Thu Jan 16 19:40:47.104649 2020] [:error] [pid 4284] [remote 127.0.0.1:18388]     apps.populate(settings.INSTALLED_APPS)
[Thu Jan 16 19:40:47.104655 2020] [:error] [pid 4284] [remote 127.0.0.1:18388]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py", line 83, in populate
[Thu Jan 16 19:40:47.104658 2020] [:error] [pid 4284] [remote 127.0.0.1:18388]     raise RuntimeError("populate() isn't reentrant")
[Thu Jan 16 19:40:47.104672 2020] [:error] [pid 4284] [remote 127.0.0.1:18388] RuntimeError: populate() isn't reentrant
[Thu Jan 16 19:46:46.365964 2020] [mpm_prefork:notice] [pid 4279] AH00169: caught SIGTERM, shutting down
[Thu Jan 16 19:46:47.478417 2020] [suexec:notice] [pid 4716] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[Thu Jan 16 19:46:47.494121 2020] [so:warn] [pid 4716] AH01574: module wsgi_module is already loaded, skipping
[Thu Jan 16 19:46:47.496176 2020] [http2:warn] [pid 4716] AH10034: The mpm module (prefork.c) is not supported by mod_http2. The mpm determines how things are processed in your server. HTTP/2 has more demands in this regard and the currently selected mpm will just not do. This is an advisory warning. Your server will continue to work, but the HTTP/2 protocol will be inactive.
[Thu Jan 16 19:46:47.496186 2020] [http2:warn] [pid 4716] AH02951: mod_ssl does not seem to be enabled
[Thu Jan 16 19:46:47.496728 2020] [lbmethod_heartbeat:notice] [pid 4716] AH02282: No slotmem from mod_heartmonitor
[Thu Jan 16 19:46:47.496790 2020] [:warn] [pid 4716] mod_wsgi: Compiled for Python/3.6.2.
[Thu Jan 16 19:46:47.496794 2020] [:warn] [pid 4716] mod_wsgi: Runtime using Python/3.6.8.
[Thu Jan 16 19:46:47.498977 2020] [mpm_prefork:notice] [pid 4716] AH00163: Apache/2.4.41 (Amazon) mod_wsgi/3.5 Python/3.6.8 configured -- resuming normal operations
[Thu Jan 16 19:46:47.498995 2020] [core:notice] [pid 4716] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'
[Thu Jan 16 19:46:50.530525 2020] [:error] [pid 4721] [remote 127.0.0.1:0] mod_wsgi (pid=4721): Target WSGI script '/opt/python/current/app/educess/wsgi.py' cannot be loaded as Python module.
[Thu Jan 16 19:46:50.530599 2020] [:error] [pid 4721] [remote 127.0.0.1:0] mod_wsgi (pid=4721): Exception occurred processing WSGI script '/opt/python/current/app/educess/wsgi.py'.
[Thu Jan 16 19:46:50.531288 2020] [:error] [pid 4721] [remote 127.0.0.1:0] Traceback (most recent call last):
[Thu Jan 16 19:46:50.531332 2020] [:error] [pid 4721] [remote 127.0.0.1:0]   File "/opt/python/current/app/educess/wsgi.py", line 16, in <module>
[Thu Jan 16 19:46:50.531337 2020] [:error] [pid 4721] [remote 127.0.0.1:0]     application = get_wsgi_application()
[Thu Jan 16 19:46:50.531344 2020] [:error] [pid 4721] [remote 127.0.0.1:0]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application
[Thu Jan 16 19:46:50.531347 2020] [:error] [pid 4721] [remote 127.0.0.1:0]     django.setup(set_prefix=False)
[Thu Jan 16 19:46:50.531353 2020] [:error] [pid 4721] [remote 127.0.0.1:0]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
[Thu Jan 16 19:46:50.531356 2020] [:error] [pid 4721] [remote 127.0.0.1:0]     apps.populate(settings.INSTALLED_APPS)
[Thu Jan 16 19:46:50.531362 2020] [:error] [pid 4721] [remote 127.0.0.1:0]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate
[Thu Jan 16 19:46:50.531365 2020] [:error] [pid 4721] [remote 127.0.0.1:0]     app_config = AppConfig.create(entry)
[Thu Jan 16 19:46:50.531371 2020] [:error] [pid 4721] [remote 127.0.0.1:0]   File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/config.py", line 90, in create
[Thu Jan 16 19:46:50.531374 2020] [:error] [pid 4721] [remote 127.0.0.1:0]     module = import_module(entry)
[Thu Jan 16 19:46:50.531379 2020] [:error] [pid 4721] [remote 127.0.0.1:0]   File "/opt/python/run/venv/lib64/python3.6/importlib/__init__.py", line 126, in import_module
[Thu Jan 16 19:46:50.531382 2020] [:error] [pid 4721] [remote 127.0.0.1:0]     return _bootstrap._gcd_import(name[level:], package, level)
[Thu Jan 16 19:46:50.531388 2020] [:error] [pid 4721] [remote 127.0.0.1:0]   File "<frozen importlib._bootstrap>", line 994, in _gcd_import
[Thu Jan 16 19:46:50.531393 2020] [:error] [pid 4721] [remote 127.0.0.1:0]   File "<frozen importlib._bootstrap>", line 971, in _find_and_load
[Thu Jan 16 19:46:50.531399 2020] [:error] [pid 4721] [remote 127.0.0.1:0]   File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
[Thu Jan 16 19:46:50.531414 2020] [:error] [pid 4721] [remote 127.0.0.1:0] ModuleNotFoundError: No module named 'debug_toolbar'

Notice the ModuleNotFoundError at the end of the log. I have completely uninstalled debug_toolbar from the application as far as I know but somehow the server still believes it is present.
Any assistance that could point me in the right direction would be greatly appreciated.
Edit 1: Whether DEBUG is set to True or False in base.py, I still receive a 500 internal server error.
Edit 2: I believe the problem is to do with versioning but I don't know what to change to correct it and whether it will require me to recreate the entire project or not.
Thanks,
Joshua.

A: Remove Debug toolbar from installed apps.
INSTALLED_APPS = [
    #'debug_toolbar',
]

Remove Debug toolbar from middlewares.
MIDDLEWARE = [
   #'debug_toolbar.middleware.DebugToolbarMiddleware',
]

Remove Debug toolbar from urls.py.
urlpatterns = [
    #url(r'^__debug__/', include(debug_toolbar.urls)),
]

Remove Debug toolbar imports from application
#import debug_toolbar

Now check your application locally, if its working fine then it should work on beanstalk as well.


text:
Q: didn't check the character between the numbers in numeric validation The following function is used to numeric validation alone.If I copy and paste the string "123we" it will paste 123.
But my problem is if I copy "123we23q" it will paste like 123we23.Only the last digit is removed and didnt check the character between the numbers
$( "input[type=text]" ).on("keyup", function() {
  var o=$(this);
  o.val(o.val().replace(/[^\d]/g,""));
});

A: Your code is working perfectly
<input type="text">

check this fiddle
http://jsfiddle.net/shyamchandranmec/vLnqj/


text:
Q: BFS Tree Has Empty Output. What could be wrong? I am trying to implement a BFS algorithm. It's supposed to get a graph as an input. Then the output should be the BFS tree. It's also supposed to keep track of the parent and the level. I have tried to follow the pseudocode from Wikipedia. However, I am getting an empty BFS tree. Which part that I did wrong and how to fix it? Thanks. Here is the code snippet:
Graph Bicc::breadthFirstSearch(Graph& sparseGraph) {
    Graph tree;

    Vertex root = sparseGraph.getVertex(0);
    Vertex parent(-1);
    root.parent = &parent;
    root.color = "white";
    root.level = 0;

    for(size_t i = 0; i < sparseGraph.getVertexCount(); i++){
        sparseGraph.getVertex(i).color = "white";
    }

    queue<Vertex> q;
    list<Vertex> neighbors = root.getNeighbors();
    root.color = "gray";
    q.push(root);

    while(!q.empty())
    {
        root = q.front();
        q.pop();

        for(auto& neighbor : neighbors)
        {
            if(neighbor.color == "white")
            {
                neighbor.color = "gray";
                neighbor.level = neighbor.level + 1;
                Vertex n_parent(0);
                neighbor.parent = &n_parent + 1;
                q.push(neighbor);
                tree.add(neighbor);
            }
        }
    }
    return tree;
}


text:
Q: FMX: How to create a ToolWindow form that cannot be maximised? I have a form in my application which is triggered with ShowModal. I have set the BorderStyle to ToolWindow because I don't want it to be resizable. However, I discovered that it can still be maximised by double clicking the title bar. I don't want that. To prevent this I tried setting biMaximize to False in BorderIcons. This seems to work when I run the application from the IDE - it can no longer be maximised by double clicking the title bar. However, when I run the application directly from the compiled executable, that form always appears the wrong size (much too high)! WindowState is set to wsNormal. My application is built for Windows and I'm running on Windows 10.
How can I create a form that cannot be resized and why is it behaving differently when run outside the IDE?
Edit: I've discovered that this is related to the Windows display settings with multiple monitors. My screen scale is set to 125% on one monitor and 100% on the other. If I set both to 100% then the form appears the right size. If I turn off one monitor then it also appears correctly. My main question is, how can I prevent a double click of the title bar maximising the form without setting biMaximize to false?
See the following example. To reproduce the error you will need two monitors. Set one to 100% scale and the other to 125% in Display Settings. Then build the app for Windows and run the exe from outside the IDE. Click the button to show the second form and it appears much too large. I'd appreciate if anyone could confirm that they get the error and also if it still occurs in the latest version of 10.4. If so then I will report it.
Project:
program Project1;

uses
  System.StartUpCopy,
  FMX.Forms,
  Unit1 in 'Unit1.pas' {Form1},
  Unit2 in 'Unit2.pas' {Form2};

{$R *.res}

begin
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Application.CreateForm(TForm2, Form2);
  Application.Run;
end.

Main Form and Unit:
object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 480
  ClientWidth = 640
  Position = ScreenCenter
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  DesignerMasterStyle = 0
  object Button1: TButton
    Position.X = 256.000000000000000000
    Position.Y = 168.000000000000000000
    Size.Width = 137.000000000000000000
    Size.Height = 22.000000000000000000
    Size.PlatformDefault = False
    Text = 'Show ToolWindow'
    OnClick = Button1Click
  end
end

.
unit Unit1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
  FMX.Controls.Presentation, FMX.StdCtrls, Unit2;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}

procedure TForm1.Button1Click(Sender: TObject);
begin
  Form2.ShowModal;
end;

end.

Second Form and Unit:
object Form2: TForm2
  Left = 0
  Top = 0
  BorderIcons = [biSystemMenu, biMinimize]
  BorderStyle = ToolWindow
  Caption = 'Form2'
  ClientHeight = 237
  ClientWidth = 344
  Position = ScreenCenter
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  DesignerMasterStyle = 0
  object Button1: TButton
    ModalResult = 8
    Position.X = 136.000000000000000000
    Position.Y = 208.000000000000000000
    Text = 'Close'
  end
end

.
unit Unit2;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
  FMX.Controls.Presentation, FMX.StdCtrls;

type
  TForm2 = class(TForm)
    Button1: TButton;
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form2: TForm2;

implementation

{$R *.fmx}

end.


text:
Q: How to read a node in an xml in this format I have an getting an xml response on this format
  <?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n
       <PlatformResponse xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://platform.intuit.com/api/v1\">\r\n
<ErrorMessage>OAuth Token rejected</ErrorMessage>\r\n
<ErrorCode>270</ErrorCode>\r\n
<ServerTime>2012-06-19T00:01:31.5150146Z</ServerTime>\r\n
</PlatformResponse>

I need to grab the value in the <ErrorCode> node, for that I did the following but it is not getting any values..
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(xmlResponse);

            XmlNodeList xnList = xml.SelectNodes("PlatformResponse");
            foreach (XmlNode xn in xnList)
            {
                result.Message = xn["ErrorCode"].InnerText;
            }

Any help would be much appreciated.

A: There seems to be some dirt in your PlatformResponse node that's giving problems, (  xmlns:xsd= etc... )
Using this xml
String sXml = @"<?xml version='1.0' encoding='utf-8'?>
   <PlatformResponse >
        <ErrorMessage>OAuth Token rejected</ErrorMessage>
        <ErrorCode>270</ErrorCode>
        <ServerTime>2012-06-19T00:01:31.5150146Z</ServerTime>
    </PlatformResponse>";

And select like
XmlNodeList xnList = xml.SelectNodes("/PlatformResponse");

Your code works fine.

A: I just tested the code and it does work fine:
        XmlDocument xml = new XmlDocument();
        XmlTextReader reader = new XmlTextReader("Path_to_your_xml");
        xml.Load(reader);
        XmlNodeList xnList = xml.SelectNodes("PlatformResponse");
        foreach (XmlNode xn in xnList)
        {
            MessageBox.Show(xn["ErrorCode"].InnerText);
        }

A: For this, since the attribute is on the main document element itself, you can simply do
    XmlDocument xml = new XmlDocument();
    xml.LoadXml(xmlText);
    result.Message = xml.DocumentElement["ErrorCode"].InnerText


text:
Q: Algorithms for symbolic manipulation If you take a look at WolframAlpha, or other computer algebraic system, you will find that it is able to do symbolic manipulation like real humans.
For example, if you type in an integral, it can show you step by step on how to solve the integration.
What are the algorithms behind all this?

A: The algorithms behind symbolic integration (due to Liouville, Ritt, Risch, Bronstein et al.) are discussed in prior questions here, e.g. the transcendental case and algebraic case.
For general references on symbolic computation see any of the standard texbooks, e.g. Geddes et al. Algorithms for computer algebra, Grabmeier et al: Computer algebra handbook,von zur Gathen: Modern computer algebra, and Zippel: Effective polynomial computation, and many other books. See also the Journal of Symbolic Computation and various conferences: SIGSAM ISSAC, EUROCAL, etc.


text:
Q: One word for 'Person being evaluated' I am developing a software application for a Medical Committee which will analyse [medical] examination results and issue certificates based on them. The Committee never sees the person and the exam results may be years old, so 'patient' is not a good term.
What can I call the person who is being evaluated? In Spanish they use Evaluado which may be 'Evaluated' or 'Evaluee' but I don't know which to use or if they are correct.
It would be great to use a single word, not a phrase like 'Person being evaluated'.

A: A term used for the person being evaluated in many scientific and medical studies is subject

a person or thing that undergoes experiment, analysis, treatment, etc

A: I would suggest Patient is exactly the right term. The person was a patient at the time the original examination was performed.
Evaluee is a possibility, but it seems rather impersonal. The Committee is dealing with results from real people.

A: An evaluee is usually used in flight related duties i.e. in the military. In the U.S. Navy we use this term for people getting an evaluation on their crew position - enlisted or officer (pilot, gunner and etc.)/

A: how about Examinee?
it's a fairly neutral term.


text:
Q: Check if value input in textbox exists in database and insert if not How to check if the text I input in textbox already exists in database and if so update only the data or anything solution you recommend and if not the data will automatically insert into database? Here is my code:
 cn.Open();
        cm = new MySqlCommand("SELECT * FROM tblcustomer WHERE fullname LIKE '" + txtCustomer.Text + "'", cn);
        dr = cm.ExecuteReader();
        dr.Read();
        if (dr.HasRows)
        {

            cm = new MySqlCommand("UPDATE tblcustomer SET fullname = '" + txtCustomer.Text + "' WHERE id LIKE '" + lblCustomerId.Text + "'", cn);
            cm.ExecuteNonQuery();

        }
        else
        {

            cm = new MySqlCommand("INSERT INTO tblcustomer(fullname) VALUES ('" + txtCustomer.Text + "')", cn);
            cm.ExecuteNonQuery();

        }

        dr.Close();
        cn.Close();

A: Change your SQL to this:
"INSERT INTO tblcustomer fullname VALUES" + txtCustomer.Text + "
ON DUPLICATE KEY UPDATE fullname= " + txtCustomer.Text
Pseudo, didn't validate this, but it is sort of the right idea, of what you want. And does it in a single connection attempt to the DB.
You can find a guide here:
https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html


text:
Q: How best to display a list of items as a popup that gets sized correctly in ExtJS 6 I have a list of errors (between 1 and 20 in the list).  I want to create a popup window that shows the list and is sized to contain it reasonably well regardless of the users font or browser.  I made an example in sencha's fiddle here that shows my issue and my non optimal solution.  Please suggest how to improve (or use some other mechanism in sencha to get what I want).
https://fiddle.sencha.com/#fiddle/18ef
Ext.application({
    name: 'Fiddle',

    launch: function() {

        var errorTpl = new Ext.XTemplate('<tpl for=".">', '
', '
{Message}
', '
', '</tpl>');

        var errorView = Ext.create('Ext.view.View', {
            layout: 'fit',
            // data: errorList,
            data: [{
                Message: '1 alsfdjaslfkjas;fljksafjsakflsalfjsalf;safsa;lfsal;dfsalfd'
            }, {
                Message: '2 alsfdjaslfkjas;fljksafjsakflsalfjsalf;safsa;lfsal;dfsalfd'
            }, {
                Message: '3 alsfdjaslfkjas;fljksafjsakflsalfjsalf;safsa;lfsal;dfsalfd'
            }, {
                Message: '4 alsfdjaslfkjas;fljksafjsakflsalfjsalf;safsa;lfsal;dfsalfd'
            }, {
                Message: '5 alsfdjaslfkjas;fljksafjsakflsalfjsalf;safsa;lfsal;dfsalfd'
            }, {
                Message: '6 alsfdjaslfkjas;fljksafjsakflsalfjsalf;safsa;lfsal;dfsalfd'
            }, {
                Message: '7 alsfdjasl alsfdjasl alsfdjasl fkjas;fljksafjsakflsalfjsalf;safsa;lfsal;dfsalfd'
            }],
            tpl: errorTpl,
            itemSelector: 'div.thumb-wrap'
        });

        var win = Ext.create('Ext.window.Window', {
            title: 'Problems Found (Please Correct)',
            modal: true,
            layout: 'vbox',
            width: 500,
            height: 50 + errorView.data.length * 40,
            items: [{
                xtype: 'button',
                margin: "10 10 10 10",
                text: 'close',
                listeners: {
                    click: function() {
                        this.up('window').close();
                    }
                }
            },
            errorView]
        }).show();
    }
});

***UPDATE:
I did this and it seems to help a lot
var htmlError = errorTpl.apply(errorList);
Ext.Msg.alert('Problems Found (Please Correct)',htmlError);

A: Just don't set the height of the window.
Working example: https://fiddle.sencha.com/#fiddle/18ej


text:
Q: Sequelize hook depending on transaction I want to create a sequelize hook on afterCreate on my user model. it work great when i just create a user without a transaction. but if i run my create statement in a transaction the hook is run before the commit.
user Model hooks
hooks: {
    afterCreate: userModule.NewUserHook,
    afterBulkCreate: userModule.NewUserHook
}

Hook function
NewUserHook: function NewUserHook(user, options){
    console.log('Inside hook');
}

The transaction is accesssible in options.transaction.
Is there anyway to run the hook after the transaction is commited?

A: A bit late to the game but since I came across this question while searching for answers, this one may be useful for others.
If you create the user inside a transaction then the transaction object will be passed in one of the arguments of the hook callback (depending on version). Link to docs.
The following is copied directly from the source link:
// Here we use the promise-style of async hooks rather than
// the callback.
User.hook('afterCreate', (user, options) => {
  // 'transaction' will be available in options.transaction

  // This operation will be part of the same transaction as the
  // original User.create call.
  return User.update({
    mood: 'sad'
  }, {
    where: {
      id: user.id
    },
    transaction: options.transaction
  });
});

sequelize.transaction(transaction => {
  User.create({
    username: 'someguy',
    mood: 'happy',
    transaction
  });

If we had not included the transaction option in our call to User.update in the preceding code, no change would have occurred, since our newly created user does not exist in the database until the pending transaction has been committed.

A: transaction has to be present in the second argument of create, not the first as of 6.5.1
I think this has changed a bit since AlexandreF's answer, now the transaction has to be given in the second argument of create. This makes sense, as otherwise it would potentially conflict with a field named transaction.
The current documentation section https://sequelize.org/master/manual/hooks.html#hooks-and-transactions (archive) gives an example:
User.addHook('afterCreate', async (user, options) => {
  // We can use `options.transaction` to perform some other call
  // using the same transaction of the call that triggered this hook
  await User.update({ mood: 'sad' }, {
    where: {
      id: user.id
    },
    transaction: options.transaction
  });
});

await sequelize.transaction(async t => {
  await User.create({
    username: 'someguy',
    mood: 'happy'
  }, {
    transaction: t
  });
});

rather than putting transaction together with username and mood.


text:
Q: How to classify points in mapinfo table into their enclosing polygons (non overlapping polys) in one run The objective is to classify a group of points to its enclosing polygons in one run rather than using select for each polygon and do it on one by one basis (for 100,000 point and 5000 polygons it can take for ever).

A: The following example should help. You can use an SQL query using a geographical operator such as 'within' or 'contains'.
http://web.pb.com/mapinfopro-oct-2012/Query-Ninja-Joining-Tables


text:
Q: Sequence of Lipschitz maps that converge pointwise to a Lipscthiz functions must have bounded Lipschitz constants? Let $f_n:M \to M$ be a sequence of Lipschitz maps in a metric space $(M,d)$. Assume that we know that $\{f_n\}_{n=1}^\infty$ converge pointwise to $f:M\to M$ that is also a Lipschitz map. Let $L_n$ denote the Lipschitz constant of each $f_n$, that is, $L_n=\sup_{x\neq y}\dfrac{d(f(x),f(y))}{d(x,y)}$. Then, can we deduce that the sequence $\{L_n\}_{n=1}^\infty$ is bounded?
I expect this being false, but I can't find a counterexample. Maybe there is hope to argue that converging pointwise to a Lipscthiz map $f$ must bound the Lipschitz constants of the $\{f_n\}$ sequence (or otherwise we would have a contradiction)?

A: $f_n(x)=\frac 1n\sin(n^2x)$, $f(x)=0$. Then $f_n\to f$ uniformly. All the functions are Lipschitz. However $f_n'(x)=n\cos(n^2x)$ so $L_n=n$.


text:
Q: JAVA_HOME errors when run without sudo Hello I am on Linux Mint 16 KDE 64.
I have OpenJDK 7 installed and Oracle JDK 7 and if I run Intellij as a normal user I get:

'tools.jar' seems to be not in IDEA classpath.
  Please ensure JAVA_HOME points to JDK rather than JRE

Also if I run gradle build on any of our projects as a normal user I get:

Cannot find System Java Compiler. Ensure that you have installed a JDK (not just a JRE) and configured your JAVA_HOME system variable to point to the according directory.

If I run

echo $JAVA_HOME

Then I get:

/usr/lib/jvm/default-java

I get the same thing if I run it with sudo.
As per the comments below javac -version produces:

javac 1.7.0_51

Same result with sudo.
What am I doing wrong?

A: You installed only JRE. Try to install JDK:

sudo apt-get install openjdk-7-jdk

A: try to run javac -version to get version of your java compiler.
You should get answer like javac 1.7.0_something.
if it's not available then you have only Java Runtime Environment (jre), not Java Development Kit (jdk) installed and you should install the openjdk-7-jdk as Anton suggested.


text:
Q: Can I "just" create my own media type for a proprietary web/application communication I read this question but it doesn't fully answer mine.
In the linked question, the OP asks what he must do to have his custom media type registered. I do not need that.
All I'm asking is, that if I am correct in assuming that, technically, all I have to do to create a custom media type is to, well.. just use it in my communication?
Basically, what I want to do is that my website offers a download of a file, described as application/x-my-custom-thing. On the client, the user has files ending with .my-custom-thing set as to open with the application I ship along.
So, what should happen is that, when the user clicks on the link, my application opens and reads the file and does stuff with it.
Are media types even the proper use case for this? Or, should I maybe "create" my own protocol in the sense of mycustomthing://example.com/the-file-to-use? Will that work with every (reasonably modern) browser?

A: The primary purpose for media types used in HTTP communication is to tell the browser how they should treat the received content.
If you use the browser just to let the user to download the files to their computer, then you don't need to create your own media type. It will be sufficient to use the standard generic media type application/octet-stream.
If you want the browser to do more, then the user (or perhaps an installer) must associate your custom media type with your application. There is no automatic association and no relation between file extensions and media types (and some OSes don't even use the file extension to identify the type of file and how to open it).
Defining a custom protocol is unlikely to work. A protocol defines how the browser communicates with a server and browsers will not accept URIs with a protocol that they don't know.


text:
Q: Fast consecutive XmlHttpRequest doesnt work I have a code where when a div is clicked, an XmlHttpRequest is sent to a PHP script and some data is sent back. When the response is received by the client, some CSS work is done. But, if I click on a div and then after one second I click on another one, the second one doesn't fire the event.
How can I fix this issue?
Is there is a way to free memory after xmlhttp request is done?
This is my mousedown event function:
.on("mousedown",function () {

                var idgroup = $("#group_" + idBlock).val();
                var idProf = $(this).attr("name");
                if (window.XMLHttpRequest) {

                    // code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp = new XMLHttpRequest();
                } else { // code for IE6, IE5

                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                xmlhttp.onreadystatechange = function () {

                    if (this.readyState == 4 && this.status == 200) {
                 // css color change is done here
                    }
                }
                xmlhttp.open("GET", "../dnd_jq/getProfTime.php?idprof=" + idProf + "&idgroup=" + idgroup);
                xmlhttp.send();

            }

A: Chances are the XHR object can't only fire if it is still waiting for a request.
What I would do is make 2 XHR objects that fire for each request?
P.S. I am very new to XHR and bad explanation skills, so take my response with a grain of salt!


text:
Q: How to send a structure variable from client to socket? I'm working on socket programming. The client has to send a structure variable to the server. How can I go about it? I have created the server and the client and I'm stuck at this point.
PS: I'm coding in C.

A: Use write on the client side and read on the server side?
I think you have to be more precise..
Is it always the same data structure? if not how do you know which message you receive?

A: Assuming you're trying to send an instance of a struct, you could just send the binary data up (write the struct with the size of the struct). This assumes that you don't have any pointers in the struct, and that your struct definition matches perfectly on both sides (same bit alignment as well).
This is not very portable, and makes quite a few assumptions.
The better option is to encode the data into a standard format. I like JSON, mostly because it's simple and there are tons of parsers for it. You would encode the struct as JSON (see http://json.org/ for libraries), send it over the socket, and decode it on the other side.
You'd need to also send how big the data is, so you may need to come up with a simple protocol (first 4 bytes are the size of the JSON data, then send the JSON data).
Custom protocols are pretty terrible, so you may want to look into a standardized protocol. If you just want to send binary data over TCP, consider the WebSocket protocol. It's basically what I described, but a little more flexible.
This is what I do, and it works pretty well.


text:
Q: javascript attaching events I've seen that you can attach events like this
<button type="button" id="myButton" onclick="myFunction()">

can you do the same without the "onclick=", like:
document.getElementById('myButton'). //and here attach the event on click to myFunction

I'm trying to keep JavaScript and HTML separate.

A: It's similar to the onclick approach, and in fact uses the same event-handler, but is removed from the HTML:
document.getElementById('myButton').onclick = function(){
    // do stuff
    myFunction();
}

If you don't have an id on the element you could also use:
var inputs = document.getElementsByTagName('input');

for (var i=0, len=inputs.length; i<len; i++){
    if (inputs[i].type == 'text'){
        // assuming you want to affect text-inputs in this case
        inputs[i].onclick = function(){
            // do stuff. In here 'this' refers to inputs[i] element
            myFunction();
        };
    }
}

An alternative approach, using Array.prototype.forEach(), with an array of elements created using Array.prototype.slice() and document.querySelectorAll():
[].forEach.call(document.querySelector('input[type="text"]', yourFunctionName);

This will execute the yourFunctionName() function for each <input /> element, of type="text", returned by document.querySelectorAll() passing that <input /> element into the function as this.
You could also use addEventListener() in this case:
document.getElementById('myButton').addEventListener('click', myFunction, false);

And also in this situation, using document.querySelector() (as opposed to document.querySelectorAll()), which returns the first element that matches the passed-in selector, using CSS notation:
// gets the element with an 'id' of 'myButton', binding the 'click' event-handler:
document.querySelector('#myButton').addEventListener('click', myFunction, false);

Or:
// gets the first of the <input> elements, binding the 'click' event-handler:
document.querySelector('input').addEventListener('click', myFunction, false);

References:

*

*Array.prototype.forEach().

*Array.prototype.slice().

*document.querySelector().

*document.querySelectorAll().

*EventTarget.addEventListener().

A: Yes, you can (and should!).
document.getElementById('myButton').onclick = myFunction;

A: Sure, you only need to select your item and call it's correspondant callback function. p.e:
document.getElementById('myButton').onclick = function(e) {
    // your code here
}

Or, without the inline function:
document.getElementById('myButton').onclick = myObject.myMethod;

https://developer.mozilla.org/en/DOM/element.onclick

A: Something like this:
  document.getElementById('myButton').onclick = function() {location.href='http://stackoverflow.com';return false;}

A: document.getElementById('myButton').onclick = function () {
        console.log('Inline event attach');
    };

    document.getElementById('myButton').addEventListener('click', function () {
        console.log('Using native addEventListener');
    }, false);

A: document.getElementById('myButton').onclick = function() { myFunction(); }


text:
Q: Extracting image from UIImageView with transform I wrote a multi-touch based photo tweak program.
With UIImageView showing a photo, the transform value is set according to the user touch, to expand/shrink the image.
Here's some code that handle the multi-touch.
-(void) viewPanned:(UIPanGestureRecognizer *)g
{
    CGPoint translate = [g translationInView:imageView];
    CGAffineTransform nt = CGAffineTransformMake(1.0, 0, 0, 1.0, translate.x, translate.y ) ;

    imageView.transform = CGAffineTransformConcat( transform, nt ) ;

    if( g.state == UIGestureRecognizerStateEnded ) {
        transform = imageView.transform ;
    }
}

-(void) viewPinched:(UIPinchGestureRecognizer *)g
{
    switch (g.state) {
        case UIGestureRecognizerStateBegan:
        {
            startScale = g.scale ;
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            CGFloat change = g.scale ;
            switch( currentMode ) {
                case 0:
                    imageView.transform = CGAffineTransformScale( transform, change, change ) ;
                    break ;
                case 1:
                    imageView.transform = CGAffineTransformScale( transform, change, 1.0 ) ;
                    break ;
                case 2:
                    imageView.transform = CGAffineTransformScale( transform, 1.0, change ) ;
                    break ;
            }
        }
            break ;
        case UIGestureRecognizerStateEnded:
        {
            transform = imageView.transform ;
        }
        default:
            break;
    }
}

-(void) viewRotated:(UIRotationGestureRecognizer *)g
{
    CGFloat rotation = g.rotation ;

    imageView.transform = CGAffineTransformRotate(transform, rotation) ;
    if( g.state == UIGestureRecognizerStateEnded ) {
        transform = imageView.transform ;
    }
}

So, the program maintains the original photo and change the transform value to show the tweak. At the end, I got the original image and the transform value as the result.
As far as using UIImageView, I can reproduce the tweaked image, by setting .image as the original photo, and .transform as the result of tweak. Now, to redraw the tweaked image to a single image, I try to use CGContextConcatCTM to apply the transform to the drawing image.
-(UIImage *)shrinkImage:(UIImage *)img size:(CGSize)size transform:(CGAffineTransform)transform
{
    UIImage *sImage ;
    CGSize trSize = CGSizeApplyAffineTransform( size, transform ) ;
    UIGraphicsBeginImageContext(trSize) ;
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGAffineTransform tr = CGAffineTransformIdentity;
    //tr = CGAffineTransformTranslate(tr, trSize.width/2, trSize.height/2);  // only works on rotate
    tr = CGAffineTransformConcat(tr , transform);
    //tr = CGAffineTransformScale(tr, 1.0, -1.0);

    CGContextConcatCTM(context, tr);
    CGRect rect ;
    rect.origin = CGPointZero ;
    rect.size = size ;
    [img drawInRect:rect] ;
    //CGContextDrawImage(context, rect, img.CGImage); // no difference

    sImage = UIGraphicsGetImageFromCurrentImageContext() ;
    UIGraphicsEndImageContext() ;
    return sImage ;
}

Then I got a wrong image, most of the case the result is displaced from the image I expected. (What I could get with UIImageView with transform)
I searched this suite and other, and found some solutions for rotation, but there's no generic solution for any type of transform. Some mechanism only works for rotation, some works for expansion, etc.
It seems that the axis difference between UIImageView transform and CGContextConcatCTM is causing the problem. But I could not find any information about that. Logically Core graphics and UIView origin should be the same.
Can anyone tell me what is the generic solution?


text:
Q: Critique my proof of: $A \times (B \cap C) = (A \times B) \cap (A \times C)$ Critique my proof on correctness, structure, etc.
Proof. Suppose $p = (x,y)$ is an arbitrary element.
($\subseteq$)
Let $p \in A \times (B \cap C)$. By definition of cartesian product, $x \in A$ and $y \in B \cap C$. Thus, $y \in B$, $y \in C$ and $p \in (A \times B)$, $p \in (A \times C)$. By definition of $(A \times B) \cap (A \times C)$, $\ p \in (A \times B) \cap (A \times C)$ and because $p$ is arbitrary, we can say that $A \times (B \cap C) \subseteq (A \times B) \cap (A \times C)$.
($\supseteq$)
Let $p \in (A \times B) \cap (A \times C)$. Thus, $p \in (A \times B)$ and $p \in (A \times C)$. By definition of cartestian product, $x \in A$ and $y \in B$, $y \in C$. By definition of $A \times (B \cap C)$, $\ p \in A \times (B \cap C)$ and because $p$ is arbitrary, we can say that $(A \times B) \cap (A \times C) \subseteq A \times (B \cap C)$.
$\therefore$ $A \times (B \cap C) \subseteq (A \times B) \cap (A \times C)$ and $(A \times B) \cap (A \times C) \subseteq A \times (B \cap C)$, so $A \times (B \cap C) = (A \times B) \cap (A \times C)$.

A: I prefer to solve this kind of exercise by making use of the definitions and properties involved:
\begin{align*}
A\times(B\cap C) & = \{(x,y) \mid (x\in A)\wedge(y\in B\cap C)\}\\\\
& = \{(x,y) \mid (x\in A)\wedge(y\in B)\wedge(y\in C)\}\\\\
& = \{(x,y) \mid (x\in A)\wedge(x\in A)\wedge (y\in B)\wedge(y\in C)\}\\\\
& = \{(x,y) \mid ((x\in A)\wedge (y\in B))\wedge((x\in A)\wedge(y\in C))\}\\\\
& = \{(x,y) \mid (x\in A)\wedge(y\in B)\}\cap\{(x,y) \mid (x\in A)\wedge(y\in C)\}\\\\
& = (A\times B)\cap(A\times C)
\end{align*}
Hopefully this helps !

A: A first issue that seems minor, but causes all sorts of confusion:  don't use commas as connectives; they often mean 'and' but sometimes mean 'if, then' and sometimes even mean 'or', and you'll get in the habit of reading them one way and not even notice when someone else uses (or you use!) them differently.  Thus, say not "$y \in B$, $y \in C$" but "$y \in B$ and $y \in C$", and similarly elsewhere.
I think you ought not to start with "Suppose $p = (x, y)$ is an arbitrary element"; arbitrary elements (of what?) are not ordered pairs.  Indeed, unless you work with an explicit universal set, then you ought not to fix $p$ outside of the case distinction at all.  In case ($\subseteq$) you fix $p$, observe that by the definition of $A \times (B \cap C)$ we have that $p$ is of the form $(x, y)$ for some $x \in A$ and $y \in B \cap C$, and then proceed as before.  Similarly for the other case (except that you have to wait a bit longer).
Otherwise your argument looks fine to me, depending on the level of detail expected.  For example, as an instructor, I might ask you to explain why $p \in A \times B$ and $p \in A \times C$ by appealing to the definitions there.


text:
Q: Differential equations theorems(Pure mathematics) I'm currently doing some graduate work and came upon some problems. The content of the course is of a pure form with topics such as

*

*Existence and Uniqueness of solutions

*linear system of 1st order ODE

*asympotitic behaviour of soltuions and stability analysis

*boundary value problems for 2nd order ode

There are a lot of theorems and proofs in the course and I am unable to find a suitable book/books for this type of content. Some of the theorems are as follows
Theorems
Can anyone point me in the right direction as to what books would be best suitable for content such as this? Solving differential equations is irrelevant here and more emphasis is put on theory and understanding.

A: This book by Walter covers the theoretical aspects of ordinary differential equations quite well and was used for my graduate course.
Also the book by Coddington is often suggested as a good source for rigorous existence and uniqueness theorems.
I personally find the book by Hale to be rigorous yet not too hard to read.


text:
Q: Joining two tables in the dataset I am having a data set in vb.net with two tables one table is filled by using oracle databse and another one from Sql 2005. How can we join these two tables in the dataset

A: Is that what are you looking for:
How to join two DataTables using C#

A: You'll want to use VB .Net Linq to join the 2 datasets so long as they have compatible record properties.
Here's a decent MSDN article covering the VB .Net implementation;
http://msdn.microsoft.com/en-us/library/bb918093.aspx


text:
Q: How to code drawing a straight line with two mouse clicks (OSX Mac App)? I'm trying to make a simple drawing app (OSX Mac app) and I'm trying to figure out how the user can draw a line by two mouse clicks, for example, the first mouse click (mouseDown then mouseUP) would mark the origin point of the line, and the second mouse click (mouseDown then mouseUP) would mark the end point of the line. Before the user makes the second click of the end point, I'd like the line (before anchoring the end point) to be shown live, kind of like in photoshop. Both Objective-C and Swift are fine.
So far I've got...
var newLinear = NSBezierPath()

override func mouseDown(theEvent: NSEvent) {
        super.mouseDown(theEvent)
        var lastPoint = theEvent.locationInWindow
        lastPoint.x -= frame.origin.x
        lastPoint.y -= frame.origin.y
        newLinear.moveToPoint(lastPoint)
    }

override func mouseUp(theEvent: NSEvent) {
        var newPoint = theEvent.locationInWindow
        newPoint.x -= frame.origin.x
        newPoint.y -= frame.origin.y
        newLinear.lineToPoint(newPoint)
        needsDisplay = true
    }

Cheers!

A: enums with associated values are great for this as your application scales up and possibly adds other tools and states.
enum State {
    case normal
    case drawingLine(from: CGPoint, to: CGPoint)
}
var state = State.normal

override func mouseDown(theEvent: NSEvent) {
    super.mouseDown(theEvent)
    var lastPoint = theEvent.locationInWindow
    lastPoint.x -= frame.origin.x
    lastPoint.y -= frame.origin.y
    state = .drawingLine(from: lastPoint, to: lastPoint)
}

override func mouseUp(theEvent: NSEvent) {
    if case .drawingLine(let firstPoint, _) = state {
        var newPoint = theEvent.locationInWindow
        newPoint.x -= frame.origin.x
        newPoint.y -= frame.origin.y
        //finalize line from `firstPoint` to `newPoint`
    }
}

override func mouseMoved(theEvent: NSEvent) {
    if case .drawingLine(let firstPoint, _) = state {
        needsDisplay = true
        var newPoint = theEvent.locationInWindow
        newPoint.x -= frame.origin.x
        newPoint.y -= frame.origin.y
        state = .drawingLine(from: firstPoint, to: newPoint)
    }
}

override func draw(_ dirtyRect: NSRect) {
    if case .drawingLine(let firstPoint, let secondPoint) = state {
        //draw your line from `firstPoint` to `secondPoint`
    }
}

A: I understand what you are attempting to achieve here! So I have added lines of code to the andyvn22's solution that should assist your endeavours, please note: for simplicity purposes start a new 'Xcode Project' and we can make sure everything is covered together.
In your new project Right Click 'ViewController.swift' and add New File... Select 'Cocoa Class' and Click Next, name this file 'DrawingView' assure Subclass of: is 'NSView' and select Next.
Now your finished that lets setup your interface, enter 'Main.storyboard' and drag/drop a 'Custom View' make sure to add constrains according to your preferences. Now enter your 'Identity Inspector' while 'Custom View' is selected and add 'DrawingView' to Class at the top.
I hope this is making sense soo far! Ok open 'Assistant Editor' so you can view 'ViewController.swift' and 'Main.storyboard' simultaneously, Right Click and drag from 'Custom View' to 'ViewController.swift', name this 'draw' and select connect.
You will notice Xcode has automatically updated @IBOutlet to your Subclass, and your 'ViewController.swift' looks like the example below.
import Cocoa

class ViewController: NSViewController {

    @IBOutlet var draw: DrawingView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }
}

Now select the 'DrawingView.swift' file and clear all content on page, highlight the code below, copy and paste into your project.
import Cocoa

class DrawingView: NSView {

    // >>>CODE ADDED BY LC<<<
    private var path: NSBezierPath = {
        let path = NSBezierPath()
        path.lineWidth = 50.0
        path.lineJoinStyle = .roundLineJoinStyle
        path.lineCapStyle = .roundLineCapStyle
        return path
    }()

    enum State {
        case normal
        case drawingLine(from: CGPoint, to: CGPoint)
    }
    var state = State.normal

    override func mouseDown(with event: NSEvent) {
        super.mouseDown(with: event)
        var lastPoint = event.locationInWindow
        lastPoint.x -= frame.origin.x
        lastPoint.y -= frame.origin.y
        state = .drawingLine(from: lastPoint, to: lastPoint)
    }

    override func mouseUp(with event: NSEvent) {
        if case .drawingLine(let firstPoint, _) = state {
            var newPoint = event.locationInWindow
            newPoint.x -= frame.origin.x
            newPoint.y -= frame.origin.y

            // >>>CODE ADDED BY LC<<<
            path.move(to: convert(event.locationInWindow, from: nil))
            path.line(to: firstPoint)
            needsDisplay = true
        }
    }

    override func draw(_ dirtyRect: NSRect) {
        if case .drawingLine(let firstPoint, let secondPoint) = state {

            // >>>CODE ADDED BY LC<<<
            NSColor.orange.set()
            path.lineWidth = 5.0
            path.stroke()
            path.line(to: firstPoint)
            path.line(to: secondPoint)
        }
    }
}

Everything should be running as intended, you will be incapable of drawing a crocked line. I hope this has helped and feel free to reply for additional information.


text:
Q: What is the default encoding for source files in Visual Studio 2017? It seems Visual Studio 2017 always saves new files as UTF8-BOM.
It also seems this was not the case with earlier versions of Visual Studio, but I could not find any documentation.
Also there has been an option "Advanced Save Options\Encoding" which did allow to change the encoding of newly saved files which is missing in VS2017.
Questions:

*

*Are all file types saved with UTF8-BOM encoding in VS2017?

*Is it possible to configure the encoding for new files in VS2017?

*Will VS2017 change the encoding of "old" files which don't have UTF8-BOM?

*Is there any documentation about this topic?

A: You can use EditorConfig with the charset property to define encoding for source files in VS 2017.

A: Apparently the "Advanced Save Options\Encoding" option has been removed from the "File" menu due to uncommon use. This was the reason given by a Visual Studio Team member (see this).
The option is still there, but you have to do a couple extra clicks.

*

*In the menu strip, Go To FILE -> Save as

*When the Save File Dialog appears, the Save button has a down arrow. Click it.

*Select Save with Encoding...

Once you save a file to a certain format (I believe the one you're looking for is Unicode (UTF-8 without signature) - Codepage 65001), Visual Studio should in theory not change it on a whim.
Now here's the problem though, once you remove the BOM, no reader can really know with 100% certainty that a given text file is actually UTF-8. This is just from observing the behaviour, but if you go and Save as With Encoding... and select
Unicode (UTF-8 without signature) - Codepage 65001 (which is UTF8 without BOM), the BOM will be removed.....however, when you close the file and reopen it, then go to Advanced Save Options again, you will notice that Visual Studio assumed that the text format was CodePage 1252. The file will of course be perfectly valid as it maps every possible byte value to some character, but that may give you strange results in some fringe cases.
One thing it will not do, is add the BOM back in (at least I have never seen it). Hope this helps.

A:
Also there has been an option "Advanced Save Options\Encoding" which
  did allow to change the encoding of newly saved files which is missing
  in VS2017.

This feature Already exists! You can save files with specific character encoding to support bi-directional languages. You can also specify an encoding when opening a file, so that Visual Studio displays the file correctly.

To save a file with encoding

*

*From the File menu, choose Save File As, and then click the
drop-down button next to the Save button. The Advanced Save Options
dialog box is displayed.

*Under Encoding, select the encoding to use for the file.

*Optionally, under Line endings, select the format for end-of-line
characters.

Are all files types saved with UTF8-BOM encoding in VS2017

In my case, VS stores all the files with CodePage 1252 encoding.

Is it possible to configure the encoding for new files in VS2017

However, My Visual Studio version is 15.6.1 and some people have the same problem like yours in previous versions of 2017, but they said "We have fixed this issue and it's available in Visual Studio 2017 15.3"
If not working, for C++ projects Take a look at /utf-8 (Set Source and Executable character sets to UTF-8).

Will VS2017 change the encoding of "old" files which don't have
  UTF8-BOM

By default, Visual Studio detects a byte-order mark to determine if the source file is in an encoded Unicode format, for example, UTF-16 or UTF-8. If no byte-order mark is found, it assumes the source file is encoded using the current user code page, unless you have specified a code page by using /utf-8 or the /source-charset option.
Some people encountered a problem which is came from .editorconfig file, as below:
root = true

[*]
indent_style = tab
indent_size = 4
tab_width = 4
trim_trailing_whitespace = true
insert_final_newline = true
charset = utf-8

That final charset line is probable doing it... but I'm not asking for 'utf-8-with-bom'!

A: Check Fix File Encoding extension that prevents Visual Studio 2017/2015/2013/2012 from adding BOM to UTF-8 files.

Normally, when you edit a UTF-8 file in Visual Studio, it adds the
  byte order mark (BOM) sequence 0xEF, 0xBB, 0xBF to the beginning of
  the file. Sometimes it confuses other applications further processing
  the file. You can select an encoding manually (File - Advanced Save
  Options... or File > Save As... > Save with Encoding...), but you need
  to do it each time you reopen the file

Also, this extension will answer most of your questions.

Fix File Encoding automatically detects when a UTF-8 file is opened in
  Visual Studio and sets its encoding to UTF-8 without signature. If you
  don't edit the file, it remains unmodified. If you edit the file, it
  will be saved without the BOM.
Fix File Encoding lets you configure which files to encode based on
  the file path and the file extension. By default, only .htm and .html
  files are protected from Visual Studio.

A: Unfortunately this is to long as comment to Nik's answer, therefore I use another one:

*

*VS saves all source code files (.cpp, .cs, .h, etc) and Web files
(.htm(l), .css, .xml) in UTF-8 with BOM (with signature in MS
jargon).

*However, VS saves text files created by VS in the code page of the
local settings, for example code page 1252 for Western European
cultures. VS is clever enough to detect characters that can't be encoded in the
default code page and will prompt you to encode in UTF-8. Visual
Studio will automatically save in UTF-8, with BOM of course, if you
check "Save documents as Unicode when data cannot be saved in
codepage" in the dialog box "Tools/Options/Environment/Documents".

*You can override the encoding for each single file by using "Save
As", but you can't override the default encodings in VS Options

*But, you can override the default settings with an EditorConfig file.
How:
https://learn.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2019.


text:
Q: Need help understanding RC discharging through a transistor in a timer Once I push and release a pushbutton I want a LED to light for say 10 seconds.
I found a design for this on the web and tried it out:

What I observed on the breadboard was that the LED lighted for at least 60 secs and seemed to be exponentially decaying.
I also found equations describing a discharging RC circuit:
$$V_C=V_0e^{-\frac{t}{RC}}$$
$$I=\frac{V_0}{R}e^{-\frac{t}{RC}}$$
According to these equations the capacitor should be "fully discharged" in t=5*R*C.
In my case R = 10kOhm and C=220uF => t = 5*1e4*2.2e-4 = 11 secs.
So what is wrong in this analysis?
Also since the transistor (BC 548) needs V_BE about 0.7 V or more I would think that the LED would decay exponentially until the voltage out of the capacitor dropped down to 0.7V and then the LED would instantly shut off.
How can i modify the Circuit to behave more like what i want?

A: Use the following circuit to turn an LED fully on with button and off after 10 seconds. You will still have to connect a transistor to the OUT terminal like you did in your circuit (The timer IC 555 might not be able to drive a LED directly).

A: The following schematic will do what you ask, I think:

simulate this circuit – Schematic created using CircuitLab
\$Q_1\$ can be any small signal PNP BJT and \$M_1\$ might be a BSS123 or BSS145 or any of a list of small signal NFETs.
The timing of the circuit depends upon \$R_1\$, \$C_1\$, and the threshold voltage of the NFET you choose.
The circuit requires the use of \$M_1\$ because there's no gate current to speak of. This allows the RC timing to be selected over a very wide dynamic range of possibilities and for extended periods of time. (A BJT in its place would not allow such a dynamic range and would greatly complicate extended periods of time.)
\$Q_1\$ is isolated from the timing issues, so it's just operated as a "switch" to supply the needed current to your LED when it is turned on by the momentary push-button \$SW_1\$. Note that \$Q_1\$ appears to parallel \$SW_1\$? That's for a reason. When you press the push-button, the circuit causes \$Q_1\$ to activate and bypass the push-button. So when the push-button is released, \$Q_1\$ stays on, keeping your LED on for the timed period, and thereby replacing the need for holding down the push-button. By the time you release the push-button, \$Q_1\$ is already active and taking over, supplying current to the LED until the timing period expires.
The BAV99 is a 2-diode part with three pins. If you feel okay grabbing up one of those, use it. If not, there's really no serious need for \$D_2\$. But \$D_1\$ is required (to speed up resetting the circuit when the timing is over.) So you can use a 1N4148 for \$D_1\$ (or some other small signal diode of your choice, I suppose) and just eliminate \$D_2\$.
This circuit also completely debounces your push-button switch. So it should work consistently and as you would want to expect from it.

A: You don't have an RC circuit, that formula does not truly apply. The discharge rate with your circuit actually follows a 1/t as the capacitor approaches ~0.6V
As the voltage on the capacitor goes down, and the current through the transistor is lowered, the effective resistance is parallel with the capacitor goes up. Increasing the linearized time constant.
To get it to do what you want, add a resistor directly from the capacitor to ground to set the time constant, and increase the resistor to the base of the transistor to reduce its effect.
Alternatively, you can add a resistor in parallel with the BE junction, to define the maximum impedance on that node.


text: Q: Card Transition Animation Swift can you give some tips on how to animate the transition when I modally present a new view controller same as Apple animates the view controllers in Reminder App, when opening the App Store from iMessage app, and also like Facebook in their Messenger app?


text:
Q: Get base_path in twig file -- Drupal 8 How can i get the base path of drupal installation in twig file?
For example i need to get http://localhost/drupal/.
I have tried
{{ base_path }}

But it's returning empty.
{{ directory }}

This is returning the theme path. but i need the base path to complete the url. Is there any way to do this?

A: @Ditto P S To get base path on twig you declare a variable in .theme file inside a preprocess

andthen simply use 'base_path_success' variable in twig as
{{ base_path_success }}

You can declare variable inside any of the preprocess like
function ttnd_preprocess_node(&$variables) {}

OR
function ttnd_preprocess_block(&$variables) {}

Here ttnd is themename.
For more information you can use the below link
https://drupal.stackexchange.com/questions/205289/base-path-drupal-8

A: You can get the hostname, "localhost/drupal/", directly from the getHost() request:
$host = \Drupal::request()->getHost();

In some cases you might want to get the schema as well, fx http://localhost/drupal/:
$host = \Drupal::request()->getSchemeAndHttpHost();

Source : https://drupal.stackexchange.com/a/202811/


text:
Q: Loading Firebase SDKs via reserved URL is giving "Permission denied" error I have managed to deploy my Firebase site using a reserved url as described in the documentation. Everything works when my database rules are set to "true" however as soon as I try to put in a rule it throws an error "Permission Denied"
I haven't changed the default code for index.html except adding simple lines to try and to include the path of the node I am trying to read or write to. I have managed to use these rules in NodeJS and also in the FirebaseUI for logins through another site but I can't seem to load my sdk config automatically as it suggests in the documentation. Can anyone offer some insight? Thanks.
EDIT: I just successfully attempted to create a new user using firebase.auth(). Obviously my configuration has in fact therefore been automatically imported. I am at a loss as to why I am unable to read or write to the database except as a user within the scope of the rules. I thought the Admin SDK overrides all db rules. Am I missing something obvious?

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Welcome to Firebase Hosting</title>

Welcome

Firebase Hosting Setup Complete

You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something
      extraordinary!

    Open Hosting Documentation

Firebase SDK Loading…

/*
{
  "rules": {
    ".read": true,
    ".write": true
  }
}
*/

{
  "rules": {
    "users": {
      "$user_id": {
        ".write": "$user_id === auth.uid",
        ".read": "$user_id === auth.uid"
      },
      "Google_logins": {
        ".read":true,
        ".write":true
      }
    }
  }
}

A: Your web page is not using the Admin SDK, but the regular JavaScript SDK. This means your code has to adhere to your own security rules and this line:
firebase.database().ref('/users').on('value', snapshot => {

Won't work, since your security rules don't give anyone permission to read the /users node.
If you want the user to read their own node from the database, that'd be:
firebase.auth().onAuthStateChanged(user => {
  if (user) {
    firebase.database().ref('/users').child(user.uid).on('value', snapshot => {
      ...


text:
Q: Python - Using Strings As A Condition Operator In An If Statements In Python is it possible to use a string as an operator in an if statement condition?
I would like to have an object with two values and an operator to test them.
For Example:
class Condition:
    def __init__(self, value1, operator, value2):
        self.value1 = value1
        self.operator = operator
        self.value2 = value2

    def test(self):
        if self.value1 self.operator self.value2: <- THIS IS NOT CORRECT.
            return True
        else:
            return False

condition = Condition(5, ">", 4)
if condition.test() == True:
    print("passed")
else:
    print("failed")

Thanks.

A: Python's operator module provides functions corresponding to all the built-in operators, so you can write:
import operator

class Condition:
    def __init__(self, value1, op, value2):
        self.value1 = value1
        self.op = op
        self.value2 = value2
    def test(self):
        return self.op(self.value1, self.value2)

condition = Condition(5, operator.gt, 4)

if condition.test():
    print("passed")
else:
    print("failed")

If you want to pass strings instead of the functions, you can use a dict to map them:
import operator

OPERATOR_SYMBOLS = {
    '<': operator.lt,
    '<=': operator.le,
    '==': operator.eq,
    '!=': operator.ne,
    '>': operator.gt,
    '>=': operator.ge
}

class Condition:
    def __init__(self, value1, op, value2):
        self.value1 = value1
        self.op = op
        self.value2 = value2
    def test(self):
        return OPERATOR_SYMBOLS[self.op](self.value1, self.value2)

condition = Condition(5, '>', 4)

if condition.test():
    print("passed")
else:
    print("failed")

A: You can use eval('{}{}{}'.format(v1,op,v2))

A: The operator module provides the various comparators as functions, so you could map from string form to a function to perform the comparison:
import operator

class Condition:

    cmp_to_op = {'==': operator.eq,
                  '!=': operator.ne,
                  '<': `operator.lt,
                  '<=': `operator.le,
                  '>': `operator.gt,
                  '>=': `operator.ge}

    def __init__(self, value1, operator, value2):
        self.value1 = value1
        self.operator = self.cmp_to_op(operator)
        self.value2 = value2

    def test(self):
        # No need for if return True else return False; comparison already returns
        # True or False for normal objects
        return self.operator(self.value1, self.value2)


text:
Q: Can someone explain, what does the webhook do in api.ai? I am new to api.ai. I want to send data to the web server and receive it and then give it to the users? From the documentation that I read, I understood that I have to use a webhook. But I am not sure how will api.ai send and receive the data?
Can the webhook be developed in any language?

A: The webhook is a web service that you implement in any language and on any platform, with an HTTP (must be https for ghome) and JSON interface, that fullfils (in their lingo) a user intent.
API.AI matches a user utterance to an intent (which then suggests entity values and a response) and they pass these in the call to your web service.  You do whatever processing you need - your domain logic - and then return a speech response for the user and optionally some API.AI contexts.
You can read more about it (and about slot filling fulfillment which is a little different) here.

A: You can visualize the working of a webhook like a block where data request comes in JSON format somewhat like this:
{
  "id": "7aef9329-4a32-4d59-b661-8bf380a0f35b",
  "timestamp": "2017-06-07T05:36:12.641Z",
  "lang": "en",
  "result": {
    "source": "agent",
    "resolvedQuery": "hi",
    "action": "order.pizza",
    "actionIncomplete": true,
    "parameters": {
      "address": "",
      "crust": "",
      "sauce": "",
      "size": "",
      "time": "",
      "topping": "",
      "type": ""
    }
  }
}

and another json file is returned to it according to the prescribed settings.


text:
Q: multiple KVM guests script using virt-install I would like install 3 KVM guests automatically using kickstart.
I have no problem installing it manually using virt-install command.
virt-install \
-n dal \
-r 2048 \
--vcpus=1 \
--os-variant=rhel6 \
--accelerate \
--network  bridge:br1,model=virtio \
--disk path=/home/dal_internal,size=128 --force \
--location="/home/kvm.iso" \
--nographics \
--extra-args="ks=file:/dal_kick.cfg console=tty0 console=ttyS0,115200n8 serial" \
--initrd-inject=/opt/dal_kick.cfg \
--virt-type kvm

I have 3 scripts like the one above - i would like to install all 3 at the same time, how can i disable the console? or running it in the background?

A: Based on virt-install man page:
http://www.tin.org/bin/man.cgi?section=1&topic=virt-install
--noautoconsole

Don't automatically try to connect to the guest console. The
           default behaviour is to launch virt-viewer(1) to display the
           graphical console, or to run the "virsh" "console" command to
           display the text console. Use of this parameter will disable this
           behaviour.

virt-install will connect console automatically. If you don't want,
just simply add --noautoconsole in your cmd like
virt-install \
-n dal \
-r 2048 \
--vcpus=1 \
--quiet \
--noautoconsole \
...... other options

A: We faced the same problem and at the end the only way we found was to create new threads with the &.
We also include the quiet option, not mandatory.
---quiet option (Only print fatal error messages).
virt-install \
-n dal \
-r 2048 \
--vcpus=1 \
--quiet \
--os-variant=rhel6 \
--accelerate \
--network  bridge:br1,model=virtio \
--disk path=/home/dal_internal,size=128 --force \
--location="/home/kvm.iso" \
--nographics \
--extra-args="ks=file:/dal_kick.cfg console=tty0 console=ttyS0,115200n8 serial" \
--initrd-inject=/opt/dal_kick.cfg \
--virt-type kvm &

A: I know this is kind of old, but I wanted to share my thoughts.
I ran into the same problem, but due to the environment we work in, we need to use sudo with a password (compliance reasons). The solution I came up with was to use timeout instead of &. When we fork it right away, it would hang due to the sudo prompt never appearing. So using timeout with your example above: (we obviously did timeout 10 sudo virt-instal...)
timeout 15 virt-install \
-n dal \
-r 2048 \
--vcpus=1 \
--quiet \
--os-variant=rhel6 \
--accelerate \
--network  bridge:br1,model=virtio \
--disk path=/home/dal_internal,size=128 --force \
--location="/home/kvm.iso" \
--nographics \
--extra-args="ks=file:/dal_kick.cfg console=tty0 console=ttyS0,115200n8 serial" \
--initrd-inject=/opt/dal_kick.cfg \
--virt-type kvm

This allowed us to interact with our sudo prompt and send the password over, and then start the build. The timeout doesnt kill the process, it will continue on and so can your script.


text:
Q: How to fix the position change issue in Expandable listview I am trying to figure out how to fix the position change issue in Expandable listview. I have a image view consist of two icon basically for marking favourite and unfavourite. When i set onclick listner of imageview present in expandable listview adapter in below method
 @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
 if (convertView == null) {
            LayoutInflater inf = (LayoutInflater) context
                    .getSystemService(context.LAYOUT_INFLATER_SERVICE);
            convertView = lInflater.inflate(R.layout.myfav, parent, false);

        }

final ImageView         favourite_icon = (ImageView) convertView.findViewById(R.id.favourite_icon);
  favourite_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
 ImageView imageView = (ImageView)expandableListView.getChildAt(groupPosition).findViewById(R.id.favourite_icon);

            imageView.setColorFilter(context.getResources().getColor(R.color.datedisplay),android.graphics.PorterDuff.Mode.MULTIPLY);
}});

Position is coming wrong and some other item icon color is getting changed. When i scroll in this lisview the setted icon tint is getting changed automatically

A: It might be this:
        expandableListView.getChildAt(groupPosition)

Using the group index on the child list, that will cause problems.


text:
Q: WPF xml:lang/Language binding how can i bind Listbox's or texblock's Language attribute (or xml:lang attribute).
i want to show month names in the specific language setting
ex:
<TextBlock x:Name="Date" xml:lang="{Binding Lang}">
        <TextBlock.Text>
            <MultiBinding StringFormat=" {0:dd.MMM.yyyy}-{1:dd.MMM.yyyy}">
                <Binding Path="Date1"/>
                <Binding Path="Date2"/>
            </MultiBinding>
</TextBlock.Text>

result should be according to Lang property:
01.Apr.2011 - 01.Apr.2011  en-US
or 01.Nis.2011 - 02.Nis.2011  tr-TR
or ....
it gives XamlParseException : Language attribute cannot convert to System.Windows.Markup.XmlLanguage type (that is not exact Error Text. )
Any Idea?

A: In the Startup event of the application, add this instruction:
FrameworkElement.LanguageProperty.OverrideMetadata(
    typeof(FrameworkElement),
    new FrameworkPropertyMetadata(
        XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

It will override the default value of the Language property to the current culture, for the whole application.

EDIT: ok, I had misunderstood your question...
If you want to bind the Language property to a string containing the IetfLanguageTag, you need a converter:
[ValueConversion(typeof(string), typeof(XmlLanguage))]
public class IetfTagToXmlLanguageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string tag = value as string;
        if (tag == null)
            return Binding.DoNothing;
        return XmlLanguage.GetLanguage(tag);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        XmlLanguage lang = value as XmlLanguage;
        if (lang == null)
            return Binding.DoNothing;
        return lang.IetfLanguageTag;
    }
}

Declare the converter in the XAML resources:
<local:IetfTagToXmlLanguageConverter x:Key="languageConverter" />

And use the converter in the binding:
<TextBlock Language="{Binding Lang, Converter={StaticResource languageConverter}}">

A: you could create attached property and use it.
sealed class CultureBehavior
{
    public static DependencyProperty CultureProperty =
        DependencyProperty.RegisterAttached("Culture",
            typeof (string),
            typeof (CultureBehavior),
            new UIPropertyMetadata(OnCultureChanged));

    public static void SetCulture(FrameworkElement target, string value)
    {
        target.SetValue(CultureProperty, value);
    }

    public static string GetCulture(FrameworkElement target)
    {
        return (string) target.GetValue(CultureProperty);
    }

    private static void OnCultureChanged(DependencyObject target, DependencyPropertyChangedEventArgs args)
    {
        var element = target as FrameworkElement;
        if (element == null) return;

        element.Language = XmlLanguage.GetLanguage(args.NewValue.ToString());
    }
}

XAML
xmlns:local="clr-namespace:App.Utils"
....

<TextBlock Text="{Binding Repairs, StringFormat=c}"  local:CultureBehavior.Culture="{Binding CultureString}" />


text:
Q: Ubuntu Software Center: The upload does not appear to be a valid click package I'm trying to upload an application to the Ubuntu Software Center and have encountered this error when uploading the .deb file:
The upload does not appear to be a valid click package.
What is the reason for this error?

A: Sounds like you were accidentally in the phone section, clicks are currently for Ubuntu Touch. Click on "Desktop" as shown here:

That should get you in the right section, also remember that you won't get e-mail's for notes on the submission, so check the status and feedback areas often.


text:
Q: How to split Android activity in two part and part - 1 must be scrollable I want activity in which part one is scrollable and part two remains still.

A: You can use a vertical Linear layout as the parent with two children.
Child 1 - Scrollview with weight 1
Child 2 - A view with height as wrap_content

A: use something along the lines of this code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0"
        android:layout_weight="3"
        android:background="#abc">
        <!--some content for scrolling here-->
    </ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0"
        android:layout_weight="1"
        android:background="#cba">
        <!--put other component here-->
    </LinearLayout>
</LinearLayout>

here the ScrollView has a layout weight of 3 vs 1 for the LinearLayout so it will take 75% of height and 25% will be given to LinearLayout