text:
Q: Pandas dataframe grouping by multiple columns and dropping duplicate rows I am trying to do a task (in bioinformatics, TCGA data) using a dataframe of the following form:
df = pd.DataFrame({'ID':['TCGA-AB-0001','TCGA-AB-0001','TCGA-AB-0001','TCGA-AB-0001','TCGA-AB-0002','TCGA-AB-0002','TCGA-AB-0002','TCGA-AB-0002','TCGA-AB-0003','TCGA-AB-0002'],
              'Reference':['HG19','HG18','HG19','GRCh37','HG18','HG19','GRCh37','HG19','GRCh37','GRCh37'],
             'SampleType':['Tumor','Tumor','Normal','Normal','Tumor','Normal','Normal','Tumor','Tumor','Tumor']
               })

which looks like:
             ID Reference SampleType
0  TCGA-AB-0001      HG19      Tumor
1  TCGA-AB-0001      HG18      Tumor
2  TCGA-AB-0001      HG19     Normal
3  TCGA-AB-0001    GRCh37     Normal
4  TCGA-AB-0002      HG18      Tumor
5  TCGA-AB-0002      HG19     Normal
6  TCGA-AB-0002    GRCh37     Normal
7  TCGA-AB-0002      HG19      Tumor
8  TCGA-AB-0003    GRCh37      Tumor
9  TCGA-AB-0002    GRCh37      Tumor

I am trying to match pairs of rows if they have the same 'Reference' and different 'SampleType'. The result will be a new dataframe of the following form:
             TUMOR                                     NORMAL
index        ID Reference SampleType      index        ID Reference SampleType
0  TCGA-AB-0001      HG19      Tumor      2  TCGA-AB-0001      HG19     Normal
7  TCGA-AB-0002      HG19      Tumor      5  TCGA-AB-0002      HG19      Tumor
9  TCGA-AB-0002    GRCh37      Tumor      6  TCGA-AB-0002    GRCh37     Normal

Now I would like to drop duplicate IDs but to do so the priority is according to the list [GRCh37, HG19, HG18]. So if for example both HG19 and HG18 exist with the same ID, I will keep HG19. The result should look like the following:
             TUMOR                                     NORMAL
index        ID Reference SampleType      index        ID Reference SampleType
0  TCGA-AB-0001      HG19      Tumor      2  TCGA-AB-0001      HG19     Normal
9  TCGA-AB-0002    GRCh37      Tumor      6  TCGA-AB-0002    GRCh37     Normal

is there a way to do this by groupby or some other pandas function?
Thanks!

A: It is still not 100% clear to me what the desired output is. But this seems to do the trick based on my understanding.
import numpy as np
import pandas as pd

df = pd.DataFrame({'ID':['TCGA-AB-0001','TCGA-AB-0001','TCGA-AB-0001','TCGA-AB-0001','TCGA-AB-0002','TCGA-AB-0002','TCGA-AB-0002','TCGA-AB-0002','TCGA-AB-0003','TCGA-AB-0002', 'TCGA-AB-0001', 'TCGA-AB-0001'],
              'Reference':['HG19','HG18','HG19','GRCh37','HG18','HG19','GRCh37','HG19','GRCh37','GRCh37', 'GRCh37', 'GRCh37'],
             'SampleType':['Tumor','Tumor','Normal','Normal','Tumor','Normal','Normal','Tumor','Tumor','Tumor', 'Normal', 'Tumor']
               })

This is slightly longer than the original example and tests having redundant candidate rows.
              ID Reference SampleType
0   TCGA-AB-0001      HG19      Tumor
1   TCGA-AB-0001      HG18      Tumor
2   TCGA-AB-0001      HG19     Normal
3   TCGA-AB-0001    GRCh37     Normal
4   TCGA-AB-0002      HG18      Tumor
5   TCGA-AB-0002      HG19     Normal
6   TCGA-AB-0002    GRCh37     Normal
7   TCGA-AB-0002      HG19      Tumor
8   TCGA-AB-0003    GRCh37      Tumor
9   TCGA-AB-0002    GRCh37      Tumor
10  TCGA-AB-0001    GRCh37     Normal
11  TCGA-AB-0001    GRCh37      Tumor

Now we create a temp df that may have "redundant" rows.
##
# Create the df with sort and first level filtering
##
df_2 = df.groupby(['ID','Reference']).filter(lambda x:set(x.SampleType)=={'Tumor','Normal'}).drop_duplicates(['ID', 'Reference', 'SampleType']).sort(['ID','Reference', 'SampleType'])
# By dropping dups and sorting, the SampleType column must alternate: Normal, Tumor, Normal...

# Break into two pieces for horizontal concat
left = df_2.iloc[np.arange(0,df_2.shape[0], 2)]
right = df_2.iloc[np.arange(1, df_2.shape[0], 2)]

# Reindex by ID so that pd.concat can properly match rows
left['old_index'] = left.index.values
left.index = left['ID']
right['old_index'] = right.index.values
right.index = right['ID']
right.columns = [c + '_2' for c in right.columns]  # Rename right side columns so we can groupby(['ID'])

# Horizontal concat
temp = pd.concat([left, right], axis=1)  # with possible duplicates for each unique (ID, Reference) tuple
temp.index = np.arange(temp.shape[0])
temp

             ID Reference SampleType  old_index          ID_2 Reference_2  \
0  TCGA-AB-0001    GRCh37     Normal          3  TCGA-AB-0001      GRCh37
1  TCGA-AB-0001      HG19     Normal          2  TCGA-AB-0001        HG19
2  TCGA-AB-0002    GRCh37     Normal          6  TCGA-AB-0002      GRCh37
3  TCGA-AB-0002      HG19     Normal          5  TCGA-AB-0002        HG19

  SampleType_2  old_index_2
0        Tumor           11
1        Tumor            0
2        Tumor            9
3        Tumor            7

If I understand correctly, we only want to keep one row for each ID, choosing them in order of priority = ['GRCh37', 'HG19', 'HG18']
##
# Second level of filtering using priority list
##
priority = ['GRCh37', 'HG19', 'HG18']
g = temp.groupby(['ID'])

def filter_2(grp, priority = ['GRCh37', 'HG19', 'HG18']):
    pos = np.argsort(grp['Reference'], priority).iloc[0]
    idx = grp.index[pos]
    return grp.loc[idx, :]

final = temp.groupby(['ID']).apply(filter_2)
final.index = np.arange(final.shape[0])

Which yields my understanding of the final desired output. NOTE: this is different than the original example since I expanded in the input df.
final

             ID Reference SampleType  old_index          ID_2 Reference_2  \
0  TCGA-AB-0001    GRCh37     Normal          3  TCGA-AB-0001      GRCh37
1  TCGA-AB-0002    GRCh37     Normal          6  TCGA-AB-0002      GRCh37

  SampleType_2  old_index_2
0        Tumor           11
1        Tumor            9

A: In order to create your new dataframes you can use pandas conditionnal slicing: (in your question you made a mistake on the dataframe NORMAL on the line with index 5, the SampleType should be Normal not Tumor)
NORMAL = df[df['SampleType']=='Normal'].copy()
TUMOR = df[df['SampleType']=='Tumor'].copy()

or if you have a chance to have anything else than 'normal' and 'tumor' and you wan't to get everything but 'normal':
NORMAL = df[df['SampleType']=='Normal']
TUMOR = df[~df['SampleType']=='Normal']

Then in order to drop the duplicates and keep the specific values, you can create another column which keeps the same information but made out of integers (easier to sort than strings lists):
NORMAL['Whatever'] = 0
TUMOR['Whatever'] = 0

Of course you can do this before splitting your dataframe df (then you only do it on one dataframe instead of two). Complete this column:
NORMAL.ix[NORMAL['Reference'] == 'HG19','Whatever'] = 1
TUMOR.ix[TUMOR['Reference'] == 'HG19','Whatever'] = 1
NORMAL.ix[NORMAL['Reference'] == 'HG18','Whatever'] = 2
TUMOR.ix[TUMOR['Reference'] == 'HG18','Whatever'] = 2

Then sort by this new column, and drop the duplicates, keeping only the first row:
NORMAL.sort_values(by = 'Whatever', inplace = True)
NORMAL.drop_duplicates(subset = 'ID',inplace = True)
TUMOR.sort_values(by = 'Whatever', inplace = True)
TUMOR.drop_duplicates(subset = 'ID',inplace = True)

And in order to get the expected output, delete the temporary column, and resort by index:
NORMAL.drop('Whatever',1,inplace = True)
NORMAL.sort_index(inplace = True)
TUMOR.drop('Whatever',1,inplace = True)
TUMOR.sort_index(inplace = True)

OUTPUT:
Out[3]: NORMAL
    ID              Reference   SampleType
3   TCGA-AB-0001    GRCh37      Normal
6   TCGA-AB-0002    GRCh37      Normal

Out[32]: TUMOR
    ID              Reference   SampleType
0   TCGA-AB-0001    HG19        Tumor
8   TCGA-AB-0003    GRCh37      Tumor
9   TCGA-AB-0002    GRCh37      Tumor


text:
Q: jquery jscrollpane container acting like an iframe I dont' want it to be an iframe for the jscrollpane container. How would i fix this problem? Right now its acting like an iframe... I'm trying to create content inside the jscrollpane container and shifting it outside of the container (using absolute positioning and negative px values), but it gets cut out from the containers.
Thanks

A: Actually jscrollpane setting overflow: hidden on the main container. It is the key style to set custom scroll. So if you need to shift out something, it should be outside of this container.
You can try play with paddings, and try it to be equal to your maximum offset element. Or you can try to set it outside and set listener for scroll event.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i encode my class to json to send http put to firebase I am trying to encode my class to send a put http to firebase but my function when i prints the User.toMap shows a list with "Instance of 'Address'".
{id: -LVsaRJKo3vo6q9NWZn_, name: User 38197, email: null, address: [Instance of 'Address']}

class User {
  String id;
  String name;
  String email;
  List<Address> address = new List<Address>();

  User({this.id, this.name, this.email, this.address});

  User.fromMap(Map<String, dynamic> map) {
    this.id = map['id'];
    this.name = map['name'];
    this.email = map['email'];

    if (map['address'] == null) {
      this.address = new List<Address>();
    } else {
      this.address= (map['address'] as List).map((i) => Address.fromMap(i)).toList();
    }
  }

  Map<String, dynamic> toMap() {
    return {'id': id, 'name': name, 'email': email, 'address': address};
  }
}

===
class Address {
  String test;

  Address ({this.test});

  Address.fromMap(Map<String, dynamic> map) {
    this.test = map['test'];
  }

  Map<String, dynamic> toMap() {
    return {
      'test': test
  }
}

===
In class ApiProvider
Future<User> updateUser(User userUpdate) async {
    String id = userUpdate.id;

    print(userUpdate.toMap()); // This prints that line

    final http.Response response = await http.put(
      baseUrl + '/user/$id.json',
      body: json.encode(userUpdate.toMap()), // Here happens the error
    );

    final Map<String, dynamic> userData = json.decode(response.body);
    User user = new User.fromMap(userData);

    return user;
  }

===
The final error:
I/flutter (17495): {id: -LVsaRJKo3vo6q9NWZn_, name: User 38197, email: null, address: [Instance of 'Address']}
E/flutter (17495): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error:     Unhandled exception:
E/flutter (17495): Converting object to an encodable object failed: Instance of 'Address'
E/flutter (17495): #0      _JsonStringifier.writeObject (dart:convert/json.dart:703:7)
E/flutter (17495): #1      _JsonStringifier.writeList (dart:convert/json.dart:753:7)
E/flutter (17495): #2      _JsonStringifier.writeJsonValue (dart:convert/json.dart:735:7)
E/flutter (17495): #3      _JsonStringifier.writeObject (dart:convert/json.dart:693:9)
E/flutter (17495): #4      _JsonStringifier.writeMap (dart:convert/json.dart:786:7)
E/flutter (17495): #5      _JsonStringifier.writeJsonValue (dart:convert/json.dart:741:21)
E/flutter (17495): #6      _JsonStringifier.writeObject (dart:convert/json.dart:693:9)

A:   Map<String, dynamic> toMap() {
    return {'id': id, 'name': name, 'email': email, 'address': address};
  }

needs to be changed to
  Map<String, dynamic> toMap() {
    return {'id': id, 'name': name, 'email': email, 'address': address.map((a) => a.toMap()).toList()};
  }


text:
Q: Visualizing data from database as line chart in Rails I have a really simple request: I have a table that holds a users weight for a specific day (so two columns: kilograms and day). I now want to show this as a line chart to show a user's weight loss over time (x-Axis = day, y-Axis = kilograms).
I installed Chartkick and it renders a chart but it I really don't know how to get these value to the line chart.
Is Chartkick the right option for this purpose? And if yes, how should my code look like?
weight.rb
class Weight < ActiveRecord::Base
  belongs_to :user
  validates :day, uniqueness: { scope: :user_id,
    message: "You already stored a weight today. Go back and edit if necessary." }
end

user.rb
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  after_create :create_profile

  has_one :profile, dependent: :destroy
  has_many :weights, dependent: :destroy
end

A: Chartkick will do exactly what you want.
For the particular chart.
<%= line_chart User.weight_measurements.group_by(day).average(:weight)

In this case I'm assuming that your day is not a date. Otherwise you might want to use groupdate by the same author.
<%= line_chart User.weight_measurements.group_by_day(day).average(:weight)

There's probably a cleaner way to do it but that should work

A: Found a solution to this.
Chartkicks documentation says:

Times can be a time, a timestamp, or a string (strings are parsed)
<%= line_chart({20.day.ago => 5, 1368174456 => 4, "2013-05-07 00:00:00 UTC" => 7}) %>

So all I did is creating a hash from my Weights table in the suggested format...
weights_controller.rb
@result = {}
    Weight.where(:user_id => current_user.id).each do |weight|
      @result[weight.day] = weight.kilograms
    end

...and used this in the line chart:
<%= line_chart(@result, min: nil) %>


text:
Q: Laravel With Wherehas I'm using a query to get the companies that belong to a city, that belongs to an event.
$companies = Event::find($id)->city->companies;

Now in my view i'm iterating through the companies to output the persons that work there as following
@foreach($companies as $company)
    @foreach($company->persons as $person)
        ...
    @endforeach
@endforeach

The only problem is it's also showing me companies that don't have persons
So any idea how i can modify my query to show only the companies that have persons
I was thinking about WhereHas, but I can't seem to wrap myself around the logic of combining the two.
Thanks!

A: I'm not sure if it will work but you can try with this:
$companies = Event::find($id)->city->companies()->has('persons')->get();

A: As per the documentation:

[...] you may wish to limit your results based on the existence of a
  relationship [...] To do so, you may use the has method.

Something like this might work:
Event::find($id)->city()->companies()->has('persons')->get();

Given that I don't know the exact return objects for proper method chaining.


text:
Q: Prevent cron job from running on reboot I have a script that is set to run after reboot with @reboot. There is a problem with the script and crashing the system as soon as it boot up. Is there away to prevent the job from running?

A: Following Nasir Riley's suggest, boot into single user mode and delete the cronjob


text:
Q: SSRS a combination of three different tables with similiar values I have 3 tables

*

*The first table contains columns [membername], [id], [team]

*The second table has column [file name] with names of files for example "filename12345"

*And the third table contains columns [id] and [text] which have texts for example "yesterday i drop filename12345 to storage"
I used left join for tables 1 and 3 on [id]
Is any possibility to link these three tables together using the key word "filename12345"
I need this to make a report in report builder

A: You can use a LIKE in the JOIN to match the second table filenames up with the text in the third table.
SELECT *
FROM MEMBERS M
JOIN TEXTS T ON T.ID = M.ID
JOIN FILES F ON F.FILENAME LIKE '%' + T.TEXT + '%'


text:
Q: read a range between two rows with the same value I am trying to read the last added range of data ("A10:C15") delimited by a custom row (i.e. row 1, row 9) that will dynamically get added into the sheet.
So far I've just managed to read the entire sheet with getRange("A1:C15") but I cannot use only values in range "A10:C15" (and any other newly added range).

A: *

*Get all the data

*Do a reverse for-loop and get data up to the delimiter

*Loop starts from values.length-1 to 0
const values = sheet.getDataRange().getValues(),
  lastSet = [];
for( let i = values.length-1; i>=0 ; i-- ){
  if (values[i][0] === "xxx" ) break;
  lastSet.push(values[i])
}
console.info({lastSet});


text:
Q: Fortran code won't write to file I am working on a program to calculate minimum nozzle length in supersonic nozzles (Method of Characteristics). I can't seem to figure out why my code won't write to my output file (the lines "write (6,1000)....). My code is below:
      program tester
c----------------------------------------------------------------------c
      implicit real (a-h,o-z)
      integer count
      real kminus(0:100),kplus(0:100),theta(0:100),nu(0:100),mach(0:100)
     +     ,mu(0:100)
      open (5,file='tester.in')
      open (6,file='tester.out')
      read (5,*) me
      read (5,*) maxturn
      read (5,*) nchar
      read (5,*) theta0
      close(5)
c.....set count to 0 and calculate dtheta
      count=0
      dtheta=(maxturn-theta0)/nchar
c.....first characteristic
      do 10 an=1,nchar+1
         count=count+1
c........these are already known
         theta(count)=theta0+dtheta*(an-1)
         nu(count)=theta(count)
c........trivial, but we will "calculate" them anyways
         kminus(count)=2*theta(count)
         kplus(count)=0
c........we feed it nu(count) and get m out
         call pm_hall_approx(nu(count),m)
         mach(count)=m
c........does not work with sqrt(...) for some reason
         mu(count)=atan((1/(mach(count)**2)-1)**0.5)
         write (6,1000) count,kminus(count),kplus(count),theta(count)
     +                  ,nu(count),mach(count),mu(count)
   10 continue
c.....the other characteristics
      do 30 bn=1,nchar
         do 20 cn=1,(nchar+1-bn)
            count=count+1
c...........these are given
            kminus(count)=kminus(cn+bn)
            kplus(count)=-1*kplus(bn+1)
c...........if this is the last point, copy the previous values
            if (cn.eq.(nchar+1-bn)) then
               kminus(count)=kminus(count-1)
               kplus(count)=kplus(count-1)
            endif
c...........calculate theta and nu
            theta(count)=0.5*(kminus(count)+kplus(count))
            nu(count)=0.5*(kminus(count)-kplus(count))
c...........calculate m
            call pm_hall_approx(nu(count),m)
            mach(count)=m
            mu(count)=atan((1/(mach(count)**2)-1)**0.5)
            write (6,1000) count,kminus(count),kplus(count),theta(count)
     +                     ,nu(count),mach(count),mu(count)
   20    continue
   30 continue
      close(6)
      stop
 1000 format (11(1pe12.4))
      end
c======================================================================c

      include 'pm_hall_approx.f'

And my subroutine is given here:
      subroutine pm_hall_approx(nu,mach)
c----------------------------------------------------------------------c
c     Given a Mach number, use the Hall Approximation to calculate the
c     Prandtl-Meyer Function.
c----------------------------------------------------------------------c
      implicit real (a-h,o-z)
c.....set constants
      parameter (a=1.3604,b=0.0962,c=-0.5127,d=-0.6722,e=-0.3278)
      parameter (numax=2.2769)
      y=nu/numax
      mach=(1+a*y+b*y*y+c*y*y*y)/(1+d*y+e*y*y)
      return
      end

And here are the contents of tester.in
 2.4     = mache
 5.0     = maxturn
 7       = nchar
 0.375    = theta0

A: In fortran, unit number 6 is reserved for screen. Never use that as the unit number. Try changing it to some other number like write(7,1000) and then it should work.


text:
Q: change/substitute two different pattern in only one line i try to change two different pattern in one line from a file.
the file is a /etc/fstab like :
/dev/sda1        /               ext4    auto,acl,errors=remount-ro  0       1
/dev/sda2        /home           ext4    auto,acl,errors=remount-ro  0       2

the result must be :
/dev/sda1        /               ext4    auto,acl,errors=remount-ro  0       1
/dev/mapper/home /home           ext4    auto,acl,errors=remount-ro  0       0

what i do on the first pattern:
sed -i "s/sda2/mapper\/home/" /etc/fstab

for the second pattern i have tried :
sed -i "s/sda2/mapper\/home/;s/[0-9]$/0/" /etc/fstab

but it update all lines :
/dev/sda1        /               ext4    auto,acl,errors=remount-ro  0       0
/dev/mapper/home /home           ext4    auto,acl,errors=remount-ro  0       0

Anyone can help me ?
Thanks a lot !

A: You can use the syntax address function-list to apply a set of commands to lines that match a pattern:
sed -i "/sda2/{ s/sda2/mapper\/home/
                s/[0-9]$/0/ }" /etc/fstab

A: You can use awk:
awk '$1 ~ /sda2/{sub(/sda2/, "mapper/home", $1); $NF=0} 1' file | column -t
/dev/sda1         /      ext4  auto,acl,errors=remount-ro  0  1
/dev/mapper/home  /home  ext4  auto,acl,errors=remount-ro  0  0

Use of column -t is for formatting only.


text:
Q: Make API call and database operations atomic I want to do the following:

*

*Begin a transaction

*insert data to a database

*After the insert, submits data to an API endpoint with the newly added rows' primary key

*Then commit the transaction

If the insert fails, nothing will be done and everything is rollbacked. The problem is I don't have a good way to rollback the API request if the committing of the transaction fails because it is not a database operation. The only thing I can think of is delete the data from the endpoint. Is there a better way? I am using entity framework. Thanks.

A: So if I have understood correctly, you only want to commit to the DB if the API call was successful, but can't call the API until you have the DB generated primary Key from the DB insert.
So this would lead to a kind of 2 phase commit type of approach, but what happens if the insert is successful, the API call is successful, but the DB commit fails?  (if happens!)
Therefore, I think that you should consider to instead implement the Saga design Pattern.
This is design for complex distributed systems, especially using microservices, where you need to ensure data consistency across different distributed systems.
Basically you build a kind of chain of transactions which need to be executed in order.  You then go through them one by one and if successful then you move onto the next.
But, for every transaction you also have a compensating transaction.  So that if a transaction fails then you work backwards through your list executing all the compensating transactions one by one until in the end you have the same initial state.
There are different ways of doing this such as the Choreography-based saga or the Orchestration-based saga.
You can find more details and a better explanation here:
https://microservices.io/patterns/data/saga.html


text:
Q: Add a menu button on control bar in videojs Hi I am using videojs player framework version 5.2.4.
I am trying to add a custom button in control bar menu. I tried code given here add item in control bar
But it seems that our version of video js is causing a problem in calling functions.
Is there any help for current version of video js? Also I want it to show/hide automatically as control bar hide and show.
Please help.


text:
Q: ToolTip on DataGridView I've got a ToolTip showing when hovering over a row in my DataGridView - Works great except for the ToolTip flickering when over a row that displays it.
Private Sub DataGridView1_MouseHover(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseMove
    Dim hit As DataGridView.HitTestInfo = DataGridView1.HitTest(e.X, e.Y)

    If hit.Type = DataGridViewHitTestType.Cell Then

        If Not hit Is m_HoveredItem Then
            Me.ToolTip2.Hide(Me.DataGridView1)
            m_HoveredItem = hit
            If hit Is Nothing Then
                Me.ToolTip2.SetToolTip(Me.DataGridView1, "")
            Else
                'Me.ToolTip2.SetToolTip(Me.DataGridView1, ConnectedUsers(Me.DataGridView1.Rows(hit.RowIndex).Cells("Database").Value, Instance))
                Me.ToolTip2.Show(ConnectedUsers(Me.DataGridView1.Rows(hit.RowIndex).Cells("Database").Value, Instance), DataGridView1, e.X, e.Y)
            End If
        End If

    End If

End Sub

I used a similar method for a ListView which worked great:
Private m_HoveredItem As ListViewItem
Private Sub lv_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)

Dim lvi As ListViewItem = Me.LVDatabases.GetItemAt(e.X, e.Y)

If Not lvi Is m_HoveredItem Then
    Me.ToolTip2.Hide(Me.LVDatabases)
    m_HoveredItem = lvi
    If lvi Is Nothing Then
        Me.ToolTip2.SetToolTip(Me.LVDatabases, "")
    Else
        Me.ToolTip2.SetToolTip(Me.LVDatabases, ConnectedUsers(Me.LVDatabases.GetItemAt(e.X, e.Y).Text, Instance))
    End If
End If
End Sub

A: Private cellColumnIndex As Integer = -1, cellRowIndex As Integer = -1
Private Sub testDataGridView_CellMouseMove(ByVal sender As Object, ByVal e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseMove
    If e.ColumnIndex <> Me.cellColumnIndex OrElse e.RowIndex <> Me.cellRowIndex Then
        Me.ToolTip2.Hide(Me.DataGridView1)
        Me.cellColumnIndex = e.ColumnIndex
        Me.cellRowIndex = e.RowIndex
        If Me.cellColumnIndex >= 0 AndAlso Me.cellRowIndex >= 0 Then
            Me.ToolTip2.SetToolTip(Me.DataGridView1, ConnectedUsers(Me.DataGridView1.Rows(e.RowIndex).Cells("Database").Value, Instance))
        End If
    End If
End Sub

A: For datagridview to show your tooltiptext you should set the property "showcelltooltips" to false, then only your tool tip text will be shown

A: FWIW, I believe this is a bug in the DataGridView on Windows 7.  We used this technique in an app written in C# running on Windows XP.  Everything worked fine, but when we moved the app to Windows 7 we noticed this flickering issue.  After investigation, we found repeated calls to our MouseMove event handler.  I added a simple trace line at the top of the handler that just reported the location of the mouse at Event triggering, e.X and e.Y.  We saw continuous repeated execution at the same point, even when taking hand off mouse and backing chair away from desk.
Investigation on MSDN at the time indicated that the event would not be triggered when the mouse did not move.  This certainly appears to be incorrect for the DataGridView.  We did not notice this issue on any other controls, but we did not do exhaustive testing.
.Net 3.5 Client Profile, C# WinForms app


text:
Q: Construct rotation matrix from angle variable in TensorFlow My goal is to generate a rotation matrix based on a rotation variable, theta.
Here's my code so far:
initial = 0.0
theta = tf.Variable(initial_value=initial, name='theta')
sin = tf.sin(theta)
cos = tf.cos(theta)
rot_matrix = tf.constant([[cos, -sin, 0], [sin, cos, 0]])

The above gives: TypeError: List of Tensors when single Tensor expected for the fifth line. I'm getting this because cos and sin are tensors. But I can't find any way to extract a value from a tensor. (Only extracting sub-tensors from tensors with tf.slice())
How can I properly create the rotation matrix?

A: You could make it a list of tensors and fetch that. Right now you have a mix of tensors and numbers which you can not fetch as is.
initial = 0.0
theta = tf.Variable(initial_value=initial, name='theta')
sin = tf.sin(theta)
cos = tf.cos(theta)
rot_matrix = [[cos, -sin, tf.constant(0)], [sin, cos, tf.constant(0)]]
sess = tf.Session()
sess.run(tf.initialize_all_variables())
sess.run(rot_matrix)

Alternatively you could turn it into a single Tensor using tf.pack(), which converts numbers (and lists and arrays of numbers) to tensors automatically.
rot_matrix = tf.pack([[cos, -sin, 0], [sin, cos, 0]])


text:
Q: Retrieve ATI GPU info (memory, GPU load and so on) on OSX via python I am trying to collect info about my video card to profile it, while running my python application; although I can't find any python module that is able to do so.
On Windows I have been using GPUtil, with my Nvidia card and it works great; but my mac has an ATI card. I tried also pyadl but it require ADLSDK3.0, which from what I can tell is windows only, not OSX.
At this point I am stuck; can't use GPUtil, can't use pyadl and can't find anything similar to GPUtil; which is a great library but sadly is Nvidia only.


text:
Q: Search for visually selected text with linebreak and spaces In the question Search for selection in vim, the trick to search for visual selection is to yank the selected text and paste it after the search command /. But This doesn't seem to work in my special case.
In my case,  there are linebreak and spaces in the selected text, like so:
        something\\
    \end{align*}

Yanking and pasting the part from \\ to the end of next line (which is }) produced
\\^M    \end{align*}

But no match was found by searching for this line.
I also tried escaping
\\\\^M    \\end{align*}

but still no match was found.
Any help? Thanks.

A: My SearchHighlighting plugin provides visual mode * and g* mappings that handle this in a robust way.

A: Place the following in your ~/.vimrc:
" Search for selected text, forwards or backwards.
vnoremap <silent> * :<C-U>
  \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
  \gvy/<C-R><C-R>=substitute(
  \escape(@", '/\.*$^~['), '\_s\+', '\\_s\\+', 'g')<CR><CR>
  \gV:call setreg('"', old_reg, old_regtype)<CR>
vnoremap <silent> # :<C-U>
  \let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
  \gvy?<C-R><C-R>=substitute(
  \escape(@", '?\.*$^~['), '\_s\+', '\\_s\\+', 'g')<CR><CR>
  \gV:call setreg('"', old_reg, old_regtype)<CR>

Now you can use * to search for the selected text. This was listed here too.


text:
Q: Seria correto utilizar uma classe estática para consumir um web service? Uma dúvida que de vez enquanto surge quando estou programando é relacionada a utilização de classes estáticas.
A documentação oficial da Microsoft diz o seguinte a respeito de classes estáticas:

A static class can be used as a convenient container for sets of
  methods that just operate on input parameters and do not have to get
  or set any internal instance fields.

Então, aqui diz que classes estáticas podem ser usadas como um container para métodos que apenas operam em parâmetros de entrada e que não precisam de trabalhar com campos de instâncias.
Vamos então a um problema mais específico. Minha aplicação ASP.NET consome um web service que irá me retornar informações relativas ao negócio. Para consumir o web service eu devo fazer a autenticação juntamente com o mesmo, e após isso enviar requisições HTTP, simples, para isso então criei uma classe, que vou chamar aqui de ApiClient.
Em nenhum momento do processo eu preciso acessar recursos de instância da classe ApiClient, levando em consideração que dados como URL de endpoint, chave de acesso e período de validade da chave de acesso serão os mesmos para todos os que consumirem os métodos da classe ApiClient.
Até aí imagino que a escolha em user uma classe estática esteja correta. Minha dúvida é a seguinte, em caso de múltiplas chamadas simultâneas de um método da classe ApiClient, caso uma requisição demore digamos, 5 segundos, essas requisições seriam enfileiradas, fazendo com que a classe estática se torne um gargalo no consumo do web service?
Segue abaixo um exemplo da classe ApiClient que tentei descrever.
public static class ApiClient
{
    private static string baseUri = "http://baseuri.com";

    private static async Task<string> GetKey()
    {
        //Get the key
    }

    private static async Task<string> SendRequest(string resource)
    {
        string key = await GetKey();

        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Add("key", key);

        string url = $"{baseUri}{resource}";
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
        HttpResponseMessage response = await client.SendAsync(request);

        string result = await response.Content.ReadAsStringAsync();
        return result;
    }

    public static async Task<CustomerInfo> GetCustomerInfo(string customerId)
    {
        string resource = $"/api/method/{customerId}";
        string json = await SendRequest(resource);
        CustomerInfo customerInfo = JsonConvert.DeserializeObject<CustomerInfo>(json);
        return customerInfo;
    }
}

Essa abordagem poderia ser considerada problemática? Nesse caso eu teria problema gargalo caso múltiplas requisições sejam passadas para o método SendRequest? Se sim esse problema poderia ser solucionado com a mudança de abordagem e criação de instâncias da classe ApiClient?

A: Primeiro, de fato eu considero uma abordagem correta. Se atende suas necessidades eu não tenho como dizer. Quem defende OOP já dizer que não pode fazer isto, quem é pragmático à princípio não vê problemas. Quem acha que nenhum código pode ser escrito se não tiver testes vai dizer que não dá pra testar, quem é pragmático sabe que só impõe uma técnica diferente, se testes formais estão de fato sendo feitos.
Não há diferença de execução de métodos estáticos ou de instância. A única diferença entre eles é que o método de instância recebe um parâmetro extra oculto chamado this. Não existe um método diferente para cada instância, existe apenas um para toda a aplicação, portanto sua execução simultânea é igual ao método estático. A instância tem estado individual, mas o comportamento sempre pertence à classe, mesmo que dê a impressão que de ser diferente.
Você pode ter problemas com o SendRequest() se ele conter problema de concorrência, o que não dá para avaliar com o que foi colocado, não não é que poderia criar gargalo, é que poderia acessar dois recursos ao mesmo tempo que não podem ser acessados ao mesmo tempo, então exigiria uma coordenação. Mas isto é hipotético, nada indica que seja o caso.
Eu só tornaria baseUri readonly e eliminaria variáveis desnecessárias.


text:
Q: how can I change height value to cell or column of datagridveiw , by c# code? how can I change height value to cell or column of datagridveiw , by c# code?

A: You can change height of row with DataGridViewRow.Height. If you mean only one cell then I can't imagine how it will looks.
added:
Hope this helps:
   dataGridView1.RowTemplate.Height = 50;
   foreach (DataGridViewRow r in dataGridView1.Rows)
       r.Height = 50;


text:
Q: loading application on blackberry playbook simulator encountered an error I developed an application in BlackBerry playbook native sdk using QNX. I try to test it on simulator(running in vmware) an error occurred like "'Downloading and starting the application...' has encoundered a problem". The screenshot attached below
UPDATE
I tested it on developer alpha device and woks fine.

A: It looks like you are trying to run an application built using the BlackBerry 10 NDK on a BlackBerry PlayBook running PlayBook OS 2.1.0.  Typically, applications built in the NDK are forwards compatible, but not backwards compatible.
You'll need to use the version 2.x BlackBerry NDK to build the application for your PlayBook running 2.1.0.


text:
Q: Two Knight on chessboard We have given an integer n, we need to find the number of ways two knights can be placed on an n×n chessboard so that they do not attack each other.
I tried the simulation strategy but it is too costly as n can be of 10000. BY googling I got this formula
$ a = n * n * (n * n - 1) / 2$
$ b = 2 * (n - 2) * (2 * (n - 4) + 6)$
$ ans = a - b $
can anyone explain this formula I can't get my head through it?

A: The number of ways to put two knights on an $n\times n$ chessboard, with no other conditions, is
$$\binom{n^2}2=\frac{n^2(n^2-1)}2=a.$$
The number of ways to put two knights on an $n\times n$ chessboard so that they do attack each other is
$$4(n-1)(n-2)=b$$
as shown in the answer to this question. Namely, a pair of mutually attacking knights determines a $2\times3$ or $3\times2$ rectangle, there are $(n-1)(n-2)+(n-2)(n-1)$ such rectangles on the board, and there are two ways to place the knights in each rectangle.
The number of ways to put two knights on an $n\times n$ chessboard so that they don't attack each other is then
$$\binom{n^2}2-4(n-1)(n-2)=a-b.$$
More generally, the number of ways to put two knights on an $m\times n$ chessboard so that they don't attack each other is
$$\binom{mn}2-2[(m-1)(n-2)+(m-2)(n-1)].$$

A: Place the first knight anywhere. How many fields can it attack?
Depending on where you placed it, it can attack at least two fields and at most eight. Try to count the cases where it is less than eight, as these are the exceptional ones (placed at the border of the field, in the corner, etc.).
Now say there are $A_8$ ways to place the knight so that it can attack eight fields. Then the other one can be placed on any of the remaining $n^2 - 8$ fields, so this will contribute $A_8(n^2-8)$ to the total number of ways. Do the same for $A_2,...$ and you are done; the rest is simplifying terms.
Note that I assumed two distinguishable knights, e.g. black and white. If you can't distinguish them, you need to divide your final result by two.


text:
Q: Installing Firefox add-on globally without extracting the .xpi archive Since the great -install-global-extension option was removed in Gecko 1.9.2 (for no obvious reason, as usual), copying the extension (as root) to /usr/lib/iceweasel/extensions/<appid> is now the only way out to avoid the cumbersome Windows-ish "File-Open..." procedure (which requires that Firefox/ Iceweasel is running, too)
But I want to install my extension(s) without launching the browser first.
So this is the steps I did (or better, I was forced to do)

*

*have myapp.xpi ready on my storage media

*extract install.rdf with unzip and cat it to retrieve app ID

Lastly, I do a
sudo unzip /media/wherever/myapp.xpi -d /usr/lib/iceweasel/extensions/<appid>

The -d option will specify the directory where to extract to (if it does not exist yet, the directory will be created).
OK, that method actually works. But I thought this is a bit stone-age, perhaps?
I actually expected to only copy the *.xpi to the extensions directory and let Firefox/Iceweasel unpack it by itself. However, this does not work.
I tried all of the following four variants to no avail:

*

*copy myapp.xpi to /usr/lib/iceweasel/extensions as-is

*copy myapp.xpi to /usr/lib/iceweasel/extensions/<appid>/ as-is

*copy myapp.xpi to /usr/lib/iceweasel/extensions and rename it to  {appid}.xpi

*copy myapp.xpi to /usr/lib/iceweasel/extensions/<appid>/ and rename it to {appid}.xpi
However, neither of said methods made the extension show up in Add-On Manager.
Maybe the unpacking is mandatory under Linux?
I also consulted the official "documentation", which, TBH, is abysmal. It only gives an example for Mac OS X, but not for Linux. Plus,the wording is fairly incomprehensible. Check yourself:
https://developer.mozilla.org/en-US/docs/Installing_extensions
So how am I supposed to perform this installation under Linux (Debian here) without unpacking the extension by hand?


text:
Q: libstk.a undefined symbol for architecture x86_64 (or i386) I try to use the library libstk.a (from The Synthesis ToolKit in C++ (STK))in a XCode 4.5.1 application project to build for Standard(32/64 bit Intel) architectures.
I just drop the file libstk.a and stk.h into my project.
First I made the library of stk-4.4.4 following the instructions given in the doc of stk (./configure with --with-core and --enable-debug) and then make in the src directory. It gives the libstk.a file without errors.
In the xcode project, no syntax error, but link errors : undefined symbol for architecture x86_64 for different methods (maybe all) + the same for i386
It looks like libstk.a was not build for i386 or x86_64.
I used command lines to make the library and i am not familiar with this. How can I ensure that the library will be build for i386 and i86_64 archs ? Do I have to do something different to include the library in my project than just drop it in the files list ? I need help !

A: Use -arch i386 or -arch x86_64 gcc option..


text:
Q: Is there some way to have Newtonsoft.Create call your custom creation method on an interface? I am using Hangfire to run multiple tasks of my custom interface, let's call it IType. However, since Hangfire serializes the method, thereby destroying the instance of that type so when it tries to call it I get an error message like this:

Newtonsoft.Json.JsonSerializationException: Could not create an instance of type IType. Type is an interface or abstract class and cannot be instantiated. Path 'Something', line 1, position 17.
     at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewObject(...

I figure that one way around this is for each class that is an instance of my interface can store its fully qualified domain name, then I can use reflection to return it the type that it needs, only problem is I don't know how to get Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewObject() to call my deserialization method. Is there some attribute or some specific method name I need to have in order to make this work?

A: You need to specify a JsonSerializerSettings that includes a suitable TypeNameHandling value. That will embed the fully qualified name in the JSON in a $type property, which it can then use to deserialize. Here's a complete example:
using System;
using Newtonsoft.Json;

interface IFoo
{
    void Method();
}

class Foo1 : IFoo
{
    public string Name { get; set; }
    public void Method() => Console.WriteLine("Method in Foo1");
}

class Foo2 : IFoo
{
    public int Value { get; set; }
    public void Method() => Console.WriteLine("Method in Foo2");
}

class Root
{
    public IFoo First { get; set; }
    public IFoo Second { get; set; }
}

class Test
{
    static void Main()
    {
        Root root = new Root
        {
            First = new Foo1 { Name = "Fred" },
            Second = new Foo2 { Value = 10 }
        };
        var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
        string json = JsonConvert.SerializeObject(root, settings);

        Console.WriteLine(json);

        Root root2 = JsonConvert.DeserializeObject<Root>(json, settings);
        root2.First.Method();
        root2.Second.Method();
    }
}

Output, showing both the JSON and the fact that the interface properties in Root have been suitably deserialized:
{"$type":"Root, Test","First":{"$type":"Foo1, Test","Name":"Fred"},"Second":{"$type":"Foo2, Test","Value":10}}
Method in Foo1
Method in Foo2

There are other TypeNameHandling values you might want to use instead of All - see the documentation for details.

A: For completeness, to apply @Daisy's answer to Hangfire, in your StartUp (this is for .NET Core):
app.UseHangfireDashboard("/hangfire", ...);

app.UseHangfireServer(...);

JobHelper.SetSerializerSettings(new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.All
});

A: For .Net core
GlobalConfiguration.Configuration.UseSerializerSettings(new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.All
            })


text:
Q: Why do transitions flicker/stutter when applied in a separate function (D3) I was messing around with transitions and I noticed some stuttering and flickering when the transitions are applied to the selection in a different function. If, however, the transition is applied with method chaining, it works exactly as prescribed.
Below is small example (Fiddle) of simply moving some text. The first, leftmost, string magically teleports down the page before the transition starts. The second, rightmost, string has a smooth transition from the top to the bottom of the page.
Why does this 'teleport' happen? Obviously applying the transitions in a separate function is not the same as chaining it, but is there a way to achieve this? Say, I want to apply the same transition to many different objects - retrieved from different selects - then is there a way to relegate the transition to its own function without getting this stuttering?
var svg = d3.select('svg');
var textElem = svg.append('text')
    .data(['hello world'])
    .attr('x', 30)
    .attr('y', 100)
    .attr('fill', '#000')
    .attr('id', 'a')
    .text(function (d) {
        return d;
    });
var textElem2 = svg.append('text')
    .data(['some text'])
    .attr('x', 230)
    .attr('y', 100)
    .attr('fill', '#000')
    .attr('id', 'a')
    .text(function (d) {
        return d;
    });
setTimeout(foo, 3000);

function foo() {
    textElem.data(['hello world, again!']);
    applyTextTransitions(textElem);
    textElem.attr({
        x: 30,
        y: 150
    });
    textElem.text(function (d) {
        return d;
    });

    textElem2.data(['some more text!'])
        .transition()
        .duration(1000)
        .style('opacity', 0)
        .transition()
        .duration(1000)
        .style('opacity', 1)
        .attr({
            x: 230,
            y: 150
        })
        .text(function (d) {
            return d;
        });
}

function applyTextTransitions(element) {
    element
        .transition()
        .duration(1000)
        .style('opacity', 0)
        .transition()
        .duration(1000)
        .style('opacity', 1);
}

A: I haven't used d3, but do you mean to do this?
applyTextTransitions(textElem, { x: 30, y: 150 });

function applyTextTransitions(element, newPos) {
    element
    .transition()
    .duration(1000)
    .style('opacity', 0)
    .transition()
    .duration(1000)
    .attr(newPos)
    .style('opacity', 1)
    .text(function(d){
        return d;
     });
}

https://jsfiddle.net/k8kv4arv/3/
The "jump" happens because the calling functions waits until applyTextTransitions() is finished, then applies the new dimensions.

A: I know I'm late to the party, but...
The stuttering that you are getting is only because you call a transition function, applyTextTransition, and then immediately change the element's positioning.
applyTextTransitions(textElem);
textElem.attr({
    x: 30,
    y: 150
});

This is why you get the unwanted stuttering.

Additionally, the proper, D3 way to reuse functions that apply transitions is to use selection.call. This allows you to declare one function, and use the call method to invoke the function that applies the transition.
textElem.call(applyTextTransition);

function applyTextTransition(selection) {
  // perform selection.transition()
}

You can now use your function in your chaining and you aren't limited to using that function for just the current selection.


text:
Q: How do you turn on Code Coverage in Builds within TFS? I need to know how to turn on Code Coverage when running TFS builds on a solution with a .testrunconfig file.
There is an option in the testrunconfig file that is for code coverage, but when running a TFS build there is no code coverage results.
I am running my tests using the *Tests.dll mask and NOT using Test Lists (.vsmdi).

A: How are you running the tests?  Are you using a .vsmdi file or just specifying that you run all tests in *Tests.dll assemblies?
If it is the latter and you are using TFS 2008, then you need to add the following to the and of the first PropertyGroup in your TFSBuild.proj file for the build.
<RunConfigFile>$(SolutionRoot)\TestRunConfig.testrunconfig</RunConfigFile>

This points the build at your .testrunconfig so it can pick up the instructions to run code coverage.

A: You'll need the RunConfigFile entry whether you use the .vsmdi file for Test Lists or just specify the assembly file pattern.  In that .testrunconfig file you specify the assemblies you want to apply code coverage to.


text:
Q: why won't "toByteArray()" execute? I've been trying to figure this out for hours and it's soo frustrating!
I am serializing a 'hashtable', which is the object that I am passing to this method
'saveDataToDisk(Object o)', I tested this out in a regular java project and it executes the 'toByteArray()' correctly, but in Android it always goes into the catch whenever it hits toByteArray()... any ideas? Thank you in advance.
public static byte[] saveDataToDisk(Object o)
{
    // Storing the data into byte streams.
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try
    {
        ObjectOutputStream out = new ObjectOutputStream(bos);
        out.writeObject(o);
        out.close();
        // Get the bytes of the serialized object
        byte[] buf = bos.toByteArray();

        return buf;
    }
    catch (IOException ioe)
    {
        return null;
    }
}

A: I tried to execute your use case, seems to work for me.
Refer to the code below
I get a byte array : [-84, -19, 0, 5, 116, 0, 2, 72, 105]
public class WriteObject extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_1);
    Button button1 = (Button) findViewById(R.id.button1);
    button1.setOnClickListener(new OnClickListener(){
        String s = "Hi";
        @Override
        public void onClick(View v) {
            byte[] b = WriteObject.saveDataToDisk(s);
            Log.i("", b.toString());

        }

    });
}
public static byte[] saveDataToDisk(Object o){
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] buf = null;
    try{
        ObjectOutputStream out = new ObjectOutputStream(bos);
        out.writeObject(o);
        out.close();
        buf = bos.toByteArray();
    }catch (IOException ioe){
        Log.e("", ioe.toString(),ioe);
    }
    return buf;
}

}

A: I found this
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
byte [] data = bos.toByteArray();
return data;

So you may want to try out.flush()


text:
Q: Vba macro to check if dates match and copy data to shet if the corresponding row contains a string Hello im fairly new to vba but i been struggling with a code in working on,  i need to check if the dates on sheet1 match another in sheet2 and copy data from sheet2 to sheet1 if the corresponding row from sheet2 contains a certain text string.  Any help would be appreciated.

A: I created for you an Excel file wich contains three sheets (Sheet1, Sheet2 and Sheet3).
On the first sheet, I have the data as below:
ValueDate   Operation   User
12/08/2016  Operation1  SYS
13/08/2016  Operation2  MAN
14/08/2016  Operation3  SYS
15/08/2016  Operation4  MAN
16/08/2016  Operation5  SYS
17/08/2016  Operation6  MAN
18/08/2016  Operation7  SYS
19/08/2016  Operation8  MAN
20/08/2016  Operation9  SYS
21/08/2016  Operation10 MAN
22/08/2016  Operation11 SYS
23/08/2016  Operation12 MAN
24/08/2016  Operation13 SYS
25/08/2016  Operation14 MAN

On the second I have the details of the operations by line:
Date    Code1   Code2   Code3   Code4   Obs.
12/08/2016  ABR                        Abreviation
12/08/2016       SPL                   Spelling
12/08/2016                      OTH    Others
15/08/2016              CHK            Checklist
16/08/2016  ABR                        Abreviation
17/08/2016  ABR                        Abreviation
17/08/2016       SPL                   Spelling
19/08/2016  ABR                        Abreviation

For each date of the sheet1, it is sought whether there are matches in sheet2.
If so, we copy the found row of sheet2 into a new row of sheet3.
This is the VBA code to do this.
Sub findMatching()
Dim CurrentLine As Long, CurrentLine2 As Long, CurrentLine3 As Long
Dim MaxRows As Long, MaxRows2 As Long

MaxRows = 20
MaxRows2 = 25
CurrentLine3 = 2 '-- We start at second line because header in the first   line
'Fill Heading sheet3
Sheets(3).Cells(1, 1) = Sheets(2).Cells(1, 1)
Sheets(3).Cells(1, 2) = Sheets(2).Cells(1, 2)
Sheets(3).Cells(1, 3) = Sheets(2).Cells(1, 3)
Sheets(3).Cells(1, 4) = Sheets(2).Cells(1, 4)
Sheets(3).Cells(1, 5) = Sheets(2).Cells(1, 5)
For CurrentLine = 1 To MaxRows '-- Loop in first sheet (read data)
    For CurrentLine2 = 1 To MaxRows2 '-- Loop in second sheet (compare data)
      If Sheets(1).Cells(CurrentLine, 1) = Sheets(2).Cells(CurrentLine2, 1) Then
      '-- copying matching data
    Sheets(3).Cells(CurrentLine3, 1) = Sheets(2).Cells(CurrentLine2, 1)
    Sheets(3).Cells(CurrentLine3, 2) = Sheets(2).Cells(CurrentLine2, 2)
    Sheets(3).Cells(CurrentLine3, 3) = Sheets(2).Cells(CurrentLine2, 3)
    Sheets(3).Cells(CurrentLine3, 4) = Sheets(2).Cells(CurrentLine2, 4)
    Sheets(3).Cells(CurrentLine3, 5) = Sheets(2).Cells(CurrentLine2, 5)
    CurrentLine3 = CurrentLine3 + 1
  End If
   Next CurrentLine2
 Next CurrentLine
 '-- If the date in the first column isn't formatted well.
 Sheets(3).Columns("A:A").Select
 Selection.NumberFormat = "m/d/yyyy"
 Sheets(3).Range("A1").Select
End Sub

Below the result
Date    Code1   Code2   Code3   Code4
12/08/2016  ABR
12/08/2016        SPL
12/08/2016                      OTH
15/08/2016              CHK
16/08/2016  ABR
17/08/2016  ABR
17/08/2016        SPL
19/08/2016  ABR

Hope this can help!

A:    <code>
    With SrchRng
Range("H22").Select
Do Until i = 120
If InStr(1, Cells(j, 8), Srchwrd) < 0 And Activecells.Offset(0, -6).Value
Master.Cells(i, 2) Then _
  Master.Cells(i, 3).Value = Cells(j, 8).Offset(0, -2).Value _
 And i = i + 1
   j = j + 1

         If NCB.Cells(j, 2).Value <> Master.Cells(i, 2).Value _
   Then Master.Cells(i, 3).Value = "No Entry Today"
  i = i + 1
 j = j + 1


text:
Q: Batching php's fgetcsv I have a fairly large csv file (at least for the web) that I don't have control of. It has about 100k rows in it, and will only grow larger.
I'm using the Drupal Module Feeds to create nodes based on this data, and their parser batches the parsing in groups of 50 lines. However, their parser doesn't handle quotation marks properly, and fails to parse about 60% of the csv file. fgetcsv works but doesn't batch things as far as I can tell.
While trying to read the entire file with fgetcsv, PHP eventually runs out of memory. Therefore I would like to be able to break things up into smaller chunks. Is this possible?

A: fgetcsv() works by reading one line at a time from a given file pointer. If PHP is running out of memory, perhaps you are trying to parse the whole file at once, putting it all into a giant array. The solution would be to process it line by line without storing it in a big array.
To answer the batching question more directly, read n lines from the file, then use ftell() to find the location in the file where you ended. Make a note of this point, and then you can return to it at some point in the future by calling fseek() before fgetcsv().

A: Well, create a function to parse a bunch of lines:
function parseLines(array $lines) {
    foreach ($lines as $line) {
        //insert line into new node
    }
}

Then, just batch it up:
$numberOfLinesToBatch = 50;
$f = fopen($file, 'r');
if (!$f) die('implement better error checking');

$buffer = array();
while ($row = fgetcsv($f)) {
    $buffer[] = $row;
    if (count($buffer) >= $numberOfLinesToBatch) {
        parseLines($buffer);
        $buffer = array();
    }
}
if (!empty($buffer)) {
    parseLines(buffer);
}

fclose($f);

It streams the data in, and you can tune how many rows it buffers by tweaking the varariable...

A: I suspect the problem is the fact that you're storing too much information in memory rather than how you're reading the CSV file off disk. (i.e.: fgetcsv will only read a line at a time, so if a single line's worth of data is causing you to run out of memory you're in trouble.)
As such, you simply need to use an approach where you:

*

*Read 'x' lines into an array.

*Process this information

*Clear any temporary variables/arrays.

*Repeat until FEOF.

Alternatively, you could execute the CSV processing via the command line version of PHP and use a custom php.ini that has a much larger memory limit.


text:
Q: Search the index of an ajax request element in javascript I have an ajax response with data extracted from a sql query. It has this structure:
Response
   id:"id"
   titulo:"title"
   url:"url"

What I am trying to do is to find the position within the ajax response where a given unique id is.
$.ajax({
    url: 'select.php',
    type: 'get',
    data: {
        "id": id
    },
    dataType: "json",
    beforeSend: function() {},
    success: function(response) {
        console.log(response);
        console.log(response.indexOf(27188964));
    }
});

The second log prints -1, knowing that the number should be at the first position.
EDIT:
 I need the position in order to start moving through the array by increasing 'index'
 response[index].url

A: If your response is an array of objects you can use Array.prototype.filter():
$.ajax({
    url: 'select.php',
    type: 'get',
    data: {
        "id": id
    },
    dataType: "json",
    beforeSend: function() {},
    success: function(response) {
        var resultIndex;
        var result = response.filter(function(obj, index) {
            if (obj.id === '27188964') {
                resultIndex = index;
                return true;
            }
            return false;
        });

        console.log('resultIndex:', resultIndex);
        console.log('result:', result);
    }
});


text:
Q: load balancing percona with haproxy I am trying to configure ha-proxy for percona DB with 3 different nodes. My configuration goes as follows-
backend mysql_backend
mode tcp
option tcplog
balance leastconn
option httpchk default-server port 9200 inter 5s downinter 10s  rise 3 fall 2 maxconn 256
server  percona1  percona-1:3306 check port <port_num> inter 12000 rise 3 fall 3 maxconn 450
server  percona2 percona-2:3306 check port <port_num> inter 12000 rise 3 fall 3 maxconn 450 backup
server  percona3 percona-3:3306 check port <port_num> inter 12000 rise 3 fall 3 maxconn 450 backup

In the above configuration,*maxconn 450* specifies the maximal number of concurrent connections that will be sent to this server1 i.e. percona1. Now interesting thing that pop up in my mind, what if

*

*number of connection reach to 450 and another request comes?? Will the 451st request will be queued or it will be forwarded to percona2/percona3(which is a back up server in case percona1 fail but here percona1 did not fail but reach to limit)

*Percona1(my.conf) configured such as it can handle as many as 250  connection at a time but from proxy server, it gets more than 250 like 450 as it is configured in proxy server.
My question is what will happen in the above scenarios??
I have read documentation however i dint get any clear information. Help will be much appreciated.

A: I'm guessing that you're talking about Percona XtraDb Cluster because using HAproxy in this fashion with 3 separate MySQL instances is going to lead to disaster (if they are separate instances, re-architect now!!). Here are the answers to your questions:

*

*If config'ed for maxconn of 450, the 451st connection will be queued and wait for an open connection to the server. (the documentation is pretty clear) *One point to note is that you should check the the ulimit -n of the HAproxy process to make sure that it has a connection limit of more than 1350 (450 * 3 nodes)*

*I'm not completely sure I understand the question, but if you're referring to the max_connectionsparameter for mysqldthen you should set that parameter slightly higher than the HAproxy maxconnvalue for that particular server to avoid timeouts


text:
Q: uploading files from react to node js with multer I want to upload files from the form data in react which is being posted by axios like this.
const addNewProduct = () => {
        const newProduct = {
            name: name,
            cost: cost,
            size: size,
            color: color,
            material: material,
            discount: discount,
            description: description,
            category: category
        };

        const nulls  = Object.values(newProduct).filter(p => p === null);

        if(nulls.length === 0 && images.imageFiles) {
            let productFormData = new FormData();
            productFormData.append('productInfo', JSON.stringify(newProduct));
            productFormData.append('productImages', images.imageFiles);

            const addUrl = "http://localhost:8080/cpnl/addproduct";
            axios({
                method: "POST",
                url: addUrl,
                data: productFormData,
                headers: { "Content-Type": "multipart/form-data" }
            })
                .then((response) => {
                    console.log(response.data.msg);
                })
                .catch((response) => {
                    console.error(response);
                });
        }else {
            Notiflix.Notify.Warning("Check your inputs!");
            console.log(nulls);
            console.log("product: \n" + JSON.stringify(newProduct));
        }
};

then I want to upload images with multer to images folder. this is my code:
const storage = multer.diskStorage({
destination: "./public/images",
filename: (req, file, cb) => {
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});

const upload = multer({
    storage: storage,
    limits:{fileSize: 1000000},
    fileFilter: function(req, file, cb){
        checkFileType(file, cb);
    }
}).array("productImages", 5);

function checkFileType(file, cb) {
  // Allowed ext
  const filetypes = /jpeg|jpg|png/;
  // Check ext
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  // Check mime
  const mimetype = filetypes.test(file.mimetype);

  if(mimetype && extname){
    return cb(null,true);
  } else {
    cb('Error: Images Only!');
  }
}

//receive form data from front-end and add new product to database
router.post('/addproduct', async (req, res) => {
    upload(req, res, (err) => {
        if(err) {
            res.status(400).json({
                msg: err
            });
        } else {
            if(req.files == undefined) {
                res.status(400).json({
                    msg: "Error: No file selected! please contact the developer."
                });
            } else {
                data = req.body.productInfo;
                res.status(200).json({
                    msg: "Files uploaded!"
                });
                console.log( "images: " + req.files);
                console.log("data" + data);
            }
        }
    });
});

first problem: I'm getting image files inside req.body.productImages and not inside req.files
second problem: when I send the request node js throws me this error:

TypeError: upload is not a function

why everything is messed up!?
Edit: I restarted the server and now I'm getting data but the files are not being uploaded. no error is shown.
UPDATE: second problem fixed

A: First Problem : You have used .array("productImages", 5); in your upload function. use .array("files", 5); to get the file in req.files.
Second Problem : I guess there is some typo error in your code upload(req, res, (err)... there is one extra bracket it should be only upload(req,res,err )...


text:
Q: How can i take a screenshot of the pictureBox1 handle window? I'm using this class but that take a screenshot of the desktop handle.
And i need to take a screenshot of the pictureBox1 handle.
#region Class Imports
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.ComponentModel;
#endregion

namespace Test
{
    /// <summary>
    /// Class for taking a screen shot in code
    /// </summary>
    public class ScreenShot
    {
    /// <summary>
    /// Global variable declarations
    /// </summary>
    #region Global Variables
    private Bitmap _screenShot;
    protected static IntPtr newBMP;
    #endregion

    #region Constants
    public const int SRCCOPY = 13369376;
    public const int SCREEN_X = 0;
    public const int SCREEN_Y = 1;
    #endregion
    /// <summary>
    /// Hold the definition for the
    /// class properties
    /// </summary>
    #region Class Properties
    [Description("Gets the screenshot image")]
    public Bitmap ScreenImage
    {
        get { return _screenShot; }
    }
    #endregion

    #region Constructor
    /// <summary>
    /// Constructors for our class
    /// </summary>
    [Description("Empty constructor, instantiating _screenShot to nothing")]
    public ScreenShot()
    {
        _screenShot = null;
    }
    #endregion

    #region Methods
    /// <summary>
    /// Method for creating an image of the current desktop
    /// </summary>
    /// <returns>A Bitmap image</returns>
    [Description("Creates an image of the current desktop")]
    public Bitmap GetScreen()
    {
        int xLoc;
        int yLoc;
        IntPtr dsk;
        IntPtr mem;
        Bitmap currentView;

        //get the handle of the desktop DC
        dsk = Win32API.GetDC(Win32API.GetDesktopWindow());

        //create memory DC
        mem = Win32API.CreateCompatibleDC(dsk);

        //get the X coordinates of the screen
        xLoc = Win32API.GetSystemMetrics(SCREEN_X);

        //get the Y coordinates of screen.
        yLoc = Win32API.GetSystemMetrics(SCREEN_Y);

        //create a compatible image the size of the desktop
        newBMP = Win32API.CreateCompatibleBitmap(dsk, xLoc, yLoc);

        //check against IntPtr (cant check IntPtr values against a null value)
        if (newBMP != IntPtr.Zero)
        {
            //select the image in memory
            IntPtr oldBmp = (IntPtr)Win32API.SelectObject(mem, newBMP);
            //copy the new bitmap into memory
            Win32API.BitBlt(mem, 0, 0, xLoc, yLoc, dsk, 0, 0, SRCCOPY);
            //select the old bitmap into memory
            Win32API.SelectObject(mem, oldBmp);
            //delete the memoryDC since we're through with it
            Win32API.DeleteDC(mem);
            //release dskTopDC to free up the resources
            Win32API.ReleaseDC(Win32API.GetDesktopWindow(), dsk);
            //create out BitMap
            currentView = Image.FromHbitmap(newBMP);
            //return the image
            return currentView;
        }
        else  //null value returned
        {
            return null;
        }
    }
    #endregion

    #region Helpers
    [Description("Takes the information from GetScreen and creates a Bitmap image")]
    public void GetScreenShot(string folder, string name)
    {
        //check to see if the folder provided exists
       /* if (!Directory.Exists(Application.StartupPath + "\\" + folder))
        {
            //if it doesnt exist then we need to create it
            Directory.CreateDirectory(Application.StartupPath + "\\" + folder);
        }*/
        //set the ScreenImage Property to the
        //BitMap created in GetScreen()
        _screenShot = new Bitmap(GetScreen());
        //create a name based on the name passed in
        string ingName = folder + name + Elgato_Video_Capture.counter.ToString("D6") + ".bmp";
        //save the image
        _screenShot.Save(ingName);
        _screenShot.Dispose();
    }
    #endregion
    }

}

Then i'm using it like that:
    ScreenShot shot = new ScreenShot();
    public static int counter = 0;

    private void timer1_Tick(object sender, EventArgs e)
    {
        counter++;

        shot.GetScreenShot(@"e:\screenshots\", "screenshot");
        if (counter == 1200)
        {
            timer1.Stop();
        }
    }

I need to take a screenshot of the pictureBox1.Handle window not the pictureBox1.Image.
The problem is that the class ScreenShot take a screenshot of the desktop Handle and i want to take a screenshot only of the pictureBox1.Handle


text:
Q: Temporary Housing for Recursion Here is a simple multiplication recursive function.
public static int Mult(int x, int y)
{
    if (y == 0)
    {
        return 0;
    }
    else
    {
        return x + Mult(x, y - 1);
    }
}

Every time the function is returned and added to itself...
But until the final function returns with concatenation, where is this in memory and how come this quasi storage isn't visible in Visual Studio?
Just wondering if the Depth of the Thread represents some mysterious stack this int is temporarily living in?
Thread  Depth
[19260] [0] Line 21
[19260] [1] Line 14
...

A: The method calls exist in the call stack and the value in a registry. You can see a bit more information about the call stack in Visual Studio by opening a separate window (Debug -> Windows -> Call Stack). In VS 2013, you can access $ReturnValue to see function return values, but this doesn't seem to work for me in VS2015.
You can right click the call stack window to see the values of each call, for example:


text:
Q: Making an AJAX call to get data from a search form result to render. I am making a stock application and basically the user needs to enter a ticker and after going through the ajax call it will return the instance variable containing the price, ticker, and name. It will also render right below the search bar.
here is a pic of the UI

Here is the model

Search for Stocks

    <%= form_tag search_stocks_path, remote: true, method: :get, id: 'stock-lookup-form' do %>

        <%= text_field_tag :stock,
        params[:stock],
        placeholder: 'Stock Ticker Symbol',
        autofocus: true,
        class: 'form-control search-box input-lg' %>

        <%= button_tag(type: :submit, class: 'btn btn-lg btn-success') do %>
             Look up a stock
        <% end %>

<% end %>
<% if @stock %>

    Symbol: <%= @stock.ticker %>
    Name: <%= @stock.name %>
    Price: <%= @stock.price %>

<% end %>

Here is the controller
class StocksController < ApplicationController

    def search
        if params[:stock]
            @stock = Stock.find_by_ticker(params[:stock])
            @stock ||= Stock.new_from_lookup(params[:stock])
        end
        if @stock
            puts @stock.price
            render partial: 'lookup'
        else
            render status: :not_found, nothing: true
        end
    end

end

when I puts puts @stock.price, I am getting the information I want. It then proceeds to render the page I want, but it doesnt seem to get me the information which is rendered in an erb file with an if condition that says if @stock, render the necessary information.
here is the view to give you an idea of what I am talking about.

Search for Stocks

    <%= form_tag search_stocks_path, remote: true, method: :get, id: 'stock-lookup-form' do %>

        <%= text_field_tag :stock,
        params[:stock],
        placeholder: 'Stock Ticker Symbol',
        autofocus: true,
        class: 'form-control search-box input-lg' %>

        <%= button_tag(type: :submit, class: 'btn btn-lg btn-success') do %>
             Look up a stock
        <% end %>

<% end %>
<% if @stock %>

    Symbol: <%= @stock.ticker %>
    Name: <%= @stock.name %>
    Price: <%= @stock.price %>

<% end %>

I also am making an ajax call in a separate js file which seems to be doing its job.
var init_stock_lookup;

init_stock_lookup = function() {
    $('#stock-lookup-form').on('ajax:success', function(event, data, status) {
         $('#stock-lookup').append(data);
         init_stock_lookup();
    })
}

    $('#stock-lookupform').on('ajax:error',function(event, xhr, status, error){
        $('#stock-lookup-results').replaceWith(' ');
        $('#stock-lookup-errors').replaceWith('Stock was not found.')
    });

$(document).ready( function(){
    init_stock_lookup();
})

def not a rails or ruby master, so any help would be much appreciated!

A: What is happening in your case when you call render partial: 'lookup' in your controller action it is giving the code in response you can check that on browser's developer console but it doesn't know what to do of that response like either append it prepend it replace any HTML from the DOM etc etc.
Try this:
In your controller action write this:
def search
  if params[:stock]
    @stock = Stock.find_by_ticker(params[:stock])
    @stock ||= Stock.new_from_lookup(params[:stock])
  end
  respond_to do |format|
    format.js
  end
end

In your app/views/stocks create a file search.js.erb and in it write the code:
<% if @stock %>
  $('body').html("<%= j render partial: 'lookup' %>");
<% end %>

You will definetely need to change $('body').html to some relevant selector in your application.
Hope this helps.


text:
Q: Find the size of a query Based on the max_allowed_packet configuration parameter in MySQL, I am curious to understand how I can determine the size of the query related to that particular configuration?
We can use the SHOW VARIABLES LIKE 'max_allowed_packet' command in the MySQL Server. This will provide the current value for the parameter, which can then be used to calculate the size of the query accordingly. Additionally, one can also use the SET GLOBAL max_allowed_packet command to set the new value for the parameter.
My question is: How can I figure out the size of a query that is compared to this configuration?

A: The MariaDB protocol documentation for the packet states that each packet sent by the client must be below the max_allowed_packet limit. This means that all SQL queries must be shorter than max_allowed_packet. In most cases this is not something you have to worry about unless you are inserting large batches of data using SQL statements.
Since there's some overhead in the network packets, a good rule of thumb for queries shorter than 16Mib is to take the string length of the query in bytes and subtract 1 byte from it: the packet header's length will be the SQL query plus the COM_QUERY byte. In general going this far to match the limits is rarely worth it and staying well below the limit tends to be a more practical approach.
This does not mean that the server won't generate packets that are longer than this. Here's an example where the server exceeds the limit of max_allowed_packet:
MariaDB [test]> SET @a = (SELECT GROUP_CONCAT(seq) FROM seq_0_to_1000000);
Query OK, 0 rows affected, 1 warning (0.060 sec)

MariaDB [test]> SELECT LENGTH(@a), @@max_allowed_packet, @@group_concat_max_len;
+------------+----------------------+------------------------+
| LENGTH(@a) | @@max_allowed_packet | @@group_concat_max_len |
+------------+----------------------+------------------------+
|    1048576 |                16384 |                1048576 |
+------------+----------------------+------------------------+
1 row in set (0.001 sec)

MariaDB [test]> SELECT LENGTH(@a), @a\G
*************************** 1. row ***************************
LENGTH(@a): 1048576
        @a: 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
... More data ...

The value of max_allowed_packet is also not really related to how large your resultsets can be. You can generate a resultse that's a terabyte in size with  max_allowed_packet set to 16Kib. This happens because resultsets are a stream of packets and if each individual packet is below the limit, there is no limit on how long the result can be.
And as Georg Richter mentioned in the comments, @max_allowed_packet also affects the length of some literals/strings. For example, SET @a:= REPEAT("A", @@max_allowed_packet + 1) will fail, even if the string length of the actual SQL statement is only a few bytes.


text:
Q: Make Markdown files accessible in SharePoint and Microsoft Search We are planning to migrate our pre-written documentation from Confluence into a repo, converting everything to Markdown and image files.
The end result needs to conform to the following requirements:

*

*There are several hundred files, so the deployment process should be as automated as possible.

*Accessible in Microsoft Search (For example the top search bar in SharePoint and Teams)

*There needs to be some kind of navigation, kind of like in Docusaurus (example from my local machine)

We have set up a CI/CD process in Azure DevOps that is easily able to convert all of our special PlantUML syntax to .svg files, and render Markdown to PDF, HTML and whatever else is needed.
We have tried:

*

*Setting up a Docusaurus environment. This, however, means that the content is not indexed by Microsoft Search.

*Uploading all files as PDF. This even works automatically via CI/CD, no extra effort needed. However, when we open the files, the entire page is covered by the PDF preview. The navigation is basically just the document library. This is not intuitive at all - The navigation should be to the side of the file.

A: Try to use Microsoft Graph Connectors to bring external content into the index:
https://docs.microsoft.com/en-us/microsoftsearch/connectors-overview
https://docs.microsoft.com/en-us/microsoftsearch/overview-microsoft-search#tailoring-microsoft-search-to-your-organization
As far as I know, for the navigation covered by the PDF preview, we couldn't change the default behavior.


text:
Q: NSCFArray length]: error, array regex   StringReply = [[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding];

         //Regex Out Artist Name
         //NSString *regEx = ;
         NSArray *iTunesAristName = [stringReply componentsMatchedByRegex: @"(?<=artistname\":\")([^<]+)(?=\")"];

         if ([iTunesAristName isEqual:@""]) {
           NSLog(@"Something has messed up");
           //Regex Out Song Name
          }else{
           NSLog(iTunesAristName);
          }

         NSLog(iTunesAristName);
         [stringReply release];

I just keep getting this error ?
        2010-09-29 21:15:16.406 [2073:207] *** -[NSCFArray length]: unrecognized selector sent to instance 0x4b0b800
        2010-09-29 21:15:16.406 [2073:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFArray length]: unrecognized selector sent to instance 0x4b0b800'
        2010-09-29 21:15:16.407 [2073:207] Stack: (

please help its driving me crazy

A: The first argument to NSLog is supposed to be a format string. You're passing an NSArray. When the function tries to treat your array as a string, you get that error. Instead, use NSLog(@"%@", iTunesAristName);.

A: Chuck has answered your question, but I've noticed something else that is problematic.
NSArray is an array, not a string, so [iTunesArtistName isEqual:@""] will never return true, because they are different classes. Even if iTunesArtistName was a string, it should be compared using the isEqualToString: method, not isEqual:.
If you want to extract only the artist's name, you might be able to do this:
NSArray *matches = [stringReply componentsMatchedByRegex: @"(?<=artistname\":\")([^<]+)(?=\")"];

if ([matches count] == 0)
{
    NSLog(@"Could not extract the artist name");
}
else
{
    NSString *iTunesArtistName = [matches objectAtIndex:0];

    NSLog(@"Artist name: %@", iTunesArtistName);
}

A: I see you're using RegexKitLite, make sure you import libicucore.dylib, i was getting the same error until i imported that library.


text:
Q: How can I open android application at booting time? I have a requirement of client. Client has to load android application on android tablet. He doesn't want other applications to be opened. He wants his app should be opened at booting time OR if you restart it.As I am an android developer. Application is ready now.How can I fulfill his requirement.He doesn't want user to interact with another application.He can't go home screen. Is it possible?
Can someone help me with correct steps so I can try on one device.
Thanks,
Prashant

A: You can use the Kiosk mode of your tablet, this mode is different is you use Android or IOS. (for me Android is better because you can't quit instead of IOS... with the round button)
http://www.andreas-schrade.de/2015/02/16/android-tutorial-how-to-create-a-kiosk-mode-in-android/

A: One Possible solution might be: make your app a default launcher. you can do this by adding this lines to your manifest :
<intent-filter>
<action android:name="android.intent.action.MAIN" />
   <category android:name="android.intent.category.HOME" />
   <category android:name="android.intent.category.DEFAULT" />
   <category android:name="android.intent.category.MONKEY" />
</intent-filter>

after this you just need to select your app as a default launcher.
Some useful links about it:
How to set default app launcher programmatically
How to make app as default system launcher
Another solution is to get the android source code and compile it and build your own kernel with your favorite apps.
some useful links about how to build a kernel:
Building the System
Establishing a Build Environment
Compile android kernel source beginners guide
Of course I know the second way is a little difficult. ;)


text:
Q: Multiple user entries for multiple client data recorded in single table. how to transform SQL I'm trying to query my data which records multiple user entries for multiple client data in a single table distinguished by a unique group activity id.
Please see my table and intended output.

A: Looks to me as though you simply want all combinations of participants that are 'Users' with participants that are 'Clients' ...
-- Prep Work
IF OBJECT_ID('tempdb..#Table') IS NOT NULL DROP TABLE #Table

SELECT * INTO #Table FROM (VALUES
    (1, 'Client A'),
    (2, 'Client B'),
    (3, 'Client C'),
    (12, 'User A'),
    (12, 'User B'),
    (12, 'User C'),
    (12, 'User D')
) S(activityId, activityParticipant)

Try this query against 'your' table ....
-- Actual Query
SELECT
    U.activityParticipant,
    C.activityParticipant
FROM
    (SELECT activityParticipant FROM #Table WHERE activityParticipant LIKE 'User%') U
    CROSS JOIN
    (SELECT activityParticipant FROM #Table WHERE activityParticipant LIKE 'Client%') C
ORDER BY
    U.activityParticipant,
    C.activityParticipant


text:
Q: How to fix pip install error permission denied inside conda environment Im trying to install some packages for a project using an exported yml environment file I've been given.
During the installation with conda env create , the pip section of the yml didn't install any of the packages and I had to install them 1 by 1. Activated my environment and starting searching for each package to install with conda or conda-forge or pip.
3 of the packages required pip to install so I installed pip into my environment and then I used pip install which gave me errors of this type:
ERROR: Could not install packages due to an EnvironmentError: [Errno 1] Operation not permitted: 'classified_information_/myusername/anaconda3/envs/pytorch_1.0.1/lib/python3.7/site-packages/pretrainedmodels-0.7.4.dist-info/INSTALLEReb1alm63.tmp'

im using python3.7 if that helps and I want to add these 3 packages :
insightface
mxnet-cu100mkl
pretrainedmodels

all 3 had that type of problem and keep inmind I am not the owner of the pc ,im just a student thats allowed to use the machine for testing purposes so Sudo rights is not sth I own
Is there anything I can do?
EDIT:
I tried using the full path to pip doing anaconda3/envs/pytorch_1.0.1/bin/pip install  which worked for insightface and pretrained models but im still getting an error with mxnet :
ERROR: Could not install packages due to an EnvironmentError: [Errno 1] Operation not permitted: '/classified/myusername/anaconda3/envs/pytorch_1.0.1/lib/python3.7/site-packages/graphviz-0.8.4.dist-info/INSTALLERh4uallts.tmp'


text:
Q: Is there a way to read fixed length files using csv.reader() module in Python 2.x I have a fixed length file like:
0001ABC,DEF1234
The file definition is:
id[1:4]
name[5:11]
phone[12:15]

I need to load this data into a table. I tried to use CSV module and defined the fixed lengths of each field. It is working fine except for the name field.
For the NAME field, only the value till ABC is getting loaded. The reason is:
As I am using CSV module, it is treating 0001ABC, as a value and only parsing till that.
I tried to use escapechar = ',' while reading the file, but it removes the ',' from the data. I also tried quoting=csv.QUOTE_ALL but that didnt work either.
with open("xyz.csv") as csvfile:
    readCSV = csv.reader(csvfile)
    writeCSV = open("sample_csv", 'w');
    output = csv.writer(writeCSV, dialect='excel', lineterminator="\n")
    for row in readCSV:
         print(row) # to debug #
         data= str(row[0])
         print(data) # to debug #
         id = data[0:4]
         name = data[5:11]
         phone = data[12:15]
         output.writerow([id,name,phone])
    writeCSV.close()

Output of the print commands:
row: ['0001ABC','DEF1234']
data: 0001ABC
Ideally, I expect to see the entire set 0001ABC,DEF1234 in the variable: data.
I can then use the parsing as mentioned in the code to break it into different fields.
Can you please let me know where I am going wrong?


text:
Q: Auto scheduling I am trying to make an auto scheduling program with an excel.
For example, each number is certain job assigned to the person given day.
       1/2 1/3 1/4 1/5
Tom     1   2   2   ?
Justin  2   3   1   ?
Mary    3       3   ?
Sam         1       ?

Check   O   O   X   ?   ## check is like =if(b2=c2,"O","X")

The things I want to make sure is every person is given a different job from yesterday.
My idea
while
    randomly distribute jobs for 1/5
wend CheckCell = "O"

But I found that checking cell in the vba script doesn't work - the cell is not updated in each while loop.
Could you give me a little pointer for these kinds of program? Because I am new to vbaScript, any kinds of help would be appreciated.

A: Using VBA, I'm sure there are better ways to do this, but this will check the values from the penultimate column against values from last column and if they match it will write "O" to under the last column, else it will write "X":
Sub foo()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your worksheet, amend as required
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the last row with data on Column A
LastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column

counter = 0 'set counter

For i = 2 To LastRow 'loop through penultimate column and add values to array
    If ws.Cells(i, LastCol - 1).Value <> "" Then
    Values = Values & ws.Cells(i, LastCol - 1) & ","
    End If
Next i

Values = Left(Values, Len(Values) - 1)
Values = Split(Values, ",") 'split values into array

For i = 2 To LastRow 'loop through last column and add values to array
    If ws.Cells(i, LastCol).Value <> "" Then
    ValuesCheck = ValuesCheck & ws.Cells(i, LastCol) & ","
    End If
Next i
ValuesCheck = Left(ValuesCheck, Len(ValuesCheck) - 1)
ValuesCheck = Split(ValuesCheck, ",")

For y = LBound(Values) To UBound(Values) 'loop through both arrays to find all values match
    For x = LBound(ValuesCheck) To UBound(ValuesCheck)
        If Values(y) = ValuesCheck(x) Then counter = counter + 1
    Next x

Next y
If counter = UBound(Values) + 1 Then 'if values match
    ws.Cells(LastRow + 1, LastCol).Value = "O"
Else 'else write X
    ws.Cells(LastRow + 1, LastCol).Value = "X"
End If
End Sub

A: just to clarify are you looking to implement the random number in the vba or the check.
To do the check the best way would be to set the area as a range and then check each using the cells(r,c) code, like below
Sub checker()
Dim rng As Range
Dim r As Integer, c As Integer

Set rng = Selection
For r = 1 To rng.Rows.Count
    For c = 1 To rng.Columns.Count
        If rng.Cells(r, c) = rng.Cells(r, c + 1) Then
            rng.Cells(r, c).Interior.Color = RGB(255, 0, 0)
        End If
    Next c
Next r

End Sub

this macro with check the text you have selected for the issue and change the cell red if it matches the value to the right.
To make it work for you change set rng = selection to your range and change the rng.Cells(r, c).Interior.Color = RGB(255, 0, 0) to the action you want

A: A sligthly different approach than the other answers.
Add this function:
Function PickJob(AvailableJobs As String, AvoidJob As String)
    Dim MaxTries As Integer
    Dim RandomJob As String
    Dim Jobs() As String
    Jobs = Split(AvailableJobs, ",")

    MaxTries = 100
    Do
        MaxTries = MaxTries - 1
        If MaxTries = 0 Then
            MsgBox "Could find fitting job"
            End
        End If
        RandomJob = Jobs(Int((1 + UBound(Jobs)) * Rnd()))
    Loop Until RandomJob <> AvoidJob
    PickJob = RandomJob
End Function

And put this formula in your sheet
=PickJob("1,2,3",D2)

where D2 points to is the previous job


text:
Q: iPod Touch Updates Since I've upgraded from an iPod classic to a Touch, I've had a number of times when I've synced with iTunes and tracks have not been correctly updated, that is, they have not been marked as played that day, even when they have been played (all the way through).
Further, I've downloaded some tracks from a course on iTunesU, but they do not show in the playlist on my iPod Touch (despite being in the playlist on iTunes).
I'm running iTunes 10.10.54 and 4.1 of the firmware.  Does anyone know if either of these are known issues, or has anyone experienced similar issues.

A: I have been asking the same question in other forums about resetting play counts when syncing.
One of the strong theories is that it is an iTunes bug caused when you recreate your library in iTunes 10 from a previous iTunes 9 file (which is what I did).  Unfortunately though there is no obvious solution yet.
I have tried to solve to problem by installing a fresh copy of iTunes 9 on a separate PC and importing my existing library via the iTunes Music Library.xml file.
Unfortunately the trick for recreating the library by using the XML does not seem backwards compatible. Even if I modify the Application Version at the beginning of XML file it is not recognised by iTunes 9 and is overwritten by a new, clean iTunes Music Library.xml file.
It seems like a bug I'll have to live with until Apple fix the problem - I have submitted a bug report via their iTunes website.
Here is the thread from the apple.com forums - http://discussions.apple.com/thread.jspa?threadID=2697318
*edit*
The latest version of iTunes (10.1.2) seems to have fixed the play count reset bug.

A: These should really be seperate questions - one for the iTuensU, one for the track playdate.
As  for iTunesU issue, when you plug the iPod in there is a tab for iTunesU - you may need to check that the correct items are checked to sync.

A: For iTunes U: Make sure it's getting synced, (as Samuel said). Also, if they're videos, look for a Video Playlists section under Videos. That might let you play them from that playlist.
The reason you may have to do this: Apple wants to allow you to watch music videos/iTunes U videos without the video. This makes more sense for music videos: You get the song, and they video. You can  play the song without draining the battery from the video.

A: It's generally a good idea to run the latest version of iOS unless you're a jailbreaker.
To check out iTunesU content, go into the iPod or Music app and select "More" on the bottom right-hand corner. iTunes U should be in that list.
(Why do people say right-hand, not just right? It's not like hands are any different than other things, direction wise. Oh well.)


text:
Q: Screen freezes for about a second every 10-30 seconds My display keeps freezing for about 1-3 seconds every 10-30 seconds.  I notice in the system monitor that gnome-shell tends to accumulate ram. When it gets to using more than a couple gigs I restart it with Alt-f2 -> r which resets it memory usage to <200mb.  This seems to help for a little while but the problem doesn't go away completely.
I'm thinking it's a display issue because any time there is an animation or video playing, after each freeze it jumps ahead to where it should be had it played continuously.  When the freeze happens while I'm typing, I continue typing like normal and when it finishes the freeze everything typed during the blackout suddenly appears like it should, no missing characters.
This problem started after using Shotcut to edit a video.  I did something that locked it up completely.  The hard drive light went 100% and stayed that way.  I figured I maxed out my ram (16gb) and it was swapping so I gave it a while to work through what it was doing.  After about 10 minutes it never stopped so I hard reset.  Apparently that did not go down gracefully as I've had this glitch ever since.  I've tried reinstalling gnome-shell but that didn't help.
I'm not sure how to troubleshoot what is going on.  Could someone help please?
free -h
              total        used        free      shared  buff/cache   available
Mem:            14G        5.2G        3.9G        401M        5.5G        8.7G
Swap:           33G          0B         33G

grep -i swap /etc/fstab
# removed swapfile to use ssd instead (2/26/19)
#/swapfile                                 none            swap    sw              0       0
# swap space on ssd
/dev/disk/by-uuid/07c6e4a1-3379-454f-a727-e3fa386444da none swap sw 0 0

sysctl vm.swappiness
vm.swappiness = 60

ls -al ~/.local/share/gnome-shell/extensions
total 12
drwxrwxr-x 3 sauldog sauldog 4096 Feb  2 00:53 .
drwx------ 3 sauldog sauldog 4096 Feb 22 19:05 ..
drwxrwxr-x 6 sauldog sauldog 4096 Feb  2 00:53 arc-menu@linxgem33.com

ls -al /usr/share/gnome-shell/extensions
total 64
drwxr-xr-x 16 root root 4096 Jan 24  2019 .
drwxr-xr-x  6 root root 4096 Mar 10  2020 ..
drwxr-xr-x  2 root root 4096 Jan 24  2019 alternate-tab@gnome-shell-extensions.gcampax.github.com
drwxr-xr-x  2 root root 4096 Jan 24  2019 apps-menu@gnome-shell-extensions.gcampax.github.com
drwxr-xr-x  2 root root 4096 Jan 24  2019 auto-move-windows@gnome-shell-extensions.gcampax.github.com
drwxr-xr-x  2 root root 4096 Jan 24  2019 drive-menu@gnome-shell-extensions.gcampax.github.com
drwxr-xr-x  2 root root 4096 Jan 24  2019 launch-new-instance@gnome-shell-extensions.gcampax.github.com
drwxr-xr-x  2 root root 4096 Jan 24  2019 native-window-placement@gnome-shell-extensions.gcampax.github.com
drwxr-xr-x  2 root root 4096 Jan 24  2019 places-menu@gnome-shell-extensions.gcampax.github.com
drwxr-xr-x  2 root root 4096 Jan 24  2019 screenshot-window-sizer@gnome-shell-extensions.gcampax.github.com
drwxr-xr-x  3 root root 4096 Jul 24  2018 ubuntu-appindicators@ubuntu.com
drwxr-xr-x  3 root root 4096 Jan 30  2019 ubuntu-dock@ubuntu.com
drwxr-xr-x  2 root root 4096 Jan 24  2019 user-theme@gnome-shell-extensions.gcampax.github.com
drwxr-xr-x  2 root root 4096 Jan 24  2019 window-list@gnome-shell-extensions.gcampax.github.com
drwxr-xr-x  2 root root 4096 Jan 24  2019 windowsNavigator@gnome-shell-extensions.gcampax.github.com
drwxr-xr-x  2 root root 4096 Jan 24  2019 workspace-indicator@gnome-shell-extensions.gcampax.github.com

A: swap
16G RAM with a 33G swap is kind of nuts.
I understand moving swap to a partition on SSD, but we should switch back to a 4G /swapfile on the SSD.
I'm also a little concerned about the SSD mounting early enough in the boot process to actually use the swap. Check with free -h or swapon -s.
Note: Incorrect use of the dd command can cause data loss. Suggest copy/paste.
Note: Change /swapfile, below, to the proper location that you want on the SSD. ie: /path_to/swapfile
In the terminal...
sudo swapoff -a           # turn off swap
sudo rm -i /swapfile      # remove old /swapfile

sudo dd if=/dev/zero of=/swapfile bs=1M count=4096

sudo chmod 600 /swapfile  # set proper file protections
sudo mkswap /swapfile     # init /swapfile
sudo swapon /swapfile     # turn on swap
free -h                   # confirm 4G RAM and 4G swap

Confirm this /swapfile line at the end of /etc/fstab... and confirm no other "swap" lines...
To edit, use sudo -H gedit /etc/fstab or sudo pico /etc/fstab
/swapfile  none  swap  sw  0  0

reboot                    # reboot and verify operation

Note: You can now delete the swap partition on SSD, and add that unallocated space back to some other partition.
gnome-shell
There's a known memory leak bug in gnome-shell that causes it to consume lots of memory as time goes on.
The short term fix is to restart gnome-shell with...
ALT+F2, then r, then ENTER
gnome-shell extensions
Too many bad gnome-shell extensions that are probably causing your problem.
My particular pet peeve is that the ones installed in /usr/share/gnome-shell/extensions are system-wide for all users, and should actually have been placed in ~/.local/share/gnome-shell/extensions so that they'll be local to the current user.
So do this to remove these extensions...
sudo rm -r /usr/share/gnome-shell/extensions/*gcampax.github.com
Then restart gnome-shell...
ALT+F2, then r, then ENTER
Update #1:
We found that ~/.config/AppImageLauncher config file was being updated frequently. Uninstalled AppImageLauncher and the problem is fixed!