texts: GLSL atomic float add for architectures with out atomic float add

texts:
//MEM = initial memory, INDATA, the actual floating point value
#define atomicAddFloatX(MEM, INDATA)\
{\
    float data = INDATA;\
    float prev_mem = uintBitsToFloat(MEM);\
    float exchange_mem = prev_mem;\
    float input_mem = (data + prev_mem);\  //initially this is what we assume we want to put in here.
    while (true){\
        uint exchange_memuint = atomicExchange(MEM, floatBitsToUint(input_mem));\ //exchange with memory location, assume other threads are doing the same exact thing. atomic exchange returns the value that was already there.
        exchange_mem = uintBitsToFloat(exchange_memuint);\ //get the floating point value from returned value.
        if (prev_mem != exchange_mem){\  //if it was equal to what we initially suspected, we can exit, our data is guaranteed to be in this memory location for all other threads trying to perform this function.
            input_mem = exchange_mem + data;\ //otherwise we need to update our input. Another thread completed their atomic exchange before us.
            prev_mem = exchange_mem;\ // update our expectation of return now.
        } else {\
            break;\
        }\
    }\
}

//example
atomicAddFloatX(output[thread_id].x,  3.0);

Vulkan supports atomic float, but only for Nvidia at the moment.  It's possible however that other vendors will never support atomic float. In order to provide atomic float functionality, which is absolutely required for some algorithms, I tried my best to try to create something that would have the same effect, if less performant.
I have access to  #extension GL_KHR_memory_scope_semantics, but it is unclear if that can help me or not. I think I have bugs in how I'm dealing with loading the initial memory logically, though through internal tests in projects where this is used this seems to not have errors, but that may be a fluke of the Nvidia memory model.  I'm currently using this for the immersed boundary method for fluid solid coupling, its used to accumulate forces in a part of the algorithm.
I'm also not sure if there's other things I can do to speed this up, though I think this has serialized performance characteristics, which should be equivalent to atomic float normally.


texts: Typescript from Class to functional programming

texts:
I have a following abstract class Listener which encapsulates boiler plate code for a client. I can then have multiple listener for various events.
As a self learning excersice I converted this to functional way.

Is this is correct way to implement in functional way?
I am trying to avoid creating class for each type of listener
Should I use type or interface. As this is used for type checking of parameters, I am not sure if one is prefered over other
Any other comments on implementing functional way (currying, higher order functions)? As a noob I am trying to learn if those are applicable here and how.

abstract class Listener {
  abstract subject: string;
  private client: Client;
  abstract groupName: string;
  protected ackTimeout = 5 * 1000;

  abstract onMessage(data: any, msg: Message): void;

  constructor(client: Client) {
    this.client = client;
  }

  private subscriptionOptions(): SubscriptionOptions {
    return this.client.subscriptionOptions()
      .setOption1()
      .setOption2(this.ackTimeout)
      .setOption2(true)
      .setDurableName(this.groupName);
  }

  listen(): void {
    const subscription = this.client.subscribe(this.subject, this.groupName, this.subscriptionOptions())
    subscription.on('message', (msg: Message) => {
      console.log(`Message Received: ${this.subject}/${this.groupName}`);
      const parsedData = this.parseMessage(msg);
      this.onMessage(parsedData, msg);
    });
  }

  private parseMessage(msg: Message): any {
    const data = msg.getData();
    return typeof data === 'string' ? JSON.parse(data) : JSON.parse(data.toString('utf-8'));
  }
}

// EventType Listener
class EventCreated extends Listener {
  groupName: string = 'event:created';
  subject: string = 'event-service';

  onMessage(data: any, msg: Message): void {
    // Do something with data
    console.log(`Received `, data);
    msg.acknowledge();
  }

}

Functional Way
type Listener = {
  client: Client,
  subject: string,
  groupName: string,
  ackTimeout: number
  onMessage(data: string, msg: Message): void;
  listen(): void;
  parseMessage(msg: Message): string;
  clientOptions(): ClientOptions
}

interface ListenerOptions {
  subject: string,
  groupName: string,
  onMessage(data: any, msg: Message): void;
  parseMessage(msg: Message): string
  ackTimeout?: number,
}

const createListener = (client: Client, options: ListenerOptions): Listener => {
  options.ackTimeout = options.ackTimeout || 5 * 1000;

  return {
    client,
    groupName: options.groupName,
    ackTimeout: options.ackTimeout,
    subject: options.subject,

    onMessage: options.onMessage,

    listen: function () {
      const subscription = this.client.subscribe(this.subject, this.groupName, this.clientOptions())
      subscription.on('message', (msg: Message) => {
      console.log(`Message Received: ${this.subject}/${this.groupName}`);
      const parsedData = this.parseMessage(msg);
      this.onMessage(parsedData, msg);
    },
    parseMessage: options.parseMessage || function (msg: Message): string {
      const data = msg.getData();
      return typeof data === 'string' ? JSON.parse(data) : JSON.parse(data.toString('utf-8'));
    },
    clientOptions: function (): ClientOptions {
      // this.client.clientOptions to set various options as per external library
      return this.client.clientOptions()
        .setOption1(true)
        .setOption2()
        .setAckTimeout(this.ackTimeout)
        .setGroup(this.groupName);
    }
  }
}
```


texts:
I have one of my first PowerShell scripts that will query a list of users in Active Directory. While doing so it will keep a tally in a hashtable that will update for every group increasing it count so that a final total can then be displayed.

This is used so that given a group of users that are performing the same job I can create a role based security group in AD and move all the related groups into it. Thereby reducing the amount of work and thought involved when creating new users and making changes to existing departments.

<#
    Script     : Count Group Memberships
    Created By : Matt Something
    Created    : November 28, 2012
    Modified   : November 28, 2012

    This script will take a list of samaccountnames from active directory and count the membership lists between them. This
    is used to track the similarities between accounts.
#>

param (
    [parameter(ValueFromRemainingArguments=$true)]
    [string[]]$userNamesToCheck = $(throw "Need to supply at least one username")
)

# Functions and Subroutines
Function Get-NamedModule {
    Param([string]$name)
    if(-not(Get-Module -name $name)) {
        if(Get-Module -ListAvailable | Where-Object { $_.name -eq $name }) {
            # Check the list of available module for $name. If present import it.
            Import-Module -Name $name
            $true
        }
        else { $false } # Module not available
    } # End if
    else { $true } # Module already loaded
} # End function

# Variable Declaration
$counts = @{}

# Main
# Import the activedirectory module if its not already.
[void](Get-NamedModule -name "activedirectory")

# Cycle through usernamestocheck and get their group memberships
$userNamesToCheck | ForEach-Object{
    # Get the group memberships from each user.
    $memberships = (Get-AdUser -Filter { SamAccountName -eq $_ } -Properties MemberOf).MemberOf

    # Add the groups to a table for counting
    $memberships | ForEach-Object{
        [void]($_ -match "^CN=(?<membership>.*?),")

        # Continue to build the table
        $singleGroup = $matches.membership

        If($counts.ContainsKey($singleGroup)){
            # This group already exists in the table.
            $counts.Set_Item($singleGroup, [int]($counts.($singleGroup)) + 1)
        } else {
            $counts.Add($singleGroup, 1)
        }
    }
}

Write-Host "$((Measure-Object -InputObject $userNamesToCheck).Count) users checked"
$userNamesToCheck
$counts.GetEnumerator() | Sort-Object -Property Value -Descending


texts: Best accuracy and performance with timers in JS

texts:
Regular timers in JavaScript (setInteval & setTimeout) have two problems:

They aren't as much accuracy as you can get in JS. If you set it like this:

setInterval(fn, 1000);

You can't be sure that it will be called every 1000 ms. It'll be called 1000 + 1-10ms or even more if some heavy tasks were before the tick.

This is normal behaviour. The bad thing about it is that these delays will accumulate.
Throttling when tab is inactive. When you switch tabs for a while, timers that are in a invisible tab will tick at a higher frequency because of CPU saving. It's a reasonable thing, but killer for multiplayer gaming.

Both problems can be solved by webworker and some variables. That's why I've built a class for it and need a review.

My class also provide anti-blocking mechanism. When there was heavy tasks before timer tick and we need to deal with lag - timer will make up all lost ticks but it can be "forever" loop. To prevent this you can set the max ms for "making lost ticks" and after them will be a break for other code/events/etc and back to work.

module.exports = UberTimer = function UberTimer(callback, interval, blockThreadMaxMs) {
  this.callback = callback;
  this.interval = interval;

  this.lastTickTime = -1;

  this.blocking = {};
  this.blocking.maxTime = blockThreadMaxMs;
  this.blocking.startTime = -1;
}

////////////////////////////////////////////////////////////////////////

UberTimer.worker = null;
UberTimer.instances = [];

UberTimer.__startWorker = function() {
  if ( UberTimer.worker ) return;

  var blobURL = URL.createObjectURL( new Blob([ '(', (

    function() {
      setInterval(() => self.postMessage(0), 1);
    }

  ).toString(), ')()' ], { type: 'application/javascript' } ) );

  UberTimer.worker = new Worker(blobURL);
  UberTimer.worker.onmessage = UberTimer.__tick;
}

UberTimer.__stopWorker = function() {
  UberTimer.worker.terminate();
  UberTimer.worker = null;
}

UberTimer.__tick = function(timer) {
  for ( var timer of UberTimer.instances )
    timer.__workerTick();
}

UberTimer.create = function(callback, interval, blockThreadMaxMs=100) {
  var timer = new UberTimer(callback, interval, blockThreadMaxMs);

  UberTimer.instances.push(timer);
  UberTimer.__startWorker();

  return timer;
}

UberTimer.release = function(timer) {
  var i = UberTimer.instances.indexOf(timer)
  if ( i ) UberTimer.instances.splice(i, 1);

  if ( UberTimer.instances.length == 0 )
    UberTimer.__stopWorker();
}

////////////////////////////////////////////////////////////////////////

UberTimer.prototype.__makeCall = function() {
  this.callback();
  this.lastTickTime += this.interval;
}

UberTimer.prototype.__workerTick = function() {
  if ( this.lastTickTime == -1 ) return;

  var now = performance.now();

  if ( this.blocking.startTime == -1 )
    this.blocking.startTime = now;

  var elapsedTime = now - this.lastTickTime;

  if ( elapsedTime >= this.interval ) {
    this.__makeCall();

    var blockingTime = now - this.blocking.startTime;

    if ( blockingTime < this.blocking.maxTime )
      this.__workerTick();
    else
      this.blocking.startTime = -1;
  }
}

UberTimer.prototype.start = function() {
  this.__makeCall();
  this.lastTickTime = performance.now();
}

UberTimer.prototype.stop = function() {
  this.lastTickTime = -1;
}

Usage:

var timer = UberTimer.create(callback, intevalInMs, optional: maxBlockingTime);

timer.start();
timer.stop();

UberTimer.release(timer);


texts:
Working on the 2 element subset sum problem (finding two numbers in a list that sum to a given value), I came up with a relatively short solution code-wise.

The code could fit on a single line but I'm not super familiar with python so is this is a naive way to solve/implement it?

How efficient is creating a set and intersecting it with a list vs using a loop?

l = [10, 7, 11, 3, 5, 11]
k = 22

#create a set of the differences between K and L including duplicate elements that sum to K
diff = {k-x for i, x in enumerate(l) if k != 2*x or x in l[i+1:len(l)]}

#Return true if an element of Diff is in L
print(bool(diff.intersection(l)))


texts: Forced Async operation in a (event like) method

texts:
I have a piece of code that I am not feeling comfortable.

I don't want to block the UI
Read operation works synchronously (reading may broke 50 ms rule)
Save operation supports async (returns Task)
I have to await SaveChanges (so operation could be completed before Dispose)

public Task AddToMyProject(string directory) {
    return Task.Run(async () => {
        if (!Directory.Exists(directory)) return;

        using (var context = _contextFactory.CreateContext()) {
            var existing = context.WatchDirectories.FirstOrDefault(wd => wd.Directory == directory);
            if (existing == null) {
                var childWatchers = context.WatchDirectories.Where(wd => wd.Directory.StartsWith(directory));
                foreach (var watchDirectory in childWatchers) {
                    context.Delete(watchDirectory);
                    RemoveDirectoryWatcher(watchDirectory.Directory);
                }

                context.Insert(new WatchDirectory { Directory = directory });
                await context.SaveChanges()
                    .ContinueWith(t => AddDirectoryWatcher(directory));
            }
        }
    });
}

I just want to know if there is a better approach for this.


texts:
Any one suggest me right way to write mapping more then one table using spring-boot (jpa), i was done it, but its required more time to extract result,

Following are the Mapping of Pojo:

First:-

@Entity
@Table(name="DIM_CORPORATE_AND_SERVICE_ATTRIBUTE_MAPPING")
public class ServiceAttributeMapping {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="N_CORPORATE_SERVICE_MAP_SKEY")
    private long serviceMapSkey;

    @Column(name="V_MAP_WITH")
    private String mapWith;

    @Column(name="F_LINKED_WITH_MAIN_SERVICE")
    private String fLikedWithMainService;

    @Column(name="V_STATUS")
    private String status;

    @Column(name="N_DIM_ATTRIBUTE_OPTION_SKEY")
    private Long attOptionSkey;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "N_DIM_CORPORATE_SKEY", referencedColumnName = "N_DIM_CORPORATE_SKEY")
    private CorporateServicesDetails corporateSericeDetails;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "N_DIM_ATTRIBUTE_SKEY", referencedColumnName = "N_DIM_ATTRIBUTE_SKEY")
    private ServiceAttribute serviceAttribute;
}

Second Mapping :

@Entity
@Table(name="DIM_CORPORATE_SERVICE_ATTRIBUTE")
public class ServiceAttribute {

    @Id
    @Column(name="N_DIM_ATTRIBUTE_SKEY")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long attributeSkey;

    @Column(name="V_ATTRIBUTE_NAME")
    private String attributeName;

    @Column(name="F_FINAL_ELEMENT")
    private String fFinalElement;

    @Column(name="V_STATUS")
    private Integer status;

     @JsonIgnore
     @OneToOne(mappedBy="serviceAttribute")
     private ServiceAttributeMapping AttributeMapping;

     @OneToMany(fetch = FetchType.EAGER,mappedBy="serviceAttribute")
     private Set<ServiceAttributeOptions> serviceAttributeOptions;

     @OneToOne(cascade = CascadeType.ALL)
     @JoinColumn(name = "N_ATTRIBUTE_TYPE_ID", referencedColumnName = "N_ATTRIBUTE_TYPE_ID")
     private AttributeType attributeType;

}

Third Pojo:

@Entity
@Table(name="DIM_CORPORATE_SERVICE_ATTRIBUTE_OPTIONS")
public class ServiceAttributeOptions {

    @Id
    @Column(name="N_DIM_ATTRIBUTE_OPTION_SKEY")
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long optionSkey;

    @Column(name="N_ATTRIBUTE_TYPE_ID")
    private long attributeTypeId;

    @Column(name="V_ATTRIBUTE_OPTION_NAME")
    private String optionName;

    @Column(name="F_FINAL_ELEMENT")
    private String finalElement;

    @Column(name="V_STATUS")
    private String status;

    @ManyToOne(cascade= CascadeType.ALL)
    @JoinColumn(name = "N_DIM_ATTRIBUTE_SKEY")
    private ServiceAttribute serviceAttribute;
}

Query :-

@SuppressWarnings("unchecked")
        List<CorporateServicesDetails> corporateServiceslist = entityManager.createQuery(
                "select r from ServiceAttributeMapping r INNER JOIN r.serviceAttribute i where r.mapWith=:mapWith and r.fLikedWithMainService='Y' and r.status='1' ")
                .setParameter("mapWith", "MAIN").getResultList();
        return corporateServiceslist;

Thanks in advance


texts: Find-and-replace for Excel charts in a PowerPoint document

texts:
The code is run through PowerPoint and must include an Excel reference to work. This will Search through all slides and shapes until it finds a chart, if it's not a Pie chart then it will open up the ActiveWorkbook behind that Chart then it will check the sheet for words in fndList and replace with with words in rplcList.

I would really just like to make this code run faster and smoother, and ask here in case there is a better/faster/more reliable way to do a find and replace for charts in PowerPoint.

Some things I believe could be improved are:

Every Chart has its ActiveWorksheet opened up and activated on the screen, so making this all run in the background would be nice.
I believe Excel.Application DisplayAlerts = False is a great solution to keeping the error We couldn't find anything to replace. Click options for more ways to search. from popping up, but if I'm not mistaken, turning off DisplayAlerts just automatically "clicks" the default value. So the pop-up still happens, and the code is still "pressing ok." So these are two unnecessary things that are happening in the background and consuming memory.
Late binding could be an option here, but I've never done it before and am not very familiar with how to do it correctly so I stayed away. But right now I have to load a reference to excel every time I run the code.

These are only three things that I could think of that could be improved. There might be many more.

Option Explicit

Private Sub findAndReplaceChrt()

'Timer start
Dim StartTime As Double
Dim SecondsElapsed As Double
StartTime = Timer

Dim pptPres As Object
Dim sld As Slide
Dim shpe As Shape
Dim c As Chart

Dim sht As Object
Dim fndList As Variant
Dim rplcList As Variant
Dim listArray As Long

Excel.Application.DisplayAlerts = False
Application.DisplayAlerts = False

fndList = Array("blue", "green")
rplcList = Array("Blue", "Green")

'Make pptPres the ppt active
Set pptPres = PowerPoint.ActivePresentation

'Loop through each sld and check for chart title, grab avgScore values and create pptTable to paste into ppt chart
For Each sld In pptPres.Slides

    'searches through shapes in the slide
    For Each shpe In sld.Shapes

        'Checks if shape is a Charts and has a Chart Title
        If Not shpe.HasChart Then GoTo nxtShpe

        Set c = shpe.Chart

        If Not c.ChartType = xlPie Then

            ActiveWindow.ViewType = ppViewNormal
            c.ChartData.Activate

            'Loop through each item in Array lists
            For listArray = LBound(fndList) To UBound(fndList)

                    Worksheets(1).Cells.Replace What:=fndList(listArray), Replacement:=rplcList(listArray), _
                    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
                    SearchFormat:=False, ReplaceFormat:=False

            Next listArray

            c.ChartData.Workbook.Close

        End If

nxtShpe:
    Next shpe

Next sld

Excel.Application.DisplayAlerts = True
Application.DisplayAlerts = True

'End Timer
SecondsElapsed = Round(Timer - StartTime, 2)
MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", vbInformation

End Sub


texts:
I am using Java and COM4j to communicate with Word. The approach I used here is brute force. I have a password protected .doc, and I forgot its password.

Complexity is (26)(maxPassLength). [a-z characters only]

Before I run this code and wait for 7-10 days here are my concerns.

My main concern is checking whether a generated string matches the password. Is there any alternative to this? Would you recommend threading to reduce the search space?

import com4j.Variant;
import java.util.HashMap;
import javax.swing.JOptionPane;
import word.Documents;
import word.WdOpenFormat;
import word._Application;
import word._Document;

public class DocPasswordFinder {

    public final static String filePath2 = "\\file\\abc.doc";
    private static HashMap<Integer, Character> mapC;
    private static final int passMaxLength;
    public static  _Application app;
    public static Documents doc;
    public static char[] arr;

    static {
    passMaxLength=9;
    arr = new char[passMaxLength];
    app = word.ClassFactory.createApplication();
    doc = app.documents();
    mapC=new HashMap<>();
        for (int i = 0; i < 26; ++i) {
            mapC.put(i, (char) ('a' + i));
        }
    }

    public static void genPass(int start, int indx) {
        if (indx == passMaxLength) {
            String PASSWORD = String.valueOf(arr);
            try {
        doc.open2000(filePath, false, true, false, PASSWORD, "", false,
    PASSWORD, "", WdOpenFormat.wdOpenFormatAuto, false, false);
                JOptionPane.showMessageDialog(null, "FOUND: " + PASSWORD);
                System.exit(0);
            } catch (com4j.ComException ex) {
                //continue;
            }
        } else {
            if (indx < arr.length) {
                for (int i = start; i < 26; ++i) {
                    arr[indx] = mapC.get(i);
                    genPass(start, indx + 1);
                }
            }
        }
    }

    public static void main(String[] args) {
        genPass(0, 0);
    }
}

EDIT
Bottleneck appears to be the doc.open2000() part.


texts: Writing many cells to sheet causes Excel to not respond, replacing vlookups

texts:
I have found that my code causes my Excel to 'not respond' when it gets to this for loop, For thisRow = 2 To lastWSrow(outWS). I'm guessing this is because I am writing cell by cell and the data is too much for excel to handle.

My code essentially does 55 of vlookups on sheet2. It would be similar to doing vlookup(c2&y2,Sheet1!I:J,2,false) but manually it takes long to do.

Could anyone look at this loop and help me optimize this area? I have left only the part needed adjustment. I have put comments on each line to provide description.

outws = sheet2

For thisRow = 2 To lastWSrow(outWS) '2 to last row of sheet2
    For thisCol = 1 To UBound(mappings, 1)

        'create unique key
        thisScen = outWS.Cells(thisRow, posIDcol).Value & "|" & mappings(thisCol, 1)

        'search
        thisDataRow = findInArrCol(thisScen, 1, scenData)

        'write to sheet2
        If thisDataRow = 0 Then
            If outWS.Cells(thisRow, posUnitsCol).Value <> 0 Then 'missing scenario
                outWS.Cells(thisRow, mappings(thisCol, 3)).Value = "No data"
                outWS.Cells(thisRow, mappings(thisCol, 3)).Value = 0

            End If
        Else
            If mappings(thisCol, 1) = "irpv01|PV01_Swap_1M" Then
                outWS.Cells(thisRow, PV01_1MCol).Value = outWS.Cells(thisRow, PV01_1MCol).Value + scenData(thisDataRow, 2) * scenData(thisDataRow, 3) 'since map PV01_0D to PV01_1m already, sum PV01_1M to that column in database.
            Else
                outWS.Cells(thisRow, mappings(thisCol, 3)).Value = scenData(thisDataRow, 2) * scenData(thisDataRow, 3) 'need to scale by position units to get correct risk
            End If
        End If

    Next thisCol
Next thisRow

findInArrCol

Public Function findInArrCol(matchVal As Variant, matchCol As Long, sortedArr() As Variant, Optional nearest As String) As Long

    Dim low As Long, mid As Long, high As Long

    findInArrCol = 0
    low = 1
    high = UBound(sortedArr, 1)
    Do While low <= high
        mid = (low + high) / 2
        If sortedArr(mid, matchCol) = matchVal Then
            findInArrCol = mid
            Exit Function
        ElseIf sortedArr(mid, matchCol) < matchVal Then
            low = mid + 1
        Else
            high = mid - 1
        End If
    Loop

    If findInArrCol = 0 Then
        If nearest = "lessThan" Then
            findInArrCol = WorksheetFunction.Max(high, 1)
        End If
        If nearest = "greaterThan" Then
            findInArrCol = WorksheetFunction.Min(low, UBound(sortedArr, 1))
        End If
    End If

End Function


texts:
I have written the following the code to complete a matrix based on data provided in a second worksheet, but the code is really slow (note that s1=12,000, s2=40 and s3 = 200,000). Any suggestions on how to make this code faster?

Sub UpdateMatrix()

Dim wsOverview As Worksheet, wsData As Worksheet
Dim rngTable As Range
Dim varAccount As Variant, varData As Variant
Dim i As Long, t As Long

Set wsOverview = ThisWorkbook.Worksheets(1)
Set wsData = ThisWorkbook.Worksheets(2)

Set rngTable = wsOverview.Range("A:A")
i = Application.WorksheetFunction.CountA(rngTable) + 1

Set rngTable = wsData.Range("A:A")
t = Application.WorksheetFunction.CountA(rngTable)

For s1 = 2 To i
varAccount = wsOverview.Range("A" & s1).Value

For s2 = 1 To 37
varData = wsOverview.Range("A1").Offset(0, s2).Value

For s3 = 2 To t

    If varAccount = wsData.Range("B" & s3).Value And varData = wsData.Range("A" & s3).Value Then

    wsOverview.Range("A" & s1).Offset(0, s2).Value = wsData.Range("F" & s3).Value

    Exit For

    End If

Next s3

Next s2

Next s1

End Sub


texts: Code for creating combinations taking a long time to finish

texts:
I have the following code that I'm using to create combinations of elements in my dataset:

start_time = time.time()
question_pairs = []
import itertools as iter

for memberid in IncorrectQuestions.memberid.unique():
    combinations = IncorrectQuestions[IncorrectQuestions.memberid == memberid].groupby('memberid').questionid.apply(
        lambda x: list(iter.combinations(x, 2)))
    for elem in combinations:
        for el in elem:
            question_pairs.append(list(el))

print("--- %s seconds ---" % (time.time() - start_time))

the DataFrame IncorrectQuestions has about 40 Million records. Here's the sample dataset:

    memberid    created firstencodedid  questionid
0   9   2016-01-18 05:10:44 MAT.CAL.110 5696d0248e0e0869c96357d3
1   9   2016-01-18 05:10:44 MAT.CAL.110 5696cbc45aa413444ffd9973
2   9   2016-01-18 05:10:44 MAT.CAL.110 5696cf86da2cfe6f21d09879
3   34  2016-11-10 04:24:14 MAT.ARI.300 51d8cd415aa41337ec50425a
4   34  2016-11-10 04:24:14 MAT.ARI.300 559a84505aa4136cb37be676

The piece of code above takes way too long. It has been an hour and it is still running. Is there a way to optimize this piece of code so it takes less time?

The desired output would create all possible combinations of questionid for each memberid. For example, the combinations for memberid = 9 would be:

['5696d0248e0e0869c96357d3','5696cbc45aa413444ffd9973']

['5696d0248e0e0869c96357d3','5696cf86da2cfe6f21d09879']

['5696cbc45aa413444ffd9973','5696cf86da2cfe6f21d09879']

The combinations for memberid = 34 would be:

['51d8cd415aa41337ec50425a','559a84505aa4136cb37be676']

And finally, the combined output would be both the lists combined, i.e.:

['5696d0248e0e0869c96357d3','5696cbc45aa413444ffd9973']

['5696d0248e0e0869c96357d3','5696cf86da2cfe6f21d09879']

['5696cbc45aa413444ffd9973','5696cf86da2cfe6f21d09879']

['51d8cd415aa41337ec50425a','559a84505aa4136cb37be676']

I hope this makes things clearer.

Any pointers would be appreciated.


texts:
I've written a program following the instructions of an exam paper. There are no solutions available so I would appreciate a feedback. I'm concerned with main in particular (I've already posted a similar question here). I've tried to solve the problem as I've seen it's done in other solutions made available by our teacher. Also the constructors made me think a lot.

I was asked to make a program to represent destinations in a square [0,1]x[0,1], a salesman that has to go in some destinations in that square and another salesman inheriting from the former but with slightly different habits.

#include <iostream>
#include <vector>
#include <set>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstdlib>

class Location {
private:
    double x_, y_;
public:
    Location(double x, double y) : x_(x), y_(y) { }
    Location() {
        x_ = drand48();
        y_ = drand48();
    }
    Location(const Location & L) : x_(L.x_), y_(L.y_) { }
    double getx() {return x_; }
    bool operator<(const Location & L) { return x_ < L.x_; }

    double distance(const Location & L) {
        return std::sqrt(std::pow(x_ - L.x_, 2) + std::pow(y_ - L.y_, 2));
    }

};

class Salesman {
private:
    Location start_;
protected:
    std::vector<Location> tobevisited_;
public:
    Salesman(const Location & start, std::vector<Location>::iterator it1, std::vector<Location>::iterator it2) : start_(start), tobevisited_(it1, it2) { }

    int ndest() { return tobevisited_.size(); }

    virtual double visit() {
        double dist = 0;
        sort(tobevisited_.begin(), tobevisited_.end());
        dist = (*(tobevisited_.begin())).distance(start_);
        for(std::vector<Location>::iterator it = tobevisited_.begin()+1; it != tobevisited_.end(); it++) {
            dist += (*(it)).distance(*(it-1));
        }
        return dist;
    }

};

class LazySalesman : public Salesman {
private:
    double d_;
public:
    LazySalesman(double d, std::vector<Location>::iterator it1, std::vector<Location>::iterator it2) : d_(d), Salesman(Location(0,0), it1, it2) { }

    double visit() {
        double dist = 0;
        dist = Salesman::visit();
        dist += d_*ndest();
    }
};

int main() {

    srand48(time(NULL));
    Location start(0., 0.);
    Location start2(1,1);
    int cont = 0;

    for(int i=0; i<3000; i++) {
        std::vector<Location> v;

        for(int j=0; j<10; j++) {
            v.push_back(Location());
        }
        Salesman Willy(start, v.begin(), v.end());
        if(Willy.visit() < 2.) cont++;
    }

    std::cout << "cont = " << cont << std::endl;

    std::vector<Location> loc;
    Location a(0.1, 0.1);
    Location b(0.5, 0.1);
    Location c(0.5, 0.5);
    loc.push_back(a);
    loc.push_back(b);
    loc.push_back(c);

    std::vector<Salesman*> vett;

    vett.push_back(new Salesman(start2, loc.begin(), loc.end()));
    vett.push_back(new LazySalesman(0.1, loc.begin(), loc.end()));
    vett.push_back(new LazySalesman(0.5, loc.begin(), loc.end()));

    for(auto el : vett) {
        std::cout << el->visit() << std::endl;
        delete el;
    }

}


texts: A class and a function to create and light up buttons in PyGame

texts:
This is my first ever try at making reusable code. The function makes use of two images to give the illusion of turning on and turning off a button in pygame.

I would like to know what would you do differently and if I did a good job? Thanks everyone.

Also, this is assuming you already loaded your images and gave it a name using pygame.image.load() function in pygame.

"""
    The function `mouse_on_button() takes all the arguments needed
to produce a light-able button. For example, you have an image
of a thumbs up in grey and another image of a thumbs up in bright red and stack the on top of each other.
They are called by clicking the position of the image. By clicking they dark image will get transformed into the lit up image and vice-versa.

thumbs_up_img = pygame.image.load('thumbsup.png')
thumbs_up_lit_up_img = pygame.image.load('thumbsupred.png')

thumbs_up = Buttons(60, 240, 50, 50) # X, Y, Width, Height

mouse_on_button(pygame, screen, thumbs_up_img, thumbs_up_lit_up_img,thumbs_up.btn_x, thumbs_up.btn_y, thumbs_up.width, thumbs_up.height, SCREEN_HEIGHT, SCREEN_WIDTH)
"""

class Buttons:

    """
    This class takes the x-position and the y-position, width and height of an image.
    """
    def __init__(self, btn_x, btn_y, width, height):

        self.btn_x = btn_x
        self.btn_y = btn_y
        self.width = width
        self.height = height

def mouse_on_button(pygame, screen, off_btn, on_btn, btn_x, btn_y, width, height, SCREEN_HEIGHT, SCREEN_WIDTH):
    """
    This function takes a dark image and a bright image to give the illusion of turning on a button.
    """

    # Get mouse position.
    mouse = pygame.mouse.get_pos()

    # Setting up the boundries to light up or turn off around the button.
    if (mouse[0] >= btn_x and mouse[0] <=  btn_x + width) and (mouse[1] >= btn_y and mouse[1] <= btn_y + height):
        # This will return the ON value of an image in the screen.
        return screen.blit(on_btn,(btn_x, btn_y, SCREEN_HEIGHT, SCREEN_WIDTH))
    else:
        # This will return the OFF value of an image in the screen.
        return screen.blit(off_btn,(btn_x, btn_y, SCREEN_HEIGHT, SCREEN_WIDTH))


texts:
I am querying an API and populating a C# Datatable with the results, then using a Table Value Parameter to populate a SQL Server table with the results.  This is my solution, but it is slow and takes quite some time to process. Is there any optimization that can be done to this syntax to speed up the process? Sorry for the length of code provided, just trying to provide full C# procedure so all transparency is seen.

namespace Test
{
    class Program
    {
        public static string gg;
        public static string ff;
        public static string ee;
        public static string dd;

        static void Main(string[] args)
        {
            DataTable SQLHelperTable = GenerateDataTable();
            var response = syncClient.DownloadString(url);
            var o = JsonConvert.DeserializeObject<PrimaryObject[]>(response);

            foreach (PrimaryObject ro in o)
            {
                if (ro.dataPull != null)
                {
                    foreach (dataPull data in ro.dataPull)
                    {
                        var secondaryData = data.DP.FirstOrDefault();

                        if (secondaryData != null)
                        {
                            gg = secondaryData["gg"];
                            ff = secondaryData["ff"];
                            ee = secondaryData["ee"];
                            dd = secondaryData["dd"];
                        }

                        SQLHelperTable.Rows.Add(ro.Alpha, data.a data.b data.c data.d data.e data.f data.g data.h data.i data.j data.k data.l data.m data.n data.o data.p data.q data.r data.s data.t data.u data.v data.w data.x data.y data.z data.aa data.bb, data.cc, gg,ff,ee,dd);
                    }
                }
            }
        }
        public static DataTable GenerateDataTable()
        {
            DataTable dt = new DataTable();
            \\Generate DataTable
            return dt;
        }
    }
    public class PrimaryObject
    {
        public string Alpha { get; set; }
        public List<dataPull> dataPull { get; set; }
    }
    public class dataPull
    {
        public int a { get; set; }
        //Remaining get set statements
        public List<Dictionary<string, string>> cc { get; set; }
    }
}


texts:
I was trying to solve a question on CodeChef. My code works perfectly fine in my IDE (Visual Studio here) but when I submit my code at CodeChef, it says "Time Limit Exceeded".

What the code does:

Input T number of test cases each with one input N
Let A and B be two numbers chosen randomly from 1,2,3...N
Output the probability that Greatest Common Divisor of A and B equals B for each test case.

int _tmain(int argc, _TCHAR* argv[])
{
    int T;
    cin>>T;
    int tests[1000];
    for(int k=0;k<T;k++) //  Take the test cases as input
        cin>>tests[k];

    for(int i=0;i<T;i++)   // the main loop that runs T times
    {
        int N=tests[i];

        int result=2*N-1;   //  the numerator of the result

        int square=N*N;   //  the denominator of the result

        for(int j=2;j<=(N/2);j++)
        {
            result=result+(N/j)-1;
        }

        for(int w=2;w<=result;w++)  //  Loop to convert fraction into irreducible form
        {
            if(result%w==0 && square%w==0)
            {
                result=result/w;
                square=square/w;
                w--;
            }
        }

        cout<<result<<"/"<<square<<endl;
    }
    return 0;
}

How can I optimize this code of mine so that it compiles within the specified time limit? Any optimization possible whatsoever?


texts:
This is a follow-up of: Rearrange page numbers for printing a book

Input:

Total pages of a book: int
Pages per booklet: int (divisible by 4 evenly)

Processing:

Rearrange the pages in each booklet to follow a specific format, [n, f, f+1, n-1], where n is the last page of the booklet, and f is the first.

Output:

Print a list/tuple of the rearranged integers

Bugs:

If pages is not a multiple of 4 the last booklet (list that get processed by arrange_booklet()) always has errors at the end.

Misc:

int pages will generally be a large number (50~500). I wrote the program because my printer software doesn't allow me to just print the pages in this order. I have to manually type every integer, comma-separated. Which would obviously get tedious very quickly.

from math import ceil

# f is the first page (smallest input integer), n is the last (largest)
def arrange_booklet(f, n):
    '''Creates a list by using the page # order formula.'''
    _ = list()
    while n > f:
        _.extend([n, f, f+1, n-1])
        f += 2
        n -= 2
    return _

def make_book():
    '''Combines all the lists into one and returns the result.'''
    pages = list(range(1, int(input("Enter a number of pages: "))+1))
    while True:
        len_booklet = int(input(
            "Enter booklet length, must be a multiple of four: "))
        if len_booklet % 4 == 0:
            break
    book = list()  # permanent list, to be returned
    _ = list()  # temporary list, to populate permanent list
    for page in pages:
        _.append(page)
        if page % len_booklet == 0:
            _ = arrange_booklet(_[0], _[-1])
            book.extend(_)
            _.clear()
    # the last booklet, if pages % 4 != 0, is still in the temp list and broke
    # out of the loop it has to be handled separately below, or it will never
    # reach the book
    if _:
        _ = arrange_booklet(_[0], _[-1])
        book.extend(_)
    print(book)

if __name__ == '__main__':
    make_book()


texts: Sliding marker on link hover with jQuery

texts:
The following code is for a vertical menu, where I needed a marker to slide down next to a link upon hovering over said link. Therefore I needed to change CSS properties of a HTML element (the top-margin in this case).

What I've done in jQuery is add a class ('.movedown1' or '.movedown2') to the marker div ('#slide') when the mouse hovers over one of the links ('#menulink2' or '#menulink3'), and remove the class when the mouse stops hovering over the link.

It works!...But is it a clean method to add/change CSS properties of a HTML element? Does it follow best practices for jQuery? I've only used jQuery a few times in the past so I'm not familiar with best practices.

Codepen

HTML(Pug):

#slide

#menu
  a.menulink#menulink1(href="#")
    p RED
  a.menulink#menulink2(href="#")
    p BLUE
  a.menulink#menulink3(href="#")
    p GREEN

CSS (Sass)

a
  color: white
  text-decoration: none

#slide
  width: 10px
  height: 30px
  background-color: red
  position: absolute
  border-radius: 15px
  transition: 0.3s ease-in-out

.movedown1
  margin-top: 40px
  background-color: blue !important

.movedown2
  margin-top: 80px
  background-color: green !important

#menu
  margin-left: 30px

.menulink
  height: 40px
  width: 70px
  display: block

.menulink p
  height: 30px
  width: 70px
  margin: 0px
  border-radius: 15px
  display: flex
  align-items: center
  justify-content: center

#menulink1 p
  background: red
#menulink2 p
  background: blue
#menulink3 p
  background: green

jQuery

$('#menulink2').hover(
  function(){
  $('#slide').addClass('movedown1');
  },
  function(){
  $('#slide').removeClass('movedown1')

});

$('#menulink3').hover(
  function(){
  $('#slide').addClass('movedown2');
  },
  function(){
  $('#slide').removeClass('movedown2')

});


texts: Make DFS Implementation faster for 8 puzzle problem in Python

texts:
I am implementing DFS  algorithm for the 8 puzzle problem which works fine if the goal is reached in less than 10 iterations. But for longer number of iterations, my implementation doesn't return the solution. I need to complete the algorithm in less than 80 seconds. How can the algorithm be improved?

import time
import sys

goal_state = [0,1 , 2, 3, 4, 5, 6, 7, 8]
state_dict = {}
def move_up(state):
 new_state = state[:]
 index = new_state.index(0)
 if index not in [0, 1, 2]:
    new_state[index], new_state[index - 3] = new_state[index - 3], new_state[index]
    return new_state
 else:
    return None

def move_down(state):
 new_state = state[:]
 index = new_state.index(0)
 if index not in [6, 7, 8]:
    new_state[index], new_state[index + 3] = new_state[index + 3], new_state[index]
    return new_state
 else:
    return None

def move_left(state):
 new_state = state[:]
 index = new_state.index(0)
 if index not in [0, 3, 6]:
    new_state[index], new_state[index - 1] = new_state[index - 1], new_state[index]
    return new_state
 else:
    return None

def move_right(state):
 new_state = state[:]
 index = new_state.index(0)
 if index not in [2, 5, 8]:
    new_state[index], new_state[index + 1] = new_state[index + 1], new_state[index]
    return new_state
 else:
    return None

def create_node(state, parent, operator, depth, cost):
 return Node(state, parent, operator, depth, cost)

def expand_node(node, nodes):
 expanded_nodes = []
 expanded_nodes.append(create_node(move_up(node.state), node, "Up", node.depth + 1, 0))
 expanded_nodes.append(create_node(move_down(node.state), node, "Down", node.depth + 1, 0))
 expanded_nodes.append(create_node(move_left(node.state), node, "Left", node.depth + 1, 0))
 expanded_nodes.append(create_node(move_right(node.state), node, "Right", node.depth + 1, 0))
 expanded_nodes = [node for node in expanded_nodes if node.state is not None]
 return expanded_nodes

class Node:
  def __init__(self, state, parent, operator, depth, cost):
    self.state = state
    self.parent = parent
    self.operator = operator
    self.depth = depth
    self.cost = cost

def dfs(start,goal):
 # A list (can act as a stack too) for the nodes.
 nodes = []
 visited = []
 depth_limit = 5000
 # Create the queue with the root node in it.
 nodes.append(create_node(start, None, None, 0, 0))
 start_time = time.time()
 while len(nodes) > 0:
    elapsed_time = time.time() - start_time
    if (elapsed_time < 80):
    # We've run out of states, no solution.
        if len(nodes) == 0: return None
    # take the node from the front of the queue
        node = nodes.pop(0)
    #state_str = "".join(str(n) for n in node.state)
        state_str = "".join(str(n) for n in node.state)
        if state_str in state_dict:
            continue
        state_dict[state_str] = True
        visited.append(node)
    # if this node is the goal, return the moves it took to get here.
    # print(node.state)
        print(node.state)
        if node.state == goal:
            moves = []
            temp = node
            print(temp.depth)
            while True:
                moves.insert(0, temp.operator)
                if temp.depth <= 1: break
                temp = temp.parent
            return moves
    # Add all the expansions to the beginning of the stack if we are under the depth limit
        if node.depth < depth_limit:
            expanded_nodes = expand_node(node, nodes)
            if(expanded_nodes not in visited):
                expanded_nodes.extend(nodes)
                nodes = expanded_nodes
    else:
        return None


texts:
For past two days I made my first OpenGL project, I know, It's fixed pipeline, but my focus was on gravity algorithm, so, tell what do you think, and how can I make it faster?

main.cpp

#pragma comment(lib, "glew32.lib")
#include <stdlib.h>
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include "GL/glew.h"
#define GLEW_STATIC
#include <glut.h>
#define WIDTH   800
#define HEIGHT  640
#define AU      (149.6e6 * 1000)
#define SCALE   (250 / AU)
#define G       6.67428e-11

int scale = 10;

struct Vec2 {
    double x;
    double y;
};

using namespace std;

struct Object {
    int id;
    Vec2 pos;
    Vec2 vel;
    double mass;
    double r;
};

Object b = Object{ 0, Vec2{ 2 * AU, 1 * AU, }, Vec2{ 0, 20 * 1000 }, 1.98892 * pow(10, 30), 40 };
Object b2 = Object{ 1, Vec2{ 1 * AU, 1 * AU }, Vec2{ 0, -20 * 1000 }, 1.98892 * pow(10, 30), 40 };
vector<Object> bodies;
int bodyIndex = 0;

void init() {
    glClearColor(0, 0, 0, 1);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, WIDTH, 0, HEIGHT);
    glewInit();

    glPointSize(10);

    bodies.push_back(b);
    bodies.push_back(b2);
    bodyIndex = bodies.size();
}

Vec2 attraction(Object body, Object other) {
    // Compute the distance of the other body
    double dx = other.pos.x - body.pos.x;
    double dy = other.pos.y - body.pos.y;
    double d = sqrt(pow(other.pos.x - body.pos.x, 2) + pow(other.pos.y - body.pos.y, 2));

    // Report an error if the distance is zero; otherwise we'll
    // get a ZeroDivisionError exception further down
    if (d == 0) std::cout << "[ ! ] Collision between objects is not possible;" << std::endl;

    // Compute the force of attraction
    double f = G * body.mass * other.mass / pow(d, 2);

    //Compute the direction of the force
    double theta = atan2(dy, dx);
    return Vec2{ cos(theta) * f, sin(theta) * f };
}

void render() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);

    int timestep = 24 * 3600;
    glBegin(GL_POINTS);
    for (auto b : bodies) {
        Vec2 totalForce{ 0, 0 };
        for (auto other : bodies) {
            if (bodies.at(b.id).id != bodies.at(other.id).id) {
                Vec2 force = attraction(bodies.at(b.id), bodies.at(other.id));
                totalForce.x += force.x;
                totalForce.y += force.y;
            }
        }

        bodies.at(b.id).vel.x += totalForce.x / bodies.at(b.id).mass * timestep;
        bodies.at(b.id).vel.y += totalForce.y / bodies.at(b.id).mass * timestep;
        bodies.at(b.id).pos.x += bodies.at(b.id).vel.x * timestep;
        bodies.at(b.id).pos.y += bodies.at(b.id).vel.y * timestep;

        for (int x = 0; x < WIDTH; x += scale) {
            for (int y = 0; y < HEIGHT; y += scale) {
                float sum = 0;
                for (auto b : bodies) {
                    sum += (b.r / (sqrt(pow(b.pos.x*SCALE - x, 2) + pow(b.pos.y*SCALE - y, 2))*0.001))*0.0001;
                    glColor3f(sum, sum, sum);
                    glVertex2i(x, y);
                }
            }
        }
    }
    glEnd();

    glutSwapBuffers();
}

void OnMouseClick(int button, int state, int x, int y){
    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN){
        Object X = Object{ bodyIndex, Vec2{ x / SCALE, (HEIGHT - y) / SCALE, }, Vec2{ 0, 0 }, 3.302 * pow(10, 13), 40 };
        bodies.push_back(X);
        bodyIndex++;
    }
}

void timer(int) {
    glutPostRedisplay();
    glutTimerFunc(1000 / 60, timer, 0);
}

int main(int argc, char* argv[]) {
    glutInit(&argc, argv);
    glutInitWindowSize(WIDTH-2, HEIGHT);
    glutInitWindowPosition(500, 200);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
    glutCreateWindow("Gravity");

    init();
    glutDisplayFunc(render);
    glutMouseFunc(OnMouseClick);
    glutTimerFunc(50, timer, 50);

    glutMainLoop();
    return 0;
}


texts: Generating HTML code dynamically with jQuery

texts:
I am doing a college project and I would like to write my jQuery code following best practices. The project involves using the jQuery .getJSON method to retrieve information from a json file. I have left out parts of the code so that it is more readable (however this is indicated in the comments).

The code shows two approaches I have come up with:

In the first approach, I define a variable which contains HTML code and inserts this dynamically when making a call to the JSON file. I then do a small amount of DOM manipulation with this.
In the second approach I don't need to define the variable at all. However, there is slightly more jQuery DOM manipulation when retrieving the information from the json file. also I'm not sure if what I have done is a bit 'hacky'.

Do you have any advice on which way would be better practice to do?

Option 1:

$(document).ready(function(){

//define a variable which contains html code that will be inserted dynamically depending on the contents of the json
        var gift_love_template =    '' +
                            '' +
                            '' +
                        '';

        //the following code is inside the call to the JSON file:
        $.each(profile.posts, function(i, post){
            var quantity_love = post.gifts.love;    //number of loves is stored in the gifts array within the post object.

            if(quantity_love != 0){
                var love_title = "" + quantity_love + " loves received"; //create a string for the title attribute
                $("#" + post_id + " .gift-area").append(gift_love_template);
                $("#" + post_id + " .love-gift").attr("title", love_title).append("(" + quantity_love + ")");
            }

        });
});

Option 2:

$(document).ready(function(){

    //the following code is inside the call to the JSON file:

        $.each(profile.posts, function(i, post){
            var quantity_love = post.gifts.love;    //number of loves is stored in the gifts array within the post object.

            if(quantity_love != 0){
                var love_title = "" + quantity_love + " loves received"; //create a string for the title attribute
                $('(' + quantity_love + ')').attr("class", "gift").attr("title", love_title).appendTo("#" + post_id + " .gift-area");
            }

        });
});


texts: Find the lowest and second lowest values in an array of numbers

texts:
Trying to find way to do this with only one pass through the array, so I won't run a sort on it and take arr[0..1]. Not sure how to make it look better:

def LowestSecondLowest(arr)
  lowest,second_lowest = nil,nil

  arr.each do |n|

    if second_lowest.nil?
      second_lowest=n
    elsif lowest.nil?
      if n>second_lowest
        lowest=second_lowest
        second_lowest=n
      elsif n<second_lowest
        lowest=n
      end
    elsif n<lowest
      second_lowest=lowest
      lowest=n
    elsif n>lowest && n<second_lowest
      second_lowest=n
    end
  end

  "#{lowest} #{second_lowest}"
end


texts: Calculate sum of multiple series within array

texts:
The exercise is as follows:

Player A will write list \$ a \$ consisting of \$ n \$ numbers. Player B will take a look at the paper. After that the A player will ask player B \$q\$ questions. Each question will be of the following form:
If I give you two \$ R \$ and \$ L \$ in \$ a \$ such that (\$ 1<=L<=R<=n\$ ), calculate the following value:
$$ 1*a[L] + 2*a[L+1] + 4*a[L+2] + ... + 2^{R-L-1}*a[R-1]+2^{R-L}*a[R] $$
Because the numbers can be really large, we need to find the residue that the result will give when divided by \$ 10^9 + 7\$.
Input is as follows:

n q
a1 a2 an
L1 R1
L2 R2
Lq Rq

The output is: on one line the result for one query.

The problem:
I need to improve performance so it is finished within 1 second. I think the problem may be because I have 2 for loops. Because the number of numbers can be up to 200,000 as well as the pairs. This means that in the worst case it has to go through the process 40,000,000,000 times.
Can someone please tell me how to improve the performance?
#include <iostream>

using namespace std;

const int MAXN = 200000;

int residues[MAXN];
int numbers[MAXN];
int pairs[MAXN][2];

void findResidues(int i)
{
    residues[i] = (residues[i - 1] * 2) % 1000000007;
}

long long int sumBetween(int first, int second)
{
    long long int sum = 0;
    int pos = first;
    while(pos <= second)
    {
        sum += (long long)residues[pos - first] * numbers[pos];
        sum %= 1000000007;
        pos++;
    }
    return sum;
}

int main()
{
    residues[0] = 1;
    int n, q ;
    cin >> n >> q;
    for(int i = 0; i < n; i++)
    {
        cin >> numbers[i];
        findResidues(i + 1);
    }
    for(int i = 0; i < q; i++)
    {
        cin >> pairs[i][0] >> pairs[i][1];
        cout << sumBetween(pairs[i][0] - 1, pairs[i][1] - 1) << endl;
    }
    return 0;
}


texts:
I did not find a single working implementation of using an Executor Service with a Blocking Queue. So , I have come with with a working sample. Thoughts?

import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

class Producer implements Runnable {

    protected BlockingQueue queue = null;

    public Producer(BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {

            for (int i = 0; i < 10000; i++) {
                queue.put(i);
                // System.out.println("Producer ID "+Thread.currentThread().getId()+" is adding task : "+i);
            }
            // poison pill
            // System.out.println("Poison number added! "+Thread.currentThread().getId());
            queue.put(-1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Consumer implements Runnable {

    protected BlockingQueue queue = null;
    ConcurrentHashMap<Integer, Integer> hashmap;

    public Consumer(BlockingQueue queue,
            ConcurrentHashMap<Integer, Integer> hashmap) {
        this.queue = queue;
        this.hashmap = hashmap;
    }

    public void run() {
        try {

            while (ExecutorTest.isRunning) {
                Integer i = (Integer) queue.take();
                System.out.println("Consumer " + Thread.currentThread().getId()
                        + ": taking Task : " + i);
                if (i == -1) {
                    queue.put(i);
                    ExecutorTest.isRunning = false;
                    // System.out.println("Setting isRunning to false :  "+Thread.currentThread().getId());
                    break;
                }
                hashmap.put(i, i);
            }

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

public class ExecutorTest {

    static BlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>();
    static ConcurrentHashMap<Integer, Integer> hashmap = new ConcurrentHashMap<Integer, Integer>();
    static volatile boolean isRunning = true;

    public static void main(String[] args) {
        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue, hashmap);

        new Thread(producer).start();
        ExecutorService executorService = Executors.newFixedThreadPool(4);

        executorService.execute(consumer);
        executorService.execute(consumer);
        executorService.execute(consumer);
        executorService.execute(consumer);

        // wait for the threads to finish
        while (isRunning) {
        };

        executorService.shutdown();
        System.out.println("SHUT DOWN THREAD POOL");

        try {
            executorService.awaitTermination(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("HASHMAP SIZE : " + hashmap.size());
    }

    public static void printHashMap() {
        for (Map.Entry<Integer, Integer> map : hashmap.entrySet()) {
            System.out.println("Entry " + map.getKey() + ":" + map.getValue());
        }
    }

}


texts: Time limit of a c program while calculating factorial of numbers in c

texts:
I am solving a problem on calculation of factorial and the challenge is as follows!

You are asked to calculate factorials of some small positive integers.

Input

An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines,
each containing a single integer n, 1<=n<=100.

Output

For each integer n given at input, display a line with the value of n!

My Code is giving me the correct solution but Time limit is exceeded which is 2 seconds:

The code is as follows:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void factorial(int N)
{
    printf("\n\n");
    int q,i,j,t,d,z;
    float p=0.0;
    for(i=2;i<=N;i++)
    p=p+log10(i);
    d=(int)p+1;//No of terms in the factorial
    int *b;
    //initialization of an array
    b=(int *)malloc(d*sizeof(int));
    b[0]=1;
    for(i=1;i<d;i++)
    b[i]=0;
    //calculation of factorial
    p=0.0;
    for(j=2;j<=N;j++)
    {
        q=0;
        p=p+log10(j);
        z=(int)p+1;
        for(i=0;i<N;i++)
        {
           t=(b[i]*j)+q;
           q=t/10;
           b[i]=t%10;
        }
    }
    for(i=d-1;i>=0;i--)
    printf("%d",b[i]);

}
int main()
{
    int n,i,j;
    scanf("%d",&n);
    int *b;
    b=(int *)malloc(n*sizeof(int));
    for(i=0;i<n;i++)
    {
        scanf("%d",&b[i]);
    }
    for(i=0;i<n;i++)
    factorial(b[i]);
    return 0;
}

How can i make my program more efficient and produce the output in the given time limit? This challenge is from HackerEarth


texts: Wrapping an asynchronous generator in Python

texts:
Since Python 3.6 and PEP 525 one can use asynchronous generator:

import asyncio

async def asyncgen():
    yield 1
    yield 2

async def main():
    async for i in asyncgen():
        print(i)

asyncio.run(main())

I created a function which is able to wrap any asynchronous generator, the same way you would wrap a basic function using @decorator.

def asyncgen_wrapper(generator):

    async def wrapped(*args, **kwargs):
        print("The wrapped asynchronous generator is iterated")

        gen = generator(*args, **kwargs)

        try:
            value = await gen.__anext__()
        except StopAsyncIteration:
            return

        while True:
            to_send = yield value

            try:
                value = await gen.asend(to_send)
            except StopAsyncIteration:
                return

    return wrapped

Wrapping an asynchronous generator seems quite complicated compared to wrapping a basic generator:

def gen_wrapper(generator):
    def wrapped(*args, **kwargs):
        return (yield from generator(*args, **kwargs))
    return wrapped

I mainly concerned about correctness of my wrapper. I want the wrapper to be as transparent as possible regarding the wrapped generator. Which leads me to have two questions:

Is there a more straightforward way to implement a decorator for asynchronous generators?
Does my implementation handle all possible edge cases (think to asend() for example)?


texts:
I wrote this small test, i would love to know if it's possible to achieve the same result in a more "efficient" way, before any moderator closes this question, it's not subjective because my defention of efficient here means less lines of code, and less memory usage.

Here is a Demo :
http://jsfiddle.net/YsjLp/

and here is the JS code :

var position = 0;
var divToEdit = document.getElementById('here');

function executeIt(){
    setInterval(function(){moveIt()},300);
}

function moveIt(){
    var textToInsert = '';
    var textLength = 10;

    for (var i = 0; i <= textLength; i++) {

        if(i == position){
            textToInsert += '[-]';
        }else{
            textToInsert += '-';
        }
    };

    if(position == textLength){
        position = 0;
    }else{
        position += 1;
    }

    divToEdit.innerHTML = textToInsert;
}

executeIt();


texts:
Is there a better way to implement a binary search than I am in my code? My function is taking two two lists - first_booth_voters and second_booth_voters with second_booth_voters being sorted and first_booth_voters not sorted. I feel like I am making an unnecessary amount of comparisons.

from classes import VoterList

def fraud_detect_bin(first_booth_voters, second_booth_voters):
    fraud = VoterList()
    comparisons = 0

    for i in range(0, len(second_booth_voters)):
        item = second_booth_voters[i]
        first = 0
        last = len(second_booth_voters) - 1

        while first <= last:
            midpoint = (first + last) // 2

            if first_booth_voters[midpoint] == item:
            comparisons += 1
            fraud.append(first_booth_voters[midpoint])
            break
        else:
            if item < first_booth_voters[midpoint]:
                last = midpoint - 1
                comparisons += 2
            else:
                first = midpoint + 1
                comparisons += 2

    return fraud, comparisons


texts: What constructor implementaton follows best practice in Java

texts:
I am looking for best practices as they apply to constructor usage in common Java class construction.

Example 1

import javax.swing.*;
import java.awt.*;

public class Painter extends JPanel{

  public Painter(){
     buildGUI();
  }

  private void buildGUI(){
    JFrame frame = new JFrame();
    frame.setLayout(new BorderLayout());
    frame.setTitle("Paint drawing demonstration");
    new Center_frame(frame);

    JPanel headerPanel = new JPanel();
    headerPanel.add(new JLabel("The drawing panel is below"));

    Drawing_panel dp = new Drawing_panel();

    frame.add(BorderLayout.NORTH,headerPanel);
    frame.add(BorderLayout.SOUTH,dp);

    frame.pack();
    frame.setVisible(true);
  }

  public static void main(String args[]){
      new Painter();
  }

}//end class Painter

Example2

import javax.swing.*;
import java.awt.*;

public class Painter extends JPanel{

  public Painter(){
       JFrame frame = new JFrame();
       frame.setLayout(new BorderLayout());
       frame.setTitle("Paint drawing demonstration");
       new Center_frame(frame);

       JPanel headerPanel = new JPanel();
       headerPanel.add(new JLabel("The drawing panel is below"));

       Drawing_panel dp = new Drawing_panel();

       frame.add(BorderLayout.NORTH,headerPanel);
       frame.add(BorderLayout.SOUTH,dp);

       frame.pack();
       frame.setVisible(true);
  }

public static void main(String args[]){
    //create a Painter object
    new Painter();
}

}//end class Painter


texts: "What is the maximum that Player 1 can win?"

texts:
This is a question that I encountered in one of the competitive coding tests. The question goes as follows:

  A 2-player game is being played. There is a single pile of stones. Every stone has an amount (positive) written on top of it. At every turn, a player can take the top 1 or 2 or 3 stones and add to his kitty. Both players want to maximize their winnings. Assuming both players play the game optimally and Player 1 starts the game, what is the maximum amount that Player 1 can win?

I have devised the following recursive approach:

class Main {
  public static void main(String[] args) {
    int a[] = {1,2,3,7,4,8,1,8,1,9,10,2,5,2,3};
    int sum = 0;
    for (int i=0;i<a.length; i++) {
      sum += a[i];
    }
    System.out.println(maxPlayer1(a, 0, sum, 0, a.length));
  }
  public static int maxPlayer1(int[] a, int currSum, int sum, int start, int len) {
    if (len-start <=3) {
      int val = 0;
      for (int i=start; i<len; i++) {
        val += a[i];
      }
      return val;
    }

    int v1 = a[start] + (sum - currSum - a[start]) -
    maxPlayer1(a, currSum + a[start], sum, start + 1, a.length);

    int v2 = a[start] + a[start+1] + (sum - currSum - a[start] - a[start+1]) -
    maxPlayer1(a, currSum + a[start] + a[start+1], sum, start + 2, a.length);

    int v3 = a[start] + a[start+1] + a[start+2] + (sum - currSum - a[start] - a[start+1] - a[start+2]) -
    maxPlayer1(a, currSum + a[start] + a[start+1] + a[start+2], sum, start + 3, a.length);

    return Math.max(v1, Math.max(v2, v3));
  }
}

I have checked my solution on a few inputs. Is my algorithm correct?


texts: Object Oriented Graph Hierarchy with Depth First Search

texts:
I would like to receive review on my code. It has only depth first search (DFS) and bidirected graph  is the only member of the hierarchy. I added name member for the BiGraph to make it easier to debug in the future, because there might be several BiGraph instances. Also, I would like the review to primarily focus on names of the functions'. I couldn't come with better names. The last thing is performing DFS. I think there are too many indirections, so, could you please suggest some relaxations? Any other suggestions are appreciated.

The call to make DFS is achieved through calling areConnected which calls implementation. Implementation resets the history of the last DFS, and then calls traverse which actually performs DFS and fills the isvVisited bool array, which indicates all vertices which were visited.

Graph.h

#pragma once
#include <vector>

class Graph
{
public:
    Graph()=default;

    void addAdjacent(int fvertex, int svertex) { addAdjacentImpl(fvertex, svertex); }
    const std::vector<bool>&  areConnected(int sourcevertex) { return areConnectedImpl(sourcevertex); }
    void print() { printImpl(); }
    virtual ~Graph()=default;

private:
    virtual void printImpl() const = 0;
    virtual void addAdjacentImpl(int fvertex, int svertex) = 0;
    virtual const std::vector<bool>& areConnectedImpl(int sourcevertex) = 0;
    virtual void traverse(int sourcevertex) = 0;
};

BiGraph.h

#pragma once
#include "graph.h"
#include <vector>
#include <string>

class BiGraph :public Graph
{
    std::vector<std::vector<int> > graph;
    int maxVertexCount;
    std::string name;
    std::vector<bool> isVisited;
public:
    BiGraph(int maxVertexCount_, std::string name_);

    ~BiGraph();
private:
    virtual void printImpl() const override;
    virtual void addAdjacentImpl(int fVertex, int sVertex) override;
    virtual const std::vector<bool>& areConnectedImpl(int sourcevertex) override;
    virtual void traverse(int sourceVertex) override;
};

BiGraph.cpp

#include "BiGraph.h"
#include <exception>
#include <iostream>

void ZeroBoolArray(std::vector<bool>& arr)
{
    for (auto &x : arr)
    {
        x = false;
    }
}

BiGraph::BiGraph(int maxvertexcount_, std::string name_):graph(maxvertexcount_), maxVertexCount(maxvertexcount_), name(name_), isVisited(maxVertexCount)
{

}

void BiGraph::addAdjacentImpl(int fVertex, int sVertex)
{
    if (fVertex > maxVertexCount)
    {
        throw std::out_of_range(name + ": trying to add vertex which doesn't exist");
    }
    graph[fVertex].push_back(sVertex);
    graph[sVertex].push_back(fVertex);
}

void BiGraph::traverse(int sourceVertex)
{
    if (isVisited[sourceVertex])
        return;
    isVisited[sourceVertex] = true;
    for (auto& x:graph[sourceVertex])
    {
        traverse(x);
    }
}

const std::vector<bool>& BiGraph::areConnectedImpl(int sourceVertex)
{
    ZeroBoolArray(isVisited);
    traverse(sourceVertex);
    return isVisited;
}

BiGraph::~BiGraph()
{

}

void BiGraph::printImpl() const
{
    for (size_t i = 0; i < graph.size(); i++)
    {
        std::cout << i << ": ";
        for (size_t j = 0; j < graph[i].size(); j++)
        {
            std::cout << j << ' ';
        }
        std::cout << std::endl;
    }
}

GraphFactory.h

#pragma once
#include "graph.h"
#include <memory>
#include <string>

class GraphFactory
{
public:
    GraphFactory()=default;

    std::unique_ptr<Graph> getBiGraph(int size, std::string name);

    ~GraphFactory()=default;
};

GraphFactory.cpp

#include "GraphFactory.h"
#include "BiGraph.h"

std::unique_ptr<Graph> GraphFactory::getBiGraph(int size, std::string name)
{
    return std::make_unique<BiGraph>(size, name);
}


texts: Avoiding RequireJS circular dependencies

texts:
My app module bootstraps a Backbone.js application.
I need app to be available in every other view for easy access to router, triggering navigation, etc.

I never ported an app to RequireJS before, and I got stuck on circular dependency problem, and this answer isn't quite clear to me, so I'm not sure if I applied the solution correctly.

I'm using AMD sugar style throughout the app, so here's what I came up with:

app.js

define(function (require, exports) {

  'use strict';

  var _ = require('underscore'),
      Backbone = require('backbone'),
      Router = require('Router'),
      AppView = require('common/views/app_view'),

  // ...

  return _.extend(exports, {
    start: function () {
      this.router = new Router();
      Backbone.history.start();

      this.appView = new AppView();
      this.appView.render();
    },

    // ...
  });

});

Extending exports instead of directly returning an object allows me to do app = require('app') in any view of the app without worrying about circular dependencies.

All other modules in the app return value normally (i.e. I'm not using exports anywhere else).

Is this an OK strategy for a Require.js Backbone app?
Are there better solutions (that will also work with optimizer or Almond)?

An example of how I'm using app in a (rather deeply nested) view:

zine_item_view.js

define(function (require) {

  'use strict';

  var View = require('common/views/view'),
      Misc = require('common/helpers/misc'),
      app = require('app');

  var ZineItemView = View.extend({
    template: 'templates/social/items/zine_item.html',

    events: {
      'click': 'showZine'
    },

    showZine: function (e) {
      if (!Misc.shouldHandleClick(e)) {
        return;
      }

      app.presenter.showZine({
        zine: this.model,
        route: app.router.routeToZineTrending(this.model.id)
      });
    }
  });

  return ZineItemView;

});


texts:
I develop a small game using C# and need A* in it. For that, I need a PriorityQueue, which .NET does not have. I wanted to make my own one for practice. Here is it, please comment on performance and usability:

public class PriorityQueue<T> : IEnumerable
{
    List<T> items;
    List<int> priorities;

    public PriorityQueue()
    {
        items = new List<T>();
        priorities = new List<int>();
    }

    public IEnumerator GetEnumerator() { return items.GetEnumerator(); }
    public int Count { get { return items.Count; } }

    /// <returns>Index of new element</returns>
    public int Enqueue(T item, int priority)
    {
        for (int i = 0; i < priorities.Count; i++) //go through all elements...
        {
            if (priorities[i] > priority) //...as long as they have a lower priority.    low priority = low index
            {
                items.Insert(i, item);
                priorities.Insert(i, priority);
                return i;
            }
        }

        items.Add(item);
        priorities.Add(priority);
        return items.Count - 1;
    }

    public T Dequeue()
    {
        T item = items[0];
        priorities.RemoveAt(0);
        items.RemoveAt(0);
        return item;
    }

    public T Peek()
    {
        return items[0];
    }

    public int PeekPriority()
    {
        return priorities[0];
    }
}

I tested it with...

        PriorityQueue<String> pQ = new PriorityQueue<string>();

        for (int i = 0; i < 100; i++)
        {
            int prio = Provider.Rnd.Next(0, 1000);
            pQ.Enqueue(prio.ToString(), prio);
            if (pQ.Count > 0 && Provider.Rnd.Next(0, 2) == 0) pQ.Dequeue();
        }

        while (pQ.Count > 0)
        {
            Console.WriteLine(pQ.Dequeue());
        }


texts:
I want move a  Vertical line segment across a plane or another way sweep the plane, from Left to right.

The figure illustrates how the segment is moving at the X-axis. When x1 >= X beginning and i translate it to the upper part and so on, till y2 which is the upper part of the segment reaches Y. You can think of it as how a scanner works.

Line = (x1,y1,x2,y2)

When x1 pr x2 coordinates becomes greater or equal to -rightBorder I increase y1 and y2 to the next level and so on till y2 becomes greater than Y.

Algorithm:

  #define STEP 9
  #define Y 20
  #define X 30
    void moveLine(int, int, int, int);
    int main()
    {
            moveLine(5, 0, 5, 10);
            return 0;

    }

    void moveLine(int x1, int y1, int x2, int y2)
    {
        //Reaches upper border (Y-axis)
        if (y1 >= Y)
        {
            return;
        }
       // cout << y1 <<"   "<< y2 << endl;
       // Increase y1 and y2 and Return to the beginning
        if (x1 >= X)
        {
           //startint points
            y1 += 10;
            y2 += 10;
            // Reinitialize x1 and x2
            x1 = -4;
            x2 = -4;
        }
        // sweep again
        moveLine(x1 + STEP, y1, x2  + STEP,y2);

    }

Explanation:

I start with x1 = 5, and x2 = 5, y1 = 5 and y2 = 10 then x1+=9, x2+=9 till x1 >= X, then I reinitialize the x1 and x2, and increase y1 by 5 and y2 + 5 till y2 becomes greater than Y.

I wrote the piece of Code. it worked ok, but I wanted to your advice and if the recursion function is okay.

Thank you.


texts:
I'm trying to improve on my basic C++ skills and create really nice, concise and clean code that is free from artifacts.

The program can add and subtract radius values from each circle, assign one circle to another and furthermore give the area.

Any tips on how this program can be improved, whether considering readability issue or anything else would be great.

//  Basic circle exercise 23rd March

#include <cstdio>
#include <math.h>

using namespace std;

//==============================================================================
/*                               interface                                    */
//==============================================================================
namespace corey
{
    class Circle
    {
    public:
        Circle(const int & r = 1.0);
        ~Circle();

        const double & getRadius() const;
        const double getArea() const;

        Circle & operator = (const Circle &);
    private:
        double radius;
    };
};

//==============================================================================
/*                              implementation                                */
//==============================================================================
/*I'd probably included using namespace corey if
    i'd have bothered with seperate files*/

corey::Circle::Circle(const int & r) : radius(r){}

corey::Circle::~Circle(){}

const double & corey::Circle::getRadius() const
{
    return radius;
}

const double corey::Circle::getArea() const
{
    const double area = (M_PI * radius * radius);
    return area;
}

corey::Circle operator + ( const corey::Circle & lhs, const corey::Circle & rhs)
{
    return corey::Circle(lhs.getRadius() + rhs.getRadius());
}

corey::Circle operator - ( const corey::Circle & lhs, const corey::Circle & rhs)
{
    return corey::Circle(lhs.getRadius() - rhs.getRadius());
}

corey::Circle & corey::Circle::operator = (const Circle & lhs)
{
    if(&lhs != this)
    {
        radius = lhs.radius;
    }
    return (*this);
}

//==============================================================================
/*                                   useage                                   */
//==============================================================================
int main( int argc, char ** argv )
{
    //this stuff is just some info printed out so not super important...
    corey::Circle c1(2);
    printf("Circle made with radius %lf & area %lf\n", c1.getRadius(), c1.getArea());

    const corey::Circle c2(6);
    printf("Circle made with radius %lf & area %lf\n", c2.getRadius(), c2.getArea());

    corey::Circle c3;
    c3 = c2 + c1;
    printf("Circle made with radius %lf & area %lf\n", c3.getRadius(), c3.getArea());

    c1 = c3;
    printf("Circle made with radius %lf & area %lf\n", c1.getRadius(), c1.getArea());

    return 0;
}


texts: mapping & loops - counting up or counting down

texts:
I am building a time tracking application and my requirement says that any hours past 40 total should be counted as overtime and not regular hours.

Which function is more clear? What can be done to clarify the function? Even the second one at ~ 10 lines seems wordy

Option #1

function calculateOvertime(days) {
    var totalHours = 0;
    var over40 = false;
    return $.map(days, function(hours) {
        var ot = 0;
        totalHours += hours;
        if (totalHours > 40 && !over40) {
            ot = totalHours - 40;
            hours = hours - ot;
            over40 = true;
        } else if (over40) {
            ot = hours;
            hours = 0;
        }
        return { reg: hours, ot: ot};
    })
}
calculateOvertime([16,16,16,16]);

Option #2

function calculateOvertime(days) {
    var hoursUntilOT = 40;
    return $.map(days, function(hours) {
        var ot = 0;
        hoursUntilOT -= hours;
        if (hoursUntilOT < 0) {
            ot = hoursUntilOT * -1;
            hours = hours - ot;
            hoursUntilOT = 0;
        }
        return { reg: hours, ot: ot};
    })
}
calculateOvertime([16,16,16,16]);


texts: Find items in a table that match a set of conditions in another table

texts:
I have two tables. Table 1 has sets of EXPORT conditions: e.g., SET 1 has FOOD, GARMENT, and TECHNOLOGY, and SET 2 contains GARMENT and TECHNOLOGY.

TABLE 1
SETID       EXPORT
-----------------------
1           FOOD
1           GARMENT
1           TECHNOLOGY
-----------------------
2           GARMENT
2           TECHNOLOGY
-----------------------
3           GARMENT
3           FOOD
-----------------------
4           TECHNOLOGY
(more sets of conditions) ...

Table 2 has a list of countries with different types of exports.

TABLE 2
COUNTRY     EXPORT
-----------------------
GERMANY     AUTO
GERMANY     TECHNOLOGY
-----------------------
ITALY       FOOD
ITALY       GARMENT
-----------------------
CHINA       FOOD
CHINA       GARMENT
CHINA       TECHNOLOGY
CHINA       STEEL
-----------------------
FRANCE      FOOD
FRANCE      GARMENT
-----------------------
(more countries)...

I would like to find countries that satisfy each set of the conditions. A country satisfies a set of conditions if it meets all the conditions in a set (even if it may meet additional conditions) -- For example, CHINA satisfies SET 1 even though it also meets the additional condition STEEL.

The expected output is something like:

SET          Country
--------------------------
1            CHINA
2            CHINA
3            ITALY
3            CHINA
3            FRANCE
4            GERMANY
4            CHINA
...

Here's the query I have. It does the job, but I wonder if there is a way to make it perform better. Currently, when Table 1 has 5000 rows (approx. 600 sets of conditions), and Table 2 has 6 million rows, it takes 15 minutes to get the output.

WITH TEMP AS (  SELECT   SETID, COUNTRY, COUNT(*) AS TOTALCOUNT
                  FROM   #TABLE1 AS T1
                  JOIN   #TABLE2 AS T2 ON T2.EXPORT = T1.EXPORT
              GROUP BY   SETID, COUNTRY
              )
      SELECT  TEMP.SETID, COUNTRY
        FROM  TEMP
        JOIN  (  SELECT  COUNT(*) AS TOTALCOUNT, SETID
                   FROM  #TABLE1
               GROUP BY  SETID
              ) AS TEMP2 ON  TEMP.TOTALCOUNT = TEMP2.TOTALCOUNT AND TEMP.SETID = TEMP2.SETID
    ORDER BY  TEMP.SETID

Code for generating sample tables:

CREATE TABLE #TABLE1 (SETID INT, EXPORT NVARCHAR(MAX))
INSERT INTO #TABLE1(SETID, EXPORT)
VALUES (1, 'FOOD'), (1, 'GARMENT'), (1, 'TECHNOLOGY'), (2, 'GARMENT'),
       (2, 'TECHNOLOGY'), (3, 'GARMENT'), (3, 'FOOD'), (4, 'TECHNOLOGY');

CREATE TABLE #TABLE2 (COUNTRY NVARCHAR(MAX), EXPORT NVARCHAR(MAX))
INSERT INTO #TABLE2(COUNTRY, EXPORT)
VALUES ('GERMANY', 'AUTO'), ('GERMANY', 'TECHNOLOGY'), ('ITALY', 'FOOD'),
       ('ITALY', 'GARMENT'), ('CHINA', 'FOOD'), ('CHINA', 'GARMENT'),
       ('CHINA', 'TECHNOLOGY'), ('CHINA', 'STEEL'), ('FRANCE', 'FOOD'),
       ('FRANCE', 'GARMENT');


texts: Stack challenge - improving memory consumption

texts:
I am working on this problem:

  Stacks

  Imagine, that you are employed by a software development company. You
  work now on the famous "D++ project", which is devoted to the creation
  of a new generation programming language. Your particular task is
  quite prosaic, though. You are to develop the memory manager being
  able to work with a large number of stacks.

  Input

  The first line of the input contains the total number of stack
  operations \$N\$, \$0 < N ≤ 100000\$. Each of the next \$N\$ lines contains a
  description of a stack operation, either in the form PUSH A B (meaning
  to push B into stack A), or in the form POP A (meaning to pop an
  element from stack A), where A is the number of stack (\$1 ≤ A ≤ 1000\$),
  and B is an integer (\$0 ≤ B ≤ 10^9\$). You may assume, that every
  operation is correct (i.e., before each POP operation, the respective
  stack is not empty).

  Output

  For each POP operation, described in the input, output the value,
  which this POP operation gets from the top of that stack, to which it
  is applied. Numbers should appear according to the order of the POP
  operations in the input. Each number should be output in a separate
  line.

I have developed a solution here:

#include<map>

class MyStack
{
    public:

      int data;
      MyStack *link;
      MyStack *top;

      MyStack()
      {
          link = NULL;
          top = NULL;
      }

      void push( int data )
      {
           MyStack * tmp = (MyStack *) malloc( sizeof( MyStack ) );
           tmp->data = data;
           tmp->link = top;
           top = tmp;
      }

      void pop()
      {
          MyStack *tmp = top;
          top = top->link;
          printf( "%d\n", tmp->data );
          free( tmp );
      }

      void clear()
      {
          while( top != NULL )
          {
              MyStack *tmp = top;
              top = top->link;
              free( tmp );
          }
      }

      bool isEmpty()
      {
           return top == NULL;
      }
};

int main()
{
    static MyStack* stackPtrs[1001];

    int noOfInstructions = 0;
    scanf( "%d", &noOfInstructions );

    char instruction[3];
    short stackNumber = 0;
    int stackValue = 0;
    for( int inx = 0; inx < noOfInstructions; ++inx )
    {
        scanf("%s", &instruction );

        scanf( "%hd", &stackNumber );

        if( instruction[1] == 'U' )
        {
            scanf( "%d", &stackValue );

            if( stackPtrs[stackNumber] == NULL )
            {
                MyStack *myStack = new MyStack();
                myStack->push( stackValue );
                stackPtrs[stackNumber] = myStack;
            }
            else
            {
                stackPtrs[stackNumber]->push( stackValue );
            }
        }
        else
        {
            stackPtrs[stackNumber]->pop();
            if( stackPtrs[stackNumber]->top == NULL )
            {
                stackPtrs[stackNumber] = NULL;
            }
        }
    }

    for( int inx =0; inx < 1001; ++inx )
    {
         if( stackPtrs[inx] != NULL )
         {
             stackPtrs[inx]->clear();
             stackPtrs[inx] = NULL;
         }
    }
    // Clear memory allocated here!.

    return 0;
}

The memory limit for this question is around 0.75MB = 750KB. My program, out of 20-30 runs on an average is taking around 800KB, with 770KB being the least time.

Please suggest any improvements to this program.


texts: Simple javascript code to create an image caption

texts:
I'm trying to become better at javascript and have written a simple script that just creates some html from getting some details from some elements (e.g. the image alt text) and inserts it onto the page to create a caption. Hover over the top right of the image to see this caption.

I was able to successfully achieve what I wanted through my code. However, my javascript feels a bit 'wet', and I'd like to be able to improve this for brevity and clarity.

Can anyone recommend any improvements to my javascript, and make it either more concise or clear?

I know that jQuery can achieve this in fewer lines of code, but I'm less of a fan of jQuery and believe that ES6/ES7 etc can often write more concise code.

Thanks for any help here. Find a working demo below:

Codepen: https://codepen.io/anon/pen/PrwzBj

/* --- Wide Image Caption --- */
// Define Elements:
const wideImg = document.querySelector('.full-width-image-atf img'),
      captionText = wideImg.getAttribute('alt'),
      captionInnerHTML = '' + captionText + '',
      caption = document.createElement('div');
// Amend caption:
      caption.setAttribute('class', 'image-caption-wrap');
      caption.style.cssText = 'background: none;';
      caption.innerHTML = captionInnerHTML;
// Insert on page:
      wideImg.parentNode.appendChild(caption);
/* --- End of Wide Image Caption --- */
img {width: 100%}
.full-width-image-atf .content-main-image {
  position: relative;
  color: #fff;
}

.full-width-image-atf .image-caption-wrap {
  position: absolute;
  top: 0;
  right: 0;
  display: flex;
  flex-flow: row-reverse;
  align-items: center;
  padding: 15px 20px;
}
.full-width-image-atf .image-caption-wrap:before {
  content: '\f05a';
  font-family: 'Font Awesome 5 Pro';
  font-size: 2em;
}
.full-width-image-atf .image-caption {
  opacity: 0;
  padding-right: 10px;
}
.full-width-image-atf .image-caption-wrap:hover .image-caption {
  opacity: 1;
}
.full-width-image-atf .image-caption-wrap:hover {
  background: black !important;
  cursor: pointer;
}
.full-width-image-atf .content-main-image, .full-width-image-atf .content-main-image * { transition: 0.4s ease all }


texts: Parser written in PHP is 5.6x faster than the same C++ program in a similar test (g++ 4.8.5)

texts:
I'm absolutely dumbfounded by this. I was trying to demonstrate to myself how much faster C++ is than even modern PHP. I ran a simple CSV parsing program in both that have the same output. The CSV file is 40,194,684 parsed down to 1,537,194 lines.
EDIT: This sparked alot more conversation than I had anticipated, here's the hardware stats for the machine both programs were run on, however its actually a VM running on a nutanix server:
CPU: Intel(R) Xeon(R) Silver 4215R CPU @ 3.20GHz
RAM: 16GB
PHP code (runtime 42.750 s):
<?php
$i_fp = fopen("inFile.csv","r");
$o_fp = fopen("outFile.csv","w");

while(!feof($i_fp))
{
    $line = fgets($i_fp);
    $split = explode(';',$line);
    if($split[3] == 'E' || $split[3] == 'T')
    {
        fwrite($o_fp,join(',',[ $split[0], $split[1], $split[3], $split[4], $split[5], $split[6],
                                $split[10], $split[9],$split[11],$split[7],$split[32]])."\n");
    }
}
fclose($i_fp);
fclose($o_fp);

C++ code (runtime 3 m 59.074s) (compiled using g++ parse.cpp -o parse -O2 -std=c++1y)
#include <fstream>
#include <stdlib.h>
#include <string>
#include <vector>

using std::string;
using std::vector;

vector<string> splitStr(string line, const char delimiter = ',')
{
    vector<string> splitLine;
    string buf;
    for(size_t i=0; i<line.length(); i++)
    {
        if(line[i] == delimiter)
        {
            splitLine.push_back(buf);
            buf.clear();
        }else{
            buf += line[i];
        }
    }
    return splitLine;
}
string makeCSVLine(vector<string> splitLine)
{
    string line =
        splitLine[0] + ',' +
        splitLine[1] + ',' +
        splitLine[3] + ',' +
        splitLine[4] + ',' +
        splitLine[5] + ',' +
        splitLine[6] + ',' +
        splitLine[10] + ',' +
        splitLine[9] + ',' +
        splitLine[11] + ',' +
        splitLine[7] + ',' +
        splitLine[32] + '\n';
    return line;

}
int main(int argc, char* argv[])
{
    if(argc < 3)
    {
        exit(EXIT_SUCCESS);
    }
    string inPath = argv[1];
    string outPath = argv[2];

    std::ifstream inFile;
    std::ofstream outFile;

    inFile.open(inPath.c_str());
    outFile.open(outPath.c_str());

    string line;
    while(std::getline(inFile,line))
    {
        vector<string> split = splitStr(line, ';');
        if(split[3][0] == 'E' || split[3][0] == 'T')
        {
            outFile << makeCSVLine(split);
        }
    }
    inFile.close();
    outFile.close();
}

Both running on Red Hat Linux 8. I'm sure that it's some mistake I'm making in terms of C++ efficiency (possibly somewhere in how I'm using strings and vectors and whether they need to be re-sized repeatedly per loop), but I'm not sure what it could be. If anyone could help, shed some light. That would be great.
EDIT: Unfortunately, I cannot provide the input file as its a sensitive internal file.
Thanks to everyone for taking so much interest in this and all the advice provided. I've been extremely busy at work lately and unable to re-visit but look forward to doing so soon.


texts: Function to sum values of most significant digit contained

texts:
ABOUT

  For each subsequence, look at its position in the original decimal representation of \$x\$. Let's say that the most significant digit it
  contained was the \$e\$-th digit, where \$e=0\$ corresponds to the
  least significant digit of \$x\$. For example, \$388, 822, 442\$ can
  be split into subsequences "3", "888", "22", "44", "2", where
  \$e=7\$ for the sequence "888" and \$e=4\$ for the sequence "22".
  The value of a subsequence which contains a digit \$d\$ repeated one or more times is \$d \cdot 10^e\$.

  \$f(x)\$ is the sum of values of these subsequences. For example, \$f(388,  822, 442) = 3 \cdot 10^8 + 8 \cdot 10^7 + 2 \cdot 10^4 + 4
> \cdot 10^2 + 2 \cdot 10^0\$.
  Since this number could be very large, compute it modulo \$109+7\$.

  INPUT

  The first line of the input contains a single integer denoting the number of cases
  The first line of each test case contains two space-separated integers
  The second line contains two space-separated integers \$N > 10^{18}\$

from itertools import groupby
def encode(num):
    out , num = [] , list(map(int , str(num)))
    for v, g in groupby( enumerate(num), lambda k: k[1] ):
        l = [*g]
        for i in l:
            out.append((abs(l[0][0]- len(num) + 1)))
    s , value = 0 , False
    for i in range(len(num)):
        if value == num[i]: pass
        else:
            s += num[i]*10**out[i]
            value = num[i]
    return s

for i in range(int(input())):
    start = list(map( int , input().split()))
    end , output = list(map( int , input().split())) , 0
    for num in range(start[1] , end[1]+1):
        output += encode(num)
    print(output)


texts: Inserting a node at a specific position in a linked list

texts:
Given a node class like

class Node {
     int data;
     Node next;
  }

Provide an implementation to Insert a node at a specific position in a linked list

Node insert(Node head, int data, int position) {

    Node newNode = new Node();
    newNode.data = data;
    newNode.next = null;

    if(head == null && position != 0) {
        return head;
    } else if(head == null && position == 0) {
        head = newNode;
        return head;
    }

    if(position == 0) {
        newNode.next = head;
        head = newNode;
        return head;
    }

    Node current = head;
    Node previous = null;
    int i = 0;

    for(i = 0; i < position; i++) {
        previous = current;
        current = current.next;
        if(current == null)
            break;
    }

    newNode.next = current;
    previous.next = newNode;
    return head;

}

Can you please critic my code and provide your thoughts on where I should improve my code.


texts:
Recently I had to lock collections (of type List<T>) when items were added or removed. Because several collections were used in given code instead of creating helper methods for each collection, I made an extension methods:

public static class MyExtension
{
    public static void AddThreadSafely<T>(this ICollection<T> collection, T item)
    {
        if (collection == null)
            throw new ArgumentNullException("collection");

        bool locked = false;
        try
        {
             System.Threading.Monitor.Enter(collection, ref locked);
             collection.Add(item);
        }
        finally
        {
             if (locked)
                 System.Threading.Monitor.Exit(collection);
        }
    }

    //The same with remove
}

and then simply replaced Add with AddThreadSafely.

I like the simplicity of this solution but... What are the drawbacks of using this method? Will it be good idea to use this method of locking collections in future projects?


texts:
I have a script to load a range of number. This range of number is only 200 lengths. However, it has a change function. When the start number is change, the the end number will try to find its range again.

The whole of code is working fine. However, it gives me a time lag (sometime get crash) on each change.

Can anyone help me to clean this code, please?

function pad (str, max)
    {
        str = str.toString();

        return str.length < max ? pad("0" + str, max) : str;
    }

$("#game, #camp").on('change', function(){
    a = $("#game").val(),
    b = $("#camp").val(),
    j = pad(a,2);
    k = pad(b,2);
    c = j+k;

    $("#serial").empty();

    for (var i = 1; i<=200; i++)
         {
             l = pad(i,3)
             $("#manual").append("<option value='"+(c+l)+"'>"+(c+l)+"</option>");
         }

var $auto = $('#automatic'),
    $manual = $('#manual'),
    lastValue = +$manual.find('option').last().val();

    $manual.on('change', function () {

        var value = +$(this).val(),
        max = lastValue;

        //alert(max);

        $auto.empty();

        for (var i = value; i < max; i++)
            {
                $('<option>',
                     {
                        value:i+1,
                        text: i+1
                     }).appendTo($auto);
            }
    }).change()

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select id="game">
    <option value="01">01</option>
    <option value="02">02</option>
    <option value="03">03</option>
    <option value="04">04</option>
    <option value="05">05</option>
    <option value="06">06</option>
    <option value="07">07</option>
</select>

<select id="camp">
    <option value="11">11</option>
    <option value="22">22</option>
    <option value="33">33</option>
    <option value="44">44</option>
    <option value="55">55</option>
    <option value="66">66</option>
    <option value="77">77</option>
</select>

<select id="manual"></select>
<select id="automatic"></select>


texts:
So, I have two tables, customers and orders and I want to get all orders associated with a customer.

The tables look like this:

Customers

customer_no   order_no
       1027       V327
       1027       V391
       1028       V400
etc..

Orders

order_no article1 article2 size order_date quantity
    V327    Jeans    Black   36   20150101        2
    V327    Shirt     Blue    L   20150101        1
    V327    Shirt    White    L   20150101        2
    V391    Jeans      Red   34   20150202        3
    V400    Shirt    Green   32   20150226        2
etc..

Now, I currently use the following query, but it is dog slow and I just know I'm approaching this wrongly. I feel like it should be possible to solve this with a join somewhere, but for the life of mine, I just cannot figure this one out.

SELECT article1, article2, size, order_date, SUM(quantity)
FROM orders
WHERE order_no IN (
    SELECT order_no
    FROM customers
    WHERE customer_no = '1027'
)
GROUP BY article1, article2, size, order_date, SUM(quantity)

The output for customer 1027 is (and should be):

article1 article2 size order_date SUM(quantity)
   Jeans    Black   36   20150101             2
   Shirt     Blue    L   20150101             1
   Shirt    White    L   20150101             2
   Jeans      Red   34   20150202             3

Does anyone have a better way of solving this? Performance is my main issue here.


texts: Using JavaScript-bitwise AND and -bitwise NOT for setting a number to 0

texts:
Obviously is the XOR-operator is used in low-level programming-languages used a lot for setting a value back to all bits 0.

For example:

11010 ^ 11010 => 00000

Brought my teacher to figuring a out few exercises.

One is:
"Set the bits of a number back to 0 by using just the bitwise AND (&) and the bitwise NOT (~) operators."

I've got now this solution:

let readline = require('readline-sync');

const limit = 100;

// THAT THE PART WHICH IS IMPORTANT TO ME !!

function setNumberToNull(num) {
  // First invert the bits of the number.
  // Then compare every bit with the not
  // inverted number using an bitwise and.
  return num & (~num);
}

// ########################################

function testSetNumberToNull(limit) {
  let i;

  for (i = 0; i < limit; i++) {
    let testNum = Math.floor(Math.random() * 10000);
    let tmp = setNumberToNull(testNum);

    if (tmp) {
      return { test : i, message : testNum + ' caused failure.' };
    }
  }

  return { test : i, message : 'All tests passed.'};
}

console.log(testSetNumberToNull(limit).message);

I works fine. Nevertheless I would appreciate your review.


texts: is it good practice to use relative path in xpath more than once

texts:
I am using Selenium Webdriver-Java to automate a web application.

Suppose the html is somewhat like below:

          sometext

To locate a element i am using xpath as below:

//div[@id='a1']//span[@id='s1']

is this xpath a good practice

or is it bad practice to use relative path(//) twice in a single xpath?