texts: How to refactoring function when I've to do many things in one function

texts:
I always want to improve my code by refactoring but when I've to work with complicated function that have many thing to do . How can I refactoring them.

Here is my data for example I get data from request

My DB structure look like this

 DB
    id  PK
    blog int
    date_end string
    date_start string
    employee_id FK [ by table employee ]
    total_time_in_hr int
    value int

//my data
req = {
            data: [
                {
                    blog: 1,
                    date_end: "19-02-2020",
                    date_start: "19-02-2020",
                    employee_id: [2290,3],
                    work_id: 1,
                    total_time_in_hr: 10,
                    value: 5100
                }
            ]
    };

First I've to loop my data then I've to loop again in my employee_id and insert them into DB

//looop data
async store({ request, response }) {
    const data = req.data
    await Promise.all(
        data.map(async (getData, i) => {
            const empId = getData.employee_id;
            const workId = getData.work_id;
            let date_start = getData.date_start;
            let date_end = getData.date_end;
            const value = getData.value;
            date_start = moment(date_start, "DD-MM-YYYY").format(
                "YYYY-MM-DD"
            );
            date_start = moment(date_end, "DD-MM-YYYY").format(
                "YYYY-MM-DD"
            );
            await Promise.all(
                empId.map(async (empId, i) => {
//insert to my DB
                    const storeData = new MyDB();
                    storeData.employee_id = empId;
                    storeData.work_id = workId;
                    storeData.value = value;
                    storeData.date_start = date_start;
                    storeData.date_end = date_end;
                    storeData.status = 3;
                    storeData.group_name = groupName;
                    await storeData.save();
// insert to my Log DB
                    const createLog = new MyDBLog();
                    createLog.my_db_id = storeData.id;
                    createLog.value = value;
                    createLog.msg = 'somthing';
                    createLog.status = 3;
                    createLog.total_time = 0;
                    await createLog.save();

                    //this part in my work I've to make json and insert it to another DB
                    const data = {
                        work_id: workId,
                        blog: getData.blog,
                        total_time: getData.total_time_in_hr,
                        my_db_id: storeData.id
                    };
                    const store = await AnotherDB.create(data);
                })
            );
            return { workId, value };
        })
    ).then(async data => {
//update last Value
        await Promise.all(
            data.map(async ({ workId, value }) => {
                const updateTotalAssign = await AssignWork.query()
                    .where("work_id", workId)
                    .update({ total_value: value });
            })
        );
    });
    return response.status(200).json({
        status: 200,
        success: true,
        message: "success"
    });
}

As you see my code are very mess up How to refactoring function and clean code this kind of function


texts: Retaining and passing data between Activities

texts:
I'm making an Android app where users can create posts. This process of creating a new post  can potentially be a few activities/screens, so I need a way to save and pass the data between the activities. My first (bad) solution was just to pass the data with the intent in a Bundle, but this soon got very messy as I really needed to pass a Post object between the activities. I switched from that solution to using a Singleton class called, DataHolder.

In every activity, I call DataHolder.getInstance() and when the create post button is clicked, I create a new Post object by executing: DataHolder.getInstance().setPost(new Post()). In the following activities, as the user enters more information about a post, I set the Post's properties.

This was all working well until I ran into this issue. When I would return to my app (presumably it had been killed) I would get a NullPointerException because the Post object was null. I was looking through the Android docs on passing data between activites/services and needed a little help.

Should I be using the Singleton class pattern here?
What would be the most efficient and easiest way to pass this Post object between the activities?
Should I use Parcelable? (I don't like it though because doesn't it violate the single responsibility principle?)

Here is the DataHolder class:

import com.my_name.app_name.models.Post;

public class DataHolder {

    private static final DataHolder instance = new DataHolder();

    private Post post;
    private Venue venue;
    private int mediaType;
    private Uri imageUri;
    private Uri videoUri;

    // define the media types for a new post here
    public static final int PHOTO = 0;
    public static final int VIDEO = 1;
    public static final int TEXT = 2;
    public static final int PLACE = 3;

    public Uri getImageUri() {
        return imageUri;
    }

    public void setImageUri(Uri iu) {
        this.imageUri = iu;
    }

    public Uri getVideoUri() {
        return videoUri;
    }

    public void setVideoUri(Uri vu) {
        this.videoUri = vu;
    }

    public int getMediaType() {
        return mediaType;
    }

    public void setMediaType(int mt) {
        this.mediaType = mt;
    }

    public Venue getVenue() {
        return venue;
    }

    public void setVenue(Venue v) {
        this.venue = v;
    }

    public Post getPost() {
        return post;
    }

    public void setPost(Post p) {
        this.post = p;
    }

    public static DataHolder getInstance() {
        return instance;
    }
}

I would appreciate any feedback. Let me know if you would like to see more or have any questions.


texts:
When I read some code,I think the usage of Event is not necessary,is it right?

# start server
while True:
    # accept a request here
    queue.put(info)
    event.set() # notify all the threads?
    # pass queue and event here to a Thread constructor

other place there are more than 10 threads running,

# inside a Thread class
def __init__(self, queue, event):
    threading.Thread.__init__(self)
    self.queue, self.event = queue, event

def run(self):
    while True:
        self.event.wait() # <- block here, I think this can be removed
        info = self.queue.get() # <- block here again, only one thread can get job to do?
        # do something
        self.queue.task_done()
        self.event.clear() #


texts: HTTP Get & Post code with slow performance

texts:
I had developed an application in which I hit several URLs and show data on mobile. But the problem is that it requires more time. If I check the same URL on Firebug tool I get a response in 2-3 seconds, but the same URL requires 8-15 seconds on mobile.  In my Android application I am using HTTP get and post method as follows:

public InputStream httpGetResponseStream(String url, String request) {
connectionUrl = url;
InputStream response = null;
try {
    processGetRequest();
    HttpResponse httpresponse = httpclient.execute(host, get);
    response = httpresponse.getEntity().getContent();
} catch (Exception e) {
    response = null;
}
return response;
}

public InputStream httpPostResponseStream(String url, String request) {
connectionUrl = url;
InputStream response = null;
try {
    processPostRequest();
    if (request != null) {
        InputStreamEntity streamEntity = new InputStreamEntity(
                new ByteArrayInputStream(request.getBytes()), request
                        .length());
        post.setEntity(streamEntity);
    }
    HttpResponse httpresponse = httpclient.execute(host, post);
    response = httpresponse.getEntity().getContent();
}catch (Exception e) {
    response = null;
}
return response;
}

private void processGetRequest(){
    uri = Uri.parse(connectionUrl);
    String protocol = connectionUrl.substring(0, 5).toLowerCase();
    if (protocol.startsWith("https")) {
        securedConnection = true;
    } else {
        securedConnection = false;
    }
    if (securedConnection) {
        host = new HttpHost(uri.getHost(), 443, uri.getScheme());
    } else {
        host = new HttpHost(uri.getHost(), 80, uri.getScheme());
    }
    get = new HttpGet(uri.getPath()+query_string);
}

private void processPostRequest() {
uri = Uri.parse(connectionUrl);
String protocol = connectionUrl.substring(0, 5).toLowerCase();
if (protocol.startsWith("https")) {
    securedConnection = true;
} else {
    securedConnection = false;
}
if (securedConnection) {
    host = new HttpHost(uri.getHost(), 443, uri.getScheme());
} else {
    host = new HttpHost(uri.getHost(), 80, uri.getScheme());
}
post = new HttpPost(uri.getPath());
}

Any suggestion to improve code will be appreciated


texts: Scraping names from multipages without clicking on the next button

texts:
I've written a script in python in association with selenium to harvest some coffee shop names from yellowpages. Although, the webpage is not javascript injected one, I used selenium for the purpose of experiment, specially how to handle multipage without clicking on the next button.

Upon execution I could notice that my script runs flawlessly and parses the names from that page. However, it does all this very slowly. Is there any way I can make it's performance faster than how it is now being limited within selenium?

Here is the code:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)

for page_num in range(1,3):
    driver.get('https://www.yellowpages.com/search?search_terms=pizza&geo_location_terms=San%20Francisco%2C%20CA&page={0}'.format(page_num))
    for item in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.info"))):
        try:
            name = item.find_element_by_css_selector('a.business-name span[itemprop=name]').text
        except:
            name = ''
        print(name)

driver.quit()


texts: Better way of setting input scope on text box in WP7

texts:
This works but there must be a better way:

txtBox.InputScope = new InputScope { Names = { new InputScopeName { NameValue = InputScopeNameValue.Text } } };


texts:
I've written this class to generate a random password and was wondering if there's anything I could improve upon here and whether or not this a safe (most random) method of generating a password.

There's only one function in here which can be used to create an alphanumerical password of a specified length. It can also be overloaded to be more specific in which characters it will use.

The code works as it's supposed to.

import UIKit

class codeGen: NSObject {

    private let base: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    private let lowerChars: String = "abcdefghijklmnopqrstuvwxyz"
    private let numberChars: String = "1234567890"
    private let specialChars: String = "!@#$%^&*"

    func generate(length: Int) -> String
    {
        let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        let len = UInt32(letters.length)

        var result = ""

        for _ in 0 ..< length {
            let rand = arc4random_uniform(len)
            var nextChar = letters.character(at: Int(rand))
            result += NSString(characters: &nextChar, length: 1) as String
        }

        return result
    }

    func generate(length: Int, lowers: Bool, numbers: Bool, specials: Bool) -> String
    {
        var letters = base

        if (lowers == true)
        {
            letters += lowerChars
        }
        if (numbers == true)
        {
            letters += numberChars
        }
        if (specials == true)
        {
            letters += specialChars
        }

        let NSletters : NSString = letters as NSString
        let len = UInt32(NSletters.length)

        var result = ""

        for _ in 0 ..< length {
            let rand = arc4random_uniform(len)
            var nextChar = NSletters.character(at: Int(rand))
            result += NSString(characters: &nextChar, length: 1) as String
        }

        return result
    }

}


texts: Array manipulation: add a value to each of the array elements between two given indices

texts:
This is a Hackerrank problem: https://www.hackerrank.com/challenges/crush/problem

You are given a list of size \$N\$, initialized with zeroes. You have
to perform \$M\$ operations on the list and output the maximum of
final values of all the \$N\$ elements in the list. For every
operation, you are given three integers \$a, b\$ and \$k\$ and you
have to add value to all the elements ranging from index \$a\$ to
\$b\$ (both inclusive).
Input Format
First line will contain two integers \$N\$ and \$M\$ separated by a
single space. Next \$M\$ lines will contain three integers \$a, b\$
and \$k\$ separated by a single space. Numbers in list are numbered
from \$1\$ to \$N\$.
Constraints
\$3 \leq N \leq 10^7\$
\$1\leq M \leq 2*10^5\$
\$1 \leq a \leq b \leq N\$
\$ 0 \leq k \leq 10^9\$
Output Format
A single line containing maximum value in the updated list.
Sample Input
5 3
1 2 100
2 5 100
3 4 100

Sample Output
200

My code:
def arrayManipulation(n, queries):
    nums = [0] * (n + 1)
    for q in queries:
        nums[q[0]-1] += q[2]
        nums[q[1]] -= q[2]
    current = 0
    max = 0
    for i in nums:
        current += i
        if current > max: max = current
    return max

Is there any way to optimize this?


texts: Repair orders query in SQL Server with subselects

texts:
I was wondering if you guys know how to reduce the amount of subselects in this SQL Server Query? I think I'm using bad practices in this:

WITH TotalizedRepairOrders AS
(SELECT SalesOrder,Items,DepartmentName, LastCompletedActivity,NextActivity,Plant,ParallelNextActivity  FROM OrdersSynthesis)

SELECT  Plant,
        DepartmentName,
        BlindsInQuestioning =( SELECT ISNULL(SUM(Items),0) FROM TotalizedRepairOrders WHERE NextActivity = 'NEW ORDER REVIEW' AND DepartmentName  = RO.DepartmentName),
        BlindsReadyToCross =( SELECT ISNULL( SUM(Items),0)  FROM TotalizedRepairOrders WHERE (LastCompletedActivity = 'LBM INVOICE' OR NextActivity  = 'LBM INVOICE' OR NextActivity ='PLANT ARRIVAL')  AND  DepartmentName  = RO.DepartmentName),
        BlindsPendingForShipmentCreation = ( SELECT  ISNULL(SUM(Items),0)  FROM TotalizedRepairOrders WHERE ( NextActivity  = 'RETURN SHIPMENT CREATION')  AND  DepartmentName  = RO.DepartmentName),
        PendingForInstructions = ( SELECT  ISNULL(SUM(Items),0)  FROM TotalizedRepairOrders WHERE ( ParallelNextActivity = 'INSTRUCTIONS' )  AND  DepartmentName  = RO.DepartmentName),
        PendingToBeRepaired = ( SELECT ISNULL( SUM(Items),0)  FROM TotalizedRepairOrders WHERE ( NextActivity = 'PRODUCTION' )  AND  DepartmentName  = RO.DepartmentName),
        PendingForQualityControl = ( SELECT  ISNULL(SUM(Items),0)  FROM TotalizedRepairOrders WHERE ( NextActivity = 'INSPECTION')  AND  DepartmentName  = RO.DepartmentName),
        PendingToBePacked = ( SELECT  ISNULL(SUM(Items),0)  FROM TotalizedRepairOrders WHERE ( NextActivity = 'PACKING LABEL')  AND  DepartmentName  = RO.DepartmentName)

FROM TotalizedRepairOrders RO GROUP BY  Plant ,DepartmentName


texts: For a query over multiple databases, is it faster to do GROUP BY first or UNION first?

texts:
Having several databases with the same table, I need to group the union of the records.

The xTables are stored in separate databases named by the year (this is by third-party design and I cannot change it). There are 3 databases in my case but it could be say up to 10. Each of the tables contains about 2500 records with about 300 distinct xID values.

I have tried two approaches but I do not know which is better. I need to calculate the MIN and SUM of the grouped values. The first approach calculates the values for the years (databases) first, and then calculates it again from the agregated values.

CREATE VIEW dbo.view1 AS
    SELECT
        id,
        MIN(minA) AS a,
        CONVERT(numeric(19, 2), SUM(sumB)) AS b
    FROM (
        SELECT
            xID AS id,
            MIN(xA) AS minA,
            SUM(xB) AS sumB
        FROM x2014.dbo.xTable
        GROUP BY xID
        UNION
        SELECT
            xID AS id,
            MIN(xA) AS minA,
            SUM(xB) AS sumB
        FROM x2013.dbo.xTable
        GROUP BY xID
        UNION
        SELECT
            xID AS id,
            MIN(xA) AS minA,
            SUM(xB) AS sumB
        FROM x2012.dbo.xTable
        GROUP BY xID
        ) AS u
    GROUP BY id

The second approach unions all the record first and groups the flatted records later:

CREATE VIEW dbo.view2 AS
    SELECT
        xID AS id,
        MIN(xA) AS a,
        CONVERT(numeric(19, 2), SUM(xB)) AS b
    FROM (
        SELECT
            xID,
            xA,
            xB
        FROM x2014.dbo.xTable
        UNION
        SELECT
            xID,
            xA,
            xB
        FROM x2013.dbo.xTable
        UNION
        SELECT
            xID,
            xA,
            xB
        FROM x2012.dbo.xTable
        ) AS u
    GROUP BY id

The execution plans differ and they show only percentage of the calculation time. I am not that good to read them. By intuition, the first approach may take advantage of statistics bound to the separate databases. However, I am not sure how it is implemented.

The view may be used intensively, and I need to decide which form is more efficient.


texts: How to make a good session handling with NHibernate?

texts:
here I leave my code for a repository pattern with NHibernate and Autofac. I would like to receive some feedback about it. Especially about the session handling with NHibernate. By now I don't like the way that is implemented. Currently the session is created in an IHttpModule on the beginning of the request. Could this session be created with Autofac?.
ISessionModule
public class ISessionModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += context_BeginRequest;
        context.RequestCompleted += context_requestCompleted;
    }
    private void context_BeginRequest(object sender, EventArgs e)
    {
        NHibernateHelper.GetCurrentSession();
    }
    private void context_requestCompleted(object sender, EventArgs e)
    {
        NHibernateHelper.CloseSessionFactory();
    }
    public void Dispose()
    {
        //throw new NotImplementedException();
    }
}

Repository class
public class BaseRepository<T,TId> : IRepository<T, TId> where T : class
{
    protected ISession session = HttpContext.Current.Items["nhibernate.current_session"] as ISession;
    protected ITransaction transaction = null;
    public BaseRepository()
    {
        //session = NHibernateHelper.OpenSession();
        transaction = session.BeginTransaction();
    }
    public async void Create(T entity)
    {
        await session.SaveOrUpdateAsync(entity);
        await transaction.CommitAsync();
    }
    public async void DeleteAsync(TId key)
    {
        var entity = await session.LoadAsync<T>(key);
        await session.DeleteAsync(entity);
        await transaction.CommitAsync();
    }

    public async Task<List<T>> FindAll()
    {
         return await session.Query<T>().ToListAsync();
    }

    public async Task<T> FindOne(TId key)
    {
         return await session.GetAsync<T>(key);
    }

    public async void Update(T entity)
    {
        await session.SaveOrUpdateAsync(entity);
        await transaction.CommitAsync();
    }
}

Example of the controller
public class ContractsController : ODataController
{
    private readonly BaseRepository<Contract, int> contractRepository;
    public ContractsController(BaseRepository<Contract, int> contractRepository)
    {
        this.contractRepository = contractRepository;
    }
    public async Task<IHttpActionResult> Get([FromODataUri] int key)
    {
        var contract = await contractRepository.FindOne(key);
        if (contract == null)
        {
            return StatusCode(HttpStatusCode.NotFound);
        }
        return Ok(contract);
    }

Global.asax
    public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        var builder = new ContainerBuilder();
        builder.RegisterGeneric(typeof(BaseRepository<,>)).As(typeof(BaseRepository<,>)).InstancePerRequest();
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
        var container = builder.Build();
        var webApiResolver = new AutofacWebApiDependencyResolver(container);
        GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}


texts: Count the word frequencies within a given directory

texts:
I have built a tiny script count the word frequencies of all text files with a specified directory. I would be glad to receive any suggestions and feedback.

import re, glob,os
from collections import OrderedDict, Counter

class CountWords:
    def __init__(self,dir,ext):
        self.dir = dir
        self.ext = ext

    @property
    def files(self):
        #collect all the files with `.txt` extension
        os.chdir(self.dir)
        return glob.glob(f"**/*.{self.ext}", recursive=True)
    @property
    def contents(self):
        #concatenate files
        cat_content = []
        for file in self.files:
            with open(file, 'r') as f:
                content = f.read()
                cat_content.append(content)
        contents = ",".join(cat_content)
        return contents
    @property
    def words(self):
        words = re.findall(r"[a-zA-z_]+", self.contents)
        words = [word.lower() for word in words]
        return words

    def count(self):
        words_counter = Counter(self.words)
        words_counter = OrderedDict(sorted(words_counter.items(),key=lambda t:t[1], reverse=True))
        return words_counter

The function version:

def count_words(dir,ext):
    os.chdir(dir)
    #collect all the files with `.txt` extension
    files = glob.glob(f"**/*.ext", recursive=True)
    #concatenate files
    cat_content = []
    for file in files:
        with open(file, 'r') as f:
            content = f.read()
            cat_content.append(content)
    contents = ",".join(cat_content)
    #extract the words
    words = re.findall(r"[a-zA-z_]+", contents)
    words = [word.lower() for word in words]
    words_counter = Counter(words)
    words_counter = OrderedDict(sorted(words_counter.items(),key=lambda t:t[1], reverse=True))
    return words_counter


texts:
I have a file that seems to mix encoding in it. It seems like a Unicode encoded file, but the character length string is encoded like a UTF8 or similar. Here is an example:

05 41 00 72 00 69 00 61 00 6C 00
5  A  .  r  .  i  .  a  .  l  .

In this example it stores the string like Unicode, using the extra character, but the length of the string is half of what it should be, 05 instead of 0A, as if it were encoded as UTF8.

If I use:

using (var reader = new BinaryReader(File.Open(fileName, FileMode.Open), Encoding.Unicode))
{
  temp = reader.ReadString();
}

When I run this then temp = "Ar"

I have this code that works. But is there a better way?

using (var reader = new BinaryReader(File.Open(fileName, FileMode.Open), Encoding.Unicode))
{
  tempByte = reader.ReadByte();
  var length = Convert.ToInt32(tempByte) * 2;
  byteArray = reader.ReadBytes(length);
  for (var ww = 0; ww < length; ww = ww + 2)
  {
    tempString = tempString + (char)byteArray[ww];
  }
}


texts:
Is there a design pattern I can use for a situation like below.  This is an example I made up to try and explain the situation I'm dealing with currently.  I keep having to add new DeviceScript classes to my DeviceAnalyzer as situation come up and adding logic about when to return the new type in the 'GetScriptForDevice'.

This example I have given is pretty simple but the business logic I'm having to implement for my real 'GetScriptForDevice' isn't always this easy.  Any suggestions on a pattern or an example of a better way to structure this code to follow a better pattern would be greatly appreciated.  I'm violating OCP every time I need to add a new DeviceScript and I'm trying to find a way around this because my class is getting quite long and fragile.

Thanks.

public class DeviceScript {
    public string Name { get; set; }
    public string SecurityScriptName { get; set; }
    public string BusinessScriptName { get; set; }
}

public class DeviceAnalyzer {

    public const string US_SecurityScript = "US_SecurityScript";
    public const string US_BusinessScript = "US_BusinessScript";
    public const string UK_SecurityScript = "UK_SecurityScript";
    public const string UK_BusinessScript = "UK_BusinessScript";

     private DeviceScript UnitedStates = new DeviceScript {
         Name = "US_Script",
         SecurityScriptName = US_SecurityScript,
         BusinessScriptName = US_BusinessScript
     };

     private DeviceScript UnitedKingdom = new DeviceScript {
         Name = "UK_Script",
         SecurityScriptName = UK_SecurityScript,
         BusinessScriptName = UK_BusinessScript
     };

     public DeviceScript GetScriptForDevice(IDevice device) {

         if(device.Location == Locations.US) {
          return UnitedStates;
         }

         if(device.Location == Locations.UK) {
          return UnitedKingdom;
         }

        return null;
     }

}


texts: How to make a int not be used twice when it randomly generates them?

texts:
I've coded a simple quiz game for Android, and currently Im having troubles with making questions not appear after they've been shown, i.o. I dont want it to ask me the same question twice..

This is the method Im using

 private void QBegin() {
   /*
    * Gets a random question
    */
    question = (TextView) findViewById(R.id.question);
    String[] types = { "Question one",
            "Question two",
            "Question three",
            "Question four",
            "Question five"};
    Random random = new Random();
    int qType = random.nextInt(types.length);
    question.setText(types[qType]);
    getAnswers(qType); //gets four answers
}

Im not sure if this will work but, what if I add something like

Edit : Doesn't work..

    int i = 0;
    ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(qType);
    i++;
    if(list.contains(qType) && i != types.length + 1){
        return;
    } else {
        answerCounter.setText("Hit the bricks pal, you're done..");
    }

On http://stackoverflow.com got told to , add smth like:

    ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(types.length);
    Collections.shuffle(list);
    if(!list.contains(qType)){
        // help please, as I have no idea on what I should be doing!
    }


texts:
I have a few thousand binary files that have corresponding structs in them, followed by any number of bytes (this exact number of bytes is given in one of the fields in the structs). I read in data from the binary files to a struct, and assign variables from certain fields in those structs. I was wondering if there is any significant improvement I could make to speed things up, specifically regarding the binary file reading?

Note: I'm reading in 256 bytes at a time to a struct, and in that struct is a number that says how many bytes follow until the next struct. So there isn't a static pattern to the data that I can follow.

const int STRUCT_HEADER_SIZE = 256; //256 bytes
const int FILE_HEADER_SIZE = 1024; //1024 bytes

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct STRUCTHEADER
{
    //Sample fields
    public ushort MagicNumber;
    public byte SubChannelNumber;
    public ushort NumChansToFollow;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
    public ushort[] Reserved1;

    public int NumBytesThisRecord; //This value says how many bytes there are total in the current 'packet' which includes this struct header.

    public ushort Year;
    public byte Month;
    public byte Day;
    public byte Hour;
}

FileStream stream1;
STRUCTHEADER testStruct = new STRUCTHEADER();
List<string> filePaths = new List<string>();

foreach (string filePath in filePaths) //for each binary file
{
    ReadBinaryFile(filePath); //Read the binary file
}

public void ReadBinaryFile(string filePath)
{
    try
    {
        stream1 = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None);
    }
    catch(Exception ex)
    {
    }

    try
    {
        stream1.Position = FILE_HEADER_SIZE; //Start stream after the file header

        while (stream1.Position < stream1.Length) //While not at the end of the stream
        {
            testStruct = ReadRecFromStream<STRUCTHEADER>(stream1); //read data from binary file into STRUCTHEADER type struct

            //assigning fields here
            //ex: int year = testStruct.year;

            stream1.Position += Math.Abs(testStruct.NumBytesThisRecord - STRUCT_HEADER_SIZE); //Advance to the end of current packet
        }
        stream1.Close();
        //Adding field values to a textbox
        //ex: textbox1.Text += year;
    }
    catch
    {
        stream1.Close();
    }
}

//Used to read in data in binary file to a struct
private T ReadRecFromStream<T>(Stream stream) where T : struct
{
    byte[] buffer = new byte[Marshal.SizeOf(typeof(T))];
    stream.Read(buffer, 0, STRUCT_HEADER_SIZE);
    GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
    try
    {
        return (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
    }
    finally
    {
        handle.Free();
    }
}

Here's a link to two sample .xtf binary files (they are the same type I'm reading in):
https://sourceforge.net/projects/imagejforxtf/files/?source=navbar


texts:
I would be glad if someone could take a look at my code and maybe improve it. It's an animation effect to gradually reveal text as if it were being decoded. I wouldn't mind if it could run with jQuery (if it's shorter or better). I uploaded it on jsbin.com. It's all about the effect and not about encryption or decryption.

I've written the following JS Code:

var got,
    chars,
    decrypted = document.getElementById("decoded"),
    encrypted = document.getElementById("encoded");
function change() {
    var randstring = "",
        rslength = chars.length - got.length,
        i;
    for (var x=0;x<rslength;x++) {
        i = Math.floor(Math.random() * chars.length);
        randstring += chars[i];
    }
    if (randstring[0] === chars[got.length]) {
        got += randstring[0];
        decrypted.textContent = got;
    } else {
        encrypted.textContent = randstring;
    }
    if (chars.length > got.length) {
        setTimeout(change, 10);
    } else {
        encrypted.textContent = "";
    }
}
function startdecrypt() {
    chars = decrypted.textContent;
    decrypted.textContent = "";
    got = "";
    setTimeout(change, 10);
}
if (window.addEventListener) {
    window.addEventListener('load', startdecrypt, false); //W3C
} else {
    window.attachEvent('onload', startdecrypt); //IE
}

And this short HTML part:

Enjoy this effect!


texts: LeetCode: Trie Tree implementation, Search, Insert, startWith C#

texts:
https://leetcode.com/problems/implement-trie-prefix-tree/

Please comment about performance and style.

  Implement a trie with insert, search, and startsWith methods.

  Example:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app");     // returns true

  Note:

  You may assume that all inputs are consist of lowercase letters a-z.
  All inputs are guaranteed to be non-empty strings.

using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TrieQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/implement-trie-prefix-tree/
    /// </summary>
    [TestClass]
    public class TrieTreeImplementation
    {
        [TestMethod]
        public void TrieInsertTest()
        {
            Trie trie = new Trie();
            trie.Insert("cat");
            Assert.IsTrue(trie.Search("cat"));
        }

        [TestMethod]
        public void TriePrefixSearchTest()
        {
            Trie trie = new Trie();
            trie.Insert("cats");
            Assert.IsTrue(trie.StartsWith("cat"));
        }

        [TestMethod]
        public void OneLetterEdgeCaseTest()
        {
            Trie trie = new Trie();
            trie.Insert("a");
            Assert.IsTrue(trie.Search("a"));
            Assert.IsTrue(trie.StartsWith("a"));
        }
    }

    public class Trie
    {
        public TrieNode Head { get; set; }

        /** Initialize your data structure here. */
        public Trie()
        {
            Head = new TrieNode();
        }

        /** Inserts a word into the trie. */
        public void Insert(string word)
        {
            var current = Head;
            for (int i = 0; i < word.Length; i++)
            {
                if (!current.Edges.ContainsKey(word[i]))
                {
                    current.Edges.Add(word[i], new TrieNode());
                }
                current = current.Edges[word[i]];
            }
            current.IsTerminal = true;
        }

        /** Returns if the word is in the trie. */
        public bool Search(string word)
        {
            var current = Head;
            for (int i = 0; i < word.Length; i++)
            {
                if (!current.Edges.ContainsKey(word[i]))
                {
                    return false;
                }
                current = current.Edges[word[i]];
            }
            return current.IsTerminal == true;
        }

        /** Returns if there is any word in the trie that starts with the given prefix. */
        public bool StartsWith(string prefix)
        {
            var current = Head;
            for (int i = 0; i < prefix.Length; i++)
            {
                if (!current.Edges.ContainsKey(prefix[i]))
                {
                    return false;
                }
                current = current.Edges[prefix[i]];
            }
            return true;
        }
    }

    public class TrieNode
    {
        public Dictionary<char, TrieNode> Edges { get; set; }
        public bool IsTerminal { get; set; }
        public TrieNode()
        {
            Edges = new Dictionary<char, TrieNode>();
        }
    }
}


texts: Removing the massive amount of for-loops in this code

texts:
Are there ways to avoid this triply nested for-loop?

def add_random_fields():
from numpy.random import rand
server = couchdb.Server()
databases = [database for database in server if not database.startswith('_')]
for database in databases:
    for document in couchdb_pager(server[database]):
        if 'results' in server[database][document]:
            for tweet in server[database][document]['results']:
                if tweet and 'rand_num' not in tweet:
                    print document
                    tweet['rand_num'] = rand()
                    server[database].save(tweet)

Update

People suggesting that I use a generator reminded me that I forgot to mention that couchdb_pager is a generator over the list server[database].


texts: Generate dictionary of points on n-sphere

texts:
This is a long-shot, but my question is to simply optimize this particular function in some code I have written:

import numpy as np
from numpy.core.umath_tests import inner1d

def getSpherePoint(dim,pList,psetLen):
    npgauss = np.random.standard_normal
    pt = abs(np.random.standard_normal(psetLen))
    pt = pt/np.sqrt(inner1d(pt,pt))

    d = dict(zip(pList,pt))
    return d

Note that dim is some integer \$n\$, pList is simply a list of \$2^n-1\$ strings, and psetLen is \$2^n-1\$. This function is designed to return a dictionary keyed  by elements of pList with values determined by a point on the unit \$n\$-hypersphere.

At this point, I need to run this function around a billion times or so to get the results I want, which will take hours. I've done as much optimization as possible here, and my micro-optimization seems to indicate that all three major parts of the function (the random number, the normalization, and the dictionary association) all take approximately a third of the run-time, and I'm not sure how to reduce it further. I've squeezed a bit out of Cythoning it, but I'm not sure how much of an improvement that will give me as compared to actually writing it in C and then importing the C function. Unfortunately, I don't know C (or C++) and haven't written Java in years, so I'm pretty stuck using Python (or extensions thereof).

Is it possible to optimize this further by any significant factor? Would changing languages help dramatically? What improvements could be made in Python?


texts: Read uncommited rows and lock row on update

texts:
I have 5 (or more) instances of an application running on same or different machines. Each of these application will pass a comma separated string of UserIDs and the app should pick up a unique unused record (UserID) from a DB table, matching the user IDs as passed through the SP.
So if App-1 picks User-3 and marks it as 'locked' then User-3 will not be available for other apps until, App-1 remarks it as 'unlocked'.

I have written a small SP to mark the first 'unlocked' user as 'locked' in the DB table and return the UserID to the calling app.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Souvik Ghosh
-- Create date: 12-Nov-2016
-- Description: Lock a user ID and return it
-- =============================================
ALTER PROCEDURE LockHROSAPID
@UserIDs varchar(max)
AS
BEGIN
    SET NOCOUNT ON;
    BEGIN TRY
        BEGIN TRANSACTION
            UPDATE [wm_uc1].[UK_HR_HROSAPUserIDs] SET IsLocked = 1
            OUTPUT Inserted.HROSAPUID
            WHERE ID = (SELECT TOP 1 ID FROM [wm_uc1].[UK_HR_HROSAPUserIDs]
            WHERE HROSAPUID IN (@UserIDs) AND IsLocked IS NULL OR IsLocked <> 1)
        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
        ROLLBACK
    END CATCH
    RETURN
END
GO

I have tested it and it seems to work fine. But, I want to have a second opinion about this.


texts: Checking whether a timestamp is 10 minutes old

texts:
I have a timestamp (searchTimestamp) which I need to check to see whether it is less than 10 minutes old or not:

long currentTimestamp = System.currentTimeMillis();

long searchTimestamp = getTheTimestampFromURL();// this also gives me back timestamp in 13 digit (1425506040493)

long difference = Math.abs(currentTimestamp - searchTimestamp);

System.out.println(difference);

if (difference > 10 * 60 * 1000) {
    System.out.println("timestamp is greater than 5 minutes old");
}

I have got the above code which is working fine. Is this the right way to do this or is there any better way?

getTheTimestampFromURL will always be older than the current timestamp in milliseconds.


texts:
My Java app converts its modal object to JSON (using the GSON Library).

This is just fine, but I have to get it back into a modal in PHP. Now I've created a modal (in my case it's, for example, GeoLocation) which has several getters and setters.

Example:

class GeoLocation {

    private $cellTowerId;
    private $dateCreated;
    private $dateModified;
    private $geoLocationId;
    private $geoLocationLatitude;
    private $geoLocationLongitude;
    private $geoLocationName;
    private $geoLocationStatus;
    private $geoLocationTime;
    private $isSynch;
    private $geoLocationAccuracy;
    private $geoLocationAltitude;
    private $geoLocationBearing;
    private $geoLocationProvider;
    private $geoLocationSpeed;
    private $geoStreet;
    private $geoPostalCode;
    private $geoLocality;
    private $geoCountryName;
    private $geoCountryCode;
    private $geoFeatureName;
    private $geoPhone;

    public function getCellTowerId() {
        return $this->cellTowerId;
    }

    public function getDateCreated() {
        return $this->dateCreated;
    }

    public function getDateModified() {
        return $this->dateModified;
    }

    public function getGeoLocationId() {
        return $this->geoLocationId;
    }

    public function getGeoLocationLatitude() {
        return $this->geoLocationLatitude;
    }

    public function getGeoLocationLongitude() {
        return $this->geoLocationLongitude;
    }

    public function getGeoLocationName() {
        return $this->geoLocationName;
    }

// and many more...
}

I have a loader class which processes the JSON and should re-create the object as soon as the set<Varname>() method exists.

Are there any "security" problems so far or any way to improve it?

public function process() {
    foreach (parent::getData() as $key) {
        try {
            $geolocation = new GeoLocation();
            foreach ($key as $keyName => $keyValue) {
                if (method_exists($geolocation, "set" . ucfirst($keyName))) {
                    call_user_func(array($geolocation, "set" . ucfirst($keyName)), $keyValue);
                }
            }
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }
}

Since the class methods are always synchronized with the Java classes, the getter and setter methods should always exist. Is there maybe a way of doing the getters and setters dynamically using the JSON?

If there is JSON data which has no methods, like setJSONDataOfEvilStuff(), then it's not necessarily so far.


texts: Currying addition function in ECMAScript 6

texts:
I wanted to write an add function that implemented currying in JavaScript. I welcome criticism and suggestions for improvement.

function add(...args1) {
  if(!args1.length) {
    return sum(args1);
  }

  return (...args2) => {
    if(!args2.length) {
      return sum(args1.concat(args2));
    }

    return add.apply(null, args1.concat(args2));
  };
}

function sum(arr) {
  return arr.reduce((p,c) => p+c,0);
}

console.assert(add(1,2)(3)(4)() === 10, '1+2+3+4 should be 10');


texts:
I solved this problem and was looking for feedback on my code. More efficient, cleaner, more verbose variable names, anything helps.

  There are N strings. Each string's length is no more than 20  characters. There are also Q  queries. For each query, you are given a string, and you need to find out how many times this string occurred previously.

import Foundation

func readIntegers() -> Int {
    return Int(readLine()!)!
}

func sparseArrays() {
    let numOfStrings = readIntegers()
    var arrayOfStrings = [String]()
    for _ in 0..<numOfStrings {
        let string = readLine()!
        arrayOfStrings.append(string)
    }
    let numOfQueries = readIntegers()
    for _ in 0..<numOfQueries {
        let singleString = readLine()!
        let arrayOfSingleString = arrayOfStrings.filter {$0 == singleString}
        print(arrayOfSingleString.count)
    }
}

sparseArrays()


texts:
I want to find the number of the pairs in an array that equal a given sum.

I've naively tried to implement brute force as a solution, but it is too slow and this task should not take more than one second.

def getPairsCount(numbers, shouldEqualTo):
    count = 0
    for i in range(len(numbers)):
        for j in range(i + 1, len(numbers)):
            if numbers[i] + numbers[j] == shouldEqualTo:
                count += 1
    return count


texts:
Could you please offer some suggestions about my self learning project?

It is really hard-coded, but I have no idea what to do next. I'm using angular (only few features for now) and grunt + bower.

tester.html

    First form
    Second form
    Third form
    Translation

{{ verb }}

        <input ng-model="val[$index]" ng-hide="isActive($index)" type="text">

{{ verb }}

          {{ val[$index] }}

{{ verb }}

  Check

  Next

iwt.coffee

angular.module('IWTTester', [])

  .controller('IWTTesterController', [
    '$http'
    '$scope'
    ($http, $scope) ->

      $http.get 'js/words.json'
      .success (data, status, headers, config) ->
        console.log data, status, config, 'good'
        $scope.irregulars = data
        $scope.init()
      .error (data, status, headers, config) ->
        console.log data, status, config, 'bad'

      $scope.isActive = (formIndex) ->
        formIndex is $scope._activeForm

      $scope.isStage = (value) ->
        value is $scope._stage

      $scope.init = ->
        ROWS = $scope.irregulars.length
        COLS = $scope.irregulars[0].length

        create_counter = (module) ->
          i = 0
          -> (i++) % module
        rowCounter = create_counter(ROWS)
        colCounter = create_counter(COLS)

        $scope.val = []
        $scope._stage = 'input'

        update = ->
          $scope.verbs = $scope.irregulars[rowCounter()]
          $scope._activeForm = colCounter()
        update()

        $scope.isSuccess = (i) ->
          $scope.val[i] is $scope.verbs[i]

        $scope.isDanger = (i) ->
          $scope.val[i] isnt $scope.verbs[i] and not $scope.isActive(i)

        $scope.check = ->
          $scope._stage = 'validation'

        $scope.next = ->
          $scope.val = []
          update()
          $scope._stage = 'input'
  ])

  .directive('iwtTester', ->
    restrict: 'AE'
    templateUrl: 'templates/tester.html'
    controller: 'IWTTesterController'
  )

words.json

[
  [
    "be",
    "was",
    "been",
    "быть"
  ],
  [
    "bring",
    "brought",
    "brought",
    "приносить"
  ]
]


texts: Reverse a linked list from position m to n, in-place and in one pass

texts:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
public:
    ListNode *reverseBetween(ListNode *head, int m, int n)
     {
        ListNode *pre=NULL, *cur=head, *front=NULL, *rear=NULL,*follow=head->next;
        int subLoop=n-m;
        if(m==1 && subLoop==0)
        {
            return head;
        }

        if(m==1)
        {
            rear=head;
        }
        else
        {
            for(int i=0;i<m-1;++i)
            {
                if(i==m-2)
                {
                    front=cur;
                }
                cur=cur->next;
            }
            rear=cur;
        }
        while(cur!=NULL&&subLoop-->=0)
        {
            follow=cur->next;
            cur->next=pre;
            pre=cur;
            cur=follow;
        }
        if(m!=1)
        {
            front->next=pre;

        }
        else if(m==1&&pre!=NULL)
        {
            head= pre;
        }
        rear->next=cur;
        return head;

    }
};


texts:
I am unsure if the list could store a large number of messages.

There are 50,000 queue messages which I am receiving and assigning to the messages list:

    var msgEnumerator = msgQueue.GetMessageEnumerator2();
    var messages = new List<System.Messaging.Message>();
    while(msgEnumerator.MoveNext(new TimeSpan(0, 0, 1))) {
    var msg = msgQueue.ReceiveById(msgEnumerator.Current.Id, new TimeSpan(0, 0, 1));
    messages.Add(msg);
     }

    foreach( var k in messages){
    MailMessage mailM = (k.Body as SerializeableMailMessage).GetMailMessage();

    try {
    SmtpClient sp = new SmtpClient(smtpip, 25);
    sp.EnableSsl = false;
    sp.Send(mailM);
    }

    catch (Exception ex){
    logger.ErrorException("General error sending email.", ex);
    }
   }

Is this the correct way, or is there an alternative?  Let me hear your suggestions.


texts:
I'm reading this tutorial and it's the first time I try something this new.

Here is my attempt:

import sys
import math
import pygame
import random

pygame.init()
windowwidth, windowheight = 900, 500
windowsurface = pygame.display.set_mode((windowwidth, windowheight), 0, 32)
clock = pygame.time.Clock()
fps = 30
MAX_INT = (1<<31) - 1
grey = (128, 128, 128)

def linear_interpolate(a, b, x):
    return a*(1-x) + b*x

def int_noise(x):
    # I'm pretty sure I can use random.uniform(-1, 1) as I need a value in the range (-1, 1)
    # I just saw this function on SO that is said to be faster that the build-in.
    x = int(x)
    x = ((x << 13) & MAX_INT) ^ x
    x = ( x * (x * x * 15731 + 789221) + 1376312589 ) & MAX_INT
    return 1.0 - x / 1073741824.0

def smooth_noise(x):
    return int_noise(x)/2 + int_noise(x-1)/4 + int_noise(x+1)/4

def noise_interpolate(x):
    int_x = int(x)
    fractional_x = x - int_x

    v1 = smooth_noise(int_x)
    v2 = smooth_noise(int_x+1)

    return linear_interpolate(v1, v2, fractional_x)

def perlin_noise(x):
    total = 0
    persistence = 1/4
    octaves = 10

    for i in range(octaves):
        frequency = pow(2, i)
        amplitude = pow(persistence, i)

    total = total + noise_interpolate(x*frequency) * amplitude

    return total

#---------------------------------------------------------------------------

def mainloop():
    scale = 50
    points = [(i, perlin_noise(0.6*i) * scale)
              for i in range(0, windowwidth, 10)]
    points.append((900, perlin_noise(0.5)))

    while True:
        clock.tick(fps)
        pygame.display.set_caption('fps: %.2f' % clock.get_fps())

        # handle events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        # update game state

        # draw
        for i in range(len(points) - 1):
            pygame.draw.line(windowsurface, grey,
                             (points[i][0], 350+points[i][1]),
                             (points[i+1][0], 350+points[i+1][1]), 1)
        pygame.display.update()

if __name__ == '__main__':
    mainloop()

I know the design is awful, but I'm more concerned if it is the correct way to write all this. From interpolating function, to the smoothing function, all the way to perlin.

I have the feeling that this Perlin noise function is completely wrong and very misleading, regardless the fact that I draw the wave onto the screen.


texts:
This is a simple script that I use for wrapping a selected word in a textarea field.  I'm looking to:

make sure my logic is valid/see what others have done in a relative context.
request improvements to the OO approach I'm going for.

Formatter = {};

Formatter.getSelection = function(event) {
  var text  = document.getElementById("mass_message");
  var sPos  = text.selectionStart;
  var ePos  = text.selectionEnd;
  var front = (text.value).substring(0, sPos);
  var sel   = (text.value).substring(sPos, ePos);
  var back  = (text.value).substring(ePos, text.value.length);
  format    = event.data.format;

  var print = Formatter.setString(text, format, front, back, sel);
}

Formatter.setString = function(text, format, front, back, sel) {
  text.value = front + "<" + format + ">" + sel + "</" + format + ">" + back;
}

$(document).ready(function(){
  $( '#bolden' ).on('click', { format: "b" }, Formatter.getSelection);
  $( '#italicize' ).on('click', { format: "i" }, Formatter.getSelection);
});

I'm appreciative of any suggestions and am happy to answer questions about the code.


texts:
I'm writing some simple emacs tools for visual studio solutions.

I've got a function sln-process-csproj-file.  This function takes the path to a project, and returns a tuple that's just a data model of the innards of the project.

Right now the return value on the last line of that function is `(,project-name ,project-path ,project-files).

I have written three getter functions to use with the list:

(defun sln-project-name (project)
  (nth 0 project))

(defun sln-project-path (project)
  (nth 1 project))

(defun sln-project-files (project)
  (nth 2 project))

Does this getter and setter boilerplate code match best practices? Is there a shorter way to write it?


texts: Dimension comparisons for calculating image thumbnail size

texts:
I've been toying around with some code I wrote a while back, in an attempt to make it "cleaner" based on what I've read. Does anything stand out to you as bad conventions here? What are your thoughts about doing some conditional checks as separate variables at the top of the function? I thought of putting those into the if/elseif statements, but I thought this method would be DRYer.

/**
 * Calculate the dimensions for the thumbnails.
 *
 * @param  $width, $height, $target_width, $target_height
 * @return array
 */
private function calculateThumbnailSize($width, $height, $target_width, $target_height) {
    $widthHeightComparison = !is_negative(gmp_cmp($width, $height));
    $widthTargetWidthComparison = !is_negative(gmp_cmp($width, $target_width));
    $heightTargetHeightComparison = is_positive(gmp_cmp($height, $target_height));
    $heightGTETargetHeight = !is_negative(gmp_cmp($height, $target_height));
    $heightCalc = floor($height * ($target_width / $width));

    if ($widthHeightComparison && $widthTargetWidthComparison && ($heightCalc <= $target_height )) {
        $new_width = $target_width;
        $new_height = floor( $height * ($target_width / $width) );
    } elseif ($widthHeightComparison && $widthTargetWidthComparison && ($heightCalc > $target_height )) {
        $new_width = floor( $width * ($target_height / $height) );
        $new_height = $target_height;
    } elseif ($widthHeightComparison && !$heightTargetHeightComparison) {
        $new_width = $width;
        $new_height = $height;
    } elseif($widthHeightComparison && $heightTargetHeightComparison) {
        $new_width = floor( $width * ($target_height / $height) );
        $new_height = $target_height;
    } elseif (!$widthHeightComparison && $heightGTETargetHeight){
        $new_width = floor( $width * ($target_height / $height) );
        $new_height = $target_height;
    } elseif (!$widthTargetWidthComparison && !$heightGTETargetHeight) {
        $new_width = $width;
        $new_height = $height;
    } else {
        $new_width = $target_width;
        $new_height = floor( $height * ($target_width / $width) );
    }
    return array($new_width, $new_height);
}

/**
 * Check if expression is negative integer.
 *
 * @param $str
 * @return bool
 */
private function is_negative($str) {
  return (is_numeric($str) && $str < 0 && $str == round($str));
}

/**
 * Check if expression is positive integer.
 *
 * @param $str
 * @return bool
 */
private function is_positive($str) {
  return (is_numeric($str) && $str > 0 && $str == round($str));
}


texts: Receiving and sending notifications from database

texts:
I'm not much familiar with Task Api programming in C#. Can anyone review my following code?

The following is a ElapsedEventHandler of a System.Timers.Timer. In this event, I'm getting pending notifications from database and sending them. After I send the notification, I update that notification in database by setting HasSent = true. We require our notifications to be sent as soon as possible. This is the reason, I'm updating HAsSent in a separate thread by using Task Api. I would like to know if this is a bad practise? Should I use this? If not then why?

protected void ProcessNotifications(object source, ElapsedEventArgs e)
{
    UtilityMethods.StopTimer(_notificationTimer);

    try
    {
        var notificationService = new NotificationService();
        var pendingNotifications = notificationService.GetPendingNotifications();

        if (pendingNotifications.Count > 0 && LoadConfigurations())
        {
            foreach (var notification in pendingNotifications)
            {
                try
                {
                    var notificationType = (NotificationType)notification.NotificationTypeId;

                    notification.NotificationTemplate = new NotificationTemplateService().GetById(notification.NotificationTemplateId);
                    notification.NotificationAttachments = notificationType == NotificationType.Email ?
                        new NotificationAttachmentService().GetByNotificationId(notification.NotificationId) : null;

                    using (var sender = NotificationSenderFactory.Create(notificationType))
                    {
                        if (sender.Send(notification))
                        {
                            Task.Factory.StartNew(() =>
                            {
                                notificationService.MarkNotificationsAsSent(notification.NotificationId);// A database Hit
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    AppLogger.LogException(ex);
                }
            }
        }
    }
    catch (Exception ex)
    {
        AppLogger.LogException(ex);
    }
    finally
    {
        UtilityMethods.StartTimer(_notificationTimer);
    }
}


texts: Idiomatic use of computed properties in Polymer 2

texts:
I'm trying to wrap my head around how computed observables / properties in Polymer 2 work and should be used. I've created a repro analogous to my real code that zooms in on the thing I'd like to see reviewed: my use of computed properties in a Polymer 2 component.

Some things that might be helpful while reviewing:

I've explicitly left out CSS and styling because I want to focus on getting the code right.
We're targeting modern browsers, specifically for IE only Edge.

The main thing I'm worried about is hasSelectedPerson and its underlying "private" function. For one thing, it feels weird that I have to ask for a person as an argument, when it's also available as a property on the class.

<link rel="import" href="//polygit.org/polymer+:master/components/paper-button/paper-button.html">

<dom-module id="people-template">

  <template>
    <template is="dom-repeat" items="[[people]]" as="person">
      <paper-button raised on-click="_onSelectClick" item="[[person]]">
        [[person.name]]
      </paper-button>
    </template>
    <template is="dom-if" if="[[hasSelectedPerson]]">

Selected: [[selectedPerson.id]] [[selectedPerson.name]]

    </template>
  </template>

</dom-module>

You can also check it on plnkr.co where it's wrapped in a plain index file to see it actually running.

So, to summarize:

Any specific comments on my use of computed?
Any generic comments on this component?


texts: How to have better performance of code insert many to many relation

texts:
I want improve performance of this code.
One product or residence have multiple criterion wich have criterion have multiple criterion value.
public function createOrUpdateCriteriaIfEntityUpdated(
HasCriterionInterface $ownerEntity,
array $criteria,
DateTime $dateImportStarted
) {
    if (!$ownerEntity->getIsUpdated()) {
        return false;
    }

    foreach ($criteria as $criterion) {
            $criterionValue = $this->criterionValueRepository->createOrUpdate($criterion, $dateImportStarted);
            $ownerEntity->addCriterionValue($criterionValue);
    }
    $this->em->persist($ownerEntity);

    return true;
}

Here i check criterion and create value if not eist but performance is very bad,
for each ownerEntity n criteria with n criteria values. How i can improve performance?
public function createOrUpdate(
    Criterion $criterion,
    DateTime $dateImport
): CriterionValue {

    $comment = $criterion->getComment();
    $criterionDatabase = $this->getEntityManager()->getRepository(Criterion::class)
    ->findOneBy(['keyCriterion' => $criterion->getKeyCriterion()]);

    if(!$criterionDatabase) {
        $criterion->setUpdatedAt($dateImport);
        $criterionValue = $this->createCriterionValue($comment, $dateImport);
        $criterionValue->setCriterion($criterion);

        $this->getEntityManager()->persist($criterion);
        $this->getEntityManager()->persist($criterionValue);
        $this->getEntityManager()->flush();

        return $criterionValue;
    }

    $criterionDatabase->setLabelCriterion($criterion->getLabelCriterion());
    $criterionDatabase->setUpdatedAt($dateImport);

    $criterionValues = $criterionDatabase->getCriterionValues();

    $criterionValueMatch = null;
    foreach($criterionValues as $criterionValue) {
        if($comment === $criterionValue->getLabelCriterionValue()) {
            $criterionValueMatch = $criterionValue;
            break;
        }
    }

    if(!$criterionValueMatch){
        $criterionValue = $this->createCriterionValue($comment, $dateImport);
        $criterionValue->setCriterion($criterionDatabase);
        $this->getEntityManager()->persist($criterionValue);
        return $criterionValue;
    }

    return $criterionValueMatch;
}

private function createCriterionValue(
    string $comment,
    Datetime $dateImport
) : CriterionValue {
    return (new CriterionValue())->setLabelCriterionValue($comment)->setUpdatedAt($dateImport);
}

Thanks for you hep


texts: Databinding entire objects between child Vue components and the root Vue instance

texts:
I have a form in which I am collecting data from two applicants. In order to minimize HTML duplication I built an applicant Vue component that generates each applicant from a template.

Each applicant has an applicant data object. My question is regarding the best practice for data binding these applicant objects inside the component back to the root Vue instance. Here is my working code:

Vue Root Instance

var app = new Vue({
   el: '#app',
   data: {
      form: {
         borrower: {
            firstname: 'John',
            middlenames: '',
            surname: 'Rambo'
         },
         coborrower: {
            firstname: 'Homer',
            middlenames: '',
            surname: 'Simpson'
         }
      }
   }
})

Template

Component

The applicant prop gives me access to the applicant objects in the root Vue instance

Vue.component('applicant', {
   template: '#applicant-container',
   props: ['applicant'],
})

Component Instance

I pass each applicant object to the component instance through the applicant prop.

<applicant :applicant="form.borrower"></applicant>
<applicant :applicant="form.coborrower"></applicant>

This code works perfectly. Any changes that are made using the inputs generated from the components is reflected when I output the applicant objects e.g

{{ form.borrower }}
{{ form.coborrower }}

The thing that I'm unsure about is this approach best practice? The Vue's docs state:

  ...the parent may need to pass data down to the child, and the child may need to inform the parent of something that happened in the child. However, it is also very important to keep the parent and the child as decoupled as possible via a clearly-defined interface

  Every component instance has its own isolated scope. This means you cannot (and should not) directly reference parent data in a child component’s template1

Since I'm passing the parent applicant object to the component and am modifying it directly through that passed in reference using the v-model directive am I not directly modifying the parent object so therefore keeping the data coupled as the docs recommended against.

1https://vuejs.org/v2/guide/components.html#Composing-Components


texts:
I'm new to Python and want to make sure I'm not developing bad habits. If you could please review this code below and give me any tips, practice ideas or critiques you might have. Any ideas on which aspects of the language I should focus on early would also be appreciated.

#!usr/env/python
#Modeling a soccer team with substitutions

#Players stored in dictionary {Name:Numbers}
players = {}
# Player positions stored in a list
forward = []
midfield = []
defense = []
goalie = []

class Team(object):
    def __init__(self, name):
        self.name = name

class Players(object):
    def __init__(self):
        pass
#creates a player list with names, numbers, and preferred positions
    def addPlayer(self, name, number, position):
        self.name = name
        self.number = number
        self.position = position
        players[name] = number

        if position == 'forward':
            forward.append(name)
            return forward
        elif position == 'midfield':
            midfield.append(name)
            return midfield
        elif position == 'defense':
            defense.append(name)
            return defense
        elif position == 'goalie':
            goalie.append(name)
            return goalie
        else:
            print 'Only forward, midfield, defense, goalie accepted'

        print "Added %s to the team!" % name

#Should list the players currently on the field. Only 3 player sample data
players_on_field = []
class OnField(object):
        def __init__(self):
            pass
        def sub_in(self, sub_name):
            self.sub_name = sub_name
            if len(players_on_field) == 3:
                print "Field is full, sub_out first!"
                #testing some options
                #x = raw_input('Which player would you like to sub out?')
                #OnField.sub_out(x)
            else:
                players_on_field.append(sub_name)
                print "%s entering the game" % sub_name
            return

        def sub_out(self, sub_name):
            for i in range(3):
                if players_on_field[i] == sub_name:
                    del players_on_field[i]
                    print "%s has been removed from the game" % sub_name
                    return
                #testing some options
                #x = raw_input('Who would you like to sub in?')
                #OnField.sub_in(x)
            else:
                print "That player is not on the field"
                return

        def list_players_on_field(self):
            print players_on_field

#Testing
Barcelona = Team('Barcelona')
this = Players()
game = OnField()

this.addPlayer('Messi', 10, 'forward')
this.addPlayer('Neymar', 11, 'forward')
this.addPlayer('Song', 9, 'midfield')
this.addPlayer('Valdes', 1, 'goalie')
this.addPlayer('Pique', 25, 'defense')
this.addPlayer('Pedro', 8, 'forward')

print players

print 'Forward Players'
print forward
print 'Midfield Players'
print midfield
print 'Defense Players'
print defense
print 'Goalies'
print goalie

#Subsitution testing
print "Players currently on the field"
print players_on_field
game.sub_in('Messi')
game.sub_in('Pedro')
game.sub_in('Song')
game.list_players_on_field()
game.sub_out('Pedro')
print players_on_field
game.sub_in('Neymar')
print players_on_field


texts: Counting number of unique elements in a sorted container

texts:
Similar to this question, but in C++. Although my priority is performance (and correctness!) rather than readability.

#include <algorithm>
#include <iterator>
#include <cstddef>

template <typename Container>
size_t count_unique(const Container& elements)
{
    size_t result {};

    for (auto it = std::cbegin(elements), last = std::cend(elements); it != last;) {
        ++result;
        it = std::upper_bound(it, last, *it);
    }

    return result;
}


texts:
I wanted to write a c++ program to solve a 3x3 rubik's cube, but failed at it. So I picked up a 2x2 rubik's cube and wrote a program using Blindfold cubing algorithm. Can anyone help me write a more efficient program ?
This is the program I wrote

#include<iostream>
#include<string>
using namespace std;
class Solver
{
    string b = "RD' RU' R'U' RU R'F' RU R'U' R'FR DR'      ";
    string c = "F RU' R'U' RU R'F' RU R'U' R'FR F'         ";
    string d = "FU' R'U' RU R'F' RU R'U' R'FR2F'           ";
    string e = "F'D RU' R'U' RU R'F' RU R'U' R'FR D'F      ";
    string f = "F2D RU' R'U' RU R'F' RU R'U' R'FR D'F2     ";
    string g = "RF RU' R'U' RU R'F' RU R'U' R'FR F'R'      ";
    string h = "D RU' R'U' RU R'F' RU R'U' R'FR D'         ";
    string i = "U' R'U' RU R'F' RU R'U' R'FR R             ";
    string j = "R'U' R'U' RU R'F' RU R'U' R'FR R2          ";
    string k = "R2U' R'U' RU R'F' RU R'U' R'F              ";
    string l = "RU' R'U' RU R'F' RU R'U' R'FR              ";
    string n = "D2 RF RU' R'U' RU R'F' RU R'U' R'FR F'R' D2";
    string o = "D'RU' R'U' RU R'F' RU R'U' R'FR D          ";
    string p = "R'F RU' R'U' RU R'F' RU R'U' R'FR F'R      ";
    string r = "F2 RU' R'U' RU R'F' RU R'U' R'FR F2        ";
    string s = "DR F RU' R'U' RU R'F' RU R'U' R'FR F' R'D' ";
    string t = "D2 RU' R'U' RU R'F' RU R'U' R'FR D2        ";
    string u = "F RU' R'U' RU R'F' RU R'U' R'FR F'         ";
    string v = "D'F RU' R'U' RU R'F' RU R'U' R'FR F'D      ";
    string w = "D2F RU' R'U' RU R'F' RU R'U' R'FR F'D2     ";
    string x = "DF RU' R'U' RU R'F' RU R'U' R'FR F'D'      ";
    public:
    string getSol(char letter)
    {
        switch(letter)
        {
            case 'b': return b;
            case 'c': return c;
            case 'd': return d;
            case 'e': return e;
            case 'f': return f;
            case 'g': return g;
            case 'h': return h;
            case 'i': return i;
            case 'j': return j;
            case 'k': return k;
            case 'l': return l;
            case 'n': return n;
            case 'o': return o;
            case 'p': return p;
            case 'r': return r;
            case 's': return s;
            case 't': return t;
            case 'u': return u;
            case 'v': return v;
            case 'w': return w;
            case 'x': return x;
            default: return "Please Enter Correct sequence";
        }
    }
};
int main()
{
    int i = 0;
    char seq[50];
    string solution;
    Solver sol;
    cout<<"-----------------------------------------------"<<endl;
    cout<<"|            Cube Solver 2x2 v1.0             |"<<endl;
    cout<<"|            Developed by Pavan P             |"<<endl;
    cout<<"-----------------------------------------------"<<endl<<endl;
    cout<<"Enter the Sequence in small letters: ";
    cin.clear();
    cin>>seq;
    while(seq[i]!='\0')
    {
        i++;
    }
    cout<<endl;
    cout<<"-----------------------------------------------"<<endl;
    cout<<"|    This may be a solution, try buddy        |"<<endl<<endl;
    for(int j=0;j<i;j++)
    {
        solution = sol.getSol(seq[j]);
        cout<<"| "<<solution<<" |"<<endl;
    }
    cout<<"-----------------------------------------------"<<endl;
    cout<<"Thank You"<<endl;
    cin.get();
        cin.get();
    return 0;
}


texts:
Can someone review my code? I am trying to implement radix sort in JavaScript.

var numbers = [90, 46, 7, 12, 100, 68];
var length = numbers.length;
var buckets = new Array(10);

Clear();
function Clear() {
    for (var i = 0; i < 10; i++)
        buckets[i] = [];
}

RadixSort();
function RadixSort() {
    var maxElement = Math.max.apply(null , numbers);
    var maxDigits = GetDigitsCount(maxElement);
    var count = 0;
    while (count < maxDigits) {
        CopyToArray();
        for (var index = 0; index < length; index++) {
            var tenIndex = Math.pow(10, count);
            var remNumber = parseInt(numbers[index] / tenIndex, 10);
            var bucketIndex = remNumber % 10;
            buckets[bucketIndex].push(numbers[index]);
        }
        count++;
    }
    for (var i = 0; i < 9; i++) {
        var arr = buckets[i];
        var arrLength = arr.length;
        for (var j = 0; j < arrLength; j++)
            console.log(arr[j]);
    }
}

function GetDigitsCount(number) {
    var count = 0;
    while (number > 0) {
        number = parseInt(number / 10);
        count++;
    }
    return count;
}

function CopyToArray() {
    var k = 0;
    for (var i = 0; i < 10; i++) {
        var arr = buckets[i];
        var arrLength = arr.length;
        for (var j = 0; j < arrLength; j++) {
            numbers[k++] = arr[j];
        }
        buckets[i] = [];
    }
}


texts: How to set state of multiple properties in one event handler (React)

texts:
Pretty straight forwards really...I know that it's usually bad practice to repeat your code so I'm wondering how I could join handleAuthorChange() and handleContentChange() into one method. I guess it was hard for me to find a solution because I don't understand how I would know which part of the state I'm updating. I was thinking maybe embed a HTML id and check on the event target if IDs match but that seems pretty inefficient. Thanks in advance!

import React, { Component } from 'react';

class AddComment extends Component {
    state = {
        author: '',
        content: ''
    }

    handleAuthorChange = (e) => {
        this.setState({
            author: e.target.value
        });
    }

    handleContentChange = (e) => {
        this.setState({
            content: e.target.value
        });
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.addComment(this.state);
        this.setState({
            author: '',
            content: ''
        });

    }

    render() {
        return (

                <form onSubmit={ this.handleSubmit } className="card hoverable p-bottom">

ADD COMMENT

                    <input onChange={ this.handleContentChange } value={this.state.content} type="text" placeholder="comment" />
                    <input id="name" onChange={ this.handleAuthorChange } value={this.state.author} type="text" placeholder="name" />
                    <input value="submit" type="submit"/>
                </form>

        )
    }
}

export default AddComment;


texts: Adding input strings and finding occurrences of certain prefixes

texts:
A user inputs data using a keyword add word and when he wants to find  words with particular prefix then he enters find keyword.

Example input:

4
add hack
add hacker
find hac
find hak

Output:

2
0

Although the code is working fine but for bigger cases it takes too much time.Please help me in reducing its time complexity.

#include<iostream>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
vector<string> v;
vector<string>::iterator i;
//char  *a;
string a,b;
int n;
cin>>n;
while(n--)
{

    cin>>a>>b;
      //char *Split = strtok (a," ");
    //vector<char*> Split = a.split_cstr(" ");
    if(a=="add")
{
    v.push_back(b);sort(v.begin(),v.end());}
    else if(a=="find")
    {  int mycount=0;
         //mycount = std::count (v.begin(), v.end(),find(b));
        //strncmp(string1, string2, strlen(string2))
        //          cout<<mycount<<endl;
        std::string prefix(b);

        //std::set<std::string>::iterator i;
        for (i = v.begin(); i != v.end(); ++i)
        {
           if ((*i).compare(0, prefix.length(), prefix) == 0)
              mycount++;
            else if((*i).compare(0, prefix.length(), prefix) == 1)
              break;
        }
        cout<<mycount<<endl;
    }

 }

}


texts: Can you help me optimize this code that calculates a Simple Moving Average?

texts:
The below function takes in a dataframe consisting of an excel sheet with the Price column. It works correctly however it looks unnecessarily long for something quite simple. Basically calculating a Simple Moving Average based on Price : SMA = Sum of all prices in a period/period:
def SimpleMA(Timing, n):
    sum = 0
    count = 0
    for i in range(n, len(df.index)):
        count += 1
        sum += df['Price'][i]
        if count == Timing:
            df.loc[i, f'MA_{Timing}'] = sum/Timing
            n += 1
            if n != len(df.index) - Timing:
                SimpleMA(Timing, n)
            else:
                plt.figure(figsize = (20,6))
                plt.title("Price vs MA")
                plt.plot(x, df[f'MA_{Timing}'], x, df['Price'])
                plt.show()
            break


texts:
The following code works, but I'm sure there's a cleaner way to implement it and I'd appreciate any guidance on how to go about that.

I have a class Result which I want to sort sometimes by score (which is just an int) and sometimes by parts which are strings whose first char is a digit in [1,7] and whose second char is one of C, D, H, S, N (which are in alphabetical order except that the N needs to come last).

public class Result : IEquatable<Result>, IComparable<Result>
{
    private int score;// Unique NS value for all par contracts.
    private string pars;// All possible pars on this deal.

  // Default comparer for Result type.
    public int CompareTo(Result compareResult)
    {
        // A null value means that this object is greater.
        if (compareResult == null)
            return 1;

        else
            return this.Score.CompareTo(compareResult.Score);
    }
    public override int GetHashCode()
    {
        return score;
    }

    public bool Equals(Result other)
    {
        if (other == null) return false;
        return (this.Score.Equals(other.Score));
    }

    public override string ToString()
    {
        return "Score: " + Score + "   Par: " + Pars;
    }
};

public class InitArray
{
    public static readonly char[] bridgeChar = new char[Constants.CHAR_MAX];

    static InitArray()
    {
        for (int i = 0; i < bridgeChar.Length; i++)
        {
            bridgeChar[i] = Char.ToUpper((char)i);
        }
        //Only concerned with ordering C, D, H, S, N=NT.
        bridgeChar['N'] = bridgeChar['Z'];
    }
};

static void Main(string[] args)
{

    Result result = new Result();

    // Create a list of results.
    List<Result> results = new List<Result>();

    // Add results to the list.
    results.Add(new Result() { Score = 110, Pars = "3C" });
    results.Add(new Result() { Score = -200, Pars = "4Hx" });
    results.Add(new Result() { Score = -100, Pars = "3Hx" });
    results.Add(new Result() { Score = -100, Pars = "3Sx" });
    results.Add(new Result() { Score = 400, Pars = "3N" });

    // Sort on the list using the default comparer.

    results.Sort();

    // Sort calling the Sort(Comparison(T) overload using
    // an anonymous method.
    results.Sort(delegate (Result x, Result y)
    {
        if (x.Score == 0 && y.Score == 0) return 0;
        else if (x.Score == 0) return -1;
        else if (y.Score == 0) return 1;
        else return x.Score.CompareTo(y.Score);
    });

    Console.WriteLine("\nAfter sort by score:");
    foreach (Result aResult in results)
    {
        Console.WriteLine(aResult);
    }

    // Sort on pars using an anonymous method.
    results.Sort(delegate (Result x, Result y)
    {
        if ((x == null) && (y == null)) return 0;
        else if (x == null) return -1;
        else if (y == null) return 1;
        else
        {// Compare the two strings.
            if (x.Pars[0].CompareTo(y.Pars[0]) == 0)
            {
                // If the strings start with the same character, sort them by Denomination.
                return InitArray.bridgeChar[y.Pars[1]].CompareTo(InitArray.bridgeChar[x.Pars[1]]);
            }
            else
            { // sort them with ordinary string comparison.
                return x.CompareTo(y);
            }
        }
    });

    results.Reverse(); //Need them in ascending order.

    Console.WriteLine("\nAfter sort by denom:");
    foreach (Result aResult in results)
    {
        Console.WriteLine(aResult);
    }
  }
}

Output is as required:

After sort by score:
Score: -200   Par: 4Hx
Score: -100   Par: 3Hx
Score: -100   Par: 3Sx
Score: 110   Par: 3C
Score: 400   Par: 3N

After sort by denom:
Score: 110   Par: 3C
Score: -100   Par: 3Hx
Score: -100   Par: 3Sx
Score: 400   Par: 3N
Score: -200   Par: 4Hx


texts: Pinging the user requested host - is this code insecure?

texts:
<?php
    $userinput = $_GET['host'];
    $e = escapeshellcmd($userinput);
    $arr = (explode(".",$e));
    $num = count($arr);
    $times = (int)$_GET['times'];
    $time = (range(1,51));
    if (!isset($time[$times])){
        $times = 5;
    }
    function isValidURL($url){
        return preg_match('/(www\.)?(.)*[\.](.)*$/i', $url);
    }
    if($num == "2"){
        if(isValidURL($e)){
            echo"
", passthru("ping -n $times $e"),"
";}
        else {
            echo "The URL or IP $e isn't valid
";
    }
?>

This code is pinging the user requested host. Is this code insecure because I am using the  passthru() function?

I am using explode to know if it's domain.com or just text and a regular expression to validate its not texttext.text. Is there way for the user to access my terminal with this?


texts:
I'm a beginner in Python. I wrote this code which encrypts and decrypts text using Caesar chipher. I wrote it in many days and optimized it many times. But how it can be improved more?

I've used lists because they are flexible and they serve my algorithm.

print('''# This is version 1.0 Caesar Encryption-Decryption Tool.
# This tool is written by Mahmoud Naguib and it will be improved.
# You can contact me at : https://www.facebook.com/naguibarea
-----------------------------------------------------------------''')
letters_table = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
                 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

def caesar():
    # This line iterates through every letter in the string.
    for letter in range(len(text)):
        # If there is a letter which isn't an English alphabet.
        if not text[letter].isalpha():
            letters_table.append(text[letter])
        # This line locates the letter's numeric value in other words its position.
        position = letters_table.index(text[letter])
        # This line adds the key entered by the user to the letter's
        # numeric value to reach the new letter.
        step = position + key
        # if the encrypted letter's numeric value is greater than 25
        # then its new numeric value is the old numeric valuu %
        # the number of English alphabet letters.
        if step > 25:
            step %= 26
        # If step is lower than 0 then we need to add 26 to it to complete the decryption process.
        if step < 0:
            step += 26
        # If position is greater than 25 that means it's not an alphabet
        # value and it will be printed without adding the key(the letter will be printed as it is).
        if position > 25:
            step = position
        # This line locates the letter's numeric value(its position) and prints the new letter.
        # end is a keyword argument to combine all letters together.
        print(letters_table[step], end='')
    print('\n' + '-----------------------------------------------------------------')

while True:
    while True:
        # This line ask the user if he wants to encrypt or decrypt a text.
        mode = input('Type E for enryption mode or D for decryption mode : ').upper()
        if mode == 'D' or mode == 'E':
            break
        else:
            print('You must enter E or D ! ')
    # This line takes the user's text and converts it to uppercase to search for it in the letter's table.
    while True:
        text = input('Enter your text : ').upper()
        if len(text) != 0:
            break
        else:
            print('You can not leave it blank ! ')
    while True:
        try:
            # This line takes the user's key.
            key = int(input('Enter a key : '))
            if type(key) == int:
                break
        except ValueError:
            print('You must enter an integer number ! ')
    # If the user wants to encrypt a text it will call the caesar() function.
    if mode == 'E':
        caesar()
    # If the user wants to decrypt a text it will make the key value negative so that there's a reverse process
    # and it will call the caesar() function.
    elif mode == 'D':
        key = 0 - key
        caesar()


texts:
I'm trying to solve this problem. After a couple of tries, this is what I pulled off:

        #include<stdio.h>
    #define primeLimit 100000

    int prime (long int Start2,  long int Stop2 )
    {
       long int a[primeLimit+1];
       long int i,j,k,l;
       for (i=Start2;i<=Stop2;i++)
       {
           a[i-Start2] = 1;
       }

       for (i=Start2;i<=Stop2;i++)
       {
            if (a[i-Start2]!= 0 && i!=1)
            {
                for (j=3; j*j< i;j=j+2)
                {
                    if(i%j==0)
                        break;

                }
                if(j*j > i)
                {
                    printf(" \n %ld",i);
                    l = i;
                    if (i<=46340)
                    {
                    for (k = i*i; k< Stop2;)
                         {
                                while (k<46340 && (k-Start2 <100000))
                                a[k-Start2] = 0;
                                k = k+l;

                         }
                    }
                }
                else
                {
                    a[i-Start2] = 0;
                }
            }
       }

        return 0;
    }

    int main (void)
    {

       long int start,stop,a,look;

       scanf("%ld", &look);

       for (a=1;a<=look;a++)
       {
           scanf("%ld %ld", &start,&stop);
            prime (start,stop);
       }

       return 0;
    }

Here I used if (i<=46340) because the 46340*46340 exceeds the limit of a long int on a 32-bit machine (2,147,483,647). For the same purpose, I used while (k<46340 && (k-Start2 <100000)).

This code exceeds the time limit (6 seconds) of the SPOJ problem rule.

How can this be faster?


texts: GCD calculation - A cross of the Euclidean and the Binary algorithm

texts:
I was reading Knuth's The Art of Computer Programming - Volume 2 (Seminumerical Algorithms) Third Edition. I saw the two algorithms (A and B). A method (due to V. C. Harris) was mentioned (in page 341), which I quote:

  V. C. Harris [...] has suggested an interesting cross between Euclid's algorithm and the binary algorithm. If \$u\$ and \$v\$ are odd, with \$u\geq v>0\$, we can always write
  $$u=qv\pm r$$ where \$0\leq r<v\$ and \$r\$ is even; if \$r\neq0\$ we set \$r\leftarrow r/2\$ until \$r\$ is odd, then set \$u \leftarrow v, v \leftarrow r\$ and repeat the process. In subsequent iterations, \$q\geq3\$

Now, I've noted that often \$r\$ turns out to be grater than its original value i.e. if we would have used the simple equation, shown below: $$u=qv+r$$just like in the ordinary Euclidean algorithm and then I've tried to halve \$r\$ (if \$r\$ is even). Now, I've implemented this approach in Java as follows (I am just providing the method):

public static long gcd(long a, long b) {
    int a0 = Long.numberOfTrailingZeros(a);
    int b0 = Long.numberOfTrailingZeros(b);
    // Make both of them odd.
    a >>>= a0;
    b >>>= b0;
    // t is the common power of 2 (may be 0)
    int t = a0 < b0 ? a0 : b0;
    while ((a & b) != 0) {  // i.e. both are non-zero
        if (a > b) {
            a %= b;
            a >>>= Long.numberOfTrailingZeros(a);
        } else {
            b %= a;
            b >>>= Long.numberOfTrailingZeros(b);
        }
    }
    return (a | b) << t;    // {the non-zero value of the two} * 2^t
}

Now, I'd like to ask:

Does my approach have any significant advantages?
Can there be (I'm sure there will be) any improvements?
Would you use it in your library? :-)

PS. I am using the if to remove the need of a third temporary variable.


texts: Create a background-image over a background-color with different opacities for each element

texts:
Here the demo

The code below creates a background-image over a background-color with different opacities for each element. Is there a cleaner way of achieving this?

.component{
 min-height: 100vh;
 min-width:100vw;
 font-size:5em;

 display:flex;
 justify-content: center;
 align-items: center;
 color:black;

}
.component::before{
 content: "";

 position: absolute;
 top: 0;
 left: 0;

 width: 100%;
 height: 100%;
 min-height: 100vh;
 min-width:100vw;

 opacity:1;
 z-index:-1;
 background: url("https://www.pngarts.com/files/5/Los-Angeles-Free-PNG-Image.png") center 100px/500px repeat;
}

.component_background_color::after{
 content: "";

 position: absolute;
 top: 0;
 left: 0;

 width: 100%;
 height: 100%;
 min-height: 100vh;
 min-width:100vw;

  opacity:0.3;
 z-index:-2;
 background:green;
}

      Awesome WebPage


texts: Encryption and decryption using alphabetic shifts

texts:
My first piece of code encrypts text by moving each letter in the string 5 letters across in the alphabet.

encrypt = input('Enter text to encrypt : ')
encrypt = encrypt.lower().replace(" ", "")
for i in encrypt:
    print(chr(ord(i) + 5))
decrypt = input('Enter text to decrypt : ')
decrypt = decrypt.lower().replace(" ", "")
for i in decrypt:
    print(chr(ord(i) - 5))

The output of this code if I enter 'hello' would be 'mjqqt'.

To decrypt, I do the reverse, I move each letter 5 letters down the alphabet.

Below is my second piece of code that encrypts text against a code word. For example...

If I had 'abc' for the codeword and 'bcd' for the text to encrypt. Then: (a + b = 1 + 2) and this is repeated for each letter in the two words. The output of having my codeword as 'abc' and the word to encrypt and 'bcd' would be 'ceg'.

codeword = input('Enter codeword : ')
codeword = codeword.replace(" ", "")

encrypt = input('Enter text to encrypt : ')
encrypt = encrypt.replace(" ", "")

j = 0
for i in codeword:
    print(chr(ord(encrypt[j])+ ord(codeword[j])-96))
    j+=1


texts: Finding missing void keywords in C source code

texts:
I'm writing a bash script to search C source files and find the lines where I missed the void keyword (unlike in C++, in C, empty parameter lists have to be indicated with the void keyword).

I read that I shouldn't use for but while: https://mywiki.wooledge.org/DontReadLinesWithFor

I find that for has an easier to follow, top-down structure (first I write the command that produces the items to be iterated, then I write what to do with each).

I understand that if a filename contained a newline it would cause trouble in case of for; however, with IFS=$'\n'; set -f I would think all other problems are solved.

My code using for:

#!/bin/bash

returnTypeOpt_BRE='\([a-zA-Z_][a-zA-Z0-9_]\{0,\}[*  ]\{1,\}\)\{0,1\}'
spaceOpt_BRE=$'[ \t\r]\\{0,\\}'
functionName_BRE='\([a-zA-Z_][a-zA-Z0-9_]\{0,\}\)'
declarationMissingVoid_BRE="^$returnTypeOpt_BRE$spaceOpt_BRE$functionName_BRE$spaceOpt_BRE($spaceOpt_BRE)$spaceOpt_BRE;$spaceOpt_BRE\$"

targetFolder_Path="$1"
if [ $# -eq 0 ]; then
    targetFolder_Path="."
fi

IFS=$'\n'; set -f; for file in $( find "$targetFolder_Path" -name '*.c' -or -name '*.h' ); do
    printf "%s\n" "$file"
    for line in $( grep --basic-regex --regexp=$declarationMissingVoid_BRE $file ); do
        printf "\t>%s\n" "$line"
    done
done; unset IFS; set +f

My code using while:

#!/bin/bash

returnTypeOpt_BRE='\([a-zA-Z_][a-zA-Z0-9_]\{0,\}[*  ]\{1,\}\)\{0,1\}'
spaceOpt_BRE=$'[ \t\r]\\{0,\\}'
functionName_BRE='\([a-zA-Z_][a-zA-Z0-9_]\{0,\}\)'
declarationMissingVoid_BRE="^$returnTypeOpt_BRE$spaceOpt_BRE$functionName_BRE$spaceOpt_BRE($spaceOpt_BRE)$spaceOpt_BRE;$spaceOpt_BRE\$"

targetFolder_Path="$1"
if [ $# -eq 0 ]; then
    targetFolder_Path="."
fi

while IFS=; read -u 3 -r -d $'\0' file; do
    printf "%s\n" "$file"
    while IFS=; read -u 4 -r line; do
        printf "\t>%s\n" "$line"
    done 4< <( grep --basic-regex --regexp=$declarationMissingVoid_BRE $file )
done 3< <( find "$targetFolder_Path" -name '*.c' -print0 -or -name '*.h' -print0 )

So, for me both scripts work correctly, and produce the same result.

Beyond the "filenames with newlines" issue is there anything else that would make while better? Can you show me a test case?

If I had to solve similar but different (possibly more complex) tasks would I have problems with for?


texts: Implementing Gaussian integers in Haskell

texts:
Currently my code (at GitHub) is this:

module Gaussian where

import qualified Data.Complex as Complex
  -- Enables toComplex.
  -- Qualified to avoid clashing.

data Gaussian = (:+)
  {
    real :: Integer,
    imaginary :: Integer
  } deriving
    (Show, Read, Eq)
  -- The gaussian integer type.
  -- A gaussian integer is a complex number of the form a + bi where a and b are integers.

instance Num Gaussian
  where
    (a1 :+ b1) + (a2 :+ b2) = (a1 + a2) :+ (b1 + b2)
    (a1 :+ b1) - (a2 :+ b2) = (a1 - a2) :+ (b1 - b2)
    (a1 :+ b1) * (a2 :+ b2) = (a1 * a2 - b1 * b2) :+ (a1 * b2 + a2 * b1)
    abs (a :+ b) = ((a ^ two) + (b ^ two)) :+ 0
      where
        two = 2 :: Integer
          -- This prevents compiler warnings about defaulting types.
    signum = id
    negate (a :+ b) = negate a :+ negate b
    fromInteger x = x :+ 0
  -- The Num instance for Gaussian.
  -- We use the euclidean norm as abs. norm(a + bi) = a^2 + b^2

i :: Gaussian
i = 0 :+ 1
  -- The imaginary unit, equal to sqrt(-1).

magnitude :: Floating c => Gaussian -> c
magnitude (a :+ b) = sqrt $ (fromInteger a ^ two) + (fromInteger b ^ two)
  where
    two = 2 :: Integer
      -- This prevents compiler warnings about defaulting types.

norm :: Gaussian -> Integer
norm (a :+ b) = (a ^ two) + (b ^ two)
  where
    two = 2 :: Integer
      -- This prevents compiler warnings about defaulting types.

conjugate :: Gaussian -> Gaussian
conjugate (a :+ b) = (a :+ negate b)
  -- The complex conjugate.
  -- Effectively flips about the real axis.

rotate_cw :: Gaussian -> Gaussian
rotate_cw (a :+ b) = (b :+ negate a)
  -- Rotate a gaussian integer clockwise.
  -- Equivalent to multiplying by i.

rotate_ccw :: Gaussian -> Gaussian
rotate_ccw (a :+ b) = (negate b :+ a)
  -- Rotate a gaussian integer counterclockwise.
  -- Equivalent to multiplying by -i.

flip_x :: Gaussian -> Gaussian
flip_x (a :+ b) = (negate a :+ b)
  -- Flips on imaginary axis.
  -- Analogous to conjugate.

flip_y :: Gaussian -> Gaussian
flip_y = conjugate
  -- Alias for conjugate.
  -- See conjugate.

swap_x_y :: Gaussian -> Gaussian
swap_x_y (a :+ b) = (b :+ a)
  -- Utility function, swaps real and imaginary axes.

toComplex :: Num p => Gaussian -> Complex.Complex p
toComplex (a :+ b) = (fromInteger a Complex.:+ fromInteger b)
  -- Converts a Gaussian to any complex number (Num p => Complex p)
  -- Fully qualified operators to avoid clashing.

As far as I know, my brace/indentation style isn't used anywhere else, so I'm a bit worried about that.


texts:
I wrote my own exception class, deriving from std::runtime_error to have Error-IDs, timestamps and inner exceptions. It seems to work, but are there any drawbacks?

The only thing I see is the deep-copy in the copy-constructor, which is not efficient, when there are many nested exceptions. But exceptions should be rare and not be nested too much, so I think it's a downside I can cope with.

#pragma once

#include <stdexcept>
#include <string>
#include <sstream>
#include <time.h>
#include <memory>

class MyException : public std::runtime_error
{
public:
    MyException(const MyException& exception)
        : std::runtime_error(exception.what()),
        exceptionId(exception.id()),
        ts(exception.timestamp()),
        innerException(NULL)
    {
        if (exception.inner() != NULL)
        {
            innerException = new MyException(*exception.inner());
        }
        else
        {
            innerException = NULL;
        }
    }

    MyException(const std::string& _Message)
        : std::runtime_error(_Message),
            exceptionId(0),
        innerException(NULL)
    {
        time(&ts);
    }

    MyException(const std::string& _Message, unsigned int id)
        : std::runtime_error(_Message),
        exceptionId(id),
        innerException(NULL)
    {
        time(&ts);
    }

    MyException(const std::string& _Message, unsigned int id, MyException* innerException)
        : std::runtime_error(_Message),
        exceptionId(id),
        innerException(new MyException(*innerException))
    {
        time(&ts);
    }

    virtual ~MyException()
    {
        delete innerException;
    }

    unsigned int id() const { return exceptionId; }
    time_t timestamp() const { return ts; }
    const MyException* inner() const { return innerException; }

private:
    unsigned int exceptionId;
    time_t ts;
    const MyException* innerException;
};

This is how I would use it:

void handleException(MyException *ex)
{
    cout << "exception " << ex->id() << " - " << ex->what() << endl;
    const MyException* innerException = ex->inner();
    int t = 1;
    while (innerException != NULL)
    {
        for (int i=0; i<t; ++i)
        {
            cout << "\t";
        }
        ++t;
        cout << "inner exception " << innerException->id() << " - " << innerException->what() << endl;
        innerException = innerException->inner();
    }
}

void throwRecursive(int temp)
{
    if (temp == 0)
    {
        throw runtime_error("std::runtime_error");
    }

    try
    {
        throwRecursive(--temp);
    }
    catch (MyException &ex)
    {
        throw MyException("MyException", (temp+1), &ex);
    }
    catch (exception &ex)
    {
        throw MyException(ex.what(), (temp+1));
    }
}

void myExceptionTest()
{
    try
    {
        throwRecursive(3);
    }
    catch (MyException &ex)
    {
        handleException(&ex);
    }
}

And the output:

exception 3 - MyException
        inner exception 2 - MyException
                inner exception 1 - std::runtime_error

I already found out here that I'm violating the rule of three, having forgotten the copy assignment operator.

Other issues mentioned: cloning, reserved names and throw specifications.

Can anyone tell me more about that?