text:
Q: Double reverse TCP proxy in C#? Edit: realized I need an implementation of this on C#:
https://en.wikipedia.org/wiki/Traversal_Using_Relays_around_NAT
I'll try to find one, if anyone has one I'll appreciate it, thanks!
I might have just made up that name on the spot.
What I'm trying to do is have a computer that is behind NAT and will need to provide a service connect to a server.
Then, I would connect to that server using a third computer and interact with the TCP stream initiated by the first computer, in a way that would work just as if I had connected straight to it.
Found a way to create a forward proxy, which works great:
blog.brunogarcia.com/2012/10/simple-tcp-forwarder-in-c.html
using System;
using System.Net;
using System.Net.Sockets;

namespace TcpProxy
{
    class Program
    {
        static void Main(string[] args)
        {
            new TcpForwarderSlim().Start(
    new IPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse("69")),
    new IPEndPoint(IPAddress.Parse("91.198.174.192"), int.Parse("80")));
        }

    }
    public class TcpForwarderSlim
    {
        private readonly Socket _mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        public void Start(IPEndPoint local, IPEndPoint remote)
        {
            _mainSocket.Bind(local);
            _mainSocket.Listen(10);

            while (true)
            {
                var source = _mainSocket.Accept();
                var destination = new TcpForwarderSlim();
                var state = new State(source, destination._mainSocket);
                destination.Connect(remote, source);
                source.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, OnDataReceive, state);
            }
        }

        private void Connect(EndPoint remoteEndpoint, Socket destination)
        {
            var state = new State(_mainSocket, destination);
            _mainSocket.Connect(remoteEndpoint);
            _mainSocket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, OnDataReceive, state);
        }

        private static void OnDataReceive(IAsyncResult result)
        {
            var state = (State)result.AsyncState;
            try
            {
                var bytesRead = state.SourceSocket.EndReceive(result);
                if (bytesRead > 0)
                {
                    state.DestinationSocket.Send(state.Buffer, bytesRead, SocketFlags.None);
                    state.SourceSocket.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, OnDataReceive, state);
                }
            }
            catch
            {
                state.DestinationSocket.Close();
                state.SourceSocket.Close();
            }
        }

        private class State
        {
            public Socket SourceSocket { get; private set; }
            public Socket DestinationSocket { get; private set; }
            public byte[] Buffer { get; private set; }

            public State(Socket source, Socket destination)
            {
                SourceSocket = source;
                DestinationSocket = destination;
                Buffer = new byte[8192];
            }
        }
    }
}

Could anyone point me to the right direction?

A: UPNP can open a port on a properly configured router.
STUN, ICE, and TURN use intermediary servers to connect when ports can't be opened. There are open source server implementations.
UDP can use UDP Hole Punching.
This answer provides a more detailed explaination but not much C# help.


text: Q: Probability of triangles in random graph $G(n,p)$ - binomial random graph on $n$ vertexes and with constant probability $p$ of edges. In general, is there formula for calculating probability that graph has no triangles. I'm not intered at asymptotic equality of this probability, for this purpose more articles in web.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Direct assignment to the reverse side of a related set is prohibited. I added a property and got this error I don't understand why i got this error, I just added a new foreign key property to Rest model and it doesn't work:
Error
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use exercises.set() instead.

I don't know if the name "rest" is causing I already changed the name of the property but I can't make it work.
models.py
class Routine(models.Model):
    name = models.CharField(max_length=30)
    creation_date = models.DateField(auto_now_add=True)
class Workout(models.Model):
    name = models.CharField(max_length=30)
    creation_date = models.DateField(auto_now_add=True)
    routine = models.ForeignKey(Routine, related_name='workouts', on_delete=models.CASCADE)
class Exercise(models.Model):
    index = models.IntegerField()
    video_url = models.URLField(max_length=200)
    workout = models.ForeignKey(Workout, related_name='exercises', on_delete=models.CASCADE)
class Rest(models.Model):
    index = models.IntegerField()
    duration = models.IntegerField()
    workout = models.ForeignKey(Workout, related_name='rests', on_delete=models.CASCADE)
    routine = models.ForeignKey(Routine, related_name='rests', on_delete=models.CASCADE)

serializers.py
class WorkoutSerializer(serializers.ModelSerializer):
    exercises = ExerciseSerializer(many=True)
    rests = RestSerializer(many=True)

    class Meta:
        model = Workout
        fields = ['id', 'name', 'creation_date', 'exercises', 'rests']

    def create(self, validated_data):
        exercises_data = validated_data.pop('exercises')
        rests_data = validated_data.pop('rests')
        workout = Workout.objects.create(**validated_data)

        for exercise_data in exercises_data:
            Exercise.objects.create(workout=workout, **exercise_data)

        for rest_data in rests_data:
            Rest.objects.create(workout=workout, **rest_data)

        return workout

class RoutineSerializer(serializers.ModelSerializer):
    workouts = WorkoutSerializer(many=True)
    rests = RestSerializer(many=True)

    class Meta:
        model = Routine
        fields = ['id', 'name', 'creation_date', 'workouts', 'rests']

    def create(self, validated_data):
        workouts_data = validated_data.pop('workouts')
        rests_data = validated_data.pop('rests')

        routine = Routine.objects.create(**validated_data)

        for workout_data in workouts_data:
            Workout.objects.create(routine=routine, **workout_data)

        for rest_data in rests_data:
            Rest.objects.create(routine=routine, **rest_data)

        return routine


text:
Q: secure hbase application - kerberos authentication I am running a infinite loop for testing expiration of kerberos credentials, I have the following code.
UserGroupInformation.loginUserFromKeytab(user, keytablocn);
Configuration config = HBaseConfiguration.create();
HConnection conn = HConnectionManager.createConnection(config);

for (;;) {
HTableInterface ht = conn.getTable(tableName);
getAndPriintRow(rowkey);
}

I expect the kerberos credentials to expire about 10 hrs after the program starts (a kinit on the linux shell using keytab requires relogin after about 10hrs in our environment).
However what I see in the log after about 10 hrs is:

15/03/06 12:39:54 DEBUG
  org.apache.hadoop.security.UserGroupInformation: PrivilegedAction
  as:*(auth:KERBEROS)
  from:org.apache.hadoop.hbase.ipc.RpcClient$Connection.handleSaslConnectionFailure(RpcClient.java:796)
  15/03/06 12:39:54 DEBUG
  org.apache.hadoop.security.UserGroupInformation: Initiating logout for
  * 15/03/06 12:39:54 DEBUG org.apache.hadoop.security.UserGroupInformation: hadoop logout
  15/03/06 12:39:54 DEBUG
  org.apache.hadoop.security.UserGroupInformation: Initiating re-login
  for *** 15/03/06 12:39:55 DEBUG
  org.apache.hadoop.security.UserGroupInformation: hadoop login

The checkTGTAndReloginFromKeytab() method was somehow invoked. I cant figure out how this method got invoked. This allows the program to run perpetually. Is this by design and what does the relogin ?

A: This is as per design. When session expires it will try to relogin.
This functionality enables HBase client's to stay up for eternity when they are used in Application Servers.


text:
Q: Replace call to System.currentTimeMillis() at runtime I am using a JAR file that uses System.currentTimeMillis() to get the current system time. I want to call my current time method (nanoTime()) when a function of JAR file calls System.currentTimeMillis().
Any suggestion how I can cover this?

A: Well... implementing you own java.lang.System comes into mind. But then you'd also need set your bootclasspath and who knows what else to make this work. You might end up patching rt.jar.
It will be tricky though to reuse the "real" System class for all other purposes.
And I hope you plan to do this on one machine only - I can't imagine the trouble to deploy such a system.


text:
Q: How to make smooth UITableView in objective-C I am working with an IOS application. In my project have several UITableView with many rows, and each row has two images. When I scroll fast then It can't load cells smoothly. How can I scroll smoothly ???
N.B: I don't want to load all rows at a time.
Please Help
Edited:
Here is my code :
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
UITableViewCell *cell;
float sca=appDelegate.deviceScaleFloat;
float XOffset=0*sca;

cell = [[UITableViewCell alloc] init];
cell.opaque = YES;

cell.selectionStyle = UITableViewCellSelectionStyleNone;

UIImage *backImg;

backImg= [UIImage imageNamed:[NSString stringWithFormat:@"background-goal-collect%@.png",ipadExtention]];
backImg=[self scaleWithScaleFactor:backImg];

UIImageView *btnBuyImageView=[[UIImageView alloc]initWithImage:backImg];
btnBuyImageView.frame=CGRectMake(XOffset, 0, backImg.size.width, backImg.size.height);
[cell.contentView addSubview: btnBuyImageView];

for (int i=0; i<5 && indexPath.row*5+i<[catFishes count]; i++) {
    int productIndex = (int)indexPath.row*5 + i;
    DBProductAttributes *productAttributes = [allProductAttributes objectAtIndex:productIndex];
    DBProductInfo *productInfo = [catFishes objectAtIndex:productIndex];

    UIImage *frameImage = [UIImage imageNamed:[NSString stringWithFormat:@"background-element-%d%@.png",productAttributes.elementid,ipadExtention]];
    frameImage=[self scaleWithScaleFactor:frameImage];UIImageView *frameView = [[UIImageView alloc] initWithImage:frameImage];

    frameView.frame = CGRectMake((frameImage.size.width*i)+10*sca+5*i*sca, 5*sca , frameImage.size.width, frameImage.size.height);
    frameView.userInteractionEnabled=YES;
    [cell.contentView addSubview:frameView];

    MyTapGestureRecognizer *tapGesture=[[MyTapGestureRecognizer alloc] init];
    tapGesture.tag=productIndex;
    [tapGesture addTarget:self action:@selector(buttonClicked:)];
    [frameView addGestureRecognizer:tapGesture];

    NSString *IconStr = [NSString stringWithFormat:@"i%db.png", productInfo.productid];
    UIImage *btnImg = [UIImage imageNamed:IconStr];

    if(![self isProductPurchesed:productInfo.productid])
    {
        if([ITIWAppDelegate blackimageforstore]>0)
        {
            btnImg = [self getBlackAndWhiteVersionOfImage:btnImg];
        }
    }
    UIImageView *imageIconView;
    imageIconView = [[UIImageView alloc] initWithImage:btnImg];
    imageIconView.frame = CGRectMake(frameView.frame.origin.x+frameImage.size.width-64*sca, frameView.frame.origin.y/*+frameImage.size.height-64*sca*/ , 64*sca, 64*sca);
    imageIconView.opaque = YES;
    [cell.contentView addSubview:imageIconView];

    UILabel *name;
    name = [[UILabel alloc] initWithFrame:CGRectMake(frameView.frame.origin.x, frameView.frame.origin.y+62*sca, frameImage.size.width-0*sca, 18.0f*sca)];
    name.text = productInfo.product_name;
    name.font = [UIFont fontWithName:@"Georgia" size:12.0f*sca];
    name.adjustsFontSizeToFitWidth = YES;
    name.textAlignment = NSTextAlignmentCenter;
    if(![self isProductPurchesed:productInfo.productid])
        name.backgroundColor=[UIColor grayColor];
    else
    name.backgroundColor = [UIColor colorWithRed:colorCodeDragonBook[productAttributes.elementid-1][0]/255.0f green:colorCodeDragonBook[productAttributes.elementid-1][1]/255.0f blue:colorCodeDragonBook[productAttributes.elementid-1][2]/255.0f alpha:1.0f];
    name.textColor = [UIColor colorWithWhite:1.0 alpha:1.0];
    //name.shadowColor = [UIColor blackColor];
    name.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
    [cell.contentView addSubview:name];

    NSArray *otherElements = [productAttributes.otherElementid componentsSeparatedByString:@","];
    int k=0;

    UIImage *habitatFlag = [UIImage imageNamed:[NSString stringWithFormat:@"flag-%d.png",productAttributes.elementid]];    UIImageView *habitatFlagView = [[UIImageView alloc] initWithImage:habitatFlag];
    habitatFlagView.frame = CGRectMake(frameView.frame.origin.x-1*sca, frameView.frame.origin.y-1*sca , 15*sca, 22*sca);
    [cell.contentView addSubview:habitatFlagView];
    k+=15;
    for (int i=0; i<[otherElements count]; i++) {
        int otherElementid = [[otherElements objectAtIndex:i] intValue];

        if(otherElementid==productAttributes.elementid) continue;

        UIImage *habitatFlag = [UIImage imageNamed:[NSString stringWithFormat:@"flag-%d.png",otherElementid]];     UIImageView *habitatFlagView = [[UIImageView alloc] initWithImage:habitatFlag];
        habitatFlagView.frame = CGRectMake(frameView.frame.origin.x+k*sca-1*sca, frameView.frame.origin.y-1*sca , 15*sca, 22*sca);
        [cell.contentView addSubview:habitatFlagView];
        k+=15;
    }
}

return cell;
}

Problem is occurring when the cells are going to off screen, the tableview release all cells of off screen. And when after that I want to scroll the cells are reloading. I think it is not optimal to load cells. But I don't know how to optimize this.

A: the best you have to do is load the images asynchronously, and not in the main thread.
If you want, you can use my ImageLoader project : https://github.com/celian-m/ImageLoader/blob/master/ImageLoader.swift
All you have to do is using CMImageView instead of UIImageView.
Then you can do [myImageView assignImageFromUrl:YOUR_URL]
This will load your images in the background thread, in FIFO mode, and save it in memory and disk cache ( i.e. : you need to load each image only 1 time ).

A: You can make use of SDWebImageCache so that it'll cache the images in disk and the loading of images becomes much faster.

A: dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0ul);
dispatch_async(queue, ^{
    //set image here
});

What about setting the image async in the tableview callback:
- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath

May I ask whether the images are web images or local images?


text: Q: Pulsaudio - Audio crashes after about thirty seconds of running on Asus Chromebook C202SA-YS02-GR running Kubuntu I am running Kubuntu on my Asus Chromebook C202SA-YS02-GR (Kubuntu 22.04). There is nothing else on my system other than Kubuntu. An issue that I have run in to is that Pulseaudio crashes after about thirty seconds of running any audio, the audio crashes (turns in to a continuous beep) and won't work again until I run killall pulseaudio; pulseaudio -k  ; rm -r ~/.config/pulse/* ; rm -r ~/.pulse* and  pulseaudio --start to restart pulseaudio. I also get an error that says that ~/.config/pulse doesn't exist.(Verbose: rm: cannot remove '/home/logan/.pulse*': No such file or directory)


text:
Q: Jquery reg ex replace - nth occurence of integer within multi dimensional array I'm not sure if this is possible, I have spent all afternoon struggling with it.
I have a table with rows of inputs, the inputs have the following names to define a multidimensional array.
attribute_set[1][options][1][attr_id]
attribute_set[1][options][1][attr_stock]
attribute_set[1][options][1][attr_price]
attribute_set[1][options][2][attr_id]
attribute_set[1][options][2][attr_stock]
attribute_set[1][options][2][attr_price]
Using a real world example attribute_set may be say 'Length' of a product, and each options would be lengths available (1m, 2m etc.) Each length options may have a unique stock level or price. so for example [options][1][attr_name], [options][1][attr_stock], [options][1][attr_price].
The user can click 'add attribute' and define a new row of attributes using Jquery. Each time this is clicked I need to be able to increment the second integer key in the string, for example:
Using the above set of attributes, the user clicks 'add attribute', I need to create an input with the name:
attribute_set[2][options][4][attr_name], attribute_set[2][options][4][attr_stock] - then 5,6,7 etc.
I have the clone functionality working, but each time a row of inputs is created I can't quite figure out how to increment the number. I have been experimenting with reg ex to extract the integer value of the attribute, and narrowed it down to:
(?:options])[(\d+)]
http://www.rubular.com/r/NpLrCerx8K
My jquery function is below:
    $(".add_option").on('click', function() {
        var $tableBody = $(this).prev('.attr-tbl').find("tbody"),
        $trLast = $tableBody.find("tr:last"),
        $trNew = $trLast.clone(true).insertAfter($trLast);

        $trNew.find('input:text').val('');
        $trNew.find('select').prop('selectedIndex',0);
        $trNew.find('input:text, select, input:checkbox').each(function(){
            //console.log(this.name);
            this.value = '';
            this.name.replace(/(?:options])\[(\d+)]/, function(str,p1){
                console.log(str + p1);
                return (parseInt(p1,10)+1);
            });
        })

    });

The above returns in the console:
str = options][1]
p1 = 1
But crucially when the next row of inputs is created the key doesn't increment. I have this working for the first integer key using the below, but I'm struggling to replicate this to change the second key only.
        $newSet.find('input:text, select, input:checkbox').each(function(){
                    //console.log(this.name);
                    this.value = '';
                    this.name = this.name.replace(/\[(\d+)\]/, function(str,p1){
                        console.log(str + p1);
                        return '[' + (parseInt(p1,10)+1) + ']';
                    });
        })

Any help would be much appreciated, many thanks in advance.

A: Just in case anybody stumbles on this page, the above was over-complicating matters. I settled on this:
    $(".add_option").on('click', function() {
        var $tableBody = $(this).prev('.attr-tbl').find("tbody"),
        $trLast = $tableBody.find("tr:last"),
        $trNew = $trLast.clone(true).insertAfter($trLast);

        $trNew.find('input:text').val('');
        $trNew.find('select').prop('selectedIndex',0);
        $trNew.find('input:text, select, input:checkbox').each(function(){
            this.value = '';
            newNum = increment_last(this.name);
            this.name = newNum;
        })

});
and the function to increment the second number is:
function increment_last(v) {
    return v.replace(/[0-9]+(?!.*[0-9])/, function(match) {
        return parseInt(match, 10)+1;
    });
}


text:
Q: How to add Stop function to my audio player on android? I have multiple audio file on res/raw folder, and the audio name is save on a database. So when the program wants to play audio, audio named will called from database with a function.
FYI, I build an app for ITP TOEFL test. And I made this part for listening section.
And the problem is when I want to go to the next question, the audio will still playing, I wish to add stop function to same button that I use to start play the audio.
Here's the part of my codes that play the audio
variable declare:
private static MediaPlayer mp;

component initialitations:
mainkan.setOnClickListener(new OnClickListener(){
        public void onClick(View arg0){
            mainkan.setEnabled(false);
                go(audioSoal);
            }
    });

*mainkan means "play"
and this is the main funciton to play audio, which is "string audio" comes from database and pointing to audio files on res/raw folder
public void go(String audio){
    int resId = getResources().getIdentifier("raw/"+audio, null, this.getPackageName());
    mp=MediaPlayer.create(section3db.this, resId);
        try {
            mp.prepare();
        }
        catch(IllegalStateException e){
            // TODO auto-generated catch block
            e.printStackTrace();
        }
        catch(IOException e){
            // TODO auto-generated catch block
            e.printStackTrace();
        }
    mp.start();
    mp.setOnCompletionListener(new OnCompletionListener(){
        public void onCompletion(MediaPlayer arg0){
            mainkan.setEnabled(true);
        }
});
}

can someone help me? Thanks in advance :)

A: call this method on any button click event:
mp.stop();

this will stop the player.
if you want to pause, then do this :
mp.pause();


text:
Q: How to perform a complex SQL query on DataTable objects? I am programming an Excel add-in in C# where I process data contained in different DataTable objects. I would like to provide a function to perform SQL queries on the data, with the ability to reference data from other tables in where and sort by clauses (for example, using a join).
An example of such a query would be
SELECT name
FROM Table1
WHERE id = Table2.id AND Table2.age > 18

The problem with this is that a DataTable doesn't know of the existance of the other DataTables, so (for so far I know) there are no such methods in the class. Also, I cannot use something like LINQ, since the query will be written by the users of the add-in in excel.
Would it be a good solution to copy the data to an in-memory database, where each DataTable is mapped to a table? How would this work performance-wise? Is there a simpler solution?

A: In terms of SQL query you are missing a table reference in selecting the tables, corrected query will look like
SELECT name
FROM Table1, Table2
WHERE Table1.id = Table2.id AND Table2.age > 18

Use Table1.name if there is same named attribute in Table2.
However using only WHERE condition in Joins without specifying the joining attribute is not recommended read this question. Use JOIN.
SELECT Table1.name
    FROM Table1 INNER JOIN Table2 ON Table1.id = Table2.id WHERE Table2.age > 18


text:
Q: How best to retrieve a record with related table items in using JOOQ? First of I apologise for the title but can't think of a better way to word it.
Secondly I have the following table:

Profiles Table:
Primary Key: profileName <-----
                              |
Repositories Table:           |
Composite Primary Keys: (profileName, repository_name)

simulating a 1 - n relationship between the profiles table and repositories table.
I recently discovered jooq and using it to retrieve and store the data from the db and have this code for retrieving a profile from the db:
profile = db.select().from(Profiles.PROFILES, Repositories.REPOSITORIES).fetch().stream()
                .filter(t -> t.getValue(Profiles.PROFILES.PROFILENAME).equalsIgnoreCase(profileName))
                .limit(1) //limit it to just the one result
                .map(this::convertToProfile)
                .collect(Collectors.toList()).get(0);

works fine, but I am unsure of how to improve this to include the the retrieval of possible repositories found in the repositories table. That is to say repositories aren't mandatory rather optional to the profiles table.
My only option right now is to create a 'second cycle logic' to retrieve the repositories using the profile name before unmarshalling the data.

A: Push operations into the database
Your query will be very slow as your data grows. Why? Because your SQL query only runs the cartesian product between PROFILES and REPOSITORIES tables, whereas the join predicate and the limit clause are then applied in Java memory.
The database never knows what you want to do with that cross product, so it runs this very slow query very dumbly. If you provide the database with more information by "pushing the predicate down" into the jOOQ/SQL query, the whole thing will run much faster (although, the stream result is technically equivalent). So, instead, write this:
profile = db.select()
            .from(PROFILES, REPOSITORIES)
            // WHERE and LIMIT are moved "up" into the SQL query:
            .where(PROFILES.PROFILENAME.equalIgnoreCase(profileName))
            .limit(1)
            .fetch().stream()
            .map(this::convertToProfile)
            .collect(Collectors.toList()).get(0);

This query is the same as yours (not yet correct), but much faster
Getting joins correctly
The above query still runs a cartesian product between the two tables. You probably want to join them, instead. There are two ways of joining in SQL:
Using the WHERE clause
Just add a JOIN predicate to the where clause and you're set
profile = db.select()
            .from(PROFILES, REPOSITORIES)
            // Join predicate here:
            .where(PROFILES.PROFILENAME.equal(REPOSITORIES.PROFILENAME))
            .and(PROFILES.PROFILENAME.equalIgnoreCase(profileName))
            .limit(1)
            .fetch().stream()
            .map(this::convertToProfile)
            .collect(Collectors.toList()).get(0);

This is also called INNER JOIN, which can be written using the JOIN clause for improved readability:
Using the (INNER) JOIN clause:
Most people will find this syntax more readable, because JOIN predicates are clearly separated from "ordinary" predicates:
profile = db.select()
            .from(PROFILES)
            // Join expression and predicates here:
            .join(REPOSITORIES)
            .on(PROFILES.PROFILENAME.equal(REPOSITORIES.PROFILENAME))
            // Ordinary predicates remain in the where clause:
            .where(PROFILES.PROFILENAME.equalIgnoreCase(profileName))
            .limit(1)
            .fetch().stream()
            .map(this::convertToProfile)
            .collect(Collectors.toList()).get(0);

"optional" JOIN
In SQL, this is called an OUTER JOIN, or more particularly a LEFT (OUTER) JOIN:
profile = db.select()
            .from(PROFILES)
            // LEFT JOIN expression and predicates here:
            .leftJoin(REPOSITORIES)
            .on(PROFILES.PROFILENAME.equal(REPOSITORIES.PROFILENAME))
            .where(PROFILES.PROFILENAME.equalIgnoreCase(profileName))
            .limit(1)
            .fetch().stream()
            .map(this::convertToProfile)
            .collect(Collectors.toList()).get(0);

Note that the list of REPOSITORIES will not be empty but contain a repository with all values set to NULL. That's how an OUTER JOIN works


text:
Q: create a dict joining two other dicts [Python] I'm trying to create a junction of the dicts bellow:
buy_dict = {'Coin1': [{'buy_price': 105, 'id_buy':2 },{'buy_price': 100, 'id_buy':1 }], 'Coin2': [{'buy_price': 1200, 'id_buy':2 },{'buy_price': 1100, 'id_buy':1 }]}

sell_dict = {'Coin1': [{'sell_price': 106, 'id_sell':1 }, {'sell_price': 110, 'id_sell':2 }], 'Coin2': [{'sell_price': 1250, 'id_sell':1 },{'sell_price': 1350, 'id_sell':2 }]}

On the buy_dict I have a dict with buy prices and its ids, grouped by Coin. The same model on the sell_dict. What I need to do is create a third dict by joining the data from two dicts adobe, so the first record of the new dict would be the first record of the dictA plus the first record of the dictB. Below is how it should look:
DictC = {'Coin1': [{'buy_price': 105, 'id_buy':2, 'sell_price': 106, 'id_sell':1}, {'buy_price': 100, 'id_buy':1, 'sell_price': 110, 'id_sell':2}], 'Coin2': [{'buy_price': 1200,'id_buy':2, 'sell_price': 1250,'id_sell':1}, {'buy_price': 1100, 'id_buy':1,'sell_price': 1350,'id_sell':2}]}

In short, the records of DictC would be a junction of the highest buying price and the lowest selling prices. No ordering is required because buy_dict and sell_dict are already ordered.
Thanks!!

A: This trick is that you are combining two dictionaries and also iterating through array in order. The difference from mine an joes answer is that mine is tolerant of a coin only existing in one dict and a different number of sells and buys in each list.
  from collections import defaultdict
  from itertools import zip_longest

  DictC = defaultdict(list)
  for coin in (buy_dict.keys() | sell_dict.keys()):
      for buy_item, sell_item in zip_longest(buy_dict.get(coin, []), sell_dict.get(coin, []), fillvalue={}):
          DictC[coin].append({**buy_item, **sell_item})

For python2.7 replace DictC[coin].append({**buy_item, **sell_item}) with
temp = buy_item.copy()
temp.update(sell_item)
DictC[coin].append(temp)

and buy_dict.keys() | sell_dict.keys() with set(buy_dict.keys() + sell_dict.keys()) and zip_longest with izip_longest

A: The simplest method I found was:
dictD = {}
for coin in sell_dict:
    coinList = []
    for things in zip(sell_dict[coin], buy_dict[coin]):
        joinedDict = {}
        for d in things:
            joinedDict.update(d)
        coinList.append(joinedDict)
    dictD[coin] = coinList

I assume here that the keys of sell_dict and buy_dict are identical.  Other than doing the obvious for loops, there isn't anything special other than the use of zip to get the lists aligned the way you want.

A: You can do this in a one-line dictionary-comprehension:
{k: [{**buy_dict[k][i], **sell_dict[k][i]} for i in range(len(buy_dict[k]))] for k in buy_dict}

which gives your desired output of:
{'Coin1': [{'id_sell': 1, 'buy_price': 105, 'id_buy': 2, 'sell_price': 106}, {'id_sell': 2, 'buy_price': 100, 'id_buy': 1, 'sell_price': 110}], 'Coin2': [{'id_sell': 1, 'buy_price': 1200, 'id_buy': 2, 'sell_price': 1250}, {'id_sell': 2, 'buy_price': 1100, 'id_buy': 1, 'sell_price': 1350}]}

why?
Well we want to iterate through each key in buy_dict, so that is our outer-most loop. Then inside this, we want to set this key to a value which is a list. This is done with the syntax: {k: [...] for k in buy_dict}.
And what goes in this list? Well since the lists in the original dictionaries are already ordered correctly, we can just unpack them in order into their own new one.
So to do this, we iterate through the different indexes in the buy_dict[k] list and then use the unpacking technique seen here to form a new dictionary.

Note that of course the outputted dictionary isn't identical in terms of order to yours as dictionaries have no order; they are merely a set of key:value pairs


text:
Q: Install/Execute a CAb file[Windows Mobile application file] from C# Code? I am developing a Windows Mobile application for Framework 6. I want to add functionality to upgrade a patch with the application currently running on a device.
While Windows Mobile application works, it should check asynchronously for any new version available in a server database. If the patch exists, the program should download the .cab (Windows Mobile installer) file and install/run it automatically.
Mainly, I have doubts on these:

*

*How to download a cab file to device's particular folder.

*How to install the cab file programmatically. (Programmatically trigger cab file installation without user intervention)

How could it be done?
Please help me on this.....

A: Downloading a file to local folder generally depends on your repository, ie. you will need slightly different code if you store it on a file share or in lets say web based one.
You have to consider option of providing pre-download version check via some sort of manifest file or database record to avoid downloading entire patch just to check its version.
Once you have downloading part sorted (again, depends on storage), you can invoke CAB installation from your app by calling wceload.exe:
            Process proc = Process.Start("wceload.exe", "\"" + Path.Combine(applicationPath, updateFileName) + "\"");
            proc.WaitForExit();

This will however require user to interact and press 'OK' to install new version on top of the old one.
[Edit]
Some device manufacturers (like Intermec) provide ways of automatic CAB install on reboot but that's very device-specific so you'd have to read up on this.

A: I solved this the following way:

*

*Open tcp/ip connection to desktop application.

*Send from PDA application the current version number.

*During compilation, add to #.inf file version field with value manually (here I could not find solution to do it automatically during compilation).

*Desktop application looks up available version in *.inf file and sends it back to PDA application.

*PDA application receives it and compares with running version.

*If version on dektop computer is higher than running version, PDA application sends request to deliver CAB file on desktop computer (here can be dialog introduced for requesting cab file).

*Desktop computer sends CAB file to PDA application.

*PDA application receives CAB file and stores it locally.

*Then run installation by wceload.exe with parameters /delete 1 /silent "full path of cab file"

*In case succesful installation, exit application or restart PDA.

*If PDA application has

It is not a few strings of code, however it works perfectly.

A: I just had to do this, it seems like the install part was answered.  If anyone needs the download portion, this worked for me.
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Timeout = 10000;
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream receiveStream = response.GetResponseStream();

        using (Stream file = File.OpenWrite("\\Windows\\Desktop\\file.cab"))
        {
            byte[] buffer = new byte[8 * 1024];
            int len;
            while ((len = receiveStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                file.Write(buffer, 0, len);
            }
        }


text:
Q: Website migrated from IIS server to Linux I changed server from IIS to Linux. In form submissions I was using if ($user) which didn't work in linux.
For Linux I changed it to if ($_POST["user"]). This means it is using the value passed in the form.
But if I keep on changing files like this, it will take lot of time. I want these to be worked as if $user only like it was on IIS. I am using WHM so maybe there is a setting for the same?

A: You need to configure the server to enable Register Globals. This setting is considered dangerous (as it is too easy to write insecure code using it) and was deprecated and then removed from PHP.
You may have to downgrade PHP in order to enable it.
Bring your code up to date. Register Globals was considered bad practice when I used PHP over a decade ago.


text:
Q: SwiftUI: Drag & Drop between Lists crashes sometimes I'm using Xcode 12 beta and trying to create a view where items from a left list can be dragged onto a right list and dropped there.
This crashes in the following situations:

*

*The list is empty.

*The list is not empty, but the item is dragged behind the last list element, after dragging it onto other list elements first. The crash already appears while the item is dragged, not when it is dropped (i.e., the .onInsert is not called yet).

The crash message tells:

SwiftUI`generic specialization <SwiftUI._ViewList_ID.Views> of (extension in Swift):Swift.RandomAccessCollection< where A.Index: Swift.Strideable, A.Indices == Swift.Range<A.Index>, A.Index.Stride == Swift.Int>.index(after: A.Index) -> A.Index:

Are there any ideas why this happens and how it can be avoided?
The left list code:
struct AvailableBuildingBricksView: View {

    @StateObject var buildingBricksProvider: BuildingBricksProvider = BuildingBricksProvider()

    var body: some View {

        List {

            ForEach(buildingBricksProvider.availableBuildingBricks) { buildingBrickItem in

                Text(buildingBrickItem.title)
                    .onDrag {

                        self.provider(buildingBrickItem: buildingBrickItem)
                    }
            }
        }
    }

    private func provider(buildingBrickItem: BuildingBrickItem) -> NSItemProvider {

        let image = UIImage(systemName: buildingBrickItem.systemImageName) ?? UIImage()
        let provider = NSItemProvider(object: image)

        provider.suggestedName = buildingBrickItem.title

        return provider
    }
}

final class BuildingBricksProvider: ObservableObject {

    @Published var availableBuildingBricks: [BuildingBrickItem] = []

    init() {

        self.availableBuildingBricks = [
            TopBrick.personalData,
            TopBrick.education,
            TopBrick.work,
            TopBrick.overviews
        ].map({ return BuildingBrickItem(title: $0.title,
                                         systemImageName: "stop") })
    }
}

struct BuildingBrickItem: Identifiable {

    var id: UUID = UUID()

    var title: String
    var systemImageName: String
}

The right list code:
struct DocumentStructureView: View {

    @StateObject var documentStructureProvider: DocumentStructureProvider = DocumentStructureProvider()

    var body: some View {

        List {

            ForEach(documentStructureProvider.documentSections) { section in

                Text(section.title)
            }
            .onInsert(of: ["public.image"]) {

                self.insertSection(position: $0,
                                 itemProviders: $1,
                                 top: true)
            }
        }
    }

    func insertSection(position: Int, itemProviders: [NSItemProvider], top: Bool) {

        for item in itemProviders.reversed() {

            item.loadObject(ofClass: UIImage.self) { image, _ in

                if let _ = image as? UIImage {

                    DispatchQueue.main.async {

                        let section = DocumentSectionItem(title: item.suggestedName ?? "Unknown")
                        self.documentStructureProvider.insert(section: section, at: position)
                    }
                }
            }
        }
    }
}

final class DocumentStructureProvider: ObservableObject {

    @Published var documentSections: [DocumentSectionItem] = []

    init() {

        documentSections = [
            DocumentSectionItem(title: "Dummy")
        ]
    }

    func insert(section: DocumentSectionItem, at position: Int) {

        if documentSections.count == 0 {

            documentSections.append(section)
            return
        }

        documentSections.insert(section, at: position)
    }
}

struct DocumentSectionItem: Identifiable {

    var id: UUID = UUID()
    var title: String
}

A: Well, I succeeded to make the problem reproducable, code below.
Steps to reproduce:

*

*Drag "A" on "1" as first item on the right.

*Drag another "A" on "1", hold it dragged, draw it slowly down after "5" -> crash.

The drop function is not called before the crash.
struct ContentView: View {
    var body: some View {
        HStack {
            LeftList()
            Divider()
            RightList()
        }
    }
}

import SwiftUI
import UniformTypeIdentifiers

struct LeftList: View {

    var list: [String] = ["A", "B", "C", "D", "E"]

    var body: some View {
        List(list) { item in
            Text(item)
                .onDrag {

                    let stringItemProvider = NSItemProvider(object: item as NSString)
                    return stringItemProvider
                }
        }
    }
}

import SwiftUI
import UniformTypeIdentifiers

struct RightList: View {
    @State var list: [String] = ["1", "2", "3", "4", "5"]

    var body: some View {
        List {

            ForEach(list) { item in
                Text(item)
            }
            .onInsert(
                of: [UTType.text],
                perform: drop)
        }
    }

    private func drop(at index: Int, _ items: [NSItemProvider]) {

        debugPrint(index)

        for item in items {

            _ = item.loadObject(ofClass: NSString.self) { text, _ in

                debugPrint(text)

                DispatchQueue.main.async {

                    debugPrint("dispatch")

                    text.map { self.list.insert($0 as! String, at: index) }
                }
            }
        }
    }
}


text:
Q: How to find linear fractional transformations of a group Finite presentation of G is $$\langle  x,y,t,q : x^2=y^3=t^2=q^2 =1,tq=qt,ty=yt,qyq=y^{−1},xt =qx \rangle.$$ I am interested in finding linear fractional transformations x,y,t,q which satisfy all its relations.

A: Let $H<G$ be generated by $y, t, q$. It is isomorphic to the dihedral group $G_2$ of order $12$; the latter embeds in $PU(2)< PSL(2,C)$ Furthermore, the (unique up to conjugation) monomorphism
$$
r: H \to G_2< PU(2)
$$
extends to the rest of $G$, since order 2 elements $r(t)$ and $r(s)$ are conjugate (in $PU(2)$). I do not know if this is what you are looking for. (Maybe you want $r$ to be also injective, this would require more work and I do not see much motivation.)


text:
Q: iOS navigationItem title with custom font loses vertical centering Is there any text attribute like line-height or any other feature that would help with vertical centering of a UINavigationItem title? After setting custom font it is higher than standard one.

A: Of course, there is a method on UINavigationBar named
- (void)setTitleVerticalPositionAdjustment:(CGFloat)adjustment forBarMetrics:(UIBarMetrics)barMetrics


text:
Q: Angular 6 - How to read angular specific attributes I have a component on which I specify the angular i18in attribute like this:
<app-text i18n="meaning|description"> DeveloperText</app-text>

I want to be able to read this property. I have tried using ElementRef and accessing nativeElement but the attribute i18n is not a part of the DOM element when I view the source. When my app is launched the DOM looks like this:
<app-text _ngcontent-c0=""> DeveloperText</app-text>

So can I somehow read properties like this using the Angular Framework?

A: In your HTML:
<app-text #something i18n="meaning|description">DeveloperText</app-text>

In your controller:
@ViewChild('something') fred;

You now have a handle on the element. If you log it like this:
console.log(this.fred);
console.log(this.fred.nativeElement);

You should find the value of the property you are interested in.


text:
Q: How to wrap the word with CSS properly? I have 2 words to wrapping with below

*

*Culture Vulture

*Kleingruppen-Reise

but when I use:

word-break: break-all;

wrapping look strange. How can I adjust the CSS file to nice wrapping?
Here is my code:

* {
  margin: 0;
  padding: 0;
}

.tabs-machine {
  margin-top: -12px;
  position: relative;
  height: 89px;
  background: url(http://aquaterra-travel.siampixel.com/images/tabs_machine_bg1.gif) no-repeat center top;
}

.tabs-machine-mask ul {
  width: 600px;
  overflow: hidden;
  margin: 0px auto;
}

.tabs-machine-mask ul li {
  float: left;
  display: inline-block;
  text-align: center;
  margin-left: 1px;
  vertical-align: middle;
}

.tabs-machine-mask ul li a {
  display: table-cell;
  width: 99px;
  height: 76px;
  color: #bf1e2d;
  font-size: 16px;
  font-family: "Myriad Pro", 'Average Sans', sans-serif;
  text-decoration: none;
  vertical-align: middle;
  padding-bottom: 1em;
  white-space: -moz-pre-wrap !important;
  /* Mozilla, since 1999 */
  white-space: -pre-wrap;
  /* Opera 4-6 */
  white-space: -o-pre-wrap;
  /* Opera 7 */
  white-space: pre-wrap;
  /* css-3 */
  word-wrap: break-word;
  /* Internet Explorer 5.5+ */
  word-break: break-all;
  white-space: normal;
}

Culture Vulture

Kleingruppen-Reise

Explorer

Family

Festival and Events

Marine

Sample

A: I believe you're looking to prevent words from breaking/hyphenating mid-word.
Try removing word-break:break-all; on .tabs-machine-mask ul li a.

.tabs-machine-mask ul {
  width: 600px;
  overflow: hidden;
  margin: 0px auto;
}

.tabs-machine-mask ul li {
  float: left;
  display: inline-block;
  text-align: center;
  margin-left: 1px;
  vertical-align: middle;
}

.tabs-machine-mask ul li a {
  display: table-cell;
  width: 99px;
  height: 76px;
  color: #bf1e2d;
  font-size: 16px;
  font-family: "Myriad Pro", 'Average Sans', sans-serif;
  text-decoration: none;
  vertical-align: middle;
  padding-bottom: 1em;

  white-space: -moz-pre-wrap !important;
  white-space: -pre-wrap;
  white-space: -o-pre-wrap;
  white-space: pre-wrap;
  word-wrap: break-word;
   /* word-break: break-all; */
  white-space: normal;
}

Culture Vulture

Kleingruppen-Reise

Explorer

Family

Festival and Events

Marine


text:
Q: Error: Element type is invalid expected a string(for built in components) or a class/function (for composite functions) but got undefined I am using TabBarIOS in react native,and running it on android emulator, but while using TabBarIOS.Item I am getting following error Element type is invalid expected a string(for built in components) or a class/function (for composite functions) but got undefined check render method of Approvals
render() method of Approvals is as follows
render(){

  return (
    <View style={styles.container}>
        <View style={styles.strip}>
            <Image style={{width:50, height:30,padding:10,top:5}} source={require('./drawable/drawable/asap.png')}/>
            <Text style={{fontSize:20,color:'white',bottom:20,left:60,padding:10}}>Approvals</Text>
        </View>
        <TabBarIOS selectedTab={this.state.selectedTab}>
            <TabBarIOS.Item
            title="Pending"
            icon={{uri:'./drawable/drawable/approvalbadge.png',scale:3}}
              selected={this.state.selectedTab==='pending'}
              onPress={() => {
                  this.setState({
                      selectedTab: 'pending',
                  });
              }}>
                <Pending>
            </TabBarIOS.Item>

         </TabBarIOS>
    </View>

  );

}

The error is in this section only cause if I remove TabBarIOS and place  it doesn't give any error. Please Help me to solve this issue.

A: When you import TabBarIOS it is imported as undefined, because you can not use it in android app.
Than you call
<TabBarIOS selectedTab={this.state.sele

it is interpreted as undefined
You better use external implementation instead (something like https://github.com/exponentjs/react-native-tab-navigator) or write your own.

A: I didn't read the question properly. You're trying to use an IOS component for an android app. But you cannot.
The Component with IOS and Android suffix will only work with IOS and Android app respectively. If you need to use cross-platform Components then you'll have to use Components without IOS and Android suffix or use 3rd party Components.
For example, Navigator works for both ios and android but NavigatorIOS works only for ios.
In this case you'll have to use something like these:
https://github.com/exponentjs/react-native-tab-navigator
https://github.com/alinz/react-native-tabbar


text:
Q: How to test an Object/Class with all the posible constructor arguments permutations? I have the next class that I want to test with pytest:
class Analysis(object, metaclass=abc.ABCMeta):

    def __init__(self, filters, and_operator, filters_comb_type):
        self.filters = filters
        self.andOperator = and_operator
        self.filtersComb_type = filters_comb_type

    def _generate_defaultfilters_combination(self):
        ...

    def _generate_allfilters_combinations(self):
        ...

    def _check_filters(self, pattern_indexes, direction=None):
        ...

So, I want to create a lot of possible Analysis() with a different set of possible values for filters, and_operator and filters_comb_type.
So I have written the next code using pytest:
import pytest
from src.statistical_analysis.analysis import Analysis, FiltersCombinationType
from tests.analysis_filters.mocks_analysis_filter import *

@pytest.fixture(params=[[],
                        [MockAllwaysTrueAnalysisFilter()],
                        [MockAllwaysFalseAnalysisFilter()],
                        [MockEvenTrueOddFalseAnalysisFilter()],
                        [MockAllwaysTrueAnalysisFilter(), MockAllwaysFalseAnalysisFilter(), MockAllwaysFalseAnalysisFilter()]])
def filters(request):
    return request.param

@pytest.fixture(params=[True, False])
def and_operator(request):
    return request.param

@pytest.fixture(params=[FiltersCombinationType.ONLY_DEFAULTS,
                        FiltersCombinationType.ONE_COMBINATION,
                        FiltersCombinationType.ALL_COMBINATIONS])
def filters_comb_type(request):
    return request.param

@pytest.fixture
def analysis():
    a = Analysis(filters, and_operator, filters_comb_type)
    return a

So, if I have understand well the analysis() fucntion will create all the possible combinations of Analysis() object.
But my problem comes when I want to write the code to test the 3 methods of Analysis class, beause if I write this:
def test_check_filters(analysis):
    ...

The test it's going to be called with each of the whole Analysis objects created in the fixture, but now how can I compare each Analsysis with his expected return value of the check_filters() method??
I want to know which one is the correct aproach when we want to test a method of a class creating a lot of instances of a class with differente constructor parameters.


text:
Q: Omit elements in list comprehension There is the following simple script:
def MyFunction(digit):
    if digit < 4:
        return digit
    else:
        return None

A = [1, 2, 3, 4, 5]
B = [MyFunction(x) for x in A]
print(B) # [1, 2, 3, None, None]

QUESTION:
Is it possible to rewrite MyFunction() somehow, so B becomes equal to [1, 2, 3] without None? Please, don't recommend me to use if expressions in the list comprehension, process B after list comprehension etc.

A:
Is it possible to rewrite MyFunction() somehow, so B becomes equal to [1, 2, 3] without None? Please, don't recommend me to use if expressions in the list comprehension, process B after list comprehension etc

No, it isn't.  Your list comprehension will not change the length of the list.  There's nothing you can do in MyFunction() to change that.  You must use an if in the list comprehension or do some kind of pre- or post-processing on the list.
As described in the Python language reference:

The comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses. In this case, the elements of the new container are those that would be produced by considering each of the for or if clauses a block, nesting from left to right, and evaluating the expression to produce an element each time the innermost block is reached.

You get one element per for iteration.  This is built right into the language.

A: To filter elements you need to use filter() or a list comprehension with if.
I.e:
B = filter(lambda digit: digit < 4, A)

You may use your function, but it should return boolean:
def MyFunction(digit):
    if digit < 4:
        return True
    else:
        return False
B = filter(MyFunction, A)

Or simply:
def MyFunction(digit):
    return digit < 4

With list comprehension:
B = [digit for digit in A if digit < 4]

A: It is possible, but ugly as hell, to tweak the iterator from the function.  Unfortunately I can't get rid of the last None, but maybe someone else could pick-up the idea and refine it.  Here is my effort, and I extended the test data:
import sys

def MyFunction(digit):
    if digit < 4:
        return digit
    else:
        while digit >= 4:
            try:
                digit = sys._getframe(1).f_locals['.0'].__next__()
            except StopIteration:
                break
        else:
            return digit

A = [6, 7, 1, 2, 3, 4, 5]
B = [MyFunction(x) for x in A]
print(B)

produces:
[1, 2, 3, None]

I fully expect someone to say this practice is highly dangerous and implementation specific - and I would not argue with such a comment.


text:
Q: How to deal with empty node in xquery? I want to print a TSV output like this. But when $x/span does not find anything, there will be only two columns printed. How to insert an empty field in the 2nd column when $x/span finds nothing? Thanks.
for $x in //td/b/a[@title]/parent::b/parent::td
return join(
    (
        $x/b/a/@title
        , $x/span
        , $x/p
    )
    , x:cps(9)
)

A: XPath:
//td[b/a[@title]]/join(
  (
    b/a/@title,
    (span,"")[1],
    p
  ),
  x:cps(9)
)

XQuery:
for $x in //td[b/a[@title]] return
$x/join(
  (
    b/a/@title,
    (span,"")[1],
    p
  ),
  "	"
)

A: You can use if/else statement to control what to do in case of the missing span tag.
if (empty($x/span)) then
    (: do what you need here :)
else
    $x/span

A: A common idiom for this is
($x/span, "default")[1]

But this might not be right for you if $x/span can select multiple items.


text:
Q: Subsets $A$ of rational numbers with $| \Bbb{Q} \setminus (A-A)|=2m$ Fix a positive integer $m$ and let $\mathbb{Q} \cap (m, +\infty) = \{ r_k \}_{k \ge m}$. If
$$A:= \left\{ m+r_m+\sum_{k=m}^n r_k : n \ge m-1\right\},$$
then we know that $A-A= \Bbb{Q} \setminus ([-m,m]\setminus \{0\})$.
But, we are looking for a subset $A$ of rationals such that $A-A= \Bbb{Q} \setminus \{ \pm1,\cdots,\pm m \}$ or (if it does not exist) $| \Bbb{Q} \setminus (A-A)|=2m$. Are there such subsets $A$?

A: Note that $A_i = \{0\} \cup \big((i,i+1)\cap \mathbb{Q}\big)$ satisfies $$A_i-A_i = \mathbb{Q} \cap \big((-i-1,-i)\cup (-1,1) \cup (i,i+1)\big)$$
Since your $A \subset [0,\infty),$ we can just union that $A$ with our $A_i$ shifted sufficiently far left to get an example.  That is, take
$$A \cup \bigcup_{i=1}^{m-1}(A_i - 3mi)$$


text:
Q: Trying to update Asus BIOS My UX31 zenbook is experiencing some weird shutdown behavior when the battery drops below 50% and the internet seems to agree that updating the BIOS is a good step forward since there were issue with the kernel before.
I downloaded both the correct BIOS file and the windows 7 utility tool and now need to boot FreeDOS to run, however, I've tried every method out there and they all fail (or so I think):

*

*Using unetbootin's FreeDOS 1.0 image I get to an error saying it couldn't run drivers then I get to a command line on disk A:. I assumed a dead end.

*Using unetbootin but with the FreeDOS 1.1 version image downloaded directly: get an error of "bad or missing command interpreter". I looked online and the solutions didn't work either.
So, is there an alternative to FreeDOS or to installing a BIOS that I could use?

A: Short answer: Read the manual (page A-12).
This product, like others, has an integrated update functionality. Put the update on a USB stick, select "EZ Flash" or "Easy Flash" from the UEFI boot menu and do the update from within this program.

This is not releated to Ubuntu, you should have asked the question on another Stack Exchange site. However:

*

*Using unetbootin's FreeDOS 1.0 image I get to an error saying it couldn't run drivers then I get to a command line on disk A:. I assumed a dead end.

No, I think that is the correct behaviour. Depending on what error messages you got (some might not be releated to the task you are trying to accomplish). You then need to run the update utility and point it to the update it should apply. The difficult part may be to find out in which drive or directory the tool and update reside.
Also there is the possibility that there doesn't exist a DOS-based update tool, or the tool is not compatible to FreeDOS (and earlier versions of MS DOS) and has to be run from a Win9x boot disk (I remember facing such a problem with a 2011 model ProBook and some service technician tools).


text:
Q: Что означают составные операторы? Что означает на С++?

*=
+=
==

A: Подобные вопросы лучше всего прояснять в справочнике языка. Значение операторов таково:

*

*x *= y эквивалентно x = x*y,

*x += y эквивалентно x = x+y,

*x == y равно true, если x равно y.


text:
Q: Kotlin: Override parent job of coroutine I am trying to migrate the following function to new Coroutine of Kotlin 1.3:
fun launchUI(strategy: CancelStrategy, block: suspend CoroutineScope.() -> Unit): Job {
    return launch(context = UI, parent = strategy.jobs, block = block)
}

But new GlobalScope.launch function doesn't have parent parameter. Documentation says:

The parent job is inherited from a CoroutineScope as well, but it
  can also be overridden with corresponding coroutineContext element.

But I don't know how to override parent job. I have implemented it like this for now but I am not sure if it will work the same way:
fun launchUI(strategy: CancelStrategy, block: suspend CoroutineScope.() -> Unit): Job {
    val job = GlobalScope.launch(context = Dispatchers.Main, block = block)
    strategy.jobs.invokeOnCompletion {
        job.cancel()
    }
    return job
}

Can anyone help me?
UPDATE:
class CancelStrategy(owner: LifecycleOwner, val jobs: Job) : LifecycleObserver {

    init {
        owner.lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        jobs.cancel()
    }
}

A: Your second example is correct. You can use plus to add the job as a parent job for the new coroutine.
fun launchUI(strategy: CancelStrategy, block: suspend CoroutineScope.() -> Unit): Job {
    return GlobalScope.launch(context = Dispatchers.Main + strategy.jobs, block = block)
}

But the usage of GlobalScope is discouraged. It would be better to create an own CoroutineScope. Your CancelStrategy looks like a good candidate.
class CancelStrategy(owner: LifecycleOwner, val jobs: Job) : LifecycleObserver, CoroutineScope {
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + jobs

    init {
        owner.lifecycle.addObserver(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        jobs.cancel()
    }
}

Now you can start your coroutines like this:
cancelStrategy.launch { ... }

A: What you want to have is called "structured concurrency" by aligning the lifecycle of your coroutines to some UI component.
Have a look at this documentation: https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md#structured-concurrency-lifecycle-and-coroutine-parent-child-hierarchy
Instead of using GlobalScope, you should consider implementing your own scope and maintaining a Job their, which you can cancel to cancel all your children as well.
Here's a simplified example:
class Activity : CoroutineScope {
    lateinit var job: Job //tied to lifecycle of Activity
    fun create() {
        job = Job()
    }

    fun destroy() {
        //will cancel all child jobs as well
        println("cancel $job and all ${job.children.toList().size} children")
        job.cancel()
    }

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Default + job + CoroutineName("MyActivityContext")

    fun doSomething() {
       //we launch in the outer scope of Activity
       launch {
          //...
       }
    }
}


text:
Q: why the output is an address? consider this is my code:
 void SportShoe::AddSportShoe() {

    SportShoe MySepatu[SIZE];
    int numOfShoe = 0;
    nodeSport *tempShoe1;

    while (numOfShoe < SIZE){
        cout << "Please enter the Shoe ID : (eg. 23210) " << endl;
        cin >> SportShoe::MySepatu[numOfShoe].ShoeID;

        cout << "Please enter the Shoe Brand: (eg. Adidas) " << endl;
        cin.sync();
        cin.getline(SportShoe::MySepatu[numOfShoe].BrandShoe,100);

        cout << "Please enter the price of the Shoe : (eg. RM123.22) " << endl;
        cin >> SportShoe::MySepatu[numOfShoe].PriceShoe;
        cout << endl;

    //passing the value from 'MySepatu' to 'tempShoe'
        SportShoe::MySepatu[numOfShoe].ShoeID = (tempShoe1->ShoeIDList);
        SportShoe::MySepatu[numOfShoe].BrandShoe[100] = (tempShoe1->BrandShoeList[100]);
        SportShoe::MySepatu[numOfShoe].PriceShoe = (tempShoe1->PriceShoeList);

   //i do some dummy to see what stored in tempShoe1
       cout << "ID =>> " << tempShoe1->ShoeIDList << endl;
       cout << "Brand =>> " << tempShoe1->BrandShoeList << endl;
       cout << "Price =>> " << tempShoe1->PriceShoeList << endl;
    }

    while (numOfShoe >= SIZE-1){
       cout << ">> List is already full !! <<";
       system("PAUSE");
       MenuSportShoe();
    }
}

The code can be run as usual and doesn't show any error on the compiler. But, when it reach to the 'cout' area it'll print out something like an address of a pointer. Not the value.
Actually i think i use the wrong method to pass the value. I don't have idea on how to assign them.
//Here my class declaration
class SportShoe  {
private:
    struct nodeSport {
        int ShoeIDList;
        char BrandShoeList[100];
        float PriceShoeList;
        nodeSport *last;
    };
    nodeSport *first = NULL;

    struct Shoe  {
        int ShoeID;
        char BrandShoe[100];
        float PriceShoe;
    }MySepatu[SIZE];

public:
    void AddSportShoe();

};
*i use array because i want to set a limit of the node. The linked list is useful for the other function like 'delete' , 'display', & etc.
Have any opinion to solve this and upgrade my code?

A: Don't use c strings, use std::string. Don't use arrays, use std::array or std::vector or a similar container. This will sure fix your problem.
class SportShoe  {
private:
    struct nodeSport {
        int ShoeIDList;
        std::string BrandShoeList;
        float PriceShoeList;
        nodeSport *last;
    };
    nodeSport *first = NULL;

    struct Shoe  {
        int ShoeID;
        std::string BrandShoe;
        float PriceShoe;
    };
    std::array<Shoe, SIZE> MySepatu;

public:
    void AddSportShoe();
};

void SportShoe::AddSportShoe() {
    std::array<SportShoe, SIZE> MySepatu;
    int numOfShoe = 0;
    nodeSport *tempShoe1;

    while (numOfShoe < SIZE){
        cout << "Please enter the Shoe ID : (eg. 23210) " << endl;
        cin >> SportShoe::MySepatu[numOfShoe].ShoeID;

        cout << "Please enter the Shoe Brand: (eg. Adidas) " << endl;
        cin.sync();
        std::getline(cin, SportShoe::MySepatu[numOfShoe].BrandShoe);

        cout << "Please enter the price of the Shoe : (eg. RM123.22) " << endl;
        cin >> SportShoe::MySepatu[numOfShoe].PriceShoe;
        cout << endl;

    //passing the value from 'MySepatu' to 'tempShoe'
        SportShoe::MySepatu[numOfShoe].ShoeID = tempShoe1->ShoeIDList;
        SportShoe::MySepatu[numOfShoe].BrandShoe = tempShoe1->BrandShoeList;
        SportShoe::MySepatu[numOfShoe].PriceShoe = tempShoe1->PriceShoeList;

   //i do some dummy to see what stored in tempShoe1
       cout << "ID =>> " << tempShoe1->ShoeIDList << endl;
       cout << "Brand =>> " << tempShoe1->BrandShoeList << endl;
       cout << "Price =>> " << tempShoe1->PriceShoeList << endl;
    }

    while (numOfShoe >= SIZE-1){
       cout << ">> List is already full !! <<";
       system("PAUSE");
       MenuSportShoe();
    }
}


text:
Q: How do I correctly install certificates to make soap request on windows 10 I need to make a request to a soap service and it is protected with certificates.
I have installed the certificates as far as I am able to tell. However the soap request fails with handshake errors.
I have a bunch of certificate files given to me but I have no idea which ones are which.
So I have as follows (names changed to protect information)
MyCertificationAuthority.pem
MyCert.pem
MyCert2.pem
then I have what looks to be the same things in a different format.
MyCertificationAuthority.p7b
MyCert.p7b
then I have a single file named MyCert.pem but is smaller in file size than the other one of the same name and contains simply

-----BEGIN NEW CERTIFICATE REQUEST----- a lot of characters
-----END NEW CERTIFICATE REQUEST-----

I was told that this was the private key file, however if I check it using
openssl rsa

then it errors.
I have double clicked on the p7b files and installed the certificates in them using the default options and I have those certificates in the Certificate Management app in windows.
3 are in the Third Part Certification Authorities folder
1 ended up in the Other People folder (which I have also copied into the Trusted Root Certification Authorities Folder)
4 have ended up in the Intermediate Certification Authorities Folder
All were installed for local computer rather than current user.
Now I am led to believe I should have a private key file too. However I can not find where this could be.
What am I doing wrong? Where would I normally get the private key file from?
I would have thought the service side has the private key in order to verify that our certificate is valid?
MyCert.pem is as follows (with the actual data removed for privacy reasons)

subject=CN=********************** issuer=CN=************************
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE----- subject=CN=**************** issuer=CN=*****************
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
subject=CN=********************** issuer=CN=***********************
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----


text:
Q: Problem to get Administrator right for program? I searched and found how to gain Administrator access level for my program (This Link, This Link, This Link and many other similar links), i did instructions step by step and think with no mistake, i checked every step for several times.
After all when i finish the steps and want to compile my program, I receive this error:
"unable to create process: the application has failed to start because its side-by-side configuration is incorrect. ..."

Where is my problem? Thank you.

Sorry for my delay, This is the manifest code i put beside my app (actually i copied and pasted it and just changed the "app.exe" name):

PROBLEM SOLVED, THIS IS THE CORRECTED AND WORKING MANIFEST:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity version="1.1.1.1"
   processorArchitecture="X86"
   name="MyApp.exe"
   type="win32"/>
  <description>elevate execution level</description>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
  <security>
   <requestedPrivileges>
    <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>
   </requestedPrivileges>
  </security>
  </trustInfo>
 </assembly>

THANKS EVERY ONE HELPED ME TO CORRECT IT!

A: Search for ] in the manifest and replace them with ">

A: Attention to the publickeytoken line, it must be in the manifest information. After that, Go to project/build...
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
 <dependency>
   <dependentAssembly>
     <assemblyIdentity
       type="win32"
       name="Microsoft.Windows.Common-Controls"
       version="6.0.0.0"
       publicKeyToken="6595b64144ccf1df"
       ...


text:
Q: java Regex: replace all numerical values with one number I have a simple line of text which might include numbers like "12.3" or "1983" or "5/8".
Whenever any number appears, I just need to replace with a fixed character, say the digit "8".
I've been fiddling about with Regex in Java, with things like this:
String line = str.replaceAll("[0-9]+/*.*[0-9]*", "8");

but to no avail.
Any idea what the correct pattern should be?

A: Try this expression: (?>-?\d+(?:[\./]\d+)?), keep in mind that in Java strings you need to escape the backslashes, i.e. you'd get "(?>-?\\d+(?:[\\./]\\d+)?)"
Here's a breakdown of the expression:

*

*The encloseing (?>...) is an atomic group to prevent catastrophic backtracking. For simple or short strings it would work without as well.

*-? a potential minus for negative numbers

*\d+ any sequence of digits (at least one)

*(?:[\./]\d+)? an optional non-capturing group consisting of either a dot (note that you don't need to escape it here, it's just for consistency) or a slash followed by at least one more digit.
Update
If you don't want to replace "numbers" like .1234, 1234. /1  or 5/ (a digit is missing either left or right), try this expression: (?>(?<![\d\./])-?\d+(?:(?:[\./]\d+)|(?![\d\./])))
Here's a breakdown again:

*

*The encloseing (?>...) is an atomic group to prevent catastrophic backtracking. For simple or short strings it would work without as well.

*(?<![\d\./]) the match must not directly follow a digit, dot or slash - note that the not follow a digit constraint is needed to match at the start of the number, otherwise you'd match 234 in .1234

*-? a potential minus for negative numbers

*\\d+ any sequence of digits (at least one)

*(?:(?:[\./]\d+)|(?![\d\./])) the match must either have a dot or slash followed by at least one digit or must not be followed by a digit, dot or slash, this would match 1.0 but not 1. - note that the not to be followed by a digit constraint is needed to prevent matching 123 in 1234.

A: If you need to replace the whole number with just a single character, use this code:
import java.io.*;

class Moo
{
  public static void main(String[] args)
  {
    String vals[] = { "1.2", "-3.14", "100500" };
    for (String s : vals)
    System.out.println(s.replaceAll("(-)?\\d+(\\.\\d*)?", "x"));
  }
}

But if you need to replace each digit, you should use different regex, like this one: "\\d".
See the demo.

A: You've forgotten to escape the . character. Other than that, your pattern looks good to me.
String line = str.replaceAll("[0-9]+/*\\.*[0-9]*", "8");

If that still doesn't work, please provide the cases that the expression isn't working correctly on.


text:
Q: How do I create a KPI list programmatically in SharePoint? I want to be able to create a KPI List on my MOSS 2007 installation via the object model. Is this possible?

A: using (SPWeb web1 = properties.Feature.Parent as SPWeb)
{
    using (SPSite objSite = new SPSite(web1.Site.ID))
    {
        using (SPWeb web = objSite.OpenWeb(web1.ID))
        {
            SPListTemplate template = null;
            foreach (SPListTemplate t in web.ListTemplates)
            {
                if (t.Type.ToString() == "432")
                {
                    template = t;
                    break;
                }
            }
            Guid gG = Guid.Empty;
            SPList list = null;
            string sListTitle = "Status List";
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                try
                {
                    web.AllowUnsafeUpdates = true;
                    gG = web.Lists.Add(sListTitle, sListTitle, template);
                    list = web.Lists[gG];
                }
                catch
                {
                    // exists
                    list = web.Lists[sListTitle];
                }
                SPContentType ct =
                  list.ContentTypes["SharePoint List based Status Indicator"];

                //declare each item which u want to insert in the kpi list
                SPListItem item1 = list.Items.Add();

                SPFieldUrlValue value1 = new SPFieldUrlValue();

                item1["ContentTypeId"] = ct.Id;
                item1.SystemUpdate();
                item1["Title"] = "Project Specific Doc.Lib.Rating";
                value1.Url = web.Url + "/Lists/Project Specific Documents";
                item1["DataSource"] = value1;
                item1["Indicator Goal Threshold"] = "3";
                item1["Indicator Warning Threshold"] = "3";
                item1["Value Expression"] =
                  "Average;Average_x0020_Rating:Number";
                item1.SystemUpdate();
            }
        }
    }

average is the calculation value and the column is Average_x0020_Rating.

A: http://alonsorobles.com/2010/03/17/important-custom-sharepoint-list-template-notes/
I found that the Template ID for a Status Indicator (KPI List) is 432. Google for this to find some info on creating a new list. I'm needing to read up what properties I can set on this list.

A: this is work for me:
   private void CreateKPIDocumentLibrary(List<PageStructure> list)
    {
        SPListTemplate kpi = null;
        foreach (SPListTemplate t in web.ListTemplates)
        {
            if (t.Type.ToString() == "432")
            {
                kpi = t;
                break;
            }
        }

        foreach (PageStructure st in list)
        {
            bool find = false;
            string[] periodType = st.tag.Split('_');
            string name = periodType[0] + "-" + st.effdate + "-" + st.template;
            SPListCollection lstCol = site.OpenWeb().GetListsOfType(SPBaseType.GenericList);
            foreach (SPList l in lstCol)
            {
                string title = l.Title;
                if (title == name)
                {
                    find = true;
                    break;
                }
            }

            if (find == false)
            {
                Guid docLibID = web.Lists.Add(name, "", kpi);
            }

            SPList itemList = web.Lists[name];
            SPListItem item = itemList.Items.Add();
            SPFieldUrlValue value = new SPFieldUrlValue();
            item["Title"] = st.tag;
            value.Url = st.docUrl;
            item["DetailLink"] = st.url;
            item["DataSource"] = value;
            item["Indicator Goal Threshold"] = "2";
            item["Indicator Warning Threshold"] = "1";
            item["View Name"] = "All Documents";
            item.SystemUpdate();
            web.Update();
            KpiObject kp = new KpiObject(name, SPContext.Current.Site.Url + itemList.DefaultViewUrl);
            this.kpiList.Add(kp);
        }
    }


text:
Q: Does AWS Cognito remove the need for a 'users' table in my database? With AWS Cognito doing its thing with authentication does this mean I no longer need a traditional 'users' table in my database?
Currently the app I have inherited has the traditional 'users' table I reference with sql queries looking for many-to-many and many-to-one joins with organisation, message boards, etc tables.
Do I query the Cognito user groups (that feels wrong) or is there some 'sync' method to have an updated 'users' table in my database.
Reading to docs and watching a few tutorials is great but no one seams to do more than authenticate. Where is the authorisation, and getting user names, email with join queries.
Be gentle, trying to work and study with a new baby in the room

A: You can certainly use Cognito User Pools service to manage authentication instead of your 'user' table, but not necessarily. You can also integrate other identity providers and login with Twitter, Amazon, etc, or even your own database. A benefit of using Cognito User Pools is that you don't have to code the authentication flows, as they are implemented by the service correctly and securely.
Best of luck with the code and the baby!

A: My experience has been it does not obsolete the need for a users table, for a couple of reasons.

*

*I would routinely run into AWS throttling errors when invoking the Cognito getUser/listUser methods while using Cognito as the primary user data store. AWS support would increase the API limits on our account but I was always worried they would reappear.

*You are essentially limited to querying users by username/email/phone. The listUser method is very limited for searching

*If you want to store other user data then you have to put them in custom Cognito attributes and managing those got tiresome quickly

The design I ended up on was to set a post-confirmation trigger on the Cognito user pool and have it copy all the user data into a relational database or DynamoDB when a user signed up. The primary key of the users table would be the Cognito username so if necessary I could lookup the user in both the database and Cognito. Basically I just use Cognito for authentication and not as a primary user database


text:
Q: Change in Energy when placing an object on the ground It seems like a simple question but I was wondering where does the energy go when I place an object from a height on the floor.
Initially it's all stored as potential energy, and as I'm moving the object it has kinetic energy. But when I have placed it on the ground where does the energy go? I'm sure a bit is lost as heat through friction but where does the majority of the energy go?

A: It depends, are you placing the object on the ground or are you dropping it? You said it yourself. As a mass falls towards the ground it loses its potential energy, which is transferred to kinetic energy. Think about what happens when you drop an object. If the object is a bouncy ball you can see that some energy is lost to heat/friction, but the rest is transferred to kinetic energy again.
What about if you drop a cannon ball on the ground? It would dent the floor right? What do you think happened to the cannon ball's kinetic energy in that scenario?
I'm sorry if my answer seems a little obscure but your question is marked "homework and exercises" so I'm trying to get you to think of the answer yourself rather than just giving it to you.

A: REVISED ANSWER:
The following is a revision to my answer in light of the following comment you gave me:
As you mentioned I am "putting" it to rest on the floor and NOT dropping it. The change in energy when dropping is clearer as the bottle keeps bouncing and losing energy as sound, friction and such
Thanks for the clarification.  I will now focus on your following specific question, coming at it a little differently:
"where does the energy go when I place an object from a height on the floor".
When you ask where the energy goes, there are two types of energy in this example: kinetic energy and gravitational potential energy.  Let's account for each.
Let's consider first kinetic energy.
You take an object that is initially at rest  (zero kinetic energy) at a certain height, say the height of the surface of a table above the floor. In order to bring it down the object needs to "get moving". That means the object needs to initially acquire kinetic energy. In order for this to happen your upward force on the object has to be less than the downward force of gravity. There is then a net downward force and gravity does positive work on the object to give the object kinetic energy.
As the object approaches the ground you now need to exert an upward force greater than the downward force of gravity in order to decelerate the object (slow it down). You are doing negative work on the object (your upward force is in the opposite direction to the displacement of the object) taking kinetic energy away from the object and transferring it to yourself.  You can also look at it as the object doing positive work on you transferring energy from itself to you.
The question of exactly how you absorb that kinetic energy is a physiological one that I am not qualified to answer. My guess is the work the object does on our muscles results in various forms of friction, raising tissue temperature and eventually being dissipated as heat.
Bottom line: The positive change in kinetic energy due to the positive work that gravity did on the object at the beginning equals the negative change in kinetic energy due to the negative work you did on the object to bring the object to rest.  The fact that the object had kinetic energy between the start and stop is irrelevant because the overall net change in kinetic energy is zero. Kinetic energy is therefore accounted for.
Now let's consider gravitational potential energy.
Since there is no net change in kinetic energy of the object, gravity does positive work on the object at the expense of the gravitational potential energy of the object/earth system, while at the same time you are doing an equal amount of negative work on the object transferring the energy gravity gave it to yourself. The net work done on the object is zero, but the gravitational potential energy of the object/earth system has been transferred to you.
Note that the reverse happens if you take an object at rest on the ground and place it at rest on the surface of the table.  In this case, you do positive work on the object, transferring energy from you to the object, while at the same time gravity does an equal amount of negative work, transferring the energy you gave the object to the gravitational potential energy of the object/earth system. The net work done on the object is zero (no change in kinetic energy), but the external work you did on the object/earth system has increased the gravitational potential energy of the object/earth system.
I hope this different way of explaining what is going on will help you. The following link will perhaps further enhance this explanation.
https://courses.lumenlearning.com/physics/chapter/7-3-gravitational-potential-energy/


text:
Q: Magento 2 - Store wise description very hard to manage I have 1000s of products and there are 3 different stores.
Product descriptions are stored on store level. So everytime I need to update any description I have to update it on all store levels.
Is there any other way of update description that when I update on one store it will update on all other stores too?
Thanks

A: You need to make description attribute global.

*

*Go to manage attribute Store -> Attributes -> Products

*search for the description attribute

*In  Advanced Attribute Properties set Scope to Global
By doing this description attribute will be same for all stores.
Note: After doing this, you would not be able to update different descriptions on store level.


text:
Q: Need to write regex for top-level web address which includes letters, numbers, underscores as well as periods, dashes, and a plus sign The check_web_address function checks if the text passed qualifies as a top-level web address, meaning that it contains alphanumeric characters (which includes letters, numbers, and underscores), as well as periods, dashes, and a plus sign, followed by a period and a character-only top-level domain such as ".com", ".info", ".edu", etc. Fill in the regular expression to do that, using escape characters, wildcards, repetition qualifiers, beginning and end-of-line characters, and character classes.
import re

def check_web_address(text):
  pattern = ___
  result = re.search(pattern, text)
  return result != None

print(check_web_address("gmail.com")) # True
print(check_web_address("www@google")) # False
print(check_web_address("www.Coursera.org")) # True
print(check_web_address("web-address.com/homepage")) # False
print(check_web_address("My_Favorite-Blog.US")) # True

I have tried with this pattern but all sample input came true:
pattern = '[^/@][A-Za-z._-]*$'

What will be exact pattern to cover all above scenario?

A: Finally I have got this way to cover all above scenarios with below code,
import re
def check_web_address(text):
  pattern = r'^[A-Za-z._-][^/@]*$'
  result = re.search(pattern, text)
  return result != None

print(check_web_address("gmail.com")) # True
print(check_web_address("www@google")) # False
print(check_web_address("www.Coursera.org")) # True
print(check_web_address("web-address.com/homepage")) # False
print(check_web_address("My_Favorite-Blog.US")) # True

A: This is working fine
  pattern = r"^\w.*\.[a-zA-Z]*$"

A: The pattern that I used to accomplish this was:
pattern = "^[\w]*[\.\-\+][^/@]*$"

A: I did it this way
import re
def check_web_address(text):
  pattern = r'^[A-Za-z0-9-_+.]*[.][A-Za-z]*$'
  result = re.search(pattern, text)
  return result != None

print(check_web_address("gmail.com")) # True
print(check_web_address("www@google")) # False
print(check_web_address("www.Coursera.org")) # True
print(check_web_address("web-address.com/homepage")) # False
print(check_web_address("My_Favorite-Blog.US")) # True

^ start
[A-Za-z0-9-_+.]* repetition qualifiers of alphanumeric characters (which includes letters, numbers, and underscores), as well as periods, dashes, and a plus sign
[.] followed by a period
[A-Za-z]* a character-only top-level domain such as ".com", ".info", ".edu", etc
$ End

A: I tried with this pattern:
pattern = "\.[a-zA-Z]+$"
This should work too. It checks if result contains dots followed by one or more occurence of upper of lower case alphabets at the end.

A: pattern = r"^[\w|\.\-\_]+\.[a-zA-Z]+$"

A: import re
def check_web_address(text):
  pattern = r'^[\w\-+.]+\.[a-zA-z]+$'
  result = re.search(pattern, text)
  return result != None

print(check_web_address("gmail.com")) # True
print(check_web_address("www@google")) # False.
print(check_web_address("www.Coursera.org")) # True
print(check_web_address("web-address.com/homepage")) # False.
print(check_web_address("My_Favorite-Blog.US")) # True

Explanations

*

*^[\w\-+.]+ => beginning of the expression should start with word,+,- .
eg: www.Coursera or www.89+- so on and can at-least have one character matching so '+' at the end

*\. => simple to catch middle section of pattern www.somedomain.

*[a-zA-z]+$ => matchs .in or .IN  simple pattern expression because domain are simple without any special characters

Hopes it helps :) Happy Stacking

A: import re
def check_web_address(text):
  pattern = r'\.[comeduorginfoUSnetintmilgov]*$'
  result = re.search(pattern, text)
  return result != None

print(check_web_address('gmail.com')) # True
print(check_web_address('www.google')) # False
print(check_web_address('www.Coursera.org')) # True
print(check_web_address('web-address.com/homepage')) # False
print(check_web_address('My_Favorite-Blog.US')) # True

A: I think this is the most accurate:
pattern = r"^[\w.+-]*\.[a-zA-Z]*$"

A: This Should Work fine:
pattern = r".*\.[A-Za-z]{1,3}.$"

In One long sentence:
Here we filter any number of character(.*) followed by a period(.) then check for 2 or 3 ending character capital or small ([A-Za-z]{1,3}.$)
Here:
.* : Accepts any Number of any character.
\. :  Backslash '' is escape character so it is only period('.')
[A-Za-z] : character class [A-Za-z] means Accepts capital and small Alphabets,
{1,3} : to limit above ([A-Za-z]) character between 1 & 3 (excluding 1 including 3)
. : usually it means any One single character but with {1,3} it accepts the provided number of character.
$ : means the string should end with
In One long sentence:
Here we filter any number of character(.*) followed by a period(.) then check for 2 or 3 ending character capital or small ([A-Za-z]{1,3}.$)


text:
Q: How to exit help in vim I just used the help files in vim and now I am stuck in help.
:q Exits the entire program and I am getting tired of having to close and reopen vim every time I use help. I would prefer a command that can close help and return me to the program I am writing.
I have trouble searching google.com because the search string exit help in vim obviously returns articles about exiting vim itself, something I have became very good at.
Does anyone know how to do this?
EDIT: I must have been somehow getting stuck in the split screen thing. That's why I was unable to get out of the help via :q

A: :q is already the solution.
It closes not the whole vim session, but only the active window (split section within vim). If this is window is the help, only the help will be closed. If your document is active, the document will be closed.
If this is the last non-help window, the help will close as well -- which means vim is closed.
Use Ctrl+W followed by a cursor key to make sure your cursor is in the help window. Then try :q again.

A: I use Ctrl+W+C or Ctrl+W+Q, although I agree that like many other more modern read only windows, it would be more natural if we could quit it with just pressing q.

A: You must have somehow arrived at a sole help window. Usually, :help splits a window, and a :q in that window will just close the help, and return to the other window.
Or, you've typed the :q while in the other window, not the help. Vim doesn't "count" help windows as full windows, and will quit completely when only help windows would be left.
There are quite some window management commands; for example, :close is a variant of :quit that won't exit Vim. Though initially confusing, learn how to use them, as they are very powerful. :help windows has all the information.

A: :bd will unload the current buffer (exit help) and return you to the last used buffer.
The command will not exit vim.
For example, the commands:
:help :bd
:only
:bd

will not exit vim despite the session having only 1 window.

A: Recent Vims have the :helpclose command (this needs a Vim 7.4.449)

A: :q is a little bit annoying since this is a readonly buffer. And I believe people rarely need to record a macro in help buffer.
So I'd like to map q to :q:
autocmd FileType help noremap <buffer> q :q<cr>

A: I know this is late, but there is a shortcut for :q which is ZQ. ZQ is quit without saving. In the same way if you want to quit with save, then use ZZ(this is similar to :wq).


text:
Q: Executing R script from shell I am trying to call an R script from a shell.
The script looks like this:
functionName <- function(file1){
  args <- commandArgs(trailingOnly = TRUE)
  print(args)
  data <- read.table(file(file1),row.names=1,header=FALSE,sep='\t',dec='.')}

functionName(args[1])

my file1 contains rows of numbers like:
1 2 1 2 4
2 4 5 4 2
1 2 3 4 5

However, calling this script from the shell:
Rscript scriptName fileName

I get the following error:
Error in args[1] : object of type 'closure' is not subsettable
Calls: processGroups -> read.table -> file
Execution halted

Can anyone explain what this error message means?

A: Try functionName(commandArgs(trailingOnly = TRUE)[1]). args object defined in functionName is not "visible" outside the function. Here, it points to the args() builtin function, see ?args.


text:
Q: Preventing an Undefined array entry I have 2 simple functions that when called either moves one entry back, or one entry forward in the array. However when you get to the end and all of the entries have been shown, there is an additional "undefined" entry. Any suggestions on how to fix this?
<?php
$slide_img_array = array();
$slide_desc_array = array();
$slide_name_array = array();

while (!$sql_pres_select->eof()) {
    array_push($slide_img_array, $sql_pres_select->valueof('file_location'));
    array_push($slide_desc_array, $sql_pres_select->valueof('description'));
    array_push($slide_name_array, $sql_pres_select->valueof('slide_name'));
    $sql_pres_select->next();
}
?>
<script>

    var slide_no = 0;
    var slides = <?php echo json_encode($slide_img_array); ?>;
    var desc = <?php echo json_encode($slide_desc_array); ?>;
    var names = <?php echo json_encode($slide_name_array); ?>;

    function nextSlide() {
        if (slide_no < slides.length) {
            slide_no++;
            document.getElementById("display").src = slides[slide_no];
            document.getElementById("func_slide_desc").innerHTML = desc[slide_no];
            document.getElementById("func_slide_name").innerHTML = names[slide_no];

        }

    }
    function prevSlide() {
        if (slide_no > 0) {
            slide_no--;
            document.getElementById("display").src = slides[slide_no];
            document.getElementById("func_slide_desc").innerHTML = desc[slide_no];
            document.getElementById("func_slide_name").innerHTML = names[slide_no];
        }
    }

    function goToSlide(id) {
        slide_no = id;
        document.getElementById("display").src = slides[slide_no];
        document.getElementById("func_slide_desc").innerHTML = desc[slide_no];
        document.getElementById("func_slide_name").innerHTML = names[slide_no];
        document.getElementById('slide_index').innerHTML = slide_no;

    }
</script>

I think I need to write a line that checks if whether the end of the array has been reached.But I'm unsure as to how I should do this. I have tried doing the following:
function nextSlide() {
            if (slide_no < slides.length) {
                slide_no++;
                document.getElementById("display").src = slides[slide_no];
                document.getElementById("func_slide_desc").innerHTML = desc[slide_no];
                document.getElementById("func_slide_name").innerHTML = names[slide_no];

            }
            else if (slide_no===slides.length){
                break;
            }

But when I tried that it simply stopped at the first entry and the nextSlide function would no longer work

A: The issue is that to access an array element, you need the index to be between 0 to the array length - 1.
In your nextSlide() first implementation you do the following:
function nextSlide() {
    if (slide_no < slides.length) {
        slide_no++;

which means that when slide_no is equal to length-1 and you call the function, the if() condition will be true because slide_no will be less than slides.length. Then you add 1 to slide_no, which means that slide_no is equal to slides.length now, and you 1 beyond the index limits - this is why you got an undefined value.
I would rewrite it like this
function nextSlide() {
    if (slide_no < slides.length - 1) {
        slide_no++;
        document.getElementById("display").src = slides[slide_no];
        document.getElementById("func_slide_desc").innerHTML = desc[slide_no];
        document.getElementById("func_slide_name").innerHTML = names[slide_no];
    }
}

A: Remove else if and everything inside it, also also replace slide_no < slides.length to slide_no < slides.length - 1 or move line slide_no++ to the end of commands in if block.
So it would fix your issue. The problem was in incremention of slide_no before accessing slides array.
To avoid execution of something you don't need to execute break within function, just simply ommit adding any new code ( add  code only into if body) or put return; in else statement if you need to stop function from futher execution.