text:
Q: How to move OpenID store to database instead of /tmp We have a rails application that uses devise, and omniauth and wanted to support openID. We have it working on a single server, but it uses "/tmp" for it's "filesystem store". It seems like this wont work for multi application server environment.
How can we create a database store instead of the standard filesystem store?  Better yet, is there a gem that will do it?
Thanks

A: There's actually a gem for this now:
https://github.com/TheNeatCompany/openid-activerecord-store
# Omniauth example:
Rails.application.config.middleware.use(
  OmniAuth::Strategies::GoogleApps,
  OpenID::Store::ActiveRecord.new,
  { :name => 'example', :domain => 'example.org' }
)

A: Here are the steps:
1) create a table to store the authentication tokens: let's name it authentications
class CreateAuthentications < ActiveRecord::Migration
  def self.up
    create_table :authentications do |t|
      t.integer :user_id
      t.string  :provider
      t.string  :uid
      t.string  :provider_name
      t.string  :provider_username
      t.text    :token

      t.timestamps
    end

    add_index :authentications, :user_id
    add_index :authentications, :provider
    add_index :authentications, :uid
    add_index :authentications, :token, :unique=>true
  end

  def self.down
    drop_table :authentications
  end
end

2) Modify the OmniauthCallbacksController::process_callback method (this is the method I used to process the all the callbacks from the OpenId and Facebook services) to create an authentication record and store it in the newly created authentications table:
def process_callbacks
  # ...some code here

   # Find if an authentication token for this provider and user id already exists
    authentication = Authentication.find_by_provider_and_uid(@omniauth_hash['provider'], @omniauth_hash['uid'])
    if authentication     # We found an authentication
      if user_signed_in? && (authentication.user.id != current_user.id)
        flash[:error] = I18n.t "controllers.omniauth_callbacks.process_callback.error.account_already_taken",
        :provider => registration_hash[:provider].capitalize,
        :account => registration_hash[:email]
        redirect_to edit_user_account_path(current_user)
        return
      end
    else
      # We could not find the authentication than create one
      authentication = Authentication.new(:provider => @omniauth_hash['provider'], :uid => @omniauth_hash['uid'])
      if user_signed_in?
        authentication.user = current_user
      else
        registration_hash[:skip_confirmation] = true
        authentication.user = User.find_by_email(registration_hash[:email]) || User.create_user(registration_hash)
      end
    end
    @user = authentication.user
    # save the authentication
    authentication.token = @omniauth_hash
    authentication.provider_name = registration_hash[:provider]
    authentication.provider_username = registration_hash[:email]

    if !authentication.save
      logger.error(authentication.errors)
    end

  #...more code here

end

3) go get a nice coffee since your are done.
Now note that the process_callbacks method depends by your application and it can be pretty complex. If you need more help with it just ask.
Hope this help


text:
Q: Eliminate pandas dataframe rows with partial matches I want to compare two pandas dataframes and find out the rows that are only in df1, by comparing the values in column A and B. I feel like I could somehow perform this by using merge but cannot figure out..
import pandas as pd

df1 = pd.DataFrame([[1,11, 111], [2,22, 222], [3, 33, 333]], columns=['A', 'B', 'C'])
df2 = pd.DataFrame([[1, 11]], columns=['A', 'B'])

df1
    A   B   C
0   1   11  111
1   2   22  222
2   3   33  333

df2
    A   B
0   1   11

Dataframe I want to see
    A   B   C
1   2   22  222
2   3   33  333

A: Based on this approach:
import pandas as pd

df1 = pd.DataFrame([[1,11, 111], [2,22, 222], [3, 33, 333]], columns=['A', 'B', 'C'])
df2 = pd.DataFrame([[1, 11]], columns=['A', 'B'])

Concatenate the dataframes:
df = pd.concat([df1, df2])
df.reset_index(drop=True)

Groupby your desired comparison columns - in your case, A and B:
df_gpby = df.groupby(['A','B'])

Get the indexes for the groups with only one value - i.e. unique A,B pairs:
idx = [x[0] for x in df_gpby.groups.values() if len(x) == 1]

Subset the concatenated dataframe by the indexes:
df.iloc[idx]

Results in:
    A   B   C
1   2   22  222
2   3   33  333

A: While vmg's solution is neat, it requires you to know which columns you need to group by. A more generic approach is this:
First subtract one data frame from another:
In [46]: df3 = df1.subtract(df2)

In [47]: df3
Out[47]:
    A   B   C
0   0   0 NaN
1 NaN NaN NaN
2 NaN NaN NaN

You see that the interesting rows, are those who don't exist in df2, so they are all NaN. Using numpy method you can find those rows:
In [50]: np.isnan(df3.iloc[0])
Out[50]:
A    False
B    False
C     True
Name: 0, dtype: bool

In [51]: np.isnan(df3.iloc[1])
Out[51]:
A    True
B    True
C    True
Name: 1, dtype: bool

Now, that you know how to locate those rows, you can do a crazy one liner:
In [52]: df1.iloc[[idx for idx, row in df3.iterrows() if
                  all(np.isnan(df3.iloc[idx]))]]
Out[52]:
   A   B    C
1  2  22  222
2  3  33  333

update, let's add a generic function
def substract_dataframe(df1, df2):
    for i in [df1, df2]:
        if not isinstance(i, pd.DataFrame):
            raise ValueError(("Wrong argument given!
                             All arguments must be DataFrame instances"))
    df = df1.subtract(df2)
    return df1.iloc[[idx for idx, row in df.iterrows() if
                    all(np.isnan(df.iloc[idx]))]]

testing ...
In [54]: substract_dataframe(df1, df2)
Out[54]:
   A   B    C
1  2  22  222
2  3  33  333

In [55]: substract_dataframe(df1, 'sdf')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-55-6ce801e88ce4> in <module>()
----> 1 substract_dataframe(df1, 'sdf')

<ipython-input-53-e5d7db966311> in substract_dataframe(df1, df2)
      2     for i in [df1, df2]:
      3         if not isinstance(i, pd.DataFrame):
----> 4             raise ValueError("Wrong argument given! All arguments must be DataFrame instances")
      5     df = df1.subtract(df2)
      6     return df1.iloc[[idx for idx, row in df.iterrows() if all(np.isnan(df.iloc[idx]))]]

ValueError: Wrong argument given! All arguments must be DataFrame instances

A: Use merge with indicator, was added in 0.17.0 version
In [3544]: df1.merge(df2, how='left', indicator='_b').query('_b != "both"').drop('_b', 1)
Out[3544]:
   A   B    C
1  2  22  222
2  3  33  333

Details
In [3545]: df1.merge(df2, how='left', indicator='_b')
Out[3545]:
   A   B    C         _b
0  1  11  111       both
1  2  22  222  left_only
2  3  33  333  left_only

In [3546]: df1.merge(df2, how='left', indicator='_b').query('_b != "both"')
Out[3546]:
   A   B    C         _b
1  2  22  222  left_only
2  3  33  333  left_only

redpajama_set_name: RedPajamaStackExchange


text:
Q: problem for deploy my django-rest project on heroku I have a problem to deploy my django REST app on heroku.
I have use heroku tutorial. I searched the solutions on stackoverflow and on google. I found many solutions but nothing is working.
this is my folder tree of my project

My Procfile
web: gunicorn source.apiNomad.apiNomad.wsgi:application --log-file=-

i use:

*

*python 3.7

*djangoREST

This is my terminal response for a command line heroku logs --tail --app MY_APP
2019-04-02T05:05:07.736659+00:00 heroku[web.1]: Starting process with command `gunicorn source.apiNomad.apiNomad.wsgi:application --log-file=-`
2019-04-02T05:05:10.137794+00:00 heroku[web.1]: State changed from starting to up
2019-04-02T05:05:09.767500+00:00 app[web.1]: [2019-04-02 05:05:09 +0000] [4] [INFO] Starting gunicorn 19.9.0
2019-04-02T05:05:09.768230+00:00 app[web.1]: [2019-04-02 05:05:09 +0000] [4] [INFO] Listening at: http://0.0.0.0:48360 (4)
2019-04-02T05:05:09.768362+00:00 app[web.1]: [2019-04-02 05:05:09 +0000] [4] [INFO] Using worker: sync
2019-04-02T05:05:09.772911+00:00 app[web.1]: [2019-04-02 05:05:09 +0000] [10] [INFO] Booting worker with pid: 10
2019-04-02T05:05:09.794722+00:00 app[web.1]: [2019-04-02 05:05:09 +0000] [11] [INFO] Booting worker with pid: 11
2019-04-02T05:05:10.051911+00:00 app[web.1]: [2019-04-02 05:05:10 +0000] [10] [ERROR] Exception in worker process
2019-04-02T05:05:10.051927+00:00 app[web.1]: Traceback (most recent call last):
2019-04-02T05:05:10.051930+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
2019-04-02T05:05:10.051931+00:00 app[web.1]: worker.init_process()
2019-04-02T05:05:10.051933+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process
2019-04-02T05:05:10.051934+00:00 app[web.1]: self.load_wsgi()
2019-04-02T05:05:10.051936+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
2019-04-02T05:05:10.051938+00:00 app[web.1]: self.wsgi = self.app.wsgi()
2019-04-02T05:05:10.051939+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
2019-04-02T05:05:10.051941+00:00 app[web.1]: self.callable = self.load()
2019-04-02T05:05:10.051943+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
2019-04-02T05:05:10.051944+00:00 app[web.1]: return self.load_wsgiapp()
2019-04-02T05:05:10.051946+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
2019-04-02T05:05:10.051948+00:00 app[web.1]: return util.import_app(self.app_uri)
2019-04-02T05:05:10.051949+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app
2019-04-02T05:05:10.051951+00:00 app[web.1]: __import__(module)
2019-04-02T05:05:10.051952+00:00 app[web.1]: File "/app/source/apiNomad/apiNomad/wsgi.py", line 16, in <module>
2019-04-02T05:05:10.051954+00:00 app[web.1]: application = get_wsgi_application()
2019-04-02T05:05:10.051955+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application
2019-04-02T05:05:10.051957+00:00 app[web.1]: django.setup(set_prefix=False)
2019-04-02T05:05:10.051959+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 19, in setup
2019-04-02T05:05:10.051960+00:00 app[web.1]: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
2019-04-02T05:05:10.051962+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 57, in __getattr__
2019-04-02T05:05:10.051963+00:00 app[web.1]: self._setup(name)
2019-04-02T05:05:10.051965+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 44, in _setup
2019-04-02T05:05:10.051967+00:00 app[web.1]: self._wrapped = Settings(settings_module)
2019-04-02T05:05:10.051968+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 107, in __init__
2019-04-02T05:05:10.051970+00:00 app[web.1]: mod = importlib.import_module(self.SETTINGS_MODULE)
2019-04-02T05:05:10.051972+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module
2019-04-02T05:05:10.051973+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2019-04-02T05:05:10.052058+00:00 app[web.1]: ModuleNotFoundError: No module named 'apiNomad'
2019-04-02T05:05:10.053218+00:00 app[web.1]: [2019-04-02 05:05:10 +0000] [10] [INFO] Worker exiting (pid: 10)
2019-04-02T05:05:10.435733+00:00 heroku[web.1]: Process exited with status 1
2019-04-02T05:05:10.450004+00:00 heroku[web.1]: State changed from up to crashed
2019-04-02T05:05:10.302761+00:00 app[web.1]: [2019-04-02 05:05:10 +0000] [11] [ERROR] Exception in worker process
2019-04-02T05:05:10.302771+00:00 app[web.1]: Traceback (most recent call last):
2019-04-02T05:05:10.302774+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
2019-04-02T05:05:10.302776+00:00 app[web.1]: worker.init_process()
2019-04-02T05:05:10.302777+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process
2019-04-02T05:05:10.302779+00:00 app[web.1]: self.load_wsgi()
2019-04-02T05:05:10.302780+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
2019-04-02T05:05:10.302782+00:00 app[web.1]: self.wsgi = self.app.wsgi()
2019-04-02T05:05:10.302784+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
2019-04-02T05:05:10.302785+00:00 app[web.1]: self.callable = self.load()
2019-04-02T05:05:10.302787+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
2019-04-02T05:05:10.302788+00:00 app[web.1]: return self.load_wsgiapp()
2019-04-02T05:05:10.302790+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
2019-04-02T05:05:10.302791+00:00 app[web.1]: return util.import_app(self.app_uri)
2019-04-02T05:05:10.302793+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app
2019-04-02T05:05:10.302795+00:00 app[web.1]: __import__(module)
2019-04-02T05:05:10.302796+00:00 app[web.1]: File "/app/source/apiNomad/apiNomad/wsgi.py", line 16, in <module>
2019-04-02T05:05:10.302798+00:00 app[web.1]: application = get_wsgi_application()
2019-04-02T05:05:10.302799+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application
2019-04-02T05:05:10.302801+00:00 app[web.1]: django.setup(set_prefix=False)
2019-04-02T05:05:10.302802+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 19, in setup
2019-04-02T05:05:10.302804+00:00 app[web.1]: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
2019-04-02T05:05:10.302805+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 57, in __getattr__
2019-04-02T05:05:10.302807+00:00 app[web.1]: self._setup(name)
2019-04-02T05:05:10.302808+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 44, in _setup
2019-04-02T05:05:10.302810+00:00 app[web.1]: self._wrapped = Settings(settings_module)
2019-04-02T05:05:10.302811+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 107, in __init__
2019-04-02T05:05:10.302813+00:00 app[web.1]: mod = importlib.import_module(self.SETTINGS_MODULE)
2019-04-02T05:05:10.302815+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module
2019-04-02T05:05:10.302817+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2019-04-02T05:05:10.302855+00:00 app[web.1]: ModuleNotFoundError: No module named 'apiNomad'
2019-04-02T05:05:10.303340+00:00 app[web.1]: [2019-04-02 05:05:10 +0000] [11] [INFO] Worker exiting (pid: 11)
2019-04-02T05:05:10.361273+00:00 app[web.1]: Traceback (most recent call last):
2019-04-02T05:05:10.361283+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 210, in run
2019-04-02T05:05:10.361666+00:00 app[web.1]: self.sleep()
2019-04-02T05:05:10.361681+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 360, in sleep
2019-04-02T05:05:10.362052+00:00 app[web.1]: ready = select.select([self.PIPE[0]], [], [], 1.0)
2019-04-02T05:05:10.362055+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 245, in handle_chld
2019-04-02T05:05:10.362307+00:00 app[web.1]: self.reap_workers()
2019-04-02T05:05:10.362314+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 525, in reap_workers
2019-04-02T05:05:10.362761+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR)
2019-04-02T05:05:10.362770+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
2019-04-02T05:05:10.362774+00:00 app[web.1]:
2019-04-02T05:05:10.362776+00:00 app[web.1]: During handling of the above exception, another exception occurred:
2019-04-02T05:05:10.362778+00:00 app[web.1]:
2019-04-02T05:05:10.362782+00:00 app[web.1]: Traceback (most recent call last):
2019-04-02T05:05:10.362827+00:00 app[web.1]: File "/app/.heroku/python/bin/gunicorn", line 11, in <module>
2019-04-02T05:05:10.362961+00:00 app[web.1]: sys.exit(run())
2019-04-02T05:05:10.362975+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 61, in run
2019-04-02T05:05:10.363193+00:00 app[web.1]: WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run()
2019-04-02T05:05:10.363195+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 223, in run
2019-04-02T05:05:10.363420+00:00 app[web.1]: super(Application, self).run()
2019-04-02T05:05:10.363427+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 72, in run
2019-04-02T05:05:10.363617+00:00 app[web.1]: Arbiter(self).run()
2019-04-02T05:05:10.363620+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 232, in run
2019-04-02T05:05:10.363878+00:00 app[web.1]: self.halt(reason=inst.reason, exit_status=inst.exit_status)
2019-04-02T05:05:10.364100+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 345, in halt
2019-04-02T05:05:10.364451+00:00 app[web.1]: self.stop()
2019-04-02T05:05:10.364453+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 393, in stop
2019-04-02T05:05:10.364997+00:00 app[web.1]: time.sleep(0.1)
2019-04-02T05:05:10.365003+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 245, in handle_chld
2019-04-02T05:05:10.365263+00:00 app[web.1]: self.reap_workers()
2019-04-02T05:05:10.365269+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 525, in reap_workers
2019-04-02T05:05:10.365692+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR)
2019-04-02T05:05:10.365723+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>

i see that one of this error shows that my wsgi file not found but, i don't know why.
Please help me because i have no any idea
thanks


text:
Q: Ruby Initialize and build methods for Object using JSON I have an object that saves incoming JSON requests in my API, a part of the JSON is the application_id, I also keep track of iteration, which represents number of API requests by application. I then save the JSON in the request_params column.
What I am trying to do is now define a method for each 'key => value' pair in the JSON. So if the JSON looked like this
{
  "application_id" : 45,
  "student_id" : 88887,
  "school_id" : 1,
  "course_id" : 1
}

It would be cool to be able to say ri = RequestInteractor.new(request_params: params) and then using helper methods to access the JSON like this ri.application_id    #=> 45
# == Schema Information
#
# Table name: request_interactors
#
#  id             :integer          not null, primary key
#  application_id :integer
#  iteration      :integer
#  request_params :json
#  result         :json
#  created_at     :datetime
#  updated_at     :datetime
#

class RequestInteractor < ActiveRecord::Base
  before_save :increment_iteration

  # Define a helper method for each key in the JSON object.
  request_params.each do |name, value|
    define_method(name) do
      value
    end
  end

  private

  def increment_iteration
    self.iteration = RequestInteractor.where(application_id: application_id).count + 1 || 1
                                                             ^^^^^^^^^^^^^^
  end
end

the application id I marked above then would be a method that is generated by the define_method metablock that should return the JSON value for its application_id
I get the following error when trying to access the object through the rails console I get.
NameError: undefined local variable or method `request_params' for #<Class:0x007fdffc940118>

I have made sure my DB is migrated and all the usual checks. I feel like I am missing some fundamental ruby knowledge between ruby classes and classes that inherit from ActiveRecord around the general initialization of the object.

A: You can use OpenStruct like this
require 'ostruct'

json = {
  "application_id" => 45,
  "student_id" => 88887,
  "school_id" => 1,
  "course_id" => 1
}

helper = OpenStruct.new(json)
helper.application_id
# => 45

Or use method_missing
@request_params = request_params

def method_missing(sym, *args)
  return @request_params[sym.to_s] if @request_params[sym.to_s]
  super
end


text:
Q: Is 10% too much for autogrow on a 4 GB sql server DB? I am getting the following error:
2011-03-07 21:59:35.73 spid64 Autogrow of file 'MYDB_DATA' in database 'MYDB' was cancelled by user or timed out after 16078 milliseconds.  Use ALTER DATABASE to set a smaller FILEGROWTH value for this file or to explicitly set a new file size.
I did some research, and I found that for large databases you should set autogrow to a fixed size (MB), and not to a percentage. I feel like this database is not large and I may not be addressing the correct issue by changing this value. Does anyone have any opinions? Thank you!
I am using SQL Server 2008 RC2 running on Windows Server 2008

A: You shouldn't relay on AutoGrow.  It should be used as a safety net and nothing more.  It should also NEVER be set to a percentage.  Change it to 1 Gig, then manually expand the database so that there is enough room for the next few years worth of data.

A: You should not rely on autogrow to manage your day-to-day needs. You should be monitoring and growing the database manually during appropriate maintenance windows. Autogrow should just be your safety net for unexpected situations.
You could also look at setting up instant file initialization to improve the speed of growth operations.

A: Check whether you have instant file initialization enabled.  This will greatly speed up your autogrow operations.


text:
Q: Can we used Facebook for Analytics to send push notyfication with mobile browsers? Is anybody know can we used Facebook for Analytics on the WEB to send push notification from the mobile browser?
Thanks for answer :)

A: It isn't presently possible to send web push notifications within mobile browsers with Facebook Analytics.


text:
Q: NOT IN WHERE Clause Error I want to fetch a list of items from my database that are not currently within my item array.
I have researched that 'NOT IN' is the perfect solution to do multiple != 'NOT EQUAL TO' in large quantities.
But my code to generate the list:
    echo $query = sprintf("SELECT * FROM %s WHERE profile_id='%s' AND id NOT IN (%s)", $table_array[$item], $profile_id, implode(',', $shop_window_items));

Causes this error:
SELECT * FROM event WHERE profile_id='945b4dbf5bf8ee1ac08a73e9e25a939772c9c9b8' AND id NOT IN (4d96b83d18a8c2db79089ac002e346fd9dea5c43,3803bb535015174e9675090fbb680a5f286ba6bf,58f07f83a8ea10ec4db9c8b7c7f39f0a6c3a2079,57c2db2ce32925bcb49b83e22513ca74cc9bcadc)Unknown column '4d96b83d18a8c2db79089ac002e346fd9dea5c43' in 'where clause

Can anyone tell me what im doing wrong?
Thanks in advance

A: You need single quotes around strings, otherwise they are assumed to be system names.
...NOT IN ('%s')", $table_array[$item], $profile_id, implode("','", ...
           ^  ^                                               ^ ^

A: Pretty sure you need quotes around the values inside the IN
echo $query = sprintf("SELECT * FROM %s WHERE profile_id='%s' AND id NOT IN (%s)", $table_array[$item], $profile_id, "'" . implode("','", $shop_window_items) . "'");


text:
Q: Editing a string using regex jquery how can i check a string if it contains a val e.g a letter, and if it does i delete it from the string?
my main issue is sending the value
$('.RemoveColumnNormalCol').live("click", function () {
            var st = $(this).attr('columnLetter'); //this can be any letter
            $('.TotalHeading').each(function () {
                var test = $(this).val();
                var replace = test.replace(/"+ st +"/g, '');
                $(this).val(replace);
            });
 });


text:
Q: Delphi TValue.Make from RttiContext.FindType with primitive types (integer, string, boolean) Hi guys i want make a TValue with TValue.Make from two string:
aNewValue := '1';        // value of TValue
aOldType  := 'integer';  // Name of TValue.TypeInfo

TValue.Make require a PTypeInfo. The idea is retrive the TypeInfo of aOldType with TRttiContext.FindType. TRttiContext.FindType return a TRttiType. TRttiType has RttiType.Handle that return a PTypeInfo.
This is my code, when i call aRttiType.Handle an Access violation is raised
var
   aRttiContext: TRttiContext;
   aRttiType:    TRttiType;
   aOldKey, aNewValue, aOldType, aNewType: string;
   aValue: TValue;
   ATypeInfo: PTypeInfo;
begin
  aNewValue := '1';
  aOldType  := 'integer';

  aRttiContext := TRttiContext.Create;
  try
      aRttiType := aRttiContext.FindType(aOldType);
      ATypeInfo := aRttiType.Handle;

      TValue.Make(@aNewValue, ATypeInfo, aValue);

      aNewType := LowerCase(aValue.TypeInfo^.Name);

      if aNewType <> aOldType then
        raise Exception.CreateFmt('"%s" is "%s" expected "%s"', [aNewValue, aNewType, aOldType]);
  finally
    aRttiContext.Free;
  end;

the problem seem aRttiContext.FindType('integer') return nil
how cai i get the type (PTypeInfo) of primitive types (integer, string, boolean)?
this works
TValue.Make(@aNewValue, TypeInfo(Integer), aValue);

but how make dynamic, eg.:
TValue.Make(@aNewValue, GetTypeInfoWithMagic('Integer'), aValue);


text:
Q: HP ProLiant DL360 G4p with 13.10 server has network issues I've just installed Ubuntu Server 13.10 x64 on my HP ProLiant DL360 G4p.
I've configured the two HDD as RAID1+0 and the installation is proceeded without problems (except during the partitioning step, it was saying that the drive was busy [or something similar] and I've chosen "Ignore")
Now the server is up and is configured on my NT intranet, the main problem is that the network adapter looks not completely working.
When I ping the server, I lose some packets before it starts reply, and during the ping some packet is lost.
The network adapter is: HP NC7782 Gigabit Server Adapter and the server has 2 of them on board.
Any help?

A: The network adapter here is a Broadcom device. Can you quickly run the firmware update for the controller and see if that resolves the issue?
Try that first before troubleshooting other levels of the stack. Cables, switch port, etc. are worth investigating, too.
Recall that the G4 series of HP ProLiant are 8-9 years-old... Keep that in mind as you invest time.


text:
Q: Angular ng-grid and JSON I'm pretty new to Angular and im trying to display my JSON in ui-grid table.
Anyways, since this is similar to ng-grid I hope someone can help me.
I have a JSON like this:
{
    Users: [
        username:'blabla',
        email:'bla@gmail.com',
        type:'admin',
        userId: [
            id:'1222'
        ]
    ],
    Teams: [
        teamName: 'team1',
        teamId: '123'
    ]
}

What I want is:
$scope.gridOptions = {
data: myDataSource,
columnDefs: [{ field: 'Users.userName', displayName: 'userName', width: 90 }]

But im unable to access all the objects. I can access username only if I set my data to myDataSource.Users

A: This is a working example :  http://jsfiddle.net/8jgpLn9h/
Controller :
var app = angular.module('app', ['ngTouch', 'ui.grid']);

app.controller('MainCtrl', ['$scope', function ($scope) {

  $scope.data = {
    Users : [{
            username : 'titi',
            email : 'bla@gmail.com',
            type : 'admin',
            userId : {
                id : '1222'
            }
        },{
            username : 'toto',
            email : 'toto@gmail.com',
            type : 'admin',
            userId : {
                id : '1'
            }
        }
    ],
    Teams : {
        teamName : 'team1',
        teamId : '123'
    }
 };
 $scope.gridOptions = { data: 'data.Users' };

}]);

HTML :


text:
Q: Partial fraction with complex root with multiplicity >1 I have the function $\frac{x^4}{(x^2+1)^5}$ but I can't remember how to calculate the fractions residues.
I know that you can calculate the residues when the root is real and have multiplicity (r) >1 by using
$b_{k}$ = $\frac{1}{(r-k)!}$ $\frac{d^{r-k}}{ds^{r-k}}$ ($\frac{N(s)}{D(s)}(s+a)^r)$ with 1<=k<=r
Is there a similar way as above for complex roots with r>1?
For example, something like
$\beta_{k}s+\beta_{l}$ = $\frac{1}{(r-k)!}$ $\frac{d^{r-k}}{ds^{r-k}}$ ($\frac{N(s)}{D(s)}((s+a)(s-a))^r)$

A: $$x^4=((x^2+1)-1)^2=(x^2+1)^2-2(x^2+1)+1$$
should reduce your expression to friendlier looking fractions.


text:
Q: Calling dlopen on ios This is a much talked about subject, particularly of late.  Hopefully this isn't a dupe as I've gone over all the other SO questions.
I'm not interested in whether this is legal or not.  Whilst it's not 100% clear whether you can freely do what you want with a dylib on iOS8, it appears some amount of dynamic loading is allowed (see for example Can you build dynamic libraries for iOS and load them at runtime?).
What I care about is just making dlopen work (forget store submissions for now)!  I've got a very basic iOS example where I manually do a dlopen followed by a dlsym to call a function in a homegrown dylib.  This works fine on the simulator but fails on device.  The device is an iPhone 4s running (non-jailbroken) iOS 7.1.2.
AFAIK it is legal to call dlopen even on iOS 7 as there are explicit Apple instructions for how to support this (see "Deploying a Containing App to Older Versions of iOS" here https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW3).
My guess is the root cause is something simple, like the dylib being in a folder which iOS doesn't like for binaries.  Does anyone have any experience doing this and know what the restrictions are, or possibly knows what I'm doing wrong.
FYI my load code is:
NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
NSString* dlPath = [NSString stringWithFormat: @"%@/frameworktest", resourcePath];
const char* cdlpath = [dlPath UTF8String];
void* hModule = dlopen(cdlpath, RTLD_LAZY);

The dylib (frameworktest) was created by creating a Cocoa Touch Framework, building and grabbing the dylib binary from the built framework and adding to the project resources (in the root folder).  otool shows the dylib as an armv7 dynmic library targeting ios min version of 7.0.  I can successfully fopen the file as well so I know I'm looking in the right folder.
I can step deep into the dlopen assembly. So far in fact that it became uninformative looking for obvious fails :)
Any ideas?

A: Checking errno after the call to dlopen I see EPERM (not a big surprise I guess).
I've added a codesign phase to the build to explicity sign the dylib and it works now.
Some extra info:  Interestingly, the sign phase for the app defaults to running over the whole .app bundle, not just the main app binary (never looked closely at that).  So one might expect this to sign the dylib as well.  In fact, when my custom phase runs codesign reports "replacing existing signature". However this might be coming from the original build of the framework.  I checked the phases for that project and the framework is also signed (again, not just the dylib but the whole framework is passed to codesign).  The sign parameters are the same.  So somewhere along the trail the dylib is getting signed incorrectly I guess.  I'll investigate this in more detail at some point and post back if there's any interesting info.  My guess is I'm breaking the system by manually creating, extracting and packaging the dylib!
Thanks to @jww and @duskwuff for the suggestions!


text:
Q: Proper escaping of quotes and parens when using expect, ssh, ant and mysqldump We currently have a working ant script that will use mysqldump to dump a database on a remote server to a file on that remote server.  We use ant's exec task to run an expect script to ssh to the remote machine and run the mysqldump command.  I'm trying to update the command to restrict the dump to only include data that is less than 3 months old.  I'm running into annoying escaping issues with quotes and parens.
Here is the command line I'm trying to get working:
expect -f ssh-pass.exp <SERVER_PASSWD> ssh <USER>@<IP_ADDRESS> \"mysqldump -h localhost -u user --password=passwd staging --where=\"createTimeFi > now() - interval 3 month\" --ignore-table=staging.JMS_MESSAGES --ignore-table=staging.JMS_ROLES --ignore-table=staging.JMS_SUBSCRIPTIONS --ignore-table=staging.JMS_TRANSACTIONS --ignore-table=staging.JMS_USERS --ignore-table=staging.TIMERS > dump.sql\"

Here is the expect script:
set password [lrange $argv 0 0]
set command [lrange $argv 1 1]
set arg1 [lrange $argv 2 2]
set arg2 [lrange $argv 3 end]
puts "command: $command"
puts "arg1: $arg1"
puts "arg2: $arg2"
set timeout -1
spawn $command $arg1 "$arg2"
match_max 100000
expect "*?assword:*"
puts "\rsending password..."
send -- "$password\r"
puts "\r**************** Running remote command, wait... ******************"
expect eof

I've tried various combinations of escaping quotes around the ssh command and the where argument to mysqldump with no success.  Sometimes expect will complain that "interval" is an unknown command.  Sometimes on my local machine the command will create files called "now" or "dump.sql" which seem to indicate that my local shell is eating the quotes and doing redirects where it shouldn't or it will complain about invalid tokens (i.e. the parens).

A: This is not an Expect issue. It's only related to shell quoting.
You need to pass that long mysqldump command and its arguments as a single "word", so you can't escape the outer quotes.  And you can use single quotes as the outer quotes so you don't have to escape the inner double quotes.
expect -f ssh-pass.exp <SERVER_PASSWD> ssh <USER>@<IP_ADDRESS> 'mysqldump -h localhost -u user --password=passwd staging --where="createTimeFi > now() - interval 3 month" --ignore-table=staging.JMS_MESSAGES --ignore-table=staging.JMS_ROLES --ignore-table=staging.JMS_SUBSCRIPTIONS --ignore-table=staging.JMS_TRANSACTIONS --ignore-table=staging.JMS_USERS --ignore-table=staging.TIMERS > dump.sql'
====
update: Some notes about your Tcl (expect)

*

*use [lindex $argv 0] instead of [lrange $argv 0 0]

*the mysqlcommand was sent with braces because you create it as a list ([lrange $argv 3 end]) but it should be a single string. Now that you're using proper shell quoting, [lindex $argv 3] will suffice and solve this issue too. If you don't pass it to expect as one argument, then set remote_command [join [lrange $argv 3 end]] and then spawn $command $arg1 $arg2


text:
Q: Make XHTML5 validate correctly and ENTITY parseable as XML I'm switching from XHTML 1.0 Strict to XHTML5, but I'm having issues with the default DOCTYPE declarations -- the documents no longer validate as XML, and cannot be loaded in some browsers when served as application/xhtml+xml with the .xhtml extension, mostly because of the entities like — etc.
I've tried just putting back the XHTML 1.0 Strict DOCTYPE and stuff, and it all works in the browsers as expected (no XML parsing errors, and the new article elements still work all right), but it no longer validates by W3 as valid HTML5, due to the meta charset specification from HTML5, for example.
How do I automatically import the entities to make the browser validate XML, but specify HTML5 for the W3 validator?

A: Use numeric HTML entities such as & for ampersands for both the HTML and XML parsers instead of & which are not valid entities. Usually MDN (Mozilla Developer Network) has reliable information and I loath W3Schools so December has a fairly exhaustive list and I'd also highly recommend the Unicode Character Table website.
My platform and website (link in my profile) is served as XHTML5 and utilizes UTF8 characters in place of images (fewer HTTP requests for better performance).
As far as doctypes are concerned you didn't specifically mention which versions of which browsers so you'd need to comment in order for me to look in to it. I have installers going all thew way back to Opera 2 and Mozilla Suite 0.8. :-)


text:
Q: Can I convert videos with javascript? I am making an application in HTML5 that lets you choose a local video file, then play it using the video tag. The problem is that some of the codecs of the videos are not playable by current browsers (XviD in general, H.264 for Firefox, etc). Is it possible to locally convert the videos to the right codec using JavaScript?
Edit: I probably didn't explain myself correctly, I am making a kind of "Media Player" using HTML5: The user chooses a file, the script reads it using the HTML5 File API and then adds it to a video tag, no server involved. This is why I need JavaScript for this.

A: I don't believe you can easily do anything like what you want - especially if you expect users to select a video file and then within seconds it's being shared online.
There are a lot of variables and a ton of processing involved in video conversion/compression and there's a reason why even gigantic sites like YouTube take quite awhile to have your videos appear.
Plus, you want people to use a variety of video file types and somehow output the same type of video file, correct? Geez. Now you have to find open source video conversion apps that you can perhaps get to work behind the scenes just to get it to play nice with whatever you final video file type will be.
I don't see how this can be done with JavaScript alone. I think you could probably build an uploader and then maybe use another app to check a directory for new files and convert the files with a script to something else....but JS alone? And from your browser? And in a halfway decent amount of time? No way.
I would suggest only allowing certain types of video files to be uploaded and reject all others. Don't even mess with converting them.

A: This would be a great deal of work, but you may want to look at the NaCl project, from Google, but it will still take a long time to do the conversion.
http://www.chromium.org/nativeclient/getting-started/getting-started-background-and-basics
Eventually this will be browser-independent, as they make plugins available, but at the moment this would only work on some versions of Chrome, I expect.
But, this way you can write your conversion in C so you can use other conversions tools already written.
You may want to explain which formats you can handle, and if they try to do one that isn't in that format, then suggest free tools to help do the conversion, to help them out.

A: I recently came across videoconverter.js but haven't had the time to try it out yet.

A: Take a look at this sample:
http://code.msdn.microsoft.com/Media-Plugins-Sample-8913a7e9


text:
Q: Kimurai in RoR - Get current_user in parse I am trying kimurai framework for rails with devise
app/models/products_spider.rb
class ProductsSpider < Kimurai::Base
  @name = 'products_spider'
  @engine = :mechanize

  def self.process(url, user)
    @start_urls = [url]
    self.crawl!
  end

  def parse(response, url:, data: {})
    Rails.logger.info "*** Spider - Start parsing"
    Rails.logger.info "    url: #{url}"
    response.xpath("//div[@class='product floatleft span6 vertical-separator' or @class='product floatleft span6 ']").each do |product|
      item = {}
      item[:title] = product.css('h2.h-pr-title')&.text&.squish
      item[:descr] = product.css('p.product_s_desc')&.text&.squish
      item[:url] = URI.parse(url).merge(URI.parse(product.css('h2.h-pr-title a')[0]["href"])).to_s
      item[:img_url] = URI.parse(url).merge(URI.parse(product.css('img')[0]["src"])).to_s
      item[:price_cents] = product.css('span.PricesalesPrice')&.text.gsub(',', '.').to_f * 100
      item[:published] = true
      item[:categories] = response.xpath("//ul[@class='breadcrumb']/li[@class='active']/span").text.squish

      add_event(:custom, :rec_total)
      Product.where(item).first_or_create
      if Product.where(item).exists?
        add_event(:custom, :rec_exists)
      else
        Product.create!(item)
        add_event(:custom, :rec_new)
      end
    end
  end
end

Inside parse I want to:

*

*get the current_user (devise session), or

*somehow I can pass the user info to parse, or

*I can use the parse! which can return the items array but in this case how can I know if the process completed ok or with errors? When using crawl! it returns the response which contains this info...

app/controllers/products_controller.rb
class ProductsController < ApplicationController
  def scrape
    url = 'https://manitaropolio.gr/proionta-manitaria/apoksiramena-manitaria'
    flash.now[:notice] = "Scrape Url: #{url}"
    response = ProductsSpider.process(url, current_user)
    if response[:status] == :completed && response[:error].nil?
      flash.now[:notice] = "Completed succesfully (added: #{response[:events][:custom][:rec_new]}, existed: #{response[:events][:custom][:rec_exists]}, total: #{response[:events][:custom][:rec_total]})"
    else
      flash.now[:alert] = response[:error]
    end
  rescue StandardError => e
    flash.now[:alert] = "Error: #{e}"
  end

config/routes.rb
Rails.application.routes.draw do
  devise_for :users

  resources :products do
    match '/scrape', to: 'products#scrape', via: :post, on: :collection
  end

  root to: "public#home"
end

app/views/products/index.html.erb

<%= notice %>

Products

<% if can? :scrape, Product %>

      <%= button_to 'Scrape', scrape_products_path %>

    <% if @products.size > 0 %>

        <%= "Count: #{@products.count}" %>
        <%= " (Total Count: #{Product.count})" if current_user.role?(:admin) %>

    <% end %>

<% end %>

Any ideas on how can I do this?
Thank you


text:
Q: Is this a solution to the equation $a|bx|+c=0$? I was working on solving a problem in math class, and I was given this problem, $a|bx|+c=0$, as a challenge to solve. This is what I came up with.
$$
a|bx|+c=0 \\
a|bx|=-c \\
|bx|=\frac{-c}{a} \\
bx=|\frac{-c}{a}| \\
x=\pm\frac{|\frac{-c}{a}|}{b}
$$
Is this the correct way to solve this equation? I graphed the equation and found that this seems to work, but I just would like some backup on it. Thanks!

A: You made a mistake when passing from the third equation to the fourth one, it should be :
$$bx=\pm\dfrac{-c}{a}.$$
Also what are $a,b,c$? Are there any restrictions on them that can allow you to divide both sides by $a$ and $b$? What if $\tfrac{-c}{a}$ is strictly negative?

A: Well look at it this way. $|ab|$ can be written as $|a||b|$
Thus, what we get is:
$$a|b||x| + c = 0$$
Regardless of whether $b$ is positive or negative, we will always get a positive value for it after applying modulus. As $b$ is a constant, we can simply remove the modulus sign without any problem.
$$ab|x| = -c$$
$$|x| = \frac{-c}{ab}$$
As $x$ is a variable who's value we are supposed to find, upon removing modulus, we have to take both positive and negative value of its possible solution. Thus we arrive at the final result:
$$x = ±\frac{-c}{ab}$$


text:
Q: How do i retain or remove the predictor variables from the logit model?
*

*Assume my data set has 15 predictor variables.while building a model using logistic regression, if i want to knock the variables off the model based on its significance/impact on the model.
Do i have to remove the predictors only when the p- value is less than 0.05?.Or do i need to consider other parameters before adding or removing a predictor variable from the glm equation? Because i was told that, Ultimately i  should be building a model with few predictor as it would be easy while implementing the model at customer's place.

please find below the model summary and help me in understand how do i remove the variables based on AIC and p values.
Call:
glm(formula = TARGET ~ duration + cons.price.idx + cons.conf.idx +
    emp.var.rate + poutcome + contact + job, family = binomial(link = "logit"),
    data = Training)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-2.9536  -0.3148  -0.1601  -0.1029   3.5807

Coefficients:
                      Estimate Std. Error z value Pr(>|z|)
(Intercept)         -1.331e+02  7.048e+00 -18.886  < 2e-16 ***
duration             8.333e-03  1.782e-04  46.764  < 2e-16 ***
cons.price.idx       1.396e+00  7.582e-02  18.408  < 2e-16 ***
cons.conf.idx        6.505e-02  5.673e-03  11.466  < 2e-16 ***
emp.var.rate        -9.507e-01  3.015e-02 -31.538  < 2e-16 ***
poutcomenonexistent  4.426e-01  8.802e-02   5.029 4.94e-07 ***
poutcomesuccess      2.054e+00  1.263e-01  16.267  < 2e-16 ***
contacttelephone    -9.380e-01  8.402e-02 -11.164  < 2e-16 ***
jobblue-collar      -4.662e-01  8.778e-02  -5.311 1.09e-07 ***
jobentrepreneur     -1.287e-01  1.623e-01  -0.793   0.4279
jobhousemaid        -2.577e-01  2.018e-01  -1.277   0.2015
jobmanagement       -2.383e-01  1.176e-01  -2.026   0.0428 *
jobretired           2.729e-01  1.222e-01   2.234   0.0255 *
jobself-employed    -2.554e-02  1.562e-01  -0.164   0.8701
jobservices         -2.343e-01  1.086e-01  -2.156   0.0311 *
jobstudent           3.178e-01  1.486e-01   2.139   0.0324 *
jobtechnician       -2.138e-02  8.854e-02  -0.241   0.8092
jobunemployed       -9.136e-02  1.890e-01  -0.483   0.6288

---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 14499  on 20592  degrees of freedom
Residual deviance:  8568  on 20575  degrees of freedom
AIC: 8604

my question is , when do i say AIC value is good? and of what basis do i remove the variables to maintain least no of variables.
Number of Fisher Scoring iterations: 6

A: The approach you are describing is known as stepwise logistic regression and has received a substantial amount of criticism due to its poor performance. Instead of using p-values it is recommended to consider AIC or SC. A nice explanation with many examples in SAS is given in http://www2.sas.com/proceedings/sugi26/p222-26.pdf


text:
Q: How to avoid "To protect your privacy, some pictures in this message were not downloaded" from appearing in Outlook I've created an email newsletter with a nice banner image, but unfortunately all of my Microsoft Outlook users are getting this message:
"To protect your privacy, some pictures in this message were not downloaded"

The problem is that the banner image is being served from our private web server, which presumably is being flagged as "not-safe."
I understand the various reasons why Outlook prevents the images from auto-loading (tracking pixels, malware, etc), but is there a way to somehow serve the image from a "safe-server" that avoids all of these hurdles?
If we serve the image from a CDN (say Cloudflare) would Microsoft then say the image is safe to auto-load? How do other services get around this problem? Surely Microsoft isn't blocking every possible image from auto-loading?
There are "white-lists" and settings within Outlook to auto-load images, but I would prefer something that's doesn't force the recipient to change their settings.

A: The correct answer is to embed the image into the message you are sending. The CID method is the most Outlook-friendly.
https://marketingland.com/embedding-images-email-consider-3-techniques-228814
https://sendgrid.com/blog/embedding-images-emails-facts/


text:
Q: saving data from promise in a variable this is a problem that is going around for DAYS in my team:
We can't figure out how to save the result of a promise (after .then) in a variable.
Code will explain better what I mean:
We start with a simple async function that retrieves the first item of a list:
const helloWorld = () => [{ name: 'hi' }];

async function getFirstHelloWorld() {
  const helloWorldList = await helloWorld();
  return helloWorldList[0].name;
}

Now, we would like to call this function and save the content of aList:
let aList;

const a = async() => {
  aList = await getFirstHelloWorld()
}

a().then(() => {
    console.log('got result:', aList)
    console.log('aList is promise:', aList instanceof Promise)
});

console.log(aList)

aList called within the .then(), console.logs the right value.
aList called outside the .then(), console.logs Promise {  }
How can we save returned values from promises to a variable?

A: You cannot take an asynchronously retrieved value, stuff it in a higher scoped variable and then try to use it synchronously.  The value will not be present yet because the asynchronous result has not been retrieved yet.  You're attempting to use the value in the variable before it has been set.
Please remember that await only suspends execution of a local function, it does not stop the caller from running.  At the point you do an await, that function is suspended and the async function immediately returns a promise.  So, NO amount of await or return gets you anything by a promise out of an async function.  The actual value is NEVER returned directly.  All async functions return a promise.  The caller of that function then must use await or .then() on that promise to get the value.
Try running this code and pay detailed attention to the order of the log statements.

console.log("1");

const helloWorld = () => [{ name: 'hi' }];

async function getFirstHelloWorld() {
  const helloWorldList = await helloWorld();
  return helloWorldList[0].name;
}

let aList;

const a = async() => {
  console.log("beginning of a()");
  aList = await getFirstHelloWorld()
  console.log("end of a()");
}

console.log("2");

a().then(() => {
    console.log('got result:', aList)
    console.log('aList is promise:', aList instanceof Promise)
});

console.log("3");

console.log('attempting to use aList value');
console.log(aList)

console.log("4");

That will give you this output:
1
2
beginning of a()
3
attempting to use aList value
undefined
4
end of a()
got result: hi
aList is promise: false

Here you will notice that you are attempting to use the value of aList BEFORE a() has finished running and set the value.  You simply can't do that in Javascript asynchronous code, whether you use await or .then().
And, remember that the return value from an async function becomes the resolved value of the promise that all async functions return.  The value is not returned directly - even though the code syntax looks that way - that's a unique property of the way async functions work.
Instead, you MUST use the asynchronous value inside the .then() where you know the value is available or immediately after the await where you know the value is available.  If you want to return it back to a caller, then you can return it from an async function, but the caller will have to use .then() or await to get the value out of the promise returned from the async function.
Assigning an asynchronously retrieved value to a higher scoped variable is nearly always a programming error in Javascript because nobody wanting to use that higher scoped variable will have any idea when the value is actually valid.  Only code within the promise chain knows when the value is actually there.
Here are some other references on the topic:
Why do I need to await an async function when it is not supposedly returning a Promise?
Will async/await block a thread node.js
How to wait for a JavaScript Promise to resolve before resuming function?
Using resolved promise data synchronously
How to Write Your Code
So, hopefully it is clear that you cannot escape an asynchronous result.  It can only be used in asynchronous-aware code.  You cannot turn an asynchronously retrieved result into something you can use synchronously and you usually should NOT be stuffing an asynchronous result into a higher scoped variable because that will tempt people writing code in this module to attempt to use the variable BEFORE is is available.  So, as such, you have to use the value inside a .then() handler who's resolved value has the value you want or after an await in the same function where the await is.  No amount of nesting in more async functions let you escape this!
I've heard some people refer to this as asynchronous poison.  Any asynchronous operation/value anywhere in a flow of code makes the entire thing asynchronous.
Here's a simplified version of your code that shows returning the value from an async function which will make it the resolved value of the promise the async function returns and then shows using .then() on that promise to get access to the actual value.  It also shows using .catch() to catch any errors (which you shouldn't forget).
FYI, since this is not real asynchronous code (it's just synchronous stuff you've wrapped in some promises), it's hard to tell what the real end code should be.  We would need to see where the actual asynchronous operation is rather than just this test code.

const helloWorld = () => [{ name: 'hi' }];

async function getFirstHelloWorld() {
  const helloWorldList = await helloWorld();
  return helloWorldList[0].name;
}

getFirstHelloWorld().then(name => {
    // use the name value here
    console.log(name);
}).catch(err => {
    console.log(err);
});

A: You need to return the variable like this and use it within the .then callback.
const a = async() => {
  const res = await getFirstHelloWorld()
  return res
}

a().then((data) => {
    console.log('got result:', data)

});


text:
Q: How do I do an automatic check every 10 seconds? Every 10 seconds, the payment status should be checked and upon successful payment, the user should receive a message about successful payment and the status should not be checked anymore.
I tried to use the setInterval() method, but it didn't stop with clearInterval().
client.on('messageCreate', (message) => { //whenever a message is sent
  if (message.content.startsWith(prefix + 'оплата')) { //if it contains an invite link

 if (!message.channel.name === 'DM') return message.channel.send("Эта команда работает только в личных сообщениях бота!")
 const nick = message.content.split(" ").splice(1).join(" ")
if (!nick) return message.author.send("Укажите ваш никнэйм!")
    const params = {
        publicKey,
        amount: "1.00" ,
        currency: 'RUB',
        billId: qiwiApi.generateId(),
        comment: "Оплата спонсорки на месяц."
       // successUrl: 'https://merchant.com/payment/success?billId=lougeghuu'
    };
    const link = qiwiApi.createPaymentForm(params);
      const PAYID  = new Discord.MessageEmbed()
      .setAuthor("GUARD QIWI", "https://media.discordapp.net/attachments/899699390082601011/903958418166005760/871755380349341797.png")
      .setTitle("Выставление счет")
      .setDescription(`
      Сумма платежа: ${params.amount} ${params.currency}
      Ваш платежный ID: ||${params.billId}||
      НИКОМУ НЕ СООБЩАЙТЕ ВАШ ПЛАТЕЖНЫЙ ID!

      Ссылка оплаты: [Нажмите сюда](${link})`)
      message.author.send({ embeds: [PAYID] })

        // generate random number between 1 and list length.

        qiwiApi.getBillInfo(params.billId).then(data => { // получаем данные о счете
          // if (error) {message.channel.send("Произошла ошибка! Возможно вы не оплатили счет!")}
           if (data.status.value == "PAID") { // Если статус счета оплачен (PAID)
             var Rcon = require('rcon');

             var conn = new Rcon("**");

             conn.on('auth', function() {
               // You must wait until this event is fired before sending any commands,
               // otherwise those commands will fail.
               console.log("Authenticated");
               console.log("Sending command: SPONSOR!")
               conn.send(`**`)

             }).on('response', function(str) {
               console.log("Response: " + str);
             }).on('error', function(err) {
               console.log("Error: " + err);
             }).on('end', function() {
               console.log("Connection closed");
               process.exit();
             });

             conn.connect();
             const embed = new Discord.MessageEmbed()
.setAuthor("GUARD QIWI", "https://media.discordapp.net/attachments/899699390082601011/903958418166005760/871755380349341797.png")
.setDescription(`Ваш счет оплачен!`)
               message.author.send({embeds: [embed]})
              }
           else {
             console.log(`${message.author.id} еще не оплатил счет.`)

           }}).catch(e => {
            console.log(`${message.author.id} еще не оплатил счет.`)

           })}})```

A: This is how you should use the setInterval method:
const interval = setInteval(()=>{
    //my code
}, 10000)

clearInterval(interval)

If you want to stop it from inside instead:
const interval = setInteval(()=>{
    //my code
    clearInterval(interval)
}, 10000)

It might be handy to put everything into a new scope to avoid clogging your code with useless variables outside the interval:
{
    const interval = setInteval(()=>{
        //my code
        clearInterval(interval)
    }, 10000)
}


text:
Q: Three diodes in series AC detection Why, in the circuit shown here, would you put three diodes in series with one another instead of using one diode?

A: It reads in the answer. To get enough voltage to be able to turn on the optocoupler LED.


text:
Q: Bad frame for custom UINavigationBar I try to make my own custom UINavigationBar, but I've a problem : with my solution, the UINavigationBar frame is in wrong position and it have wrong size... so it doesn't pass under statusbar.
So, this is my custom navigation bar :
import UIKit

class MainNavigationBar: UINavigationBar {

    override func drawRect(rect: CGRect) {
        // not translucent
        translucent = false

        // set background colo
        backgroundColor = UIColor(red: 100/255, green: 169/255, blue: 99/255, alpha: 1)

        // bar style
        barStyle = UIBarStyle.Black

        super.drawRect(rect)
    }
}

and I load it via an UITabBarController subclass (which loads a UINavigationViewController which loads my UINavigationBar) :
override func viewWillAppear(animated: Bool) {
    // init recipe
    let recipeItem = RecipeNavigationViewController(navigationBarClass: MainNavigationBar.self, toolbarClass: nil)

    [...]

    // view controllers displayed by the tab bar interface
    let controllers = [recipeItem, accountItem]
    self.viewControllers = controllers
}

So with this code, my custom UINavigationBar doesn't pass under statusbar.
What can I do?
Thank !

A: I don't think you should override UINavigationBar. The properties you're trying to customize are already exposed by the UINavigationController so you can change that in your ViewController using self.navigationController.

A: Do you really need a subclass of UINavigationBar?
Can't you achieve the same thing with the AppearanceProxy ?
UINavigationBar.appearance().titleTextAttributes = [
        NSFontAttributeName: UIFont.XXX,
        NSForegroundColorAttributeName: UIColor.XXX]

    UINavigationBar.appearance().tintColor = .XXX


text:
Q: Ошибка с messages.send Выполняю запрос к API ВКонтакте с помощью SDK (отправка сообщения из аккаунта в сообщения паблика):
String ID_Group = "-тут_ID_моего_паблика";
String message = "Test";

VKRequest request = new VKRequest("messages.send", VKParameters.from("peer_id", ID_Group, "message", message));

При выполнении появляется ошибка:

code1: 100; One of the parameters specified was missing or invalid: peer_id is accepted only from version 5.38

Я понимаю,  что оно пишет. Пробовал даже передавать version (5.38 и 5.60), но не помогло. Та же ошибка. И самое интересное, что на сайте https://vk.com/dev/messages.send в их форме ввожу всего 2 параметра (ID группы со знаком минус и текст сообщения) и сообщение отправляется. Проверял во входящих в паблике. В чем ошибка?

A: Проблема решилась добавлением в ресурсы приложения (strings.xml) строки:
string name="com_vk_sdk_ApiVersion">5.38</string


text:
Q: multiple anchor tags click event using angularjs I have multiple anchors tags in my document, I want to put only one function for every anchor tag click, For example in jQuery
$(document).on('click','a',function(){

    window.location.href='/Home.html'
});

How I need to write in angularJs. can you please help me?

A: You can make a directive and add it to anchor tag
app.directive('myevent', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function($event) {
                $window..location.href = '/Home.html' //your link here
            });
        }
    }
});

In your view you can this with anchor tag or normal div like

click me

OR

click me

It just a work around but I prefer you use JQuery that would be much more appropriate for this. Hope this helps. Thank you.

There are many other ways like using ng-click with a div tag to do the same.

In controller you can use
$scope.myEvent() {
 $window..location.href = '/Home.html' //your link here
}


text:
Q: Retain cycle and weak property I have 3 classes: Core, Cache and HttpClient
In Core I initialize Cache with param core and after I pass Cache instance to HttpClient.
Core.m
-(id)init {
    self = [super init];
    MyCache *cache = [[MyCache alloc] initWithCore:self];
    self.httpClient = [[MyHttpClient alloc] initWithCache:cache];
}

Cache.m
@interface MyCache ()
  @property (nonatomic, strong) MyHttpClient *httpClient;
@end

@interface Core ()

@property (nonatomic, strong) MyHttpClient *httpClient;

@end

@implementation MyCache
  -(instancetype) initWithCore: (Core *)core
  {
    if (self = [self init]) {
        self.httpClient = core.httpClient;
    }
    return self;
  }
@end

-(void)foo
{
  [self.httpClient doSomething];
}

MyHttpClient.m
@interface MyHttpClient : NSObject

   @property (nonatomic, strong) MyCache *cache;
  -(instancetype) initWithCache: (MyCache *)cache;

@end

@implementation MyHttpClient

-(instancetype) initWithCache: (MyCache *)cache
{
    if (self = [self init]) {
        self.cache = cache;
    }
    return self;
}

-(void) doSomething
{
  [self.cache cacheSomething];
}

What you can see, MyCache uses MyHttpClient instance through dependency injection and on other hand  MyHttpClient instance uses MyCache instance.
Is this called retain cycle?
Do I need to set MyCache or MyHttpClient property to be weak?
Thank,

A: If you put the logic into a simple diagram. You can see there is a retain cycle between HttpClient and Cache. I think it is best to set the httpclient property in Cache to weak will solve the retain cycle.


text:
Q: How To Prevent Maven from Giving Out My Password to Everybody We have a Jenkins that runs Maven on some GIT projects. It's bad enough that Jenkins prints the password when printing the command line it executes, but that is small and hidden and I guess I can live with that. What is horrible on so many levels is the following error message:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-release-plugin:2.5.3:prepare (default-cli) on project org.acme.project.build: Unable to commit files
[ERROR] Provider message:
[ERROR] The git-push command failed.
[ERROR] Command output:
[ERROR] fatal: Authentication failed for 'http://UserName:Password@bitbucket.acme.org/scm/moda/project.build.git/'
[ERROR] -> [Help 1]

Yes, the Maven release plug-in prints my username and password on the command line. That's unacceptable. I don't even know why I have to ask this question.
How do I get the maven-release-plugin to not print my password like this? (Alternatively: how do I get Jenkins to not print it?)


text:
Q: how to manage dates in shell emphasized textI have a file containing 14000 dates . I wrote a script to find the last 5 days ,
26/03/2002:11:52:25
27/03/2002:11:52:25
29/03/2002:11:30:41
30/03/2002:11:30:41
26/03/2002:11:30:41
02/04/2002:11:30:41
03/04/2002:11:30:41
04/04/2002:11:30:41
05/04/2002:11:52:25
06/04/2002:11:52:25

suppose this is the file , now I have date 02/04/2002:11:30:41 as an out put . I want to put the dates from 02/04/2002 till the end of the file in another file .
start-date = 02/04/2002 (this is my start date)
while [start-date lt end-date] do (while start date is less than end date )
start-date++ ( add one day to start day so if its 2/4/2002 it will become 3/4/2002)
echo $start-date|tee -a file1  (put it in a file)

A: There are some ways to do this: grep, sed, awk, ...
You can get the line number of matching pattern by one of the following:

*

*grep -n pattern -m 1 input | cut -d: -f1

*awk '/pattern/{ print NR }' input | head -1
and print from that line to the end of the file:

*

*$ sed -n "$(awk '/02\/04\/2002:11:30:41/ { print NR }' input | head -1),$ p"
input
or:

*

*$ awk 'NR >= line_number' line_number=$(grep -n 02/04/2002:11:30:41
-m 1 input | cut -d: -f1) input
You also can use grep -A (--after-context) or tail, ...

A: If you can do with an external helper tool, try dateutils.  It comes with a dgrep command which does what you want:
dgrep '>=2002-04-02' -i '%d/%m/%Y' < yourfile
=>
  02/04/2002:11:30:41
  03/04/2002:11:30:41
  04/04/2002:11:30:41
  05/04/2002:11:52:25
  06/04/2002:11:52:25


text:
Q: Modal View from multiple view controllers I am trying to display a view modally. The view itself works just fine but I cannot get it to pop up in this situation only:

*

*TabBarController

*
*

*NavigationController

*
*

*
*

*TableViewController: I am trying to present it from this view, programatically, from the viewDidLoad method.

*
*

*otherViews...

This is how the standard code is (taken from apple, please correct me if wrong):
LoginView *loginView = [[LoginView alloc] initWithNibName:@"LoginView" bundle:nil];

UINavigationController *loginNavigationController =
    [[UINavigationController alloc] initWithRootViewController:loginView];
[self presentModalViewController:loginNavigationController animated:YES];

[loginNavigationController release];
[loginView release];

However I cannot get it to work. Even with
self.parentViewController presentM...
self.navigationController  presentM...
self.tabbarController  presentM...

Or multiple together...
Thank you for your help

A: Try pushing and see if it works. But as per your problem is concern try to debug your application and see if there is any object is nil or not. And in case you have tabbarController+NavigationController then you need to present from tabbarController or try getting topViewController from current navigationController and then present the view modally.
Let me know if it works or not. If still it doesn't work send me your code by mail if you can I'll look into the issue.
Edit
One query - Do you want to push further viewController from the one you are trying to present modally?


text:
Q: How to pass Two templates in a same class based views I am having one issue with the django template view.
I am having two urls
1) For Current User Profile
2) For His Team mates
urls.py
path('profile/', views.UserprofileIndex.as_view(), name='user-profile'),
path('profile/<int:pk>', views.TeamProfileIndex.as_view(), name='team-profile'),

It's views
class TeamProfileIndex(TemplateView):

template_name = 'accounts/profile/team_profile.html'

def get_context_data(self, **kwargs):
    context = dict()
    self.pk = self.kwargs.get("pk")
    try:
        user_profile = Profile.objects.get(user=self.pk)
    except Profile.DoesNotExist:
        logger.error("Requested user profile not available")
        raise Http404
    teams = User.objects.all()
    context.update(
        {
            'user_profile': user_profile,
            'teams' : teams
        }
    )
    return context

class UserprofileIndex(TemplateView):

template_name = 'accounts/profile/index.html'

def get_context_data(self, **kwargs):
    context = dict()
    try:
        user_profile = Profile.objects.get(user=self.request.user)
    except Profile.DoesNotExist:
        logger.error("Requested user profile not available")
        raise Http404

    teams = User.objects.all
    context.update(
        {
            'user_profile': user_profile,
            'teams' : teams
        }
    )
    return context

In both views only one query is changing , that is 'user_profile'.
Is there any way to pass this in a single views to two diffrent html pages ?
I have tried following method
class UserprofileIndex(TemplateView):
    # template_name = 'accounts/profile/index.html'
def initialize(self, *args, **kwargs):
    self.pk = None
    self.pk = kwargs.get('pk')

def get_template_names(self, *args, **kwargs):
    if self.pk:
        return 'accounts/profile/team_profile.html'
    else:
        return 'accounts/profile/index.html'

def get_context_data(self, **kwargs):
    context = dict()
    try:
        if self.pk:
            user_profile = UserProfile.objects.get(user=self.pk)
        else:
            user_profile = Profile.objects.get(user=self.request.user)
    except Profile.DoesNotExist:
        logger.error("Requested user profile not available")
        raise Http404

    teams = User.objects.all()
    context.update(
        {
            'user_profile': user_profile,
            'teams' : teams
        }
    )
    return context

But its not working

A: This will work. But I would advise using DetailView
class UserProfile(TemplateView):
    """
    User profile view
    """
    user_profile = None
    template_name = 'accounts/profile/index.html'
    team_profile_template_name = 'accounts/profile/team_profile.html'

    def get_user_profile(self):
        """
        Get user
        """
        if not self.user_profile:
            user_profile_pk = self.kwargs.get('pk')
            model, filter_kwargs = (UserProfile, dict(user=user_profile_pk)) \
                if user_profile_pk else (Profile, dict(user=self.request.user))
            self.user_profile = get_object_or_404(model, **filter_kwargs)
        return self.user_profile

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update(dict(user_profile=self.get_user_profile(),
                            teams=User.objects.all()))
        return context

    def get_template_names(self):
        if self.kwargs.get('pk'):
            return [self.team_profile_template_name]
        return super().get_template_names()

A: If you want to use two template in signle class based view
Do something like this which i do for
DetailView
class PollDetail(DetailView):
model = Poll
context_object_name = "poll"

Instead mentioning template name in Class mention it in urls
ulrs.py
path("result/<pk>",PollDetail.as_view(template_name="results.html")),
 path("vote/<pk>",PollDetail.as_view(template_name="vote.html"))


text:
Q: Android: Change language android 8(o), Activity resources not updated while app in the background action:sendBroadcast ACTION_LOCALE_CHANGED:
I registered the broadcast in the onCreate() for ACTION_LOCALE_CHANGED. Once broadcast receiver received and localeChanged() method will call.
To get the changed locale using the below two APIs.
A) getApplicationContext().getResources().getConfiguration()
B) this.getResources().getConfiguration()
From the API (A) I can able to get the correct locale. But from the API (B) I could n't get able to get the updated/correct locale, its always giving the previous locale.
Below are the steps I tried:

*

*Open the Testapplication ->locale is in "en" (System locale also "en")

*Press home button, application went to background.

*I changed the system locale from "en" to "ja".

*All the systems has changed the locale to "ja"

*Again I opened the Testapplication (i.e Testapplication coming from background to Foreground)

*But the locale not changed, its still in the previous locale)

The below localeChanged() called whenever the ACTION_LOCALE_CHANGED broadcastreceiver received. That time application was in background.
In Android 6 and 7 this.getResources().getConfiguration() could able to bring the correct resources or locale. But android 8 and above we get this problem(locale not changed) when ACTION_LOCALE_CHANGED broadcastreceiver received.
In android emulator itself I can able to see this issue
onConfigurationChanged():
The above scenario working while using onCOnfigurationchanged().
Eventhough I can get the updated/correct locale through onConfigurationChanged(), but I want to know why its not getting the updated locale via ACTION_LOCALE_CHANGED broadcast and using this.getResources().getConfiguration() API.
Can anyone suggest any API differences are there android 7.1 and android 8.
Thanks in Advance!
Below are the source codes:
@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.i(TAG,"onCreate");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    IntentFilter testLocaleChangedFilter = new IntentFilter();
    testLocaleChangedFilter.addAction(Intent.ACTION_LOCALE_CHANGED);

    getApplicationContext().registerReceiver(new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
          localeChanged();
        }
    }, testLocaleChangedFilter);
}

LocaleChanged() method called when BroadcastReceiver() with Action: ACTION_LOCALE_CHANGED
private void localeChanged() {

   Configuration config = getApplicationContext().getResources().getConfiguration();
   Log.i(TAG, "localeChanged - getApplicationContext().getResources().getConfiguration():" + config);

   Configuration config2 = this.getResources().getConfiguration();
   Log.i(TAG, "localeChanged - this.getResources().getConfiguration():" + config2.locale);

   ((TextView)findViewById(R.id.text_language)).setText(R.string.language_text);

   Log.i(TAG,"getResources().getString(R.string.language_text):" + getResources().getString(R.string.language_text));}

@Override
public void onConfigurationChanged(android.content.res.Configuration newConfig) {
    Log.i(TAG, "onConfigurationChanged");
    super.onConfigurationChanged(newConfig);

    String locale = Locale.getDefault().toString();
    Log.i(TAG, "onConfigurationChanged(Locale):" + locale);

    Configuration config2 = this.getResources().getConfiguration();
    Log.i(TAG, "onConfigurationChanged-this.getResources().getConfiguration():" + config2.locale);}


text:
Q: SQL Server If Else and Insert /Update Why does SQL Server not support to insert/update? It only supports select.
Is there any alternative for In Duplicate Key of MySQL in SQL Server?
Please help..!
IF(SELECT accountNo
   FROM MeterReading
   WHERE accountNo = 1111) is NULL
    (INSERT INTO dbo.MeterReading
     VALUES (1, 1, 1, 1));
ELSE
    (UPDATE dbo.MeterReading
     SET currentReading = 1223
     WHERE accountNo = 1111);

A: You could go for an UPSERT:
UPDATE MeterReading SET currentReading=1223 WHERE accountNo=1111

IF @@ROWCOUNT = 0
   INSERT INTO MeterReading VALUES (1, 1, 1, 1)

A: Try this syntax:
IF NOT EXISTS(SELECT accountNo
               FROM MeterReading
               WHERE accountNo = 1111)
  BEGIN
    INSERT INTO dbo.MeterReading
    VALUES (1, 1, 1, 1)
  END
ELSE
  BEGIN
  UPDATE dbo.MeterReading
  SET currentReading = 1223
  WHERE accountNo = 1111
  END

A: You could try Merge as well
MERGE MeterReading AS target
    USING (SELECT 1111, 1223) AS source (accountNo, currentReading)
    ON (target.accountNo = source.accountNo )
WHEN MATCHED THEN
    UPDATE SET currentReading  = source.currentReading
WHEN NOT MATCHED THEN
    INSERT (col1,col2,col3,col4)
    VALUES (1, 1, 1, 1);


text:
Q: Well-defined functor of triangulated category Let $F \colon D \to D'$ be a morphism of triangulated categories, $S$ a multiplicative system compatible with triangulated structure of $D$.

Supposing the colimits below exist, Lemma 13.14.3 defines a morphism
$$
  RF(X)
  = \mathop{\mathrm{colim}}\limits_{s \colon X \to X'} F(X')
  \longrightarrow RF(Y)
  = \mathop{\mathrm{colim}}_{s' \colon Y \to Y'} F(Y')
$$
where we index over morphisms of $S$ out of $X,Y$ respectively.

The way this is defined uses MS2 of a multiplicative system.  It claims that independence follows from MS3 of a multiplicative system.
I don't see exactly why this is true.  May someone elaborate?

A: This is my attempt.

Take another choice via MS2
$$X' \rightarrow Y'', Y \rightarrow Y''$$
Then we can apply MS2 again to $(Y \rightarrow Y', Y\rightarrow Y'')$ given some $Z$. Then we obersve
$$X \rightarrow X ' \rightarrow Y' \rightarrow Z$$
is same as
$$X \rightarrow X'  \rightarrow Y'' \rightarrow Z$$

Now apply MS3 to the two morphisms $X ' \rightarrow Z$ which passes thorugh $Y', Y''$ respectively. We construct
$$Z \rightarrow Z'$$
a morphism in $S$. Now observe that we have constructed a comutative diagram in $S$ involving $(Y',Y'', Z, Z')$, this commutativity  implies that
such that both possible maps $FX' \rightarrow RFY$ conincide by definition of $RFY$.


text:
Q: IE7 Absolute Position starts at top of line as opposed to other browsers I created a fiddle that exemplifies the problem:
http://jsfiddle.net/vZtBb/
This is working exactly as I want it, but the problem is that in IE7 the absolutely positioned span (hover-tooltip-container) starts at the top of the line instead of at the bottom like it does in the other browsers.  If you add a border to hover-tooltip-container, you can see this.
This is a problem because I want the tooltip to go up, but the anchor to still be exposed.  You should be able to mouse over the tooltip as well, but the gap in IE7 makes this impossible.
If there is any way to get the hover-tooltip-container span to start in the same place on the line in IE7, IE8, and FFX, that would be perfect.
Javascript is not a solution.

A: The most simple thing you could do with the code you already have, is add a star hack to adjust the bottom rule within .hover-tooltip, for IE7.
.hover-tooltip {
   display: block;
   padding: 15px;
   position: absolute;
   margin: 0 auto;
   bottom: 1em;
   *bottom: 0;
   width: 100%;
   border: 2px outset #c0c0c0;
   background-color: #f0f0f0;
   text-align: center;
}

However, the double, nested absolute positions of .hover-tooltip-container and .hover-tooltip seem unnecessary.

A: I did something quite different (also renamed your classes, to much of a hassle to play with those looooooooooong name).
http://jsfiddle.net/vZtBb/16/
I removed the nested absolute positionning : They are the one causing the issue, since element in absolute position are taken out of context. So, 2 solo, nested absolute positionned element means that one element is in nothing (glitchy and really not wanted).
Instead of that, I placed your tooltip box in absolute, but made it start higher than the anchor by use of a negative position (top:-70px). It's sketchy a bit, but you should get my point.

A: Trying putting this after the .hover-tooltip div:

and this css:
.clearfix:after {content: ".";display: block;clear: both;visibility: hidden;line-height: 0;height: 0;}

.clearfix {display: inline-block; }

html[xmlns] .clearfix {display: block; }* html .clearfix {height: 1%; }

A: I was able to solve the problem by having the "container" element float left and have relative position.  This achieves the appearance of breaking out of containers but still provides a reference for the tooltip to go up from.


text:
Q: Error: [$parse:syntax] Syntax Error: Token ',' is an unexpected token The full error message is:

Error: [$parse:syntax] Syntax Error: Token ',' is an unexpected token at column 23 of the expression ["Serious Outcome Rate","Hospitalization Rate"] starting at [,"Hospitalization Rate"].

I have a string of data converted to an array that I'm trying to then export using the Angular ng-csv directive. A console.log of the data in array form displays the following:

[""Product Name(s)"", ""Serious Outcome Rate"", ""Hospitalization Rate"", ""IME Serious Rate"", ""DME Serious Rate"", ""STALEVO"", ""0.004234647"", ""0.002063946"", ""0.0058004"", ""0.00050709"", ""EXELON"", ""0.004005612"", ""0.001674727"", ""0.00509257"", ""0.00044815"", ""COMTAN"", ""0.000867331"", ""0.000536579"", ""0.00129375"", ""0.00024444"", ""AZILECT"", ""0.000545076"", ""0.000394459"", ""0.00102432"", ""0.00025449"", ""PARLODEL"", ""0.000375725"", ""0.000230684"", ""0.0009696"", ""0.00012616"", ""ARTANE"", ""0.00035673"", ""0.000210014"", ""0.00078005"", ""0.00033002"", ""REQUIP XL"", ""0.000318172"", ""0.000191126"", ""0.00042839"", ""0.0000432"", ""MIRAPEX"", ""0.000217509"", ""0.000144021"", ""0.00029248"", ""0.00004242"", ""SINEMET"", ""0.000177481"", ""0.000112357"", ""0.00019475"", ""0.00004321"", ""REQUIP"", ""0.000151958"", ""0.000099112"", ""0.00020999"", ""0.00001765"", ""SINEMET CR"", ""0.000135481"", ""0.000090321"", ""0.00013548"", """", ""SYMMETREL"", ""0.000083309"", ""0.000045017"", ""0.00017632"", ""0.0000544"", ""MIRAPEX ER"", ""0.000074176"", ""0.000074176"", ""0.00004945"", """", ""COGENTIN"", ""0.00005202"", ""0.000020805"", ""0.00003236"", ""0.00000694""]

Here's my code:
    var csvArray = csvData.split(',');
    csvArray.pop();

    var fp = grid.$root.find(".ng-grid-buttons");
    var csvDataLinkPrevious = grid.$root.find('.ng-grid-buttons .csv-data-link-span');
    var csvDataLinkPrevious2 = grid.$root.find('.ngHeaderButton2');
    if (csvDataLinkPrevious != null) {csvDataLinkPrevious.remove(); csvDataLinkPrevious2.remove(); }
    var csvDataLinkHtml = "

";
    csvDataLinkHtml += "";

    $(function() {
      angular.element(document).injector().invoke(function($rootScope, $compile) {
        var link = $compile(csvDataLinkHtml);
        csvDataLinkHtml = link(scope);
        fp.append(csvDataLinkHtml);
      });
    });

If I remove one set of quotes from each element in the array, the error message is slightly different:

Error: [$parse:syntax] Syntax Error: Token 'Outcome' is an unexpected token at column 9 of the expression [Serious Outcome Rate,Hospitalization Rate] starting at [Outcome Rate,Hospitalization Rate].

A: Replacing inner quotes with single quotes as dan08 suggested solved the issue.


text:
Q: Alps Touchpad on Dell: how do I install the DKMS driver to enable multitouch? Now I know that this has been asked several times here but I couldn't find any decent solution to it.
I am running Ubuntu 12.04 on my DELL N5110 and my touchpad is detected as a mouse, So I don't have the touchpad options availiable. Can't use multitouch and can't disable it either.
I have tried the dkms driver from this link.
But when I tried to install it with dpkg -i command, dpkg returns the following error:
ERROR (dkms apport): unable to determine source package for
psmouse-alps-dkms Error! Bad return status for module build on kernel:
3.2.0-25-generic-pae (i686) Consult /var/lib/dkms/psmouse-alps/0.10/build/make.log for more information.

I have installed all the updates as well.
Can someone help me out with this issue?

A: How to successfully install the ALPS Touchpad DKMS driver

*

*Download and try to install the deb file from here as the question indicates, using sudo dpkg -i. It will fail with the error in the question, which is fine (see bottom of the answer if you want to know the technical reason why.)

*To build it, type/paste the following, line-by-line, in the terminal:

sudo sed -i -e '135d' /var/lib/dkms/psmouse-alps/0.10/source/src/alps.c
sudo dkms build -m psmouse-alps -v 0.10
sudo dkms install -m psmouse-alps -v 0.10
sudo modprobe psmouse
sudo sh -c "echo psmouse >> /etc/modules"
sudo update-initramfs -u

*

*The driver should work now; reboot just in case.

*DKMS should also automatically recompile whenever you upgrade/change kernels. DO NOT install the deb file again.

What was the problem?

*

*The build log shows that compiling the module fails because of an error at character 33 in line 135 of the alps.c source file.

*That line is module_param(alps_dump_packets, int, 0644);

*The compiler expects an argument (variable name) to follow the int, but there is none.

*Since the previous line 134 disables the alps_dump_packets feature (static int alps_dump_packets = 0;), we are probably safe simply deleting the offending line 135 with sed, which allows the module to successfully build.

A: I had exact same problem on my Inspiron N5110 running Ubuntu 12.04 but was able to fix it using patch and instructions provided in these two links.
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/606238/comments/144
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/606238/comments/147
Touchpad is now recognised as a AlpsPS/2 ALPS DualPoint TouchPad and Touchpad tab is enabled in System Settings. Unfortunately, scrolling is still not an option... :-(
At least touchpad is disabled while typing, which was the biggest problem for me resulting in cryptic writings! :-) Also Fn+F3 is working now (aka, touchpad toggle).
With the last update, multitouch has been enabled on Inspiron N5110. All you need to do is install this DKMS. I think it should work for all laptops with Alps touchpad. Here are more detailed instructions on installing this module than in links provided in the answer. You'll have to change any reference of "psmouse-alps-dst-0.1" to "psmouse-alps-alt-1.3" (the latest version).

A: I've bought a DELL Latitude E6430 with ubuntu preloaded, I found the glidepoint driver installed.. 2 fingers scroll ok, pinch zoom ok, everything working. I looked for it in the dell repos, but no luck, so I did:
apt-cache show glidepoint

and found this
Package: glidepoint
Status: install ok installedPriority: extra
Section: alien
Installed-Size: 2100
Maintainer: xmy <xmy@pod-desktop>
Architecture: amd64
Version: 3.6-13
Depends: libc6 (>= 2.4), libgconf2-4 (>= 2.27.0), libglib2.0-0 (>= 2.12.0)
Conffiles:
 /etc/pm/sleep.d/90GlidePoint 85d3fe435ff5e904812cb1a03461d456
 /etc/init.d/glidepoint 5427379c9470ae9c74cba849b35e7df1
 /etc/xdg/autostart/glideusd.desktop 1585732553ad2ea2c547c9989134000f
 /etc/glidepoint/config c1aefbbc5c4fa9cec9c61b2485237d37
 /etc/glidepoint/port 72f67e70f6b7cdc4cc893edaddf0c4c6
Description: GlidePoint 3.6 touchpad driver
 GlidePoint 3.6 touchpad driver for Linux.
 .
 (Converted from a rpm package by alien version 8.79ubuntu0.1.)

so I repacked it with
sudo dpkg-repack glidepoint

and now I have this to share:
glidepoint_3.6-13_amd64.deb
try on your ubuntu, let me know if works.

A: This one works beautifully.
Download the source from the link below and place psmouse-alps-dst-0.4 folder in /usr/src/ (you need root permission).
https://docs.google.com/open?id=0BzNsvDx_ae6bQnFLQkNFT0dWc3c
Run the install.sh with root permission (Ctrl+Alt+T)
sudo bash /usr/src/psmouse-alps-dst-0.4/install.sh

You can now configure the Touchpad in System Settings.

A: Brief update to installing the ALPS driver set...
I followed the below instructions but found the driver was now at this location.
As users will note this is now version 0.11 of the ALPS driver and the line to remove in this version is line 137.
With these minor changes my Ubuntu 12.04 install (also on a Dell N5110) enabled the touchpad. Still no success with enabling edge or two-finger scrolling as yet, although the edge-scrolling option is now not grayed out in the Mouse and Touchpad control panel.


text:
Q: i2c error nvidia-gpu I installed new kernel
uname -r
6.0.0-1007-oem

And after this I get error on booting and nvidia-driver (nvidia-driver-525-open)
doesnt work
Dec  7 21:38:57 pc kernel: [    8.169416] nvidia-gpu 0000:01:00.3: i2c timeout error e0000000
Dec  7 21:38:57 pc kernel

nvidia-smi
NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver. Make sure that the latest NVIDIA driver is installed and running.: [    8.169436] ucsi_ccg 1-0008: i2c_transfer failed -110

I have nvdia 1660 Super
Thanks


text:
Q: Calculating the average of an array of logarithmic values in JavaScript I'm calculating the average of an array of log values (decibels, if it matters) in JavaScript. It occurred to me that if the numbers are log values (where 55 is 10 times 54), the average decibel level isn't going to be the average of the logarithms. What's the best way to approach this?
Below is some code with how I would normally calculate an average value in JS. What would a graceful way to calculate the average of an array of log values in JavaScript?

// These values are in decibels
const samples = [40, 50, 55, 80, 45];
document.getElementById('samples').innerText = JSON.stringify(samples);

let total = 0;

samples.forEach(value => {
  total = total + value;
});

const average = total / samples.length;

document.getElementById('avg').innerText = JSON.stringify(average);

  Decibel samples:

  Average:

A: Based on definition of Decibel (@schnauss)Decibel on Wikipedia.
There are 2 definitions: power and amplitude decibels. I take a look on power decibel.
Get rid of logarithms, find average and reapply logarithm.

var samples = [40, 50, 55, 80, 45],
    x = 0.0;

samples.forEach(value => {
    x += Math.pow(10, value/10.0);
});

var average = x / samples.length,
    logAverage = 10 * Math.log10(average);

console.log(logAverage);

Result is ~73 dB

A: A simple approach may be to invert the log in the values, do the mean as usual, and then applying the log to the result. It may be a more efficient way of doing this operation, but if performance is not critical, you could try it.
I can't try this code, so if anything goes wrong feel fry to say anything! Any suggestion is welcome.
EDIT: forgot to re-do the log at the end, just added it

// These values are in decibels
const samples = [40, 50, 55, 80, 45];

//Undo the log. Be careful if base 10 is not the one you are using!
samples.forEach(function(element, index, array){
    array[index] = Math.pow(10, element);
});

document.getElementById('samples').innerText = JSON.stringify(samples);

let total = 0;

 samples.forEach(value => {
   total = total + value;
 });

const average = Math.log10(total / samples.length);

document.getElementById('avg').innerText = JSON.stringify(average);

  Decibel samples:

  Average:

A: I think this is the appropriate formula. (Decibels can be quite confusing.)

const mean = (ns) => ns.reduce((a, b) => a + b, 0) / (ns.length || 1)

const decibelAverage = (decibels) =>
    10 * Math.log10(mean(decibels.map(n => 10 ** (n / 10))))

console.log(decibelAverage([40, 50, 55, 80, 45])) //~> 73.03013877157564

The point is that a decibel represents 10 times the base-10 logarithm of the power level.  (There is another decibel type as well.  If you need that there's a square root floating around somewhere.)


text:
Q: Single Mass Oscillator. ODE with more conditions than variables i have the following ODE of a single mass oscillator with a spring and a damper:
$m*\ddot{s}=-d*\dot{s}-c*s+m*g$
where $m = 5$, $g=10$
$c$ & $d$ are variable
The ODE is now :
$\ddot{s}=-\frac{d}{5}*\dot{s}-\frac{c}{5}*s+10$
I have 2 intitial conditions that have to apply:
$s(0)=0$
$\dot{s}(0)=0$
Now to my question: If I calculate the solution of the oscillation (e.g. with Matlab) I get
$s(t,c,d)$ which is still depending on the variables $c$ an $d$
Further i can calculate the derivatives of the solution depending on $c$ and $d$
$\dot{s}(t,c,d)$
$\ddot{s}(t,c,d)$
My problem is, that i have 3 conditions for 2 unknown variables, which makes the linear system of equations needed to solve for $c$ and $d$ overdetermined.
$s(t_{max})=s_{max}$
$\dot{s}(\ddot{s}=0)=\dot{s}_{max}$
$\dot{s}(t_{max})=0$
How do I solve for $c$ and $d$ so that all the conditions including the initial conditions are met and valid for this ODE?


text:
Q: URL rewriting with Apache .htaccess with two matches Sorry about this question - I know this is asked a lot, but this case is a little more distinct (for me at least).
I have the following content in my current .htaccess:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ index.php?mode=$1 [QSA,L]

This rewrites all URLs that are from index.php and have the mode parameter to a simply URL where the mode's content becomes the main part of the URL, like this:
http://someurl.com/index.php?mode=mymode

Becomes:

http://someurl.com/mymode

This is exactly what I need. But I also need to extend this and be able to achieve the same effect with another file of mine named user.php. The case is almost the same:
http://someurl.com/user.php?action=hello

Becomes:

http://someurl.com/hello

I have no idea how to achieve the second part without conflincting with the first one.
I'm kinda stuck on this one.

A: Keep your rules like this:
# new rules for /user.php?action=hello
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^user/([^/]+)/?$ user.php?action=$1 [QSA,L]

# existing rule for /index.php?mode=mymode
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ index.php?mode=$1 [QSA,L]

PS: Also better to use absolute path in your css, js, images files rather than arelative one. Which means you have to make sure path of these files start either with http:// or a slash /.


text:
Q: Sed replace every nth occurrence I am trying to use sed to replace every other occurrence of an html element of a file so I can make alternating color rows.
Here is what I have tried and it doesn't work.
sed 's/
/
/2' untitled.html

A: This works for me:
sed -e "s/<tr/<TR bgcolor='#E0E0E0'/g;n" simpletable.htm

sample input:

Row1 / col1	col2	col3

Row2 / col1	col2	col3

Row3 / col1	col2	col3

Row4 / col1	col2	col3

Row5 / col1	col2	col3

sample output:

Row1 / col1	col2	col3

Row2 / col1	col2	col3

Row3 / col1	col2	col3

Row4 / col1	col2	col3

Row5 / col1	col2	col3

The key is to use the n command in sed, which advances to the next line.
This works only if the TR occupy distinct lines.
It will break with nested tables, or if there are multiple TR's on a single line.

A: I'd solve it with awk:
awk '/
/&&v++%2{sub(/
/, "
")}{print}' untitled.html

First, it verifies if the line contains

/
/&&v++%2

and whether the
 is an odd found instance:
v++%2

If so, it replaces the
 in the line
{sub(/
/, "
")}

Since all lines are to be printed, there is a block that always will be executed (for all lines) and will print the current line:
{print}

A: According to http://www.linuxquestions.org/questions/programming-9/replace-2nd-occurrence-of-a-string-in-a-file-sed-or-awk-800171/
Try this.
sed  '0,/<tr/! s/<tr/<TR bgcolor='#E0E0E0'/' file.txt

The exclamation mark negates everything from the beginning of the file to the first "Jack", so that the substitution operates on all the following lines. Note that I believe this is a gnu sed operation only.
If you need to operate on only the second occurrence, and ignore any subsequent matches, you can use a nested expression.
sed  '0,/<tr/! {0,/<tr/ s/<tr/<TR bgcolor='#E0E0E0'/}' file.txt

Here, the bracketed expression will operate on the output of the first part, but in this case, it will exit after changing the first matching "Jack".
PS, I've found the sed faq to be very helpful in cases like this.

A: you can use python script to fix the html
from bs4 import BeautifulSoup

html_doc = """

Row1 / col1	col2	col3

Row2 / col1	col2	col3

Row3 / col1	col2	col3

Row4 / col1	col2	col3

Row5 / col1	col2	col3

 """

soup = BeautifulSoup(html_doc, 'html.parser')

index=0
for tr in soup.find_all('tr'):
    if tr.find('td'):
         if index % 2:
             tr.find('td').attrs['style'] = 'background-color: #ff0000;'
         else:
             tr.find('td').attrs['style'] = 'background-color: #00ff00;'
     index+=1

 print(soup)


text:
Q: C++ - Seg Fault from Deleting Dynamic Array Having some trouble deleting a dynamically allocated array, and I'm not 100% sure why. The only thing I do to this array is copy over some values from it individually (in a for loop), in another routine, which is verified to work correctly.
Here is the declaration in class:
std::complex<float> * frameData;

instantiation in constructor:
this->frameData = new std::complex<float>[n];
srand( time(NULL) );
std::complex<float> randUnityRoot;

for( int i = 0; i < this->n; i++){
    randUnityRoot = std::polar(1.0, 2*M_PI * (rand() % 1000000)/1e06);
    this->frameData[i] = randUnityRoot;
}

deletion in destructor(this is the line 70 mentioned in the backtrace):
delete[] this->frameData;

gdb backtrace after segfault at program completion:
(gdb) f 4
#4  0x00007ffff7bc579c in Frame::~Frame (this=0x602940,
__in_chrg=<optimized out>) at Frame.cpp:70
70      delete[] this->frameData;
(gdb) f 3
#3  0x00007ffff7669b96 in ?? () from /lib/x86_64-linux-gnu/libc.so.6
(gdb) f 2
#2  0x00007ffff765f39e in ?? () from /lib/x86_64-linux-gnu/libc.so.6
(gdb) f 1
#1  0x00007ffff7624b8b in abort () from /lib/x86_64-linux-gnu/libc.so.6
(gdb) f 0
#0  0x00007ffff7621425 in raise () from /lib/x86_64-linux-gnu/libc.so.6
(gdb)

I've been staring at this for a while and am right out of ideas. I figured I would turn to the hive mind. Please let me know if you would like any more information. Thanks!
EDIT: I updated everything to a vector and vector* based approach.
No segfaults :).
To generate some sort of "knowledge gained" from this however, in another class I had called something like:
std::complex<float> * frameGet;
frameGet = this->Frame->getFrame();
// Do stuff with frameGet
//THIS NEXT LINE IS THE BAD PART
delete[] frameGet;

Half question, half assertion:  delete[] frameGet calls delete on original array content? If frameGet needs to be deleted should do something like:
frameGet = NULL;
delete frameGet;

A: You most probably do not have either copy-ctor nor assignment operator explicitly defined in your class. So describe them in private section of your class (make then inaccessible):
class Frame {
//...
private:
   Frame( const Frame & );
   Frame &operator=( const Frame & );
// ...
};

you do not even have to implement them and compiler will show exact locations where your problem is by compilation errors.
About second half of your question. For some reason you think if you assign one raw pointer to another you copy that memory and need to delete them separately. That not the case, raw pointer is just a number - address in memory. So:
int *pi = new int[N]; // now pi has address of memory reserved by new, lets say 0x1234
int *api = pi;  // now api has the same address 0x1234 as pi
delete[] api; // you tell environment that you do not need memory at address 0x1234 anymore
delete[] pi; // you tell environment that you do not need memory at address 0x1234 again, which is error

The fact you just assign one pointer to another directly or do that through function result or parameter pass does not change anything.