text:
Q: eCognition - prevent rounding of raster values? I have a WorldView2 image, which I would like to segment and classify in eCognition. The image has been pre-processed to Top of the Atmosphere Reflectance, therefore hasvalues between 0-1.
The segmentation process in eCognition does not show any meaningful results and I think that is likely due to the fact that it does round decimal values. Is there a way to prevent that from happening? I would rather not have to convert to int.


text:
Q: Is there a way to enable kubernetes on docker via command line on linux? I am using docker and trying to enable kubernetes and set CPU and Memory via command line.
I have looked at this answer but unfortunately cannot find this file.
Is there any way to enable Kubernetes on Docker for Mac via terminal?

A: Docker does not have an app-ified version for Linux that I know of, so there is no relation to the Docker for Mac/Windows app. There are many tools to locally install Kubernetes on Linux so they probably didn't see much reason to make something new. Minikube is the traditional one, but you can also check out microk8s, k3s, KinD, and many others.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rubycas: empty cookies when using CASClient::Frameworks::Rails::Filter login_to_service() method I found RubyCAS very useful tool, but have problems when logging in from a form on my site.
The form is default & hidden fields a follows:
  <td id="submit-container">
    <input type="hidden" id="lt" name="lt" value="<%= @lt %>" />
    <input type="hidden" id="service" name="service" value="<%= @service %>" />
    <input type="submit" class="button" accesskey="l" value="Поехали"
           tabindex="4" id="login-submit" />
  </td>

The controller with custom login action looks like
class UsersController < ApplicationController
 before_filter CASClient::Frameworks::Rails::Filter, :except => [:new, :create, :cas_login]

 def cas_login
    credentials = { :username => params[:username], :password => params[:password]}
    client = CASClient::Frameworks::Rails::Filter
    @resp = client.login_to_service(self, credentials, 'http://local.mysite:3000/users/login')

    if @resp.service_redirect_url.nil?
      # if login failed, redisplay the page that has your login-form on it
      flash[:error] = "Invalid email or password"

      redirect_to root_url
    else
      return redirect_to(@resp.service_redirect_url)
    end
  end
end

The problem:
So after successful login in first app, and setting cookie in rubycas-server-1.1.1/lib/casserver/server.rb:
response.set_cookie('tgt', tgt.to_s)

I have empty cookies when trying to open another app using rubycas-server
When login to first app using rubycas-server out-of-the-box form everything is OK, and I logged onto second automatically
Please help! spent 3 days on this problem!


text:
Q: How to pass data to INPUT HIDE from heredoc in Oracle? I'm not able to pass data meant to be user input (passwords are hidden) to oracle scripts. My idea was to automate the development deployments using predefined user input. Please see the following example:
test.sh:
sqlplus / as sysdba @$1 <<EOF
foo
bar
baz
EOF

test.sql:
SET DEFINE ON
ACCEPT STR1 PROMPT '1: '
ACCEPT STR2 PROMPT '2: '
ACCEPT STR3 PROMPT '3: '
PROMPT Got: &&STR1 &&STR2 &&STR3

$ ./test.sh test.sql
Connected to:
Oracle Database 18c Enterprise Edition Release 18.0.0.0.0 - Production
Version 18.3.0.0.0

1: 2: 3: Got: foo bar baz

Everything looks fine until the input is hidden.
test_hide.sql:
SET DEFINE ON
ACCEPT STR1 PROMPT '1: '
ACCEPT STR2 HIDE PROMPT '2: '
ACCEPT STR3 PROMPT '3: '
PROMPT Got: &&STR1 &&STR2 &&STR3

$ ./test.sh test_hide.sql
Connected to:
Oracle Database 18c Enterprise Edition Release 18.0.0.0.0 - Production
Version 18.3.0.0.0

1: 2:
3: Got: foo  bar

Is there a way to pass data to ACCEPT ... HIDE statement or I will need to rewrite the code?


text:
Q: How bind CWebUser with model User How to bind Yii:app()->user to the model User. That there was a connection type: Yii::app()->user->getUser()
For example, I want to get the currently logged in user's email:
Yii::app()->user->getUser()->email;
I readed wiki post:http://www.yiiframework.com/wiki/80/add-information-to-yii-app-user-by-extending-cwebuser-better-version/

A: MyWbuser.php in components:
class MyWebUser extends CWebUser{

    private $_profile = null;
    public $loginUrl='/';

    public function init(){
       parent::init();
       if(!$this->getIsGuest()){
            $this->_profile = User::model()->findByPk($this->getId());
       }
    }
    public function getProfile(){
       return $this->_profile;
   }
}

In config.php:
    'user' => array(
        'class' => 'MyWebUser',
    )

Then you can use:
Yii::app()->user->profile->name

A: Try this add this code to your useridentity authenticate function
$this->setState('email',$this->email);

And use to access that email anywhere as shown
Yii::app()->user->getState('email');


text:
Q: Why Feathers client watch doesn't work sometimes (websocket, always listStrategy) We have a websocket connection in a Feathers application but it sometimes works, sometimes doesn't, you can see the clients codes here:
   return feathersClient
      .service('donations')
      .watch({ listStrategy: 'always' })
      .find({
        query: {
          lessThanCutoff: { $ne: true },
          status: { $ne: Donation.FAILED },
          $or: [{ intendedProjectTypeId: id }, { ownerTypeId: id }],
          $limit: 0,
        },
      })

https://github.com/Giveth/giveth-dapp/blob/f3d019cf4f7142077fe2910ae6de71ca78b5a4e0/src/services/MilestoneService.js#L357-L378
and feathers config in server here:
https://github.com/Giveth/feathers-giveth/blob/develop/src/app.js

A: Downgrading feathers-socketio has fixed the issue, you can checkout my PR in our project
https://github.com/Giveth/giveth-dapp/pull/2125/files


text:
Q: Pandas DataFrame naming only 1 column Is there a way with Pandas Dataframe to name only the first or first and second column even if there's 4 columns :
Here
for x in range(1, len(table2_query) + 1):
    if x == 1:
        cursor.execute(table2_query[x])
        df = pd.DataFrame(data=cursor.fetchall(), columns=['Q', col_name[x-1]])

and it gives me this :

AssertionError: 2 columns passed, passed data had 4 columns

A: Consider the df:
df = pd.DataFrame(np.arange(8).reshape(2, 4), columns=list('ABCD'))
df

then use rename and pass a dictionary with the name changes to the argument columns:
df.rename(columns=dict(A='a', B='b'))

Instantiating a DataFrame while only naming a subset of the columns
When constructing a dataframe with pd.DataFrame, you either don't pass an index/columns argument and let pandas auto-generate the index/columns object, or you pass one in yourself.  If you pass it in yourself, it must match the dimensions of your data.  The trouble of mimicking the auto-generation of pandas while augmenting just the ones you want is not worth the trouble and is ugly and is probably non-performant.  In other words, I can't even think of a good reason to do it.
On the other hand, it is super easy to rename the columns/index values.  In fact, we can rename just a few.  I think below is more in line with the spirit of your question:
df = pd.DataFrame(np.arange(8).reshape(2, 4)).rename(columns=str).rename(columns={'1': 'A', '3': 'F'})
df


text:
Q: pandas: getting the name of the column corresponding to the highest value in the row I have a pandas DF as follows:

What I want to get is a 1 Column df that contains the name of the column of the maximum value of the row, or the order number of that column. (see red circles in the pic)
Any suggestion?
here the data for copy and paste:
matrix = np.array([[0.92234683, 0.94209485, 0.90884652, 0.99763808],
       [0.86166401, 0.96755855, 0.9243107 , 0.94240756],
       [0.85457367, 0.9169915 , 0.95042024, 0.90661279],
       [0.83972504, 0.93902909, 0.91985442, 0.93765059],
       [0.84373323, 0.87762977, 0.91005636, 0.88525626]])

thanks

A: Use idxmax:
df = pd.DataFrame(matrix, columns=['Y_clm1', 'Y_clm2', 'Y_clm3', 'Y_clm4'])

>>> df.idxmax(axis=1)
0    Y_clm4
1    Y_clm2
2    Y_clm3
3    Y_clm2
4    Y_clm3
dtype: object

A: use max
df = pd.DataFrame(matrix)
max(df) == 3

max(df) corresponds to Y_clm4


text:
Q: Create Designer Workflow which is associated to particular list in all the sites I want to create a designer workflow which is associated to particular list in all the sites. Which type of workflow I need to create? Site Workflow or Reusable workflow ?

A: If you want to associate your workflow to a particular list then I believe you must choose Reusable workflow.
Reusable List Workflows (Reusable Workflow) : You can create a reusable list workflow (reusable workflow) in the top-level site in the site collection, and that workflow can be made globally reusable — meaning that the workflow can be associated to any list, library, or content type in the site collection. You can also create a reusable workflow in any subsite in the site collection; this workflow is available for reuse in that particular subsite.
If you want users to be able to use the workflows you are designing on multiple sites, lists, libraries, and content types, a reusable workflow will probably best meets your needs.
Site workflows : A site workflow is associated to a site — not to a list, library, or content type. So unlike most workflows, a site workflow is not running on a specific list item. Because of this, many of the actions that are available for items not available for site workflows.
In the browser, you start a site workflow or view the status of running site workflows by clicking the Site Actions menu, click View All Site Content, and then clicking Site Workflows.
If you want to create a workflow, but don't need a list, library, or content type for the workflows, a site workflow will probably best meet your needs. For example, you can create a site workflow as a way for people to provide feedback about your site.
For more detailed information go through Introduction to designing and customizing workflows


text:
Q: Improving packet sniffing/monitoring on raspberry pi I have several raspberry pi's that are all the same model with the same build of raspbian and running the same code where I am simply using pyshark to sniff out probe requests and record them to a log file.  I can have 5 identical raspberry pi's running the same code sniffing for probe requests in the exact same area and there will be at least a 20% different in the number of probe requests captured for say a 2 hour period.  Sometimes higher than a 20% difference.  Shouldn't they be much more similar?
I've looked at CPU usage and its not overloading one or multiple cores.  THere is plenty of RAM available.  The only thing I can think of if over time, raspbian runs various OS related "tuning" and some raspberry pi's have "configured themselves" better than others?  (is that possible?  Does raspberry pi have system events running that fine tunes itself?)
Here's a sample tshark command that captures my probe requests:
sudo nice -n -15 stdbuf -oL tshark -i wlan1 -I -f 'wlan type mgt subtype probe-req' -Y 'wlan.sa[0:3] ne b8:27:eb && radiotap.dbm_antsignal gt -73' -T fields -e frame.time_epoch -e wlan.sa -e radiotap.dbm_antsignal -E header=y -E separator=, -E quote=d -E occurrence=f >> ../data-test/tsharkoutput.txt

I would expect that if the CPU or RAM isn't tapped out, that different raspberry pi's running the same command should capture pretty close to the same number of packets, but they vary by 20% or more.  Any thoughts on why that could be?

A: Don't use tshark (or libraries that depend on it)
When capturing from a physical interface, tshark is a wrapper for dumpcap. In this mode, tshark experiences higher loss than dumpcap.
You should use dumpcap or tcpdump instead. You will want to use a library other than PyShark if you want to avoid tshark usage.
802.11 traffic is noisy
On a separate note, 802.11 traffic is by definition noisy and prone to loss, so seeing different packets on different capturing devices is expected behavior.


text:
Q: functions of calcul python i need your help i'm beginner in python and i developped a basic model in odoo  i want to develop 2 functions that help me to calculate the division of "montant"/26 and put the result in "montant journalier"
 and the second function must calculate the sum of column "montant" and put the result in "total"
if you can help i will be grateful i really need that
this is my view and my .py and .xml
my view
python file
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import math
from datetime import date

from openerp.osv import osv, fields, orm
class obj_ghb(osv.osv):
    _name = 'obj.ghb'
    _description = 'objet ghb'

   def onchange_montant( self, cr, uid, ids,montant, context = {} ):
data={}
if montant:

    data['montantjournalier']= montant/26 or False

return {'value': data}

    def get_total_days( self, cr, uid, ids,days_tota,arg, context = None ):
        diff_day={}

        for record in self.browse(cr, uid, ids, context=context):

            s_date = datetime.datetime.strptime(record.datedebut, "%Y-%m-%d").date()

            e_date =datetime.datetime.strptime(record.datefin, "%Y-%m-%d").date()

            diff_day[record.id] =(e_date-s_date).days

        return diff_day

    _columns = {
        'nomprojet': fields.char('Nom du projet'),
        'responsable': fields.char('Responsable GHB'),
        'client': fields.char('Client'),
        'contactclient': fields.char('Contact du client'),
        'datedebut': fields.date('Date de debut'),
        'datefin': fields.date('Date de fin'),
        'nombredejour': fields.function(get_total_days, type = "integer", method=True,store = True, string = "Jours travaillés"),
        'obj_ghb_parent': fields.one2many('loyer', 'loyer_obj_ghb'),
        'obj_ghb_id': fields.one2many('assurance', 'assurance_obj_ghb'),
        'obj_ghb_parenttt': fields.one2many('salaire', 'salaire_obj_ghb'),
        'obj_ghb_parentttt': fields.one2many('autres', 'autres_obj_ghb'),
        'total': fields.char('Total'),
        'totall': fields.char('Totall'),
        'totalll': fields.char('Totalll'),
        'totallll': fields.char('Totallll'),

    }

class loyer(osv.osv):
    _name='loyer'
    _columns = {
        'nom': fields.char('Nom'),
        'montant': fields.float('Montant'),
        'montantjournalier': fields.float('Montant journalier') ,
        'loyer_obj_ghb': fields.many2one('obj.ghb'),
    }

class assurance(osv.osv):
    _name='assurance'
    _columns = {
        'name': fields.char('Nom'),
        'mount': fields.char('Montant'),
        'dailymount': fields.char('Montant journalier') ,
        'assurance_obj_ghb': fields.many2one('obj.ghb'),
    }

class salaire(osv.osv):
    _name='salaire'
    _columns = {
        'nommm': fields.char('Nom'),
        'montanttt': fields.char('Montant'),
        'montantjournalierrr': fields.char('Montant journalier') ,
        'salaire_obj_ghb': fields.many2one('obj.ghb'),
    }

class autres(osv.osv):
    _name='autres'
    _columns = {
        'nommmm': fields.char('Nom'),
        'montantttt': fields.char('Montant'),
        'montantjournalierrrr': fields.char('Montant journalier') ,
        'autres_obj_ghb': fields.many2one('obj.ghb'),
    }

xml file
<?xml version="1.0" encoding="UTF-8"?>
<openerp>
    <data>

        <!-- formulaire view ghb -->
        <record id="ghb_form" model="ir.ui.view">
            <field name="name">ghb.form</field>
            <field name="model">obj.ghb</field>
            <field name="type">form</field>
            <field name="arch" type="xml">
                <form string="charge" version="7.0">
                    <sheet>
                        <group>
                            <group>
                                    <field name="nomprojet"/>
                                    <field name="responsable"/>
                                    <field name="datedebut"/>
                            </group>
                            <group>
                                     <field name="client"/>
                                     <field name="contactclient"/>
                                     <field name="datefin"/>
                            </group>
                            <group>
                                     <field name="nombredejour"/>
                            </group>
                        </group>
                        <notebook>
                            <page string="Loyer">
                            <group col="2" rowspan="2">
                                <group colspan="2" rowspan="2">
                                    <field name="obj_ghb_parent" nolabel="1">
                                        <tree  editable="top">
                                            <field name="nom"/>
                                            <field name="montant"/>
                                            <field name="montantjournalier" on_change="onchange_montant(montantjournalier)"/>
                                        </tree>
                                    </field>
                                </group>
                                <group  class="oe_subtotal_footer oe_right" colspan="2">
                                    <field name="total" string="Total" readonly="True"/>
                                </group>
                            </group>
                            </page>
                            <page string="Assurance">
                            <group>
                                <group>
                                    <field name="obj_ghb_id" nolabel="1">
                                        <tree  editable="top">
                                            <field name="name"/>
                                            <field name="mount"/>
                                            <field name="dailymount"/>
                                        </tree>
                                    </field>
                                </group>

                                <group  class="oe_subtotal_footer oe_right" colspan="2">
                                    <field name="totall" string="Total" readonly="True"/>
                                </group>
                            </group>
                            </page>
                            <page string="Salaire">
                            <group>
                                <group>
                                    <field name="obj_ghb_parenttt" nolabel="1">
                                        <tree  editable="top">
                                            <field name="nommm"/>
                                            <field name="montanttt"/>
                                            <field name="montantjournalierrr"/>
                                        </tree>
                                    </field>
                                </group>
                                <group  class="oe_subtotal_footer oe_right" colspan="2">
                                    <field name="totalll" string="Total" readonly="True"/>
                                </group>
                            </group>
                            </page>
                            <page string="Autres">
                            <group>
                                <group>
                                    <field name="obj_ghb_parentttt" nolabel="1">
                                        <tree  editable="top">
                                            <field name="nommmm"/>
                                            <field name="montantttt"/>
                                            <field name="montantjournalierrrr"/>
                                        </tree>
                                    </field>
                                </group>
                                <group  class="oe_subtotal_footer oe_right" colspan="2">
                                    <field name="totallll" string="Total" readonly="True"/>
                                </group>
                            </group>
                            </page>
                        </notebook>
                    </sheet>
                </form>
            </field>
        </record>
        <!-- tree vie ghb-->
        <record id="ghb_tree" model="ir.ui.view">
            <field name="name">ghb.tree</field>
             <field name="model">obj.ghb</field>
            <field name="type">tree</field>
            <field name="arch" type="xml">
                 <tree string="charge" >
                    <field name="nomprojet"/>
                    <field name="responsable"/>
                    <field name="datedebut"/>
                    <field name="client"/>
                    <field name="contactclient"/>
                    <field name="datefin"/>
                    <field name="nombredejour"/>
                </tree>
            </field>
        </record>

        <!-- menu action ghb -->
        <record model="ir.actions.act_window" id="action_ghb">
            <field name="name">Les charges GHB</field>
            <field name="type">ir.actions.act_window</field>
            <field name="res_model">obj.ghb</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,form</field>
            <field name="view_id" ref="ghb_tree" />
            <field name="help" type="html">
                <p class="oe_view_nocontent_create"> Cliquez ici pour creer un nouveau projet </p>
            </field>
        </record>

        <!-- search view charge -->
        <record id="ghb_search" model="ir.ui.view">
            <field name="name">ghb.search</field>
            <field name="model">obj.ghb</field>
            <field name="type">search</field>
            <field name="arch" type="xml">
                <search string="ghb" >
                   <field name="nomprojet"/>
                   <field name="client"/>
                </search>
            </field>
        </record>

        <!-- form view charge variable -->
        <record id="cv_form" model="ir.ui.view">
            <field name="name">cv.form</field>
            <field name="model">obj.cv</field>
            <field name="type">form</field>
            <field name="arch" type="xml">
                <form string="charge variable" version="7.0">
                    <sheet>

                            <group string="les charges variables" >
                                 <group>
                                    <field name="nomprojett"/>
                                    <field name="responsablee"/>
                                    <field name="datedebutt"/>
                                </group>
                                <group>
                                     <field name="clientt"/>
                                     <field name="contactclientt"/>
                                     <field name="datefinn"/>
                            </group>
                            <group>
                                     <field name="nombredejour"/>
                            </group>
                            </group>
                        <notebook>
                            <page string="Frais de transport">
                            <group>
                                <group>
                                    <field name="obj_cv_parent" nolabel="1">
                                        <tree  editable="top">
                                            <field name="nnom"/>
                                            <field name="mmontant"/>
                                            <field name="montantjournalier" on_change="onchange_montant(montantjournalier)"/>
                                        </tree>
                                    </field>
                                </group>
                                <group  class="oe_subtotal_footer oe_right" colspan="2">
                                    <field name="ttotal" string="Total" readonly="True"/>
                                </group>
                            </group>

                            </page>
                            <page string="Electricité">
                            <group col="2" rowspan="2">
                                <group>
                                    <field name="obj_cv_id" nolabel="1">
                                        <tree  editable="top">
                                            <field name="nnname"/>
                                            <field name="mmmount"/>
                                            <field name="ddailymount"/>
                                        </tree>
                                    </field>
                                </group>
                                <group  class="oe_subtotal_footer oe_right" colspan="2">

                                    <field name="tttotal" string="Total" readonly="True"/>

                                </group>
                            </group>
                            </page>
                            <page string="Sous-traitance">
                            <group>
                                <group>
                                    <field name="obj_cv_parentt" nolabel="1">
                                        <tree  editable="top">
                                            <field name="nnnnom"/>
                                            <field name="mmmmontant"/>
                                            <field name="mmmmontantjournalier"/>
                                        </tree>
                                    </field>
                                </group>
                                <group  class="oe_subtotal_footer oe_right" colspan="2">
                                    <field name="ttttotal" string="Total" readonly="True"/>
                                </group>
                            </group>
                            </page>
                            <page string="Autres">
                            <group>
                                <group>
                                    <field name="obj_cv_parenttt" nolabel="1">
                                        <tree  editable="top">
                                            <field name="nnomm"/>
                                            <field name="mmontantt"/>
                                            <field name="mmontantjournalierr"/>
                                        </tree>
                                    </field>
                                </group>
                                <group  class="oe_subtotal_footer oe_right" colspan="2">
                                    <field name="tttttotal" string="Total" readonly="True"/>
                                </group>
                            </group>
                            </page>
                        </notebook>
                    </sheet>
                </form>
            </field>
        </record>


text:
Q: Validate that at least 1 checkbox is checked I have search for the same question, and I saw a few of the similar post, however my Userform still can't work. I am new to VBA and Userform.
I have a total of 12 Checkboxes (12 Months), and I have to check that at least one of the CheckBox is checked.
Dim atLeastOneChecked As Boolean
atLeastOneChecked = False
Dim ctrlNCK As Control
For Each ctrlNCK In Controls
    If TypeName(ctrlNCK) = "chkMonth" Then
        If ctrlNCK.Value = True Then atLeastOneChecked = True
    End If
Next ctrlNCK

If Not atLeastOneChecked = True Then
    MsgBox "Month cannot be empty.", vbExclamation, "Input Data"
    Exit Sub
    End If

A: This is untested, but try:
If Left(ctrlNCK.Name,8) = "chkMonth" Then

I wouldn't ever expect the Type to be "chkMonth". This assumes that each relevant CheckBox name starts with "chkMonth".
If you only ever want one, and only one, month chosen, I'd consider using OptionButtons in a Frame.

A: If (chbindian + chbchinies + chbitalian + chbsindian) = 0 Then
MsgBox "Please select at least Two checkbox"
Exit Sub
End If

try this
(chbindian + chbchinies + chbitalian + chbsindian) replace this names with your checkbox name

A: Using similar approach to the question code I came up with this:
Private Sub CommandButton1_Click()

Dim chk As Control
Dim i As Long

For Each chk In Me.Controls
    If TypeOf chk Is MSForms.CheckBox Then
        If chk = 0 Then
            i = i + 1
        End If
    End If
Next
    If i = 12 Then
        MsgBox "Please select at least one month!"
        Exit Sub
    End If

MsgBox "You selected at least one month!"

End Sub

To explain:
The For loop is checking one by one each CheckBox on the UserForm.
If the value of the CheckBox is 0 (False) then the counter which is the i variable equals it's own value at the end of the previous iteration (current value) + 1.
Each CheckBox with a value of 0 (False) meaning it's 'unchecked' adds 1 to the counter and thus, once the loop is complete i will equal anywhere between 0 (all CheckBoxes are checked) and 12 (no CheckBoxes are checked).
After the loop is exited the next if statement checks if the value of the counter i is equal to 12 then a MsgBox displays "Please select at least one month!" otherwise whatever is meant to happen next will now execute (In my example its another MsgBox advising "You selected at least one month!").
NOTE: If more CheckBoxes were added to the UserForm at a later time for whatever reason, my solution would be flawed as it will check ALL CheckBox commands on the form.
To work around that you can put the required CheckBoxes on a Frame on the UserForm.
Assuming the Frame is named Frame1 all you would need to do is adjust the For line to specify for each CheckBox in Frame1 on the UserForm like so: For Each chk In Me.Frame1.Controls


text:
Q: Unable to replace splash screen image I have an issue with setting new splash screen image in my app. I have a splash screen activity and splash theme for it:
    <style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowBackground">@drawable/splash</item>
    <item name="android:scaleType">fitXY</item>
</style>

When I set new splash.png in my drawable folder my application still uses an old one, despite the fact that it was overridden by the new .png file. This concerns devices which had my app already installed. I don't face this issue when installing new apk with new splash for the first time. Seems like this old one splash.png was cached somewhere. How is it possible?

A: It happens sometimes. What has worked for me is changing the file name, deleting the older file. Then,
File -> Invalidate and Restart

and then you can refactor your filename to the old one again.
 Hope it works for you, good luck!


text:
Q: docker-compose how to create multiple containers with using the same image for some reason, I need to create the container with the same image, But when I started the second one, It just restarted the fist one's container
the first yml file:
version: "3.1"
services:

  php:
    image:php:php73-fpm
    restart: always
    ports:
      - "9000:9000"
      - "9501:9501"
    volumes:
      - $PWD/../:/var/www/html/
    networks:
      - app_net
    container_name: php
networks:
  app_net:
    driver: bridge

the second yml file:
version: "3.1"
services:

  php:
    image:php:php73-fpm
    restart: always
    ports:
      - "19000:19000"
      - "19501:19501"
    volumes:
      - $PWD/../:/var/www/html/
    networks:
      - app_net2
    container_name: php73
networks:
  app_net2:
    driver: bridge

when I run docker-compose up -d to start the first one:
$ cd ~/Document/php/work/docker/
$ docker-compose up -d
Creating network "docker_app_net" with driver "bridge"
Creating php ... done

then I switch the directory to the second yml file
$ cd ../../private/docker/
$ docker-compose up -d
Recreating php ... done

A: Compose has a notion of a project name.  By default the project name is the basename of the directory containing the docker-compose.yml file.  In your example both directories are named docker (even if they're in different parent directories) so Compose looks for a project named docker and a container named php, and finds a match.
There are four ways to override this:

*

*Rename one of the directories.

*Set the COMPOSE_PROJECT_NAME environment variable.

*Create a .env file in the current directory, and set COMPOSE_PROJECT_NAME there.

*Use the docker-compose -p option (on every docker-compose command).

Within your docker-compose.yml file, the second part of ports: needs to match what the container is listening on; this is allowed to be different from the first part.  So use the same 9500/9501 in both files.
Another consequence of the Compose project naming is that the standard names of containers, volumes, and networks that Compose creates will be prefixed with the project name.  If the project name (current directory name) is docker2, and you reduce the Compose file to
version: "3.1"
services:
  php:
    build: .
    restart: always
    ports:
      - "19000:9000"
      - "19501:9501"
    # no manual container_name: or networks:

The container will be named docker2_php_1, and it will be attached to a network named docker2_default; these will be different from the container/network created in the docker1 project/directory.

A: You can't have two containers with the same name. Since both names are just php, Docker thought they were settings that were supposed to be merged for the same container. Rename one of them.


text:
Q: Combine 2 PHP arrays to create a leaderboard I have 2 arrays - Dealerships and Scores:
Dealerships
Array(
    [0] => Test Dealership 2
    [1] => Test Dealership
    [2] => Test Dealership
    [3] => Test Dealership 3
    [4] => Test Dealership
)

Scores
Array(
    [0] => 0
    [1] => 427
    [2] => 266
    [3] => 375
    [4] => 180
)

All I am trying to do is create a leaderboard that looks like this:
It needs to combine the scores for matching dealerships.

Dealership Leaderboard
1. Test Dealership - 873
2. Test Dealership 3 - 375
3. Test Dealership 2 - 0

I have mapped the arrays to create this:
Array
(
    [0] => Array
        (
            [0] => Test Dealership 2
            [1] => 0
        )

    [1] => Array
        (
            [0] => Test Dealership
            [1] => 427
        )

    [2] => Array
        (
            [0] => Test Dealership
            [1] => 266
        )

    [3] => Array
        (
            [0] => Test Dealership 3
            [1] => 375
        )

    [4] => Array
        (
            [0] => Test Dealership
            [1] => 180
        )

)

But I'm drawing a blank on how to get to the next stage.

A: If your data comes from a database, you could handle this problem in the select-query.
But given your two arrays, simply create a new array where the key is the name so you can check for it
$array1=['Test Dealership 2','Test Dealership',...];
$array2=[0,427,...];

$new_array=[];

foreach($array1 as $key => $value){
   //test if KEY (= name) exists in the new array
   //if so, add the value
   if( isset( $new_array[$key] ) ){
      $new_array[$key] += $array2[$key];
      continue;
      }
   //else create a new entry in the new array
   $new_array[ $key] = $array2[$key];
   }

You'll end up with an array like this:
 [
   'Test Dealership 2' => 0 ,
   'Test Dealership' => 873 ,
   'Test Dealership 3' => 375
]

If you want the result sorted for a ranking list:
   arsort($new_array);

To get the strings you want, loop the new_array:
$rank=1;
foreach( $new_array as $key => $value ){
   echo $rank.' '.$key.' - '.$value;
   ++$rank;
   }

A: You're probably looking for a function like this:
function reduce_total_scores($input) {
        $output = array_reduce($input, function ($carry, array $current) {
                if (!isset($carry[$current[0]])) $carry[$current[0]] = 0;
                $carry[$current[0]] += $current[1];
                return $carry;
        }, []);
        arsort($output);
        return $output;
}

To show it in action:
<?php

$dealerships = [
        'Test Dealership 2',
        'Test Dealership',
        'Test Dealership',
        'Test Dealership 3',
        'Test Dealership',
];

$scores = [
        0,
        427,
        266,
        375,
        180,
];

/**
 * Just a function to create the combined array as the poster did.
 */
function join_array_values(...$arrs) {
        $result = [];
        $l = array_reduce($arrs, function ($carry, array $current) {
                $l = sizeof($current);
                return ($carry >= $l) ? $carry : $l;
        }, 0);
        foreach ($arrs as $i => $arr) {
                $arr = array_values($arr); // only take values
                for ($j=0; $j<$l; $j++) {
                        $result[$j][$i] = $arr[$j] ?? null;
                }
        }
        return $result;
}

/**
 * Reduce the totals of different dealerships
 */
function reduce_total_scores($input) {
        $output = array_reduce($input, function ($carry, array $current) {
                if (!isset($carry[$current[0]])) $carry[$current[0]] = 0;
                $carry[$current[0]] += $current[1];
                return $carry;
        }, []);
        arsort($output);
        return $output;
}

$input = join_array_values($dealerships, $scores);

echo "input\n------\n";
print_r($input);

echo "\nresult\n------\n";
print_r(reduce_total_scores($input));

Run Result:
input
------
Array
(
    [0] => Array
        (
            [0] => Test Dealership 2
            [1] => 0
        )

    [1] => Array
        (
            [0] => Test Dealership
            [1] => 427
        )

    [2] => Array
        (
            [0] => Test Dealership
            [1] => 266
        )

    [3] => Array
        (
            [0] => Test Dealership 3
            [1] => 375
        )

    [4] => Array
        (
            [0] => Test Dealership
            [1] => 180
        )

)

output
------
Array
(
    [Test Dealership] => 873
    [Test Dealership 3] => 375
    [Test Dealership 2] => 0
)

Should be easy to fashion an output from the assoc array produced by reduce_total_scores().


text:
Q: Counting classes then specify the amount to change I have the following JavaScript function where I am counting the total divs with a classname, but not all must be changed, that is specified with the amount param. So there are 4 classes, so the each counts the classes and then the for loop changes them according to the amount param.
Yet this doesn't seem to work, see commented out version too -
function changeImages(change, amount) {
  var $projImg = $('.proj-img');

  $.each($projImg, function(i) {
    $(this).attr('src', 'src/img/' + change + 'Slide' + (i + 1) + '.png');
  });

  // $.each($projImg, function (j) {
  //     for(var i = 0; i < amount; i++){
  //         $(this).attr('src', 'src/img/' + change + 'Slide' + (i) + '.png');
  //     }
  // });

}

A: You could use an array and then slice it so that it contains no more than the amount number of elements, no jQuery required:
function changeImages(change, amount) {
  const projImgs = [...document.querySelectorAll('.proj-img')]
    .slice(0, amount);
  projImgs.forEach((img, i) => {
    img.src = 'src/img/' + change + 'Slide' + (i + 1) + '.png';
  });
}

A: Just use jQuery's .slice():

function changeImages(amount) {
    const $matches = $('.foo').slice(0, amount);

    $matches.addClass('bar');
}

changeImages(10);
.foo {
  border-bottom: 8px solid red;
}

.bar {
  border-color: cyan;
}

.foo:hover {
  border-color: black;
}

Your JS code would then look like this:

function changeImages(change, amount) {
  $('img').slice(0, amount).each((i, el) => {
    el.setAttribute('src', `https://place-hold.it/200x200&text=${ change }-${ i + 1 }`);
  });
}

changeImages('UPDATED', 3);
body {
  margin: 0;
}

img {
  float: left;
  max-width: 20vw;
}

Also, regarding :lt(), keep in mind that's not part of the CSS specification, as stated in the docs:

Because :lt() is a jQuery extension and not part of the CSS specification, queries using :lt() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").slice(0, index) instead.

A: Use the :lt() selector

   var amount = 5,change = '';
   $('.proj-img:lt('+amount+')').map(function(i,el){
        $(el).attr('src', 'src/img/' + change + 'Slide' + (i + 1) + '.png');
    });
    console.log($('.proj-img'))


text:
Q: change jquery-steps Previous button colour I have included the jquery-steps plugin. How can I change the colour of the Previous button without changing the next & finish button?
Thanks
http://www.jquery-steps.com/
Previous button

A: If the code for the button is the same like on the jquery-steps pages, you can access the styles by the href-attribute of the button like this:
a[href="#previous"] {
   background-color: red !important;
}

Note that setting !important to the value might not be necessary for you when you load your styles after the css needed for jquery steps, but it just was when I added the style using the DOM inspector.


text:
Q: Custom Permission Group for Document Library In a modern SharePoint Team site, I intended to create multiple permission groups or name lists based on department and type of access, then set specific documents library only allows specific SharePoint permission group or name list. Can I do that? And, how?
This will help me just update the members from permission group or name list, instead of going to each document library to update member. And, I have no access to Delve.

A: What you can do is create different permission levels based on your requirements.
Each permission level can be assigned to any number of groups in the list and that way you can manage what permission a group is supposed to have in a document library or list.
It will be easy for you to manage users too as you will have a list which permission level a certain group has

A: Here're steps:
1.Create different groups with different permissions in the site permissions settings.
https://docs.microsoft.com/en-us/sharepoint/customize-sharepoint-site-permissions
2.Set unique permissions in specific documents libraries.
https://support.microsoft.com/en-us/office/customize-permissions-for-a-sharepoint-list-or-library-02d770f3-59eb-4910-a608-5f84cc297782


text:
Q: Push to Heroku Rejected - How do I roll back? I'm currently learning Ruby on Rails using Michael Hartl programming book. I've recently managed to make my Sample APP crash. When commands do I use to revert my local machine back to an earlier version such as those which I've committed to Heroku.
It's currently running fine on Heroku, but wont display on the local machine.

A: I am assuming you mean which Git command do you use to revert back to an old commit.
You can do this git reset --hard <commit number>
The commit number can be found on the activity page of Heroku
you might also want to read this about ways to undo changes using Git

A: another option which is easier then tracking git commits and branch in your case, is just to delete your project folder locally and clone your working stuff from heroku back to your machine. Getting rid of any mess you may have on local repo.
Just make sure you get right next time.
heroku git:clone -a yourprojectappname

else you can do this below.
git log

(see your git commits log)
git log -n 1 xxxxxxx

(which 'x' is the first seven number of your commit you want to restore to get a more detailed info from that commit)
git reset --hard xxxxxxx

(which 'x' is the commit you want to restore)


text:
Q: Express: req.params returning undefined got simple get method on server side which is using url params, and client side request for that url (react), but problem is that server is returning undefined for that params. here is code:
Server (index.js) :
router.use('/api/info/:name/:id', require('./info'))`

info.js:
router.get('/', async (req, res) => {
try {
   const name = req.params.name;
   const id = req.params.id;
   console.log('name ' + name +'  id  ' + id)

    return res.status(200).send({
       id: id,
       name: name
    })
} catch (err) {
    return res.status(500).send({
      message: err.message
    })
  }
})

and client side (ReactJS):
componentDidMount(){
 const { match: { params } } = this.props;
    axios.get(`/api/recipe/${params.name}/${params.id}`)
      .then(res => res.data)
      .then(data =>{
         console.log(data)
    })
}

and as i said this code returns undefined for both name and id on server side but client side works (i logged it and it is valid). in console it gives me this error too (DevTools's console)
Uncaught (in promise) Error: Request failed with status code 500
What is wrong? Thanks!

A: The route you're defining in index.js is /api/info/title/:id but you're making the API call to /api/recipe/${params.name}/${params.id}. Your route doesn't match and you're not defining :name as a param.
Unless this is a typo on your end, changing your router.use code to match your API call should work:
router.use('/api/recipe/:name/:id', require('./info'));

A: You're not telling Express to expect parameters (see "parameters" section here), you'll need something like this:
router.get('/:name/:id', async (req, res) => { ... })


text:
Q: NoClassDefFoundError in servler logs I'm using classes12.jar for connection pooling in our application. There is a screen which, on clicking, redirects to an error page.
When I checked the server logs I got the exception shown below. The error is coming from our db connection manager (PAYTFDbBase.java).
This class contains getConnection() returns a connection object and calls getConnDetails() where the parameters are read. These two methods are listed below.
It used to occur like once in a blue moon and when it comes infra team restarts the server and the issue is gone.
But but recently it has been occurring much more frequently.
I've checked classes12.jar is inside WEB-INF\lib folder.
All other upload screens work going through the same connection manager is working correctly
 java.lang.NoClassDefFoundError:
    oracle/jdbc/pool/OracleConnectionCacheImpl  at
    com.arch.PAYTFDbBase.getConnDetails(PAYTFDbBase.java:787)
        at
    com.arch.PAYTFDbBase.getConnection(PAYTFDbBase.java:180)
        at
    com.reports.client.PAYLIQUIDUploadJavaBean.getRecords(PAYLIQUIDUploadJavaBean.java:72)
        at
    jsp_servlet._core.__payliquiduploadfiles._jspService(__payliquiduploadfiles.java:334)
        at weblogic.servlet.jsp.JspBase.service(JspBase.java:34)    at
    weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
        at
    weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
        at
    weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:301)
        at
    weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:184)
        at
    weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3732)
        at
    weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3696)
        at
    weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
        at
    weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
        at
    weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2273)
        at
    weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179)
        at
    weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1490)
        at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)  at
    weblogic.work.ExecuteThread.run(ExecuteThread.java:221)

here is connection manager class  method which are used for getting connection object.
protected Connection getConnection()
{
    if(con == null || con.isClosed())
    {
        con = getConnDetails();
        con.setAutoCommit(false);
    }
    return con;
    SQLException se;
    se;
    printIt((new StringBuilder("SQLException in getConnection() :")).append(se).toString());
    return con;
}
protected Connection getConnDetails()
{
    try
    {
        InitialContext ic = new InitialContext();
        DataSource ds = (DataSource)ic.lookup("jdbc/OracleCoreDS");
        con = ds.getConnection();
    }
    catch(Exception exception) { }
    if(con != null)
        break MISSING_BLOCK_LABEL_264;
    boolean data1;
    if(encriptFlag.equalsIgnoreCase("Y"))
        data1 = getEncrypData();
    else
        data1 = getPropData();
    try
    {
        cpds = new OracleConnectionPoolDataSource();
        cpds.setDriverType("thin");
        cpds.setNetworkProtocol("tcp");
        cpds.setServerName(mcName);
        cpds.setDatabaseName(sid);
        cpds.setPortNumber(Integer.parseInt(port));
        cpds.setUser(UserName);
        cpds.setPassword(pwd);
        ocacheimpl = new OracleConnectionCacheImpl(cpds);
        ocacheimpl.setMaxLimit(8);
        ocacheimpl.setMinLimit(1);
        ocacheimpl.setCacheScheme(1);
    }
    catch(SQLException sqlEx)
    {
        printIt((new StringBuilder("PAYTFDbBase  SQLException getConnDetails():")).append(sqlEx).toString());
    }
    catch(Exception ex)
    {
        printIt((new StringBuilder(":2:PAYTFDbBase  Exception getConnDetails():")).append(ex).toString());
    }
    return ocacheimpl.getConnection();
    Exception sqlex;
    sqlex;
    printIt((new StringBuilder("PAYTFDbBase Exception in connection():")).append(sqlex).toString());
    return con;
}


text:
Q: Finding out which module a function belongs to In ghci (haskell) is there a command which will tell me which module (out of the loaded modules) a function belongs to. e.g. if the function is called whichMod, then it would work as follows :
Prelude>whichMod take
Prelude
Prelude>whichMod sort
Data.List

A: You want the :i command (short for :info).
Prelude> :i take
take :: Int -> [a] -> [a]   -- Defined in GHC.List
Prelude> :i sort

Top level: Not in scope: `sort'
Prelude> :m +Data.List
Prelude Data.List> :i sort
sort :: Ord a => [a] -> [a]     -- Defined in Data.List

As you suggest, it only works if the function is in a currently loaded module.
Note that you are told which module the function is originally defined in. e.g. take is defined in GHC.List (at least in my copy of ghc), but re-exported from the prelude. You are not told which module(s) you imported it from.

A: Yes, exists that function:
Prelude> :! hoogle sort
Data.List sort :: Ord a => [a] -> [a]
Data.List sortBy :: (a -> a -> Ordering) -> [a] -> [a]
Data.ByteString sort :: ByteString -> ByteString
Data.ByteString.Char8 sort :: ByteString -> ByteString
Data.Sequence sort :: Ord a => Seq a -> Seq a
package sort-by-pinyin
Data.Sequence sortBy :: (a -> a -> Ordering) -> Seq a -> Seq a
GHC.Exts sortWith :: Ord b => (a -> b) -> [a] -> [a]
package sorty
package cabal-sort
package external-sort
Data.Graph.Inductive.Internal.Heap heapsort :: Ord a => [a] -> [a]
package heapsort
package natural-sort
package NaturalSort
Data.Graph topSort :: Graph -> [Vertex]
Data.Graph.Inductive.Query.DFS topsort :: Graph gr => gr a b -> [Node]
Data.Graph.Inductive.Query.DFS topsort' :: Graph gr => gr a b -> [a]
Data.Sequence unstableSort :: Ord a => Seq a -> Seq a
Data.Sequence unstableSortBy :: (a -> a -> Ordering) -> Seq a -> Seq a
Prelude> _

you can define a alias into your "~/.ghci" configuration file
:def hoogle \str -> return $ ":! hoogle \"" ++ str ++ "\""

then, you can write
Prelude> :hoogle sort
Data.List sort :: Ord a => [a] -> [a]
Data.List sortBy :: (a -> a -> Ordering) -> [a] -> [a]
Data.ByteString sort :: ByteString -> ByteString
Data.ByteString.Char8 sort :: ByteString -> ByteString
Data.Sequence sort :: Ord a => Seq a -> Seq a
package sort-by-pinyin
Data.Sequence sortBy :: (a -> a -> Ordering) -> Seq a -> Seq a
GHC.Exts sortWith :: Ord b => (a -> b) -> [a] -> [a]
package sorty
package cabal-sort
package external-sort
Data.Graph.Inductive.Internal.Heap heapsort :: Ord a => [a] -> [a]
package heapsort
package natural-sort
package NaturalSort
Data.Graph topSort :: Graph -> [Vertex]
Data.Graph.Inductive.Query.DFS topsort :: Graph gr => gr a b -> [Node]
Data.Graph.Inductive.Query.DFS topsort' :: Graph gr => gr a b -> [a]
Data.Sequence unstableSort :: Ord a => Seq a -> Seq a
Data.Sequence unstableSortBy :: (a -> a -> Ordering) -> Seq a -> Seq a
Prelude> _

A: Prelude> :info take
take :: Int -> [a] -> [a]   -- Defined in `GHC.List'


text:
Q: Vim - 256 colors enabled, only 16 work I can't modify my Vim colors using the 256 colors grid (http://www.calmar.ws/vim/256-xterm-24bit-rgb-color-chart.html).
Unfortunately, only the 16 basic colors work. Colors from the 256 colors grid are replaced by an equivalent in the 16 colors grid: color 88 will become color 1, 214 will become 11, 224 will become 15, etc.
Here is what I use in my ~/.vimrc concerning colors:
set t_Co=256
highlight comment ctermfg=grey
highlight constant ctermfg=224
syntax enable

With this code, comments are grey and constants are white (whereas they should be beige).
I thought it would be of use to let you know that when I typed tput colors in my shell, the result was "256", which means (if I am not mistaken) that 256 colors are enabled. When I typed echo $TERM, the result was "xterm-256color", and if I am not mistaken (again), this means that I have correctly installed a 256-colors plugin.
It may be useful for you to know that I use zsh.
I ran some scripts to show the supported colors of my terminal, here is the result:

I don't understand why I can't use the 256 colors package. Where am I wrong?


text:
Q: Can I use Ruby 2.4 code in Ruby 3 without getting any error? I was wondering if I could use codes based on ruby 2.4 in ruby 3 (as in the programs, methodology, syntax and function names). I would like to slowly migrate to Ruby 3, but I would like to know if everything would be stable.
Do I need to download some package to make it stable? Is Ruby 3 backwards compatible (i heard they are not that much as they are fast innovator's, let's say compared to python which has backwards compatibility for all versions of 3.x but not that much of an innovator)?
Should I go through everything that I have written to make it compatible?
A bit of a tangent, but would it even be necessary for me to migrate to Ruby 3? I would presume that Ruby 2.4 already has enough features and updates for now for me to continue using it, and if I do not go up a version, I can always use Ruby 2.7.
Thanks!

A: The short answer is pretty No.
You will have as many compatibility issues as many legacy code you have.
Try to reach some resources like https://www.fastruby.io/blog/ruby/rails/versions/compatibility-table.html
But still, If you have well-written tests, they will fail, and deprecation warnings will occur. Those will be some kind of map for you(by fixing issues) to reach a new version.


text:
Q: Как вытащить из List элемент Подскажите пожалуйста как вытащить из List элемент типа byte ?

A: Вытащить элемент по индексу myList.get(index).
Если необходимо вытащить элемент по какому-то условию используйте Stream API.


text:
Q: Java Annotation Processor, Processing Order I'm wondering if there is a way to process annotations from top down in a class, or at least in some deterministic order.
It doesn't seem like this is the case because the Processor class only provides:
boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv);

Where the RoundEnvironment allows you to access a Set of annotated elements, e.g.:
Set<? extends Element>  getElementsAnnotatedWith(TypeElement a)

Everything  is in terms of unordered collections, and this makes the order of processing unpredictable. Is there anyway around this, besides trying to sort manually by element name or something?

A: As you have discovered, there is not a way to force processing of annotations in a specified order, using the current interfaces.
Here is a workaround.  Suppose that you wish to process every declaration annotation, such as annotations on fields and methods.  Don't register any callback for those declarations.  Instead, invoke the annotation processor for every class.  The annotation processor obtains the AST from javac, then walks it in the order you prefer.  As an example, the Checker Framework uses this implementation strategy.
This workaround might not be sufficient for your needs, because it still processes each class in an arbitrary order -- for instance, one that depends on javac's staged compilation model.


text:
Q: OpenCL kernels arguments ambiguity I have two functions:
void sum1(short * a, short * b, short * res, int size);
void sum2(float * a, float * b, float * res, int size);

and I have a single generic kernel
__kernel void sum(__global const T * a, __global const T * b, __global T * res, int size)
{
int x = get_global_id(0);
if (x < size) res[x] = a[x] + b[x];
}

is it safely to invoke this generic kernel from functions presented above with compile options -D T=short and -D T=float respectively? Do I need to use alignment or does OpenCL automatically align kernel arguments in this case to 2 and 4 bytes respectively?
In general, when I am passing cl_mem object to a kernel OpenCL does not know about a data type that stored in this cl_mem object and I could understand how OpenCL "transforms" cl_mem object to appropriate pointer in kernel arg.. I need help with that

A: 1- Yes. It is safe to use directly -D T=short or float at compile time. Since it will generate 2 proper kernels.
2- OpenCL (and other programming languages with pointers) understand that the pointer you are passing has a type. And they stick to this type when addressing the memory.
At least in C, this is not a problem since automatic pointer casting is not allowed. And the programmer gets an error if the pointer doesn't match.
However in OpenCL, the memory zones of a buffer are considered generic or void pointers. When you assign them to a kernel, the cast is implicit in the assignment. But this doesn't mean it is correct !
For example. If you create a float buffer, fill it with floats, use it as an argument to short kernel. The result will be wrong, since the kernel will interpret the buffer wrong. However if you do it wrong by passing a short array to a float kernel, the result will be a SEG_FAULT.


text:
Q: Why does the condition within the if-else statement never satisfy even though I enter the right string that matches the string in the list? Q: Take inputs from user to make a list. Again take one input from user and search it in the list and delete that element, if found. Iterate over list using for loop.
My Answer:
enter = list()

for user_input in range(1, 6):
    enter.append(input("Enter a name: "))

new_input = (input("Enter the name you need to find in the list: "))

for check_input in enter:
    if check_input == new_input:
        enter.remove(new_input)
    else:
        print("Item not found within the list")
    break

print(enter)

However, when I run the code and enter 5 random strings and then enter a string that I want to delete from the list, it never meets the 'if' condition and always shows me that the item wasn't found within the list even though I enter the exact same string as entered within the list.

A: After the first name you check, the loop breaks unconditionally, and further names are not checked. You need to break only if you find the item, and print "item not found" only if you've gone over the entire list:
found = False
for check_input in enter:
    if check_input == new_input:
        enter.remove(new_input)
        Found = true
        break

if not found:
    print("Item not found within the list")

A: for check_input in enter:
    if check_input == new_input:
        enter.remove(new_input)
    else:
        print("Item not found within the list")
    break

This loop will only remove an item if you typed in the first item of the list and then halt. Since remove() already searches through the entire list, you don't need the for or if statement at all:
try:
    enter.remove(new_input)
except ValueError:
    print("Item not found within the list")


text:
Q: Running prop.table on entire DF So I am trying to  run frequencies on a customer survey. The survey had 108 variables, and the responses are coded 1-5, with 9 being our NA. A few of the variables are text based. The raw data looks like this:
Q1 Q2 Q3 Q4
1  3  2  Mazda
2  3  4  Ford
3  5  2  Toyota
9  3  2  Hyundai

Ideally I want to know how many people responded to each question in this format for each of the 108 variables. For example, the first column in my new data frame would be:
Q1
1  25%
2  25%
3  25%
4  0%
5  0%
9  25%

I've tried using
Frequencies = apply(df, 2, table)

It spits it out as a list. I'd like to then run this list though
prop.table(Frequencies, 2)

to get the column percentages. However, I get the error "Error in margin.table(x, margin) : 'x' is not an array."
I've played around for a few days with transforming Frequencies into a data frame but have had no luck. Any ideas?
Thanks!
PS: I've been working on this for four days and couldn't find a solution online. I'm sorry it's so basic. I'm very new at this.

A: Try:
> ddf
  Q1 Q2 Q3      Q4
1  1  3  2   Mazda
2  2  3  4    Ford
3  3  5  2  Toyota
4  9  3  2 Hyundai
>
> sapply(apply(ddf, 2, table), function(x) x/sum(x))
$Q1

   1    2    3    9
0.25 0.25 0.25 0.25

$Q2

   3    5
0.75 0.25

$Q3

   2    4
0.75 0.25

$Q4

   Ford Hyundai   Mazda  Toyota
   0.25    0.25    0.25    0.25

Or, as @DavidArenburg has suggested in comments:
lapply(ddf, function(x) prop.table(table(x)))

A: First you need to format your columns as factors with the levels you care about.  Then you can use ?lapply to apply a function to a list (data frames are a type of list).  You will need to write custom functions within the lapply() call to do what you want.  The output of lapply() is another list, so you can nest it within as.data.frame() to turn it back into a data frame when you set the factor levels.  For the last lapply() call, you would do best to keep it as a list, because otherwise R will recycle the shorter outputs to make them the same length as the longer outputs.
df <- read.table(text="Q1 Q2 Q3 Q4
1  3  2  Mazda
2  3  4  Ford
3  5  2  Toyota
9  3  2  Hyundai", header=TRUE)
dfQs    <- as.data.frame(lapply(df[,1:3], function(x){ factor(x, levels=c(1:5,9)) }) )
dfQs$Q4 <- as.factor(df$Q4)
dfQs
#   Q1 Q2 Q3      Q4
# 1  1  3  2   Mazda
# 2  2  3  4    Ford
# 3  3  5  2  Toyota
# 4  9  3  2 Hyundai
proportions <- lapply(dfQs, function(x){ prop.table(table(x)) })
proportions
# $Q1
# 1    2    3    4    5    6    7    8    9
# 0.25 0.25 0.25 0.00 0.00 0.00 0.00 0.00 0.25
# $Q2
# 1    2    3    4    5    6    7    8    9
# 0.00 0.00 0.75 0.00 0.25 0.00 0.00 0.00 0.00
# $Q3
# 1    2    3    4    5    6    7    8    9
# 0.00 0.75 0.00 0.25 0.00 0.00 0.00 0.00 0.00
# $Q4
# Ford Hyundai   Mazda  Toyota
# 0.25    0.25    0.25    0.25


text:
Q: MySQL User Profile System Does MySQL have a user profile system where I can associate "permissions" and "rights" etc. with a certain user profile and assign each user to a certain profile ? For example, I want to create the profile "Intern" for student interns, "Programmers" for programmers in the organizations, "ReadOnly" for people in the organization who only need to be able to read data.
If MySQL does not nativaly provide such a system, what is a good desktop software for Linux or for Windows that allows me to do this kind of management ?
Cheers !

A: No there's no way to do that, eventually you could play with the mysql.user table to copy permission of an user to another using SQL statements.


text:
Q: Changing brightness of photos command-line I need to take a photo with my USB webcam in Ubuntu 18.04. I did this in three different ways.

*

*streamer -s [640x480] -f jpeg -c /dev/video2 -o image.jpeg

*Cheese application

*ffmpeg -f oss -f video4linux2 -s 320x240 -i /dev/video2 out.jpeg
Each of these three methods has different brightness options. The first method has good brightness, but there's no good brightness with the other two methods. How can this problem be solved?
I need a terminal command to take a photo and use it in Python.


text:
Q: radio button change only after confirm() returns true I've got a set of radio buttons in my html site. When the users changes the selection I show a dialog via the confirm('') function. I just want to change the selection if the user confirms the change - otherwise just cancel the event. My problem now is that I only got an event AFTER the value has been changes and the change is already done. How can i prevent this behaviour?

A: This isn't easy because there is no consistency across browsers in which event is appropriate to do what you need doing. However you say from your tags you're using jQuery, so here's a solution using state tracking to revert depending on your function return:
var currentradio= $("input[name='pick_up_point']:checked")[0];
$("input[name='pick_up_point']").change(function(event) {
    var newradio= $("input[name='pick_up_point']:checked")[0];

    if (newradio===currentradio)
        return;
    if (confirm('Your question here')) {
        currentradio= newradio;
    } else {
        currentradio.checked= true;
    }
});

A: $('.rdio').click(function(){
 var cnfrm = confirm('Are you sure?');
 if(cnfrm != true)
{
 return false;
}

})

live demo : http://jsfiddle.net/cTzVg/


text:
Q: Deleting a row from DataSet doesn't affect the database I'm new at ADO.NET and I'm trying to understand the disconnected model, I wrote a code to do inset update and delete using SqlDataAdapter and SqlCommandBuilder and it worked with insert and update but not with delete, why is this?, and how to fix it?.
Here is my code inside the event handler, I have one table "client" that have 3 columns id, name, city, and my DataSet Called ds.
SqlDataAdapter ad = new SqlDataAdapter("select * from client", cnx);
foreach (DataRow client in ds.Tables["client"].Rows)
{
    if (client.Field<int>(0) == 100)
    {
        ds.Tables["client"].Rows.Remove(client);
        break;
    }
}
new SqlCommandBuilder(ad);
ad.Update(ds, "client");

A: If you remove the row, there is no way for the Update method to discover which row has been removed. You need to use the Delete method
foreach (DataRow client in ds.Tables["client"].Rows)
{
  if (client.Field<int>(0) == 100)
  {
      client.Delete();
      break;
  }
}

When you call the Delete method, the RowState property of the deleted row changes to DataRowState.Deleted but it is still present in the DataSet. So when you call the Update, the method now is able to search for all the rows that have a RowState different from DataRowState.Unchanged and executes the appropriate action against the database table


text:
Q: Android openGL ES 3.0 shaders are not working I am using openGl ES 3.0 in android to render a rect on screen, and I want to use shaders to generate a mix of colors depending on vertex positions.
I am sure that the problem is in the vertex and in the fragment shader code, but I don't know what is it, these are the shader codes:
 private final String vertexShaderCode =

            "#version 300 es"+
            "in vec3 position;" +
            "out vec3 color;"+

                    "void main() {" +
                    "  gl_Position = vec4(position.x,position.y,position.z,1.0);" +
                    "  color = vec3(position.x+0.5,1.0,position.y+0.5);"+
                    "}";

    private final String fragmentShaderCode =

                    "#version 300 es"+
                    "in vec3 color;"+
                    "out vec4 out_color;"+

                    "void main() {" +
                    "  out_color= vec4(color.x,color.y,color.z,1.0);" +
                    "}";

I am trying to fill the shape with color based on vertex position, so its a mixture of generated colors for each pixel.
But I don't why its not working?
UPDATE:
I have 3 info:

*

*Link failed because of invalid vertex shader.

*Language version '300' unknown, this compiler only supports up to version '320 es'

*Unexpected text found after #version directive.

A: Your shader code does not compile successfully, because you missed the newlines (\n). The version declaration has to be in a separate line:
"#version 300 es\n"+

See OpenGL ES Shading Language 3.00 Specification - 3.4 Version Declaration:

The #version directive must be present in the first line of a shader and must be followed by a newline.

Furthermore you have to add a precision qualifier for the floating point variables to the fragment shader. e.g.:
"#version 300 es\n"+
"precision mediump float;\n"+

See OpenGL ES Shading Language 3.00 Specification - 4.5.4 Default Precision Qualifiers:

The fragment language has no default precision qualifier for floating point types. Hence for float, floating point vector and matrix variable declarations, either the declaration must include a precision qualifier or the default float precision must have been previously declared.

A: You can display shader errors like this:
    GLES20.glAttachShader(program, vertexShader);
    GLES20.glAttachShader(program, pixelShader);
    GLES20.glLinkProgram(program);
    int[] linkStatus = new int[1];
    GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
    if (linkStatus[0] != GLES20.GL_TRUE) {
        GLES20.glDeleteProgram(program);
        throw new RuntimeException("Could not link program: "
                + GLES20.glGetProgramInfoLog(program));
    }

Was you able to display any color shape? There can be many reasons why shapes are not displayed. But if it's only matter of colors, it narrows down the search area.


text:
Q: Tensorboard hangs on startup using 100% CPU So I'm trying to visualise logs generated by stable baselines 3 but when I run tensorboard from the terminal as such tensorboard --logdir logs, it only outputs this message TensorFlow installation not found - running with reduced feature set., nothing about where it's hosted. It also uses 100% of one CPU core, sometimes switching which core is used, as can be seen below. Going to localhost:6006, or any other if I specify it using --host, just says "Unable to connect". As far as I can see it stays like this indefinitely.
I have also tried with tensorflow installed, same thing. I am running on Linux Mint and have a AMD GPU.


text:
Q: Holoeverywhere Fragment not displaying I am creating an app and have stumbled across a problem. My apps fragment should display text when selected but it is not. Here is my code:
This class my fragment which should be displaying text when selected.
TestFragment.class:
public class TestFragment extends SherlockFragment {

public static final String EXTRA_TITLE = "title";

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    TextView txt = new TextView(inflater.getContext());
    txt.setGravity(Gravity.CENTER);
    txt.setText("Fragment");

    if (getArguments() != null && getArguments().containsKey(EXTRA_TITLE)) {
        txt.setText(getArguments().getString(EXTRA_TITLE));
    }
    return txt;
}

public static Bundle createBundle(String title) {
    Bundle bundle = new Bundle();
    bundle.putString(EXTRA_TITLE, title);
    return bundle;
}

}
This is my main class where from my tabs are added from. It extends TabSwipeActivity which I have previously made.
Main class:
public class TaskMain extends TabSwipeActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    addTab("Urgent", TestFragment.class,
            TestFragment.createBundle("TestFragment"));
    addTab("Due", TestFragment.class,
            TestFragment.createBundle("Fragment 2"));
    addTab("Unimportant", TestFragment.class,
            TestFragment.createBundle("Fragment 3"));
    addTab("Shopping", TestFragment.class,
            TestFragment.createBundle("Fragment 4"));
    addTab("Notes", TestFragment.class,
            TestFragment.createBundle("Fragment 5"));

}

@Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
    super.onCreateOptionsMenu(menu);

    MenuInflater inflate = getSupportMenuInflater();
    inflate.inflate(R.menu.activity_task_main, menu);

    return true;
}

}
And this is TabSwipeActivity of which my main activity extends.
TabSwipeActivity.class:
public abstract class TabSwipeActivity extends SherlockFragmentActivity {

private ViewPager mViewPager;
private TabsAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    /*
     * Create the ViewPager and our custom adapter
     */
    mViewPager = new ViewPager(this);
    adapter = new TabsAdapter(this, mViewPager);
    mViewPager.setAdapter(adapter);
    mViewPager.setOnPageChangeListener(adapter);

    /*
     * We need to provide an ID for the ViewPager, otherwise we will get an
     * exception like:
     *
     * java.lang.IllegalArgumentException: No view found for id 0xffffffff
     * for fragment TestFragment{40de5b90 #0 id=0xffffffff
     * android:switcher:-1:0} at
     * android.support.v4.app.FragmentManagerImpl.moveToState
     * (FragmentManager.java:864)
     *
     * The ID 0x7F04FFF0 is large enough to probably never be used for
     * anything else
     */
    mViewPager.setId(0x7F04FFF0);

    super.onCreate(savedInstanceState);

    /*
     * Set the ViewPager as the content view
     */

    setContentView(mViewPager);
}

/**
 * Add a tab with a backing Fragment to the action bar
 *
 * @param titleRes
 *            A string resource pointing to the title for the tab
 * @param fragmentClass
 *            The class of the Fragment to instantiate for this tab
 * @param args
 *            An optional Bundle to pass along to the Fragment (may be null)
 */
protected void addTab(int titleRes,
        Class<? extends SherlockFragment> fragmentClass, Bundle args) {
    adapter.addTab(getString(titleRes), fragmentClass, args);
}

/**
 * Add a tab with a backing Fragment to the action bar
 *
 * @param titleRes
 *            A string to be used as the title for the tab
 * @param fragmentClass
 *            The class of the Fragment to instantiate for this tab
 * @param args
 *            An optional Bundle to pass along to the Fragment (may be null)
 */
protected void addTab(CharSequence title,
        Class<? extends SherlockFragment> fragmentClass, Bundle args) {
    adapter.addTab(title, fragmentClass, args);
}

private void setContent() {

setContentView(R.layout.activity_task_new);
}

private static class TabsAdapter extends FragmentPagerAdapter implements
        TabListener, ViewPager.OnPageChangeListener {

    private final SherlockFragmentActivity mActivity;
    private final ActionBar mActionBar;
    private final ViewPager mPager;

    /**
     * @param fm
     * @param fragments
     */
    public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager) {
        super(activity.getSupportFragmentManager());
        this.mActivity = activity;
        this.mActionBar = activity.getSupportActionBar();
        this.mPager = pager;

        mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    }

    private static class TabInfo {
        public final Class<? extends SherlockFragment> fragmentClass;
        public final Bundle args;

        public TabInfo(Class<? extends SherlockFragment> fragmentClass,
                Bundle args) {
            this.fragmentClass = fragmentClass;
            this.args = args;
        }
    }

    private List<TabInfo> mTabs = new ArrayList<TabInfo>();

    public void addTab(CharSequence title,
            Class<? extends SherlockFragment> fragmentClass, Bundle args) {
        final TabInfo tabInfo = new TabInfo(fragmentClass, args);

        Tab tab = mActionBar.newTab();
        tab.setText(title);
        tab.setTabListener(this);
        tab.setTag(tabInfo);

        mTabs.add(tabInfo);

        mActionBar.addTab(tab);
        notifyDataSetChanged();
    }

    @Override
    public SherlockFragment getItem(int position) {
        final TabInfo tabInfo = mTabs.get(position);
        return (SherlockFragment) SherlockFragment.instantiate(mActivity,
                tabInfo.fragmentClass.getName(), tabInfo.args);
    }

    @Override
    public int getCount() {
        return mTabs.size();
    }

    public void onPageScrollStateChanged(int arg0) {
    }

    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    public void onPageSelected(int position) {
        /*
         * Select tab when user swiped
         */
        mActionBar.setSelectedNavigationItem(position);

    }

    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        /*
         * Slide to selected fragment when user selected tab
         */
        TabInfo tabInfo = (TabInfo) tab.getTag();
        for (int i = 0; i < mTabs.size(); i++) {
            if (mTabs.get(i) == tabInfo) {
                mPager.setCurrentItem(i);
            }
        }

    }

    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    }

    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }
}

}

A:
extends SherlockFragment

You should extend from org.holoeverywhere.app.Fragment

extends SherlockFragmentActivity

org.holoeverywhere.app.Activity


text:
Q: AJAX Internal 500 Error in Wordpress Children-Theme I got this Ajax code on Js/Jq block (/buscador/menuLateral/menu-libros.php):
$.ajax({
  url: '<?= get_stylesheet_directory_uri(); ?>' +
    '/buscador/buscador-functions.php',
  type: 'POST',
  data: {
    sendCheckedVal: 'yes',
    tipo: 'editorial',
    valor: valor_recogido,
    archivo: this_file_id.toString()
  },
  success: function(data) {
    alert('Checked value !');
  }
});

Values on this file exists and got some value, I tried seeing it with a GET on a Stringify.
And this, must be getted in a file like this (/buscador/buscador-functions.php) :
<?php
    if (ISSET($_POST['sendCheckedVal'])){
       echo 'hi, u reached here' ;
    }
?>

The values doesn't passes from js code file to next.
I get this error on console:

POST
  [WP-URL-HIDDEN-ON-PURPOSE]/themes/ChildrenNewspaper/buscador/buscador-functions.php
  500 (Internal Server Error)

On right side of the line-error :

jquery.min.js:2

Someone knows how to repair this on ajax working on a wordpress theme.Thanks

A: Issue is here : alert('hi, u reached here');. alert() is not PHP function it is javascript function. So instead of it you can use echoor return
<?php
    if (isset($_POST['sendCheckedVal'])){
       echo 'hi, u reached here';
    }
?>

A: To start you off, alert is a javascript function.
In php you need to echo out values to the page;
If you want to do it with JS you need to print out js.
echo "<script type='text/javascript'>alert('hi, u reached here');</script>";
Or you can echo out the vars to the page.


text:
Q: 2 legged oauth for google calendar v3 I am working with Version 3 of Google Calendar REST API(using HttpClient) and its working fine. Similarly I've to work with web APIs of V3 Google Calendar since my application is in Google Apps marketplace. How can I proceed with 2 legged OAuth in V3 Google Calendar APIs. Any help would be appreciated.
Thanks in advance,
Riyaz Ashraf.


text:
Q: PHP Friend Relationship between 2 rows? first time I've used this site .. I've had a good look around but I cant seem to find the answer to my question. It's been answered in other ways but not for what I want I think..
Image of the database table so it's easy to see: http://puu.sh/6BtmZ.png
So basically I've got a friends.php page that has an input field and submit button, you put a username in and press submit and I want it to send a request to that user; I've got that to work, the user can accept but it only places the "friend" into him. As in FRIENDA is friends with FRIENDB but on FRIENDB's page he isn't friends with FRIENDA .. I hope this makes sense.
I just basically want it so, you send a request and the person accepts it and BOTH parties can see each other as friends.
 <?php
include 'core/init.php';
// check
protect_page();
include 'includes/templates/header.php';

$user_id = $user_data['user_id'];

if (empty($_POST) === false) {
    $required_fields = array('username');

    foreach($_POST as $key=>$value) {
        if (empty($value) && in_array($key, $required_fields) === true) {
            $errors[] = 'You need to enter a username to send a request!';
            break 1;
        }
    }
    if (empty($errors) === true) {
        if (user_exists($_POST['username']) === false) {
            $errors[] = 'Sorry, the username \'' . htmlentities($_POST['username']) . '\' doesn\'t exist.';
        }
    }
}

if (isset($_GET['success']) && empty($_GET['success'])) {
    echo 'Friend request sent!';
} else {

if (empty($_POST) === false && empty($errors) === true) {
    // add friend
    $username = $_POST['username'];
    $get_userid = mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'");
    $row = mysql_fetch_array($get_userid);
    $username_id = $row[user_id];
    $user_id = $user_data['user_id'];

    mysql_query("INSERT INTO `users_friends` (user_id, friends_with) VALUES ('$user_id', '$username_id')");

    //redirect
    header('location: friends.php?success');
    //exit
    exit();

    } else if (empty($errors) === false) {
        // output errors
        echo output_errors($errors);
    }
}
?>

Friends

Send a friend request:

    <form id="friend_request" action="" method="POST">

Username: <input type="text" name="username"><input id="friend_request" type="submit">

    </form>

Pending requests:

<?php
if(isset($_POST['decline'])){
$decline_id = $_POST['decline_friend_id'];
$decline_query = "DELETE FROM `users_friends` WHERE `id` = $decline_id";
$accept_result = mysql_query($decline_query);
}

if(isset($_POST['accept'])){
       $accept_id = $_POST['accept_friend_id'];
       $accept_query = "UPDATE `users_friends` SET `request_pending` = 0 WHERE `id` = $accept_id";
       $accept_result = mysql_query($accept_query);
}

$result = mysql_query("SELECT * FROM `users_friends` WHERE `friends_with` = '$user_id' AND `request_pending` = 1");

while($requests_row = mysql_fetch_array($result)) {
    $get_username = mysql_query("SELECT `username` FROM `users` WHERE `user_id` = '$requests_row[user_id]'");
    $get_username_row = mysql_fetch_array($get_username);
    $request_from = $get_username_row[username];

    echo 'Request from: ' . $request_from . '<form id="decline" action="" method="POST">
                        <input type="hidden" name="decline_friend_id" value="' . $requests_row['id'] . '">
                        <input type="submit" value="Decline" name="decline">
                        </form>
                        <form id="accept" action="" method="POST">
                        <input type="hidden" name="accept_friend_id" value="' . $requests_row['id'] . '">
                        <input type="submit" value="Accept" name="accept">
                        </form>';
    echo '
';
}
?>

Your friends:

<?php
$friends_result = mysql_query("SELECT * FROM `users_friends` WHERE `friends_with` = '$user_id' AND `request_pending` = 0");
while($friends_row = mysql_fetch_array($friends_result)) {
    $get_username = mysql_query("SELECT `username` FROM `users` WHERE `user_id` = '$friends_row[user_id]'");
    $get_username_row = mysql_fetch_array($get_username);
    $friend = $get_username_row[username];

    echo $friend . '
';
    }
    ?>

    <?php include 'includes/templates/footer.php'; ?>

Hopefully someone might be able to help? Thanks in advance!

A: What you probably want to do is insert both directions in the friends relationship once both friends have confirmed.  So instead of doing this:
INSERT INTO `users_friends` (user_id, friends_with) VALUES ('$user_id', '$username_id')

You would do this:
INSERT INTO `users_friends` (user_id, friends_with) VALUES ('$user_id', '$username_id'),('$username_id','$user_id')

This would allow you to do the friend lookup in either direction.
What is unclear to me however is how you store pending friend requests in your database. So what you may ultimately need to do is to insert those relations in the DB and then simply update those DB records to change the value of an "accepted" flag once the friendship has confirmed.

A: If the structure of "users_friends" table looks like this:
me        friends_with      request_pending

to get the result (= if the user is your friend):
"SELECT * FROM `users_friends` WHERE (`friends_with` = '$user_id' AND `me`= `$me`) OR (`friends_with` = '$me' AND `me`= `$user_id `) AND `request_pending` = 0"

You check if the user is in friends_with where YOU are in me.. or if the user is in me and you're in friends_with


text:
Q: adding timeout to jena (for sparql) using dbpedia as end point? I would like to know whether there is a way to use Jena to do a sparql query through dbpedia and using the timeout setting given in http://dbpedia.org/sparql (if you see this page, you could see that there is a way to set the timeout there), this is needed since I would like to make a big query and I have tried several times (via the page) that without setting the timeout, I cannot get the result (it is always a transaction timeout exception)
edited: I use java.

A: To execute your query, I guess you're using :
QueryExecutionFactory.sparqlService(String service, Query query)

One thing you could try is:
QueryEngineHTTP objectToExec=QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql",YOUR_QUERY);
objectToExec.addParam("timeout","5000"); //5 sec
resultset=objectToExec.execSelect();

It seems that QueryEngineHTTP implements QueryExecution which has an addParam method. There's no description of that method but I'd assume that adds a parameter to the HTTP request.
Let me know if it works !!
Edited
to fix error actually it was the other way around ... QueryEngineHTTP implements QueryExecution

A: I would do it like this:
String service = "http://dbpedia.org/sparql";
QueryExecution qexec = QueryExecutionFactory.create(query, service) ;
qexec.setTimeout(10, TimeUnit.MINUTES);

ResultSet results = qexec.execSelect() ;
String result = ResultSetFormatter.asText(results);

If if the timeout limit it reached then a org.apache.jena.query.QueryCancelledException is thrown.


text:
Q: Why does svg not get requested with app load I've got a live site https://courageous-kulfi-58c13b.netlify.app/. Whenever a checkbox is clicked, it should turn green with a tick svg on it. However, on the first app load, clicking a checkbox will show a noticeable delay between the background turning green and the tick svg actually showing. NextJS only requests for the svg once I click on the checkbox. The svg is used in my css as a background image in a ::before pseudo element. How can I make next request for the svg in initial render so there isn't this delay?
const Checkbox = (props: Props) => {
  const [checked, setChecked] = useState(false);

  const handleClick = () => {
    setChecked((prevChecked) => !prevChecked);
  };
  return (
    <>
      <input
        type="checkbox"
        onClick={handleClick}
        className={cn({
          "before:bg-tick": checked,
        })}
      ></input>
    </>
  );
};

tailwind.config.js
module.exports = {
   extend: {
      backgroundImage: {
        tick: "url(/Tick.svg)",
      },
   }
}

A: You can inline the svg with something like the following. Then there will be no delay in downloading the svg.
.tick:before {
  content: url('data:image/svg+xml; utf8, <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 342.357 342.357" style="enable-background:new 0 0 342.357 342.357" xml:space="preserve"><path d="M290.04 33.286 118.861 204.427l-66.541-66.52L0 190.226l118.862 118.845L342.357 85.606z"/></svg>');
}

Note I have run the svg through svgo to optimize it.
Example here: https://play.tailwindcss.com/TlRvKKs53I?file=css
Preload image
The other option would be to preload the image in the html head.
<link rel="preload" as="image" href="/Tick.svg">

The old school hacky way was to include an image tag on the page somewhere, but use css to make it not visible, but the browser would still load it.


text:
Q: How to format date picker on mobile? I created a Visualforce page for Mobile app and want to display date picker in a format. Currently the format is very bad as shown below.
Screen Shot
I tried below code to show date picker only on click but nothing is working :

               <apex:inputField id= "date1" value="{!opportunity.CloseDate}"/>

                    <apex:commandButton action="{!save}" value="save" />


text:
Q: Discord Bot cannot access text files Long story short, I have been working in a bot for the past month but I had all of my commands on on_message listeners instead of context and command decorators, so I decided to do it properly, in the process of transferring my commands numerous changes have been needed, but this one has me puzzled.
The way I store user information is in text files, unfortunately on the new way of doing things it seems that I cannot access text files anymore, I looked at this code over and over and tried to troubleshoot it by making sure strings aren't empty and such, the more I looked into it the more I realized that there isn't anything wrong with it, based on other information i've looked up online, the only reason I could think of is because code is inside an async function which causes it to not work. It does not throw any exceptions for anyone wondering
If this is indeed the case, what would I have to do to fix it?
Current code:
userid = 'userfiles/' + ctx.message.server.id + '/' + ctx.message.author.id + '.txt' #get path based on user ID
try:
    userfile = open(userid, 'a') #open the file from
    userfile.write(i)
    userfile.close()
except IOError:
    await client.send_message(ctx.message.channel, 'Irrecovarable exception encountered')
    return


text:
Q: can we add extra buttons to iphone native address book view controller? I want to know whether we can add extra buttons to iphone native address book view controller ?
For example in contact info view contact in address book.

A: You can not customize the view controllers of the built-in frameworks unless there is a provision to customize it, like UImagePickerController to which you can add a custom cameraOverlay.
As for as I know the answer for your question is NO.


text:
Q: Unable to connect to AWS Elasticsearch instance from EC2 instance I have an EC2 instance and an Elasticsearch instance in the same vpc. I am trying to connect via requests_aws4auth package and python elasticsearch connector.
host = cfg.AWS_HOST # For example, my-test-domain.us-east-1.es.amazonaws.com
region = cfg.AWS_REGION # e.g. us-west-1

service = 'es'

awsauth = AWS4Auth(cfg.AWS_ACCESS_KEY, cfg.AWS_SECRET_KEY, region, service)

es = Elasticsearch(
hosts = [{'host': host, 'port': 443}],
http_auth = awsauth,
use_ssl = True,
verify_certs = True,
connection_class = RequestsHttpConnection
)

I am getting this ERROR when trying to connect
Traceback (most recent call last):
  File "writeData.py", line 27, in <module>
    print(es.info())
  File "/usr/lib/python2.7/site-packages/elasticsearch/client/utils.py", line 76, in _wrapped
    return func(*args, params=params, **kwargs)
  File "/usr/lib/python2.7/site-packages/elasticsearch/client/__init__.py", line 241, in info
    return self.transport.perform_request('GET', '/', params=params)
  File "/usr/lib/python2.7/site-packages/elasticsearch/transport.py", line 318, in perform_request
    status, headers_response, data = connection.perform_request(method, url, params, body, headers=headers, ignore=ignore, timeout=timeout)
  File "/usr/lib/python2.7/site-packages/elasticsearch/connection/http_requests.py", line 90, in perform_request
    self._raise_error(response.status_code, raw_data)
  File "/usr/lib/python2.7/site-packages/elasticsearch/connection/base.py", line 125, in _raise_error
    raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
elasticsearch.exceptions.AuthorizationException: AuthorizationException(403, u'{"message":"The security token included in the request is invalid."}')

A: You may need to pass the session_token information too as a parameter.
Like this..
auth = AWS4Auth(credentials.access_key, credentials.secret_key,
              region, service, session_token=credentials.token)

as shown here

A: If you are connecting within the same VPC, you do not want to use the external host address. Instead, use the internal ip of the elastic machine or an internal load balancer depending on your ES setup.


text:
Q: convert 0:00 to 0:00.00 in javascript I have a function that converts ms to s and m and it will display as 0:00 but i want it to display it as 0:00.0. How would i do this?

function millisToMinutesAndSeconds(millis) {
  var minutes = Math.floor(millis / 60000);
  var seconds = ((millis % 60000) / 1000).toFixed(0);
  return (seconds == 60 ? (minutes+1) + ":00" : minutes + ":" + (seconds < 10 ? "0" : "") + seconds);
}

console.log(
  millisToMinutesAndSeconds(123456)
)

A: set toFixed() with the desired number of digits:

var seconds = ((millis % 60000) / 1000).toFixed(1);

A: sorry, I do not know where you got the code from, the code may look something like this. I suggest you close this question.

function millisToMinutesAndSeconds(millis) {
  const minutes = Math.floor(millis / 60000);
  const seconds = Math.floor((millis - (minutes * 60000))/ 1000);
  const milliseconds = (millis - (minutes * 60000) - (seconds * 1000));

  const mins = minutes < 10 ? "0" + minutes : "" + minutes;
  const secs = seconds < 10 ? "0" + seconds : "" + seconds;
  const msecs = milliseconds < 10 ? "00" + milliseconds : milliseconds < 100 ? "0" + milliseconds : "" + milliseconds;
  return `${mins}:${secs}.${msecs}`;
}

console.log(
  millisToMinutesAndSeconds(123456)
)


text:
Q: Why does sklearn's Lasso coefficients not equal to Linear Regression ones? I am trying to implement sklearn's lasso in my code. To test it out, I have decided to make a test with alpha = 0. This should by definition yield the same result as LinearRegression, but this is not the case.
Here is the code:
import pandas as pd
from sklearn.linear_model import Lasso
from sklearn.linear_model import LinearRegression

# Don't worry about this. It is made so that we can work with the same dataset.
df = pd.read_csv('http://web.stanford.edu/~oleg2/hse/Credit.csv').dropna()
df['Asian'] = df.Ethnicity=='Asian'
df['Caucasian'] = df.Ethnicity=='Caucasian'
df['African American'] = df.Ethnicity=='African American'
df = df.drop(['Ethnicity'],axis=1).replace(['Yes','No','Male','Female',True,False],[1,0,1,0,1,0])
# End of unimportant part

ft = Lasso(alpha=0).fit(x, df.Balance)
print(ft.intercept_)
ft = LinearRegression().fit(x, df.Balance)
print(ft.intercept_)

Output:
-485.3744897927978
-480.89071679937786

The coef_s are also all different.
What am I doing wrong?

A: Indeed this seems to yield different results. However, running your code, also yielded the following warning:
ft = Lasso(alpha=0).fit(X, y)
print(ft.intercept_)
ft = LinearRegression().fit(X, y)
print(ft.intercept_)

-485.3744897927984
-480.89071679937854

UserWarning: With alpha=0, this algorithm does not converge well. You are advised to use the LinearRegression estimator

This is letting you know that since alpha=0, meaning that we're only left with an ordinary linear regression, the algorithm won't converge well. Which is why you see a difference in the intercept, and presumably a worsening of the metrics.


text:
Q: Change how button looks when path changes main app which the switches occur looks like this
function App() {
  return (
    <Router>

          <Navbar/>

            <Switch>
              <Route exact path="/">
                <Home/>
              </Route>
              <Route exact path="/create">
                <Create/>
              </Route>
            </Switch>

    </Router>
  )

My Navbar component currently looks like this
import { Link } from "react-router-dom"

const Navbar = () => {
  const handleClick = () => {
    console.log(window.location.pathname)
  }

  return (

Testing

          <Link to="/" onClick={handleClick}>Home</Link>
          <Link to="/create"
                style = {{
                  color: 'white',
                  backgroundColor: '#2d38d4',
                  borderRadius: '8px'
          }}>Finance</Link>

  );
}

export default Navbar;

I was going going to use handleClick to make it so the one clicked receives the styling however I realized that if I did do this, it wouldn't change the button appearances if someone just directly changed the url like this localhost/ ->  localhost/app and vise versa.
How are selections like this managed in React?

Inspired by the answer I marked correct here it is:
import { NavLink } from "react-router-dom"

const Navbar = () => {
  const activeStyle = {
    color: 'white',
    backgroundColor: '#2d38d4',
    borderRadius: '8px'
  }

  return (

Testing

          <NavLink exact to="/"
                activeStyle = {activeStyle}>Home</NavLink>
          <NavLink to="/create"
                activeStyle = {activeStyle}>Finance</NavLink>

  );
}

export default Navbar;

A: You should use the NavLink component rather than the Link component as the NavLink one will automatically add an active class to the link if you are on the same Route that the to is set to.

import { NavLink } from "react-router-dom"

const Navbar = () => {
  const handleClick = () => {
    console.log(window.location.pathname)
  }

  return (

Testing

          <NavLink to="/" onClick={handleClick}>Home</NavLink>
          <NavLink to="/create">Finance</NavLink>

  );
}

export default Navbar;

Then in your CSS (however you are doing it) you just need to style the active class.
The official docs also has some examples of how to give your own active class or style the link directly like you had originally.
https://reactrouter.com/web/api/NavLink


text:
Q: Is Apache server part of default installation? I have a running apache2 server on my computer.
As I do not use it as a server, can I remove it safely (to save RAM, boot-up time, etc.) or is it still useful (like part of Ubuntu default installation)?

A: Apache is not part of default Ubuntu installation, you had to install it manually. If you don't use it, you should remove it.