text:
Q: Refactoring three very similar classes using inheritance? I'm currently working on refactoring the code-base for one of our services. I'm been going through reviewing everything, and I feel it's a bit scattered, and could probably adhere to OOP principles better.
I have three classes that are all derivative of another class Cache. All three of these classes perform the exact same operations, the only difference is the type of object they are querying for and what method call they use to query them. What would be the best method of making these classes even more simple?
public static class ZenDeskCache
{
    public static ZendeskApi Api = new ZendeskApi(GlobalVariables.ZendeskUrl, GlobalVariables.ZendeskUser,
        GlobalVariables.ZendeskPass);

    public class Users : Cache<Users, List<User>>
    {
        protected override List<User> GetData()
        {
            var users = Api.Users.GetAllUsers();
            var allUsers = new List<User>(users.Users);

            while (users.NextPage != null)
            {
                users = Api.Users.GetByPageUrl<GroupUserResponse>(users.NextPage);
                allUsers.AddRange(new List<User>(users.Users));
            }

            allUsers = allUsers.OrderBy(n => n.Name).ToList();

            return allUsers;
        }

        protected override TimeSpan GetLifetime()
        {
            return TimeSpan.FromDays(1);
        }
    }

    public class Organizations : Cache<Organizations, List<Organization>>
    {
        protected override List<Organization> GetData()
        {
            var organizations = Api.Organizations.GetOrganizations();
            var allOrgs = new List<Organization>(organizations.Organizations);

            while (organizations.NextPage != null)
            {
                organizations = Api.Users.GetByPageUrl<GroupOrganizationResponse>(organizations.NextPage);
                allOrgs.AddRange(new List<Organization>(organizations.Organizations));
            }

            allOrgs = allOrgs.OrderBy(n => n.Name).ToList();

            return allOrgs;
        }

        protected override TimeSpan GetLifetime()
        {
            return TimeSpan.FromDays(1);
        }
    }

    public class Groups : Cache<Groups, List<Group>>
    {
        protected override List<Group> GetData()
        {
            var groups = Api.Groups.GetGroups();
            var allGroups = new List<Group>(groups.Groups);

            while (groups.NextPage != null)
            {
                groups = Api.Groups.GetByPageUrl<MultipleGroupResponse>(groups.NextPage);
                allGroups.AddRange(new List<Group>(groups.Groups));
            }

            allGroups = allGroups.OrderBy(n => n.Name).ToList();

            return allGroups;
        }

        protected override TimeSpan GetLifetime()
        {
            return TimeSpan.FromSeconds(600);
        }
    }
}

A: The problem is that the design of the underlying API loves to repeat type information in all property names:
... Api.Groups.GetGroups();
... groups.Groups ...

    ... Api.Groups.GetByPageUrl<MultipleGroupResponse>(...);
    ... groups.Groups ...

This misdesign makes it difficult to abstract over all otherwise identical Api.X objects. In particular, your methods differ in these points:

*

*the Api.X object that methods are called on

*the name of the Api.X.GetX() method to get the inital response

*the name of the property x.X that accesses the data in one response

*the type of the response from GetPageByUrl
The solution is to introduce an appropriate layer that levels away these differences. E.g. you could define a common function CommonGetData that could be invoked like this:[1]
[1]: Please note that I'm not fluent in C#, so only take note of the conceptual design rather than the specifics of syntax.
protected override List<User> GetData()
{
    return CommonGetData(
        Api.Users,
        (api) => api.GetAllUsers(),
        (response) => response.Users,
    );
}

With CommonGetData being defined approximately like this:
private static <T, ResponseT, ApiT> List<T> CommonGetData(
        ApiT api,
        Function<ResponseT, ApiT> getInitialResponse,
        Function<Collection<T>, ResponseT> itemsFromResponse,
    )
{
    ResponseT response = getInitialResponse(api);
    var allItems = new List<T>(itemsFromResponse(response);

    while (response.NextPage != null)
    {
        response = api.GetPageByUrl<ResponseT>(response.NextPage);
        allItems.AddRange(new List<T>(itemsFromResponse(response));
    }

    allItems = allItems.OrderBy(n => n.Name).ToList();

    return allItems;
}

If using lambdas is not your thing, you could also note that this looks remarkably like a candidate for either the Strategy Pattern (in CommonGetData, the callback parameters represent strategies), or for the template method pattern. We could then define an abstract Api like this:
abstract class CommonApi<T, ResponseT>
{
    protected abstract ResponseT GetInitialResponse();
    protected abstract Collection<T> ItemsFromResponse(ResponseT response);
    protected abstract GetPageByUrl(Url url);

    private List<T> GetData()
    {
        ResponseT response = GetInitialResponse();
        var allItems = new List<T>(ItemsFromResponse(response);

        while (response.NextPage != null)
        {
            response = GetPageByUrl(response.NextPage);
            allItems.AddRange(new List<T>(ItemsFromResponse(response));
        }

        allItems = allItems.OrderBy(n => n.Name).ToList();

        return allItems;
    }
}

class UsersApi : CommonApi<User, MultipleUserResponse>
{
    protected override MultipleUserResponse GetInitialResponse()
    {
        return Api.Users.GetAllUsers();
    }

    protected override Collection<User> ItemsFromResponse(MultipleUserResponse response)
    {
        return response.Users;
    }

    protected override GetPageByUrl(Url url)
    {
        Api.Users.GetPageByUrl<MultipleUserResponse>(url);
    }
}

which would be used like
private UsersApi usersApi = new UsersApi();

protected override List<User> GetData()
{
    return usersApi.GetData();
}

Ideally, the existing APIs could be refactored to implement common interfaces, so that wrapping them in common interfaces that delegate to the incompatible methods would not be necessary.
Also note that your very high use of static classes probably gets in the way of code reuse, since it makes it difficult to pass these around as values. If only one instance may exist, prefer the Singleton Pattern which also makes your classes easier to test when compared with static classes.

A: What you need is a non-member (static utility or base class) generic helper function for concatenating the NextPage results from different IEnumerable objects.
Once that is done, approximately five lines of code (in each class) can be condensed down to one line. This will clear up the clutter and IMHO no further refactoring is needed.
It would be best if NextPage is an interface method on the response object. Likewise, it would be best if the response object implement IEnumerable<T> for the respective return type T.
If that is not the case, you may consider:

*

*Fix the upstream library or code

*Use type dynamic

*

*But this is a very slippery path.

A: If you really want to refactor these classes using inheritance, then fine, go ahead, amon's answer is right on the money.
However, be advised that eliminating a little code duplication is one of the least legitimate reasons for complicating a design by using inheritance.  If the resulting code is more verbose than the original, then you have a net loss in readability, understandability, and maintainability.
This might actually be worse than a bit of code duplication.

A: Could you create a generic class with a type variable for the varying data class?
public class WhateverCache<T> : Cache<T, List<T>> {
  protected override List<T> GetData() {
    // whatever logic you have
  }

The specific classes would only override the time span-defining method.

A: After reviewing some of the information posted by @Amon, I think I've got something a little neater. It's more verbose, but it seems to be cleaner.
CommonApi
public abstract class CommonApi<T, TResponse>
    where TResponse : GroupResponseBase
{
    protected abstract TResponse GetInitialResponse();
    protected abstract List<T> ItemsFromResponse(TResponse response);
    protected abstract TResponse GetPageByUrl(string url);

    public ZendeskApi Api = new ZendeskApi(
        GlobalVariables.ZendeskUrl,
        GlobalVariables.ZendeskUser,
        GlobalVariables.ZendeskPass);

    public List<T> GetData()
    {
        var response = GetInitialResponse();
        var allItems = new List<T>(ItemsFromResponse(response));

        while (response.NextPage != null)
        {
            response = GetPageByUrl(response.NextPage);
            allItems.AddRange(ItemsFromResponse(response));
        }

        allItems = SortData(allItems);

        return allItems;
    }

    private List<T> SortData(List<T> list)
    {
        return list;
    }

    public List<User> SortData(List<User> list)
    {
        return list.OrderBy(n=>n.Name).ToList();
    }

    public List<Group> SortData(List<Group> list)
    {
        return list.OrderBy(n => n.Name).ToList();
    }

    public List<Organization> SortData(List<Organization> list)
    {
        return list.OrderBy(n => n.Name).ToList();
    }
}

UserListApi
public class UserListApi : CommonApi<User, GroupUserResponse>
{
    protected override GroupUserResponse GetInitialResponse()
    {
        return Api.Users.GetAllUsers();
    }

    protected override List<User> ItemsFromResponse(GroupUserResponse response)
    {
        return response.Users.ToList();
    }

    protected override GroupUserResponse GetPageByUrl(string url)
    {
        return Api.Users.GetByPageUrl<GroupUserResponse>(url);
    }
}

OrganizationListApi
public class OrganizationListApi : CommonApi<Organization, GroupOrganizationResponse>
{
    protected override GroupOrganizationResponse GetInitialResponse()
    {
        return Api.Organizations.GetOrganizations();
    }

    protected override List<Organization> ItemsFromResponse(GroupOrganizationResponse response)
    {
        return response.Organizations.ToList();
    }

    protected override GroupOrganizationResponse GetPageByUrl(string url)
    {
        return Api.Organizations.GetByPageUrl<GroupOrganizationResponse>(url);
    }
}

GroupListApi
public class GroupListApi : CommonApi<Group, MultipleGroupResponse>
{
    protected override MultipleGroupResponse GetInitialResponse()
    {
        return Api.Groups.GetGroups();
    }

    protected override List<Group> ItemsFromResponse(MultipleGroupResponse response)
    {
        return response.Groups.ToList();
    }

    protected override MultipleGroupResponse GetPageByUrl(string url)
    {
        return Api.Groups.GetByPageUrl<MultipleGroupResponse>(url);
    }
}

ZendeskCache
public class ZendeskCache
{
    public class Users : Cache<Users, List<User>>
    {
        protected override List<User> GetData()
        {
            var users = new UserListApi();

            return users.GetData();
        }

        protected override TimeSpan GetLifetime()
        {
            return TimeSpan.FromDays(1);
        }
    }

    public class Organizations : Cache<Organizations, List<Organization>>
    {
        protected override List<Organization> GetData()
        {
            var orgs = new OrganizationListApi();

            return orgs.GetData();
        }

        protected override TimeSpan GetLifetime()
        {
            return TimeSpan.FromDays(1);
        }
    }

    public class Groups : Cache<Groups, List<Group>>
    {
        protected override List<Group> GetData()
        {
            var groups = new GroupListApi();
            return groups.GetData();
        }

        protected override TimeSpan GetLifetime()
        {
            return TimeSpan.FromSeconds(1);
        }
    }
}

I think it may be possible to reduce the ZendeskCache even a bit further, but I'll keep tinkering. I'm trying to figure out methods to make my future coding practices cleaner and more maintainable.


text:
Q: Optimising a MySQL script with 1.7 billion records I am trying to optimise a MySQL script that I have created. Here is a bit of background on the project.
We have 2 system which we are now merging into one system, I am currently writing the scripts to merge the databases together. I need this to run as fast as possible, while this script is running we have to shut down the systems and we don't want too much down time.
Both systems have a table called venue, zone and device_vendor which are identical they just have different data. When I merged the tables together obviously the IDs for the values in those tables have changed and they are foreign keys in a lot of other tables. The table I am currently working on has 1.7 billion records and all has the values venue_id, zone_id and device_vendor_id so I have to change these values to the new IDs.
Here is the script that I have written to change the IDs to the new values. All these values are also indexes which is why it is taking so long.
INSERT INTO `intelli_sense`.`tracking_daily_stats_zone_unique_device_uuids_per_hour` (day_epoch, day_of_week, hour, venue_id, zone_id, device_uuid, device_vendor_id, first_seen, last_seen, is_repeat)

SELECT day_epoch, day_of_week, hour, (CASE WHEN intelli_sense_venue.id!=0 THEN intelli_sense_venue.id ELSE 0 END), (CASE WHEN intelli_sense_zone.id!=0 THEN intelli_sense_zone.id ELSE 0 END), device_uuid, (CASE WHEN intelli_sense_device_vendor.id!=0 THEN intelli_sense_device_vendor.id ELSE 0 END), first_seen, last_seen, is_repeat
FROM geo_sense.daily_stats_zone_unique_device_uuids_per_hour AS tracking_daily_stats_zone_unique_device_uuids_per_hour
LEFT JOIN geo_sense.venue AS tracking_venue ON tracking_venue.id = tracking_daily_stats_zone_unique_device_uuids_per_hour.venue_id
LEFT JOIN intelli_sense.venue AS intelli_sense_venue ON intelli_sense_venue.name = tracking_venue.name
LEFT JOIN geo_sense.zone AS tracking_zone ON tracking_zone.id = tracking_daily_stats_zone_unique_device_uuids_per_hour.zone_id
LEFT JOIN intelli_sense.zone AS intelli_sense_zone ON intelli_sense_zone.name = tracking_zone.name AND intelli_sense_zone.lat = tracking_zone.lat AND intelli_sense_zone.lon = tracking_zone.lon
LEFT JOIN geo_sense.device_vendor AS tracking_device_vendor ON tracking_device_vendor.id = tracking_daily_stats_zone_unique_device_uuids_per_hour.device_vendor_id
LEFT JOIN intelli_sense.device_vendor AS intelli_sense_device_vendor ON intelli_sense_device_vendor.name = tracking_device_vendor.name AND intelli_sense_device_vendor.description = tracking_device_vendor.description;

As you can see from the script above I have used LEFT JOINS to update these values. I have basically imported both databases into one server and now I am merging them together to create a new database called intelli_sense.
In the script above this isn't merging the 2 databases together it is just updating the values in the tracking_daily_stats_zone_unique_device_uuids_per_hour table which is from the geo_sense database because after merging the venue, zone and device_vendor tables the IDs have changed. I need to update all the tables which are related to those tables.
I have ran this script and it took 3 days to insert 50mil records which is way to long so I stopped it.
I need this script to finish in less then a day because I have 3 tables with this amount of data and I don't want too much system downtime.
I can't share the data since there is so much so I hope that script explains it enough, the actual script works its just a case of speeding it up. The data is also personal data so I wouldn't be able to share it anyway.
If you don't think this is impossible let me know and I will find a new way to do it while leaving both systems on so it can take as long as it wants.
Thanks in advance.
EDIT: Here is the explain statement for the above query.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sort lines, part of a closed shape I have an array of structures, each structure element holds the endpoints of lines in 3D space.
struct POINTS
{
   float xStart;
   float yStart;
   float zStart;

   float xEnd;
   float yEnd;
   float zEnd;
};

Combining these lines will create a closed shape. Unfortunately the lines are not in the correct order.
To make the lines in order, to create the closed loop, I think the line points should rearrange like:

*

*Take a line, say LINE-A.

*Find the start point of another line, say LINE-X, whose start point is LINE-A's end point.
OR

*Find the End point of another line, say LINE-Y, whose End point is LINE-A's start point.....

However I am not sure this is the right solution.
I will appreciate for suggesting suitable optimized methods to solve this problem.
[Note Added]
My real intention is to create the closed shape in 2D plane. So solution for 2D plane is also expected from the geniuses.

A: Main idea - put all points to multimap (where key is a point coordinates and value is a index of line and begin/end mark). After that you need to select any point as startup, find index of line that has this point and fetch another end of line. Then you mark current line as used and use end of current line as startup for next iteration.
vector<POINTS> lines = generate_lines(10);
multimap<tuple<double, double, double>, pair<double, double> > M;

for (int i = 0; i < lines.size(); i++)
{
    // start point
    M.insert(make_pair(make_tuple(lines[i].xStart, lines[i].yStart, lines[i].zStart),
                       make_pair(i, 0) ) );

    // end point
    M.insert(make_pair(make_tuple(lines[i].xEnd, lines[i].yEnd, lines[i].zEnd),
                       make_pair(i, 1) ) );
}

auto coords1 = M.begin()->first;
auto pos1 = M.begin()->second;

vector<bool> used(lines.size(), false);

for (int i = 0; i < lines.size(); i++)
{
    std::tuple<double, double, double> coords2 = pos1.second ? make_tuple(lines[pos1.first].xStart, lines[pos1.first].yStart, lines[pos1.first].zStart) :
                                                               make_tuple(lines[pos1.first].xEnd, lines[pos1.first].yEnd, lines[pos1.first].zEnd);

    cout << pos1.first << ": " << get<0>(coords1) << " " << get<1>(coords1) << " " << get<2>(coords1) << " - "
                               << get<0>(coords2) << " " << get<1>(coords2) << " " << get<2>(coords2) << endl;

    used[pos1.first] = true;

    pair<int, int> nextPos(-1, -1);

    auto r = M.equal_range(coords2);
    for (auto it = r.first; it != r.second; it++)
        if (!used[it->second.first])
        {
            nextPos = it->second;
            break;
        }

    if (nextPos.first == -1 && i != lines.size()-1)
    {
        cout << "something bad happens\n";
        return 1;
    }

    pos1 = nextPos;
    coords1 = coords2;
}

The complexity of the algorithm is O(N * logN).
This algorithm doesn't required end-to-start sorted data.
You can find full source code with example generation here:
http://ideone.com/TuzjMn


text:
Q: React Native AWS S3 upload I'm using react-native-image-picker and react-native-s3-upload to upload images to s3 bucket.
 RNS3.put(file, AWSOptions)
    .then((response) => {
        if (response.status !== 201) {
           throw new Error('Failed to upload image to S3');
         }
    })
    .catch(function (error) {
         console.log('Error', JSON.stringify(error));
         throw error;
    });

and I get a response like this without image been uploaded.
Object {
  "headers": Object {},
  "status": 0,
  "text": "Stream Closed",
}

A: I have exactly the same issue with a similar library called react-native-aws3.
It seems related to the new React Native version 0.62.2, because I've tried to upgrade today (my previous version was 0.61.5) and that library worked before.
I don't know if both libraries use a common API which now is broken in the new RN, but I suggest you to downgrade in the meanwhile.

A: I had the same issue and tried for days to fix it. This is what I came up with.
Make sure you follow the amplify guide and set up amplify init, amplify add auth and then do amplify push
Then do amplify add storage and follow the guide here (https://docs.amplify.aws/lib/storage/upload/q/platform/js). Then copy this code.
import Amplify, { Storage } from 'aws-amplify'
import config from './src/aws-exports'
// import awsconfig from './aws-exports';
// Might need to switch line 7 to awsconfig
Amplify.configure(config)

import { StatusBar } from 'expo-status-bar';
import React, { useState, useEffect } from 'react';
import { Button, Image, View, Platform, StyleSheet, Text } from 'react-native';
import * as ImagePicker from 'expo-image-picker';

function App() {
  const [image, setImage] = useState(null)

  useEffect(() => {
    (async () => {
      if (Platform.OS !== 'web') {
        const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
        if (status !== 'granted') {
          alert('Sorry, we need camera roll permissions to make this work!');
        }
      }
    })();
  }, []);

  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    console.log(result)

    async function pathToImageFile(data) {
      try {
        const response = await fetch(data);
        const blob = await response.blob();
        await Storage.put(`customer/images`, blob, {
          contentType: 'image/jpeg', // contentType is optional
        });
      } catch (err) {
        console.log('Error uploading file:', err);
      }
    }

    // later

    pathToImageFile(result.uri);
  }

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button title="Pick an image from camera roll" onPress={pickImage} />
      {image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
      <Button title="Upload image" onPress={() => {alert(image)}} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default withAuthenticator(App)```

A: I found an alternative module (aws-sdk) to upload files to the S3 bucket with RN 62 version.
Also, I have used base64-arraybuffer and react-native-fs modules well.
const s3bucket = new S3({
      accessKeyId: XXXXXXXXXX,
      secretAccessKey: XXXXXXXXXXXX,
      Bucket: XXXXXXXXX,
      signatureVersion: 'v4',
    });
    let contentType = 'image/jpeg';
    let contentDeposition = 'inline;filename="' + file.name + '"';

    const base64 = await fs.readFile(file.uri, 'base64');

    const arrayBuffer = decode(base64);

    s3bucket.createBucket(() => {
      const params = {
        Bucket: XXXXXXXXXXX,
        Key: file.name,
        Body: arrayBuffer,
        ContentDisposition: contentDeposition,
        ContentType: contentType,
      };
      s3bucket.upload(params, (err, data) => {
        if (err) {
          console.log('error in callback');
          console.log(err);
          setSpinner(false);
        }
        console.log('success');
        console.log(data.Location);
        setImageUrl(data.Location);
        setSpinner(false);
      });
    });

A: The problem is with RN >= 0.62
You can either roll back to version < 0.62 or you can follow what I did.
I solved it by commenting out line number 43 in android/app/src/debug/java/**/ReactNativeFlipper.java
NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
NetworkingModule.setCustomClientBuilder(
  new NetworkingModule.CustomClientBuilder() {
    @Override
    public void apply(OkHttpClient.Builder builder) {
      // builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); <---- This line
    }
  });
client.addPlugin(networkFlipperPlugin);
client.start();

You will need to rebuild the app after doing this.
Hope this helps.

A: AWS S3 upload is a powerful service provided by React Native AWS amplify. The issue here might be caused by the React Native version or improper configuration of the package. You can check some amazing articles out there that will definitely help you integrate React Native AWS amplify properly based on your project configurations and make the AWS S3 upload working properly as well.


text:
Q: Simple app for taking/storing photos on a server I am looking for a dead-simple app to take photos (either with the camera, or from the library) and store them onto a server via WiFi.  This is for taking photos of whiteboards at work.  I really want the app to be dead-simple, automatically storing a photo to the server would be great.
I don't really care what protocol it uses to communicate with the server, but it would be great if it were not a proprietary Apple protocol, so that I could use an existing Linux file server.
Does such a thing exist?

A: Dropbox is likely the best for storing photos in the cloud. It allows you to easily, and simply select photos from your library and then upload them to the Dropbox cloud.
The one caveat is that it is annoying to restore images because you have to go to each picture and restore it individually. Who knows, perhaps they will come out with an update that will fix that.

A: No apps come directly to mind that are that generic. Though I use PogoPlug for the very thing you describe. It is basically a private cloud. The device itself is very inexpensive, less than $50, and there are applications for all of the mobile platforms that will upload your pictures automatically. You just need to plug the PogoPlug into your network and attach an external hard drive (you can actually chain many drives to it) and let the PogoPlug device do the rest. It also provides a web interface so you can get to your data from anywhere. If you have more than one drive plugged in you can also set up a mirroring or backup task that will help in the event of a drive failure.


text:
Q: Describe a person who intentionally uses a saying out of context for their own purpose
This manager worked in a grocery store. It is a hard job that requires him to arrive at the store at 5:00AM, do various tasks to make the store ready, handle deliveries, staff management and unexpected issues.
He had this habit of always sarcastically saying "Just another day in paradise" often saying it to others but most often muttering it to himself. He did this every day, multiple times a day.
One day while he opened the store in the morning he got shot dead by robbers.

With do you call it when he "butchers" the saying intentionally.
What do you describe someone who intentionally uses a saying out of context  for their own purpose?
Not necessary only negative but rather describes the act of "butchering/abusing" the saying for your own purpose.
Another example for clarity:

Every time John drinks a glass of water he says "I just touched the hand of God"

I thought of hypocrite but that doesn't fit what I'm trying to say.

A: The manager in question was probably being facetious as a means of venting his frustration through deliberate/forced humour.
ODO:

facetious
ADJECTIVE
Treating serious issues with deliberately inappropriate humour;
  flippant.
  'a facetious remark'
'Forgive me for being facetious in these desperately serious times,
  but sometimes ridicule is the only release from anger.'
'I realize he was likely being facetious with discussing how he's
  perfect, but it still amazes me that he'd say it.'

A: The people in your examples are using irony to express their sarcasm.

irony   the expression of one's meaning by using language that normally signifies the opposite, typically for humorous or emphatic
effect : "Don't go overboard with the gratitude," he rejoined with
heavy irony.
sarcasm
the use of irony to mock or convey contempt : his voice, hardened by sarcasm, could not hide his resentment.
Irony is the implicit humor in the contradiction between what is meant and what is expressed, or in the discrepancy between appearance
and reality. An example would be to shout, in the midst of a
hurricane, "What a perfect day for a wedding!"
Although sarcasm may take the form of irony, it is less subtle and
is often used harshly or bitterly to wound or ridicule someone. Unlike
irony, however, sarcasm depends on tone of voice for its effect (: "a
fine friend you turned out to be!" he said, with obvious sarcasm).
New Oxford American Dictionary

A: A cynic?
From Dictionary.com:

cynic: a person who
  shows or expresses a bitterly or sneeringly cynical attitude.

As per your question, a cynic would "intentionally use a saying out of context for their own purpose." For example, rather than saying, "Every cloud has a silver lining," a cynic would say, "Every silver lining has a cloud." Or rather than saying, "The glass is half full," the cynic would say, "The glass is 75% empty."


text:
Q: Is it possible to generate C++ template functions that are not inline these days? It used to be that templated functions were not always inlined. There were tremendous problems in having template functions defined in a .cpp file, since it was unaware of what a different module had passed in as the template argument. So templates were almost always pure header file, everything included.
However, code can be very large, so if I wanted to create a template class, for example Matrix and have the methods actually generated as functions, is there any way to do it?
This used to work:
template<typename Precision>
Matrix<Precision> operator *(const Matrix<Precision>& a, const Matrix<Precision>& b) {

}

and then to make sure all the methods were generated for the desired types:
Matrix<float>;
Matrix<double>;
Matrix<long double>;
Matrix<int>;

g++ now gives an error on the specification of the type (which does nothing)
and the function is generated as inline, so it is not callable.
Is there any way to do this in C++20? Do modules solve this problem?

A: The issue is orthogonal to whether or not the operator is inline, the definition (body) of the template must be available at the point of instantiation.
You've explicitly instantiated the Matrix class, but the issue is your operator * is a free operator, and so it is independent of Matrix and needs to be instantiated separately.
.h file:
// template declaration
template <typename Precision>
Matrix<Precision> operator*(Matrix<Precision> const& a, Matrix<Precision> const& b);

// explicit instantiation declaration
extern template Matrix<float> operator*(Matrix<float> const&, Matrix<float> const&);
extern template Matrix<double> operator*(Matrix<double> const&, Matrix<double> const&);

.cpp file:
// template definition
template <typename Precision>
Matrix<Precision> operator*(Matrix<Precision> const& a, Matrix<Precision> const& b) {
  // . . .
}

// explicit instantiation
template Matrix<float> operator*(Matrix<float> const&, Matrix<float> const&);
template Matrix<double> operator*(Matrix<double> const&, Matrix<double> const&);

The downside of all this is nothing here will ever be inlined (unless you use LTO), which can hurt run-time performance. For this reason explicit template instantiation is rarely used.
Modules do not solve this, but they can speedup regular build times by parsing the headers only once and storing intermediate representation in binary form.


text:
Q: issues while using AWS CDK v2 typescript I have my companies own say @mycompany/cdk": "^1.11.11" (used to manage context environment) which worked with CDK v1, now while using CDK v2 we are facing the error so want to know is it possible to work with CDK v2 and what should we do without touching "mycompany/cdk"
Following error:
ashishkarpe in ~/code/metrics-service/deploy/cdk on branch > cdk ls
npx: installed 217 in 4.275s
⨯ Unable to compile TypeScript:
lib/cdk-stack.ts:31:24 - error TS2345: Argument of type 'mycompanyStackProps<ICdkStackProps>' is not assignable to parameter of type 'StackProps'.
  Types of property 'synthesizer' are incompatible.
    Type 'import("/Users/ashishkarpe/code/metrics-service/deploy/cdk/node_modules/mycompany/cdk/node_modules/@aws-cdk/core/lib/stack-synthesizers/types").IStackSynthesizer | undefined' is not assignable to type 'import("/Users/ashishkarpe/code/metrics-service/deploy/cdk/node_modules/@aws-cdk/core/lib/stack-synthesizers/types").IStackSynthesizer | undefined'.
      Type 'import("/Users/ashishkarpe/code/metrics-service/deploy/cdk/node_modules/@mycompany/cdk/node_modules/@aws-cdk/core/lib/stack-synthesizers/types").IStackSynthesizer' is not assignable to type 'import("/Users/ashishkarpe/code/metrics-service/deploy/cdk/node_modules/@aws-cdk/core/lib/stack-synthesizers/types").IStackSynthesizer'.
        Types of property 'bind' are incompatible.
          Type '(stack: import("/Users/ashishkarpe/code/metrics-service/deploy/cdk/node_modules/@mycompany/cdk/node_modules/@aws-cdk/core/lib/stack").Stack) => void' is not assignable to type '(stack: import("/Users/ashishkarpe/code/metrics-service/deploy/cdk/node_modules/@aws-cdk/core/lib/stack").Stack) => void'.
            Types of parameters 'stack' and 'stack' are incompatible.
              Type 'import("/Users/ashishkarpe/code/metrics-service/deploy/cdk/node_modules/@aws-cdk/core/lib/stack").Stack' is not assignable to type 'import("/Users/ashishkarpe/code/metrics-service/deploy/cdk/node_modules/@mycompany/cdk/node_modules/@aws-cdk/core/lib/stack").Stack'.
                Types of property 'tags' are incompatible.
                  Type 'import("/Users/ashishkarpe/code/metrics-service/deploy/cdk/node_modules/@aws-cdk/core/lib/tag-manager").TagManager' is not assignable to type 'import("/Users/ashishkarpe/code/metrics-service/deploy/cdk/node_modules/@mycompany/cdk/node_modules/@aws-cdk/core/lib/tag-manager").TagManager'.
                    Types have separate declarations of a private property 'tags'.

31       super(scope, id, props);
                          ~~~~~

Subprocess exited with error 1

My package.json:
{
  "name": "deploy",
  "version": "2",
  "bin": {
    "deploy": "bin/deploy.js"
  },
  "scripts": {
    "build": "tsc",
    "watch": "tsc -w",
    "test": "jest",
    "cdk": "cdk"
  },
  "devDependencies": {
    "@types/jest": "^26.0.10",
    "@types/node": "^17.0.18",
    "aws-cdk": "^2.12.0",
    "jest": "^26.4.2",
    "ts-jest": "^26.2.0",
    "ts-node": "^9.0.0",
    "typescript": "^3.9.10"
  },
  "dependencies": {
    "@aws-cdk/aws-glue-alpha": "^2.13.0-alpha.0",
    "@aws-cdk/aws-kinesisfirehose-alpha": "^2.13.0-alpha.0",
    "@aws-cdk/aws-kinesisfirehose-destinations-alpha": "^2.13.0-alpha.0",
    "@aws-cdk/core": "^2.13.0",
    "@mycompany/cdk": "^1.11.11",
    "athena-express": "^7.1.4",
    "aws-cdk-lib": "^2.13.0",
    "aws-sdk": "^2.1069.0",
    "constructs": "^10.0.0",
    "dotenv": "^16.0.0",
    "npm": "^5.10.0",
    "source-map-support": "^0.5.16",
    "with": "^7.0.2"
  }
}

Update1 :
I have ran following command:
alias cdk1="npx aws-cdk@1.x"
alias cdk="npx aws-cdk@2.x"

ashishkarpe in ~/code/metrics-service/deploy/cdk on branch add-apikey > cdk --version
npx: installed 217 in 5.862s
2.13.0 (build b0b744d)
ashishkarpe in ~/code/metrics-service/deploy/cdk on branch add-apikey > cdk1 --version
npx: installed 217 in 4.376s
1.145.0 (build 9f96380)
ashishkarpe in ~/code/metrics-service/deploy/cdk on branch add-apikey > cdk1 ls ==> **gives same error**

A: You are mixing dependencies from CDK V1 and the newly released CDK V2, which are incompatible.
https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html
Turns out this is a known problem with aws-cdk, since v2 isn't properly migrated, the solution is:
npm un -g aws-cdk
npm i -g aws-cdk@1.136.0


text:
Q: Gradle task dependencies: "run integration tests" vs "deploy, run integration tests, kill deployment" I have a somewhat complex deployment task as well as an integration testing task. At the moment, my integration testing task depends on the deployment task. However, I'd like to have a sort of wrapper task for the integration testing task such that I can build a task to just run the integration test against whatever is currently running and a task to deploy, run the integration test, and then take down the deployment again.
This is the current state:
task integrationTest(type: Test, dependsOn: "startWebappNodes") {
  testClassesDirs = sourceSets.integrationTest.output.classesDirs
  classpath = sourceSets.integrationTest.runtimeClasspath
  outputs.upToDateWhen { false }
}

task runIntegrationTests(type: Exec, dependsOn: "integrationTest") {
    commandLine 'docker-compose', 'down'
    doLast {
        println "Integration tests running finished"
    }
}

How can I write a task, let's call it executeIntegrationTest, that executes the integration test without depending on startWebAppNodes and then also have a test that runs startWebAppNodes, then executeIntegrationTest, then brings down the nodes again?

A: There is a simplier way: use two main tasks for running integrationTest:

*

*the first one (your current integrationTest task) to execute tests in a standalone way (without deploy/shutdown),

*the second one (your current runIntegrationTests task) to wrap the first task, and handle the deploy/shutdown nodes.

1) Remove the dependsOn dependency between integrationTest task and startWebappNodes
=> you can execute this integrationTest task in a "standalone" way ( against whatever is currently running )
./gradlew integrationTest
    // execution of dependent task

  > Task :integrationTest
    // .. test executing...

2) Update your runIntegrationTests task to make it depends on both integrationTest and startWebappNodes tasks, and also add a constraint to make startWebappNodes execute before integrationTest, using mustRunAfter
task runIntegrationTests(type: Exec) {
    group "test"
    dependsOn startWebappNodes
    dependsOn integrationTest
    commandLine 'docker-compose', 'down'
    doLast {
        println "Integration tests running finished"
    }
}

integrationTest.mustRunAfter startWebappNodes

=> when executing task runIntegrationTests it will start nodes, execute integration test, then shutdown nodes
./gradlew runIntegrationTests
    // execution of dependent task

  > Task :startWebappNodes

  > Task :integrationTest
    // .. test executing...

  > Task :runIntegrationTests
    Integration tests running finished


text:
Q: Webscraping Table with tr class data-key Im a novice at python so bare with me. I am trying to web scrape a table from a dataset table on a real estate data website. I have previously run a similiar idea on on a property listing website in my region (United Arab Emirates) https://propertyfinder.ae Where I would run a script similar to this.
from bs4 import BeautifulSoup
from requests import get
import pandas as pd
import itertools
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()

headers = ({'User-Agent':
            'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'})

# Search Page with parameters included
pf = 'https://www.propertyfinder.ae/en/search?c=1&ob=mr&page=1'

response =  get(pf, headers=headers)
html_soup = BeautifulSoup(response.text, 'html.parser')

listings = html_soup.find_all('div', class_="card-list__item")
first = listings[0]

#Location Variable
location = first.find_all('p', class_='card__location')[0].text

#Size (sqft)
size = first.find_all('p', class_='card__property-amenity card__property-amenity--area')[0].text

and so on for other variables.
However, on this new data website, their html layout intrdouces a class type that I don't know how to use the find_all() function.

...

...

...

...

I tried doing the following,(even though I know it won't help me with indexing,) but it tells me the keyword can't be an expression.
listings = html_soup.find_all('tr', class_data-key_="table-row_0")

With this in mind, I want to be able to loop each table row and the subseqent pages by indexing the 'table-row_X' with 'X' progressing to each number. Similarly I would need to get the variables with the html5 format of

        ..
        ..

How would I access the td attributes?
Thanks in advance.
P.S. I used this as guide
https://towardsdatascience.com/looking-for-a-house-build-a-web-scraper-to-help-you-5ab25badc83e

A: To get all the values from that table, you can ignore the class for each row and just read all the
 and  elements in. The header can also be obtained via the  elements:
from bs4 import BeautifulSoup
import pandas as pd

with open('Record Data - Data Finder.html') as f_html:
    html = f_html.read()

soup = BeautifulSoup(html, 'html.parser')
header = [th.text for th in soup.table.find_all('th')]
data = []

for tr in soup.table.find_all('tr'):
    data.append([td.text for td in tr.find_all('td')])

df = pd.DataFrame(data, columns=header)
print(df)


text:
Q: CakePHP Subcake Redirect I have a problem with CakePHP (1.3) project, i need to create projects inside the same domain/hosting of other project, like this:
app
cake
plugins
templates
vendors
ADMINONE (Cake project files here)
ADMINTWO (another Cake project files here)
.htaccess
index.php
README

The problem is, when I put the CakePHP code inside ADMINONE or ADMINTWO to create the other cake projects, if I put the url http://domain.com/ADMINONE/, the URL redirects to http://domain.com or the cake read the /ADMINONE as a controller name.
How can I redirect this URL to the directory ignoring the primary directory cake's redirect?

A: Dont forget to change your index.php inside the webroot folder. In there you can set up the
APP_DIR and the ROOT if need be.


text:
Q: I want to store data from database in a local storage I have coded this app that onClicklistener fetch data from the database and store them in fragments that are displayed in a frame layout on the main activity, Now I want the data to be stored in a device permanently in order to be not fetched every time the button with onclicklistener is clicked.
Sorry I am new to this.

A: You can do
localStorage.setItem('keyname', itemtostore)

But this is to simple. We need to know that type of data you want store, to do the right treatment


text:
Q: Why does the code only work partially when using multiple tabs? I previously posted a question for an app idea here.  I decided to add on something similar within the same app so that each tab would have similar function but would deal with different sets of drug instructions.  I tried to follow the query and solution posted here but somehow lost most of the outputs of mainPanel.
This is the code that incorporates two tabs
library(tidyverse)
library(shiny)
library(shinythemes)
library(xtable)

insulin <- readRDS("insulin.rda")

# User Interface

ui <- fluidPage(
  titlePanel("Pre-operative Advice on Long-term Medications for Patients Undergoing Elective Surgery - version 0.1"),

  tabsetPanel(
    tabPanel("Long-term Medications", fluid = TRUE,
            sidebarLayout(
              sidebarPanel(
                selectInput("specialty", "Choose which surgical subspecialty",
                            c("Major Orthopaedic Arthroplasty or Revision" = "ortho",
                              "All other specialties" = "other"),
                            selected = "All other specialties"),

              ),
              mainPanel(
                br(),

                uiOutput("drugs_sel"),

                h3(textOutput(outputId = "px_name")),

                br(),

                h4(textOutput(outputId = "dob")),

                br(),

                tableOutput("drugs_table")

              )
            )

    ),

    tabPanel("Insulin", fluid = TRUE,
      sidebarLayout(
        sidebarPanel(

          selectInput("DM", "What type of diabetes does patient have?",
                      c("Type One" = "Type 1",
                        "Type Two on Insulin" = "Type 2"),
                      selected = "Type One"),

          selectInput("time", "Is patient on morning or afternoon list?",
                      c("Morning List" = "AM",
                        "Afternoon List" = "PM"),
                      selected = "Morning"),
          checkboxGroupInput("class", "Which type(s) of insulin is patient on?",
                             c("Long and Intermediate acting",
                               "Pre-Mixed",
                               "Rapid or Short acting"))
        ),
        mainPanel(
          br(),

          helpText("Choose from the type(s) of insulin from left panel before typing",
                   "Please ensure the type(s) of insulin are correct before proceeding"),

          uiOutput("insulin_sel"),

          h3(textOutput(outputId = "px_name")),

          br(),

          h4(textOutput(outputId = "dob")),

          br(),

          tableOutput("insulin_table"),

          radioButtons('format', 'Document format', c('PDF'),
                       inline = TRUE),
          downloadButton('downloadReport')
        )

      )

    )

  )
)

server <- function(input, output){
  my_insulin_table <- reactive({
    insulin_subset <- insulin %>% filter(DM == input$DM,
                                         Time == input$time,
                                         Class %in% input$class)
    tab <- insulin_subset %>% filter(Name %in% input$name) %>% select(Class, Name, Plan)
    return(tab)
  })

  my_drugs_table <- reactive({
    drugs_subset <- drugsUI %>% filter(Specialty == input$specialty)

    drug_tab <- drugs_subset %>% select(Name, Recommnedations)
    return(drug_tab)
  })

  output$px_name <- renderText({input$px_name})

  output$dob <- renderText({input$dob})

  output$drugs_sel <- renderUI({
    drugs_subset <- drugsUI %>% filter(Specialty == input$specialty)

    selectizeInput("drug", "Type in name of drug",
                   choices = lsit("Type in name of drug" = "",
                                  "Names" = drugs_subset$Name),
                   selected = NULL,
                   multiple = TRUE,
                   options = NULL)

  })

  output$drug_table <- renderTable({
    xtable(my_drugs_table())
  })

  output$insulin_sel <- renderUI({

    insulin_subset <- insulin %>% filter(DM == input$DM,
                                         Time == input$time,
                                         Class %in% input$class)

    selectizeInput("name", "Type in name of insulin",
                   choices = list("Begin typing name of insulin" = "",
                                  "Names" = insulin_subset$Name),
                                  selected = NULL,
                                  multiple = TRUE,
                                  options = NULL)
  })

  output$insulin_table <- renderTable({
    xtable(my_insulin_table())
  })

  output$downloadReport <- downloadHandler(
    filename = function() {("insulin-instructions.pdf")
      # paste('my-report', sep = '.', switch(
      #   input$format, PDF = 'pdf', HTML = 'html', Word = 'docx'
      # ))
    },

    content = function(file) {
      src <- normalizePath('report_insulin.Rmd')

      # temporarily switch to the temp dir, in case you do not have write
      # permission to the current working directory
      owd <- setwd(tempdir())
      on.exit(setwd(owd))
      file.copy(src, 'report_insulin.Rmd', overwrite = TRUE)

      library(rmarkdown)
      out <- render('report_insulin.Rmd',
                    params = list(name = input$px_name, dob = input$dob),
                    'pdf_document')
      file.rename(out, file)
    }
  )

}

shinyApp(ui = ui, server = server)

If I remove the tabPanel named "Long-term Medications", the other tabPanel seems to work again.
Would anyone be able to shed any light as to why this would be?  I am very new to this so some explanation would be helpful for my own education.
These are the dput() on which this is based:
dput(tail(drugsUI, 20))
structure(list(Specialty = c("other", "other", "other", "other",
"other", "other", "other", "other", "other", "other", "other",
"other", "other", "other", "other", "other", "ortho", "ortho",
"ortho", "ortho"), Name = c("Ulipristal", "Ursodeoxycholic acid",
"Valproic acid", "Valsartan", "Varenicline", "Venlafaxine", "Verapamil",
"Vigabatrin", "Vildagliptin", "Warfarin", "Zafirlukast", "Zolendronate",
"Zolpidem", "Zopiclone", "Zotepine", "Zuclopenthixol", "Aspirin only",
"Clopidogrel or other -grels only", "NSAIDS for pain (e.g. ibuprofen, naproxen, diclofenac)",
"Dual Antiplatelet (Aspirin AND Clopidogrel)"), Recommendations = c("Continue –may not be needed post op if removing uterine fibroids",
"Continue", "Continue", "Omit on day of surgery if used for high blood pressure, continue for congestive heart failure",
"Continue", "Continue – but avoid pethidine use", "Continue",
"Continue", "See Diabetes Guideline. Usually omitted morning of surgery",
"See Anticoagulation/Antiplatelet Guideline", "Continue", "Continue - but may be safely omitted if due day of procedure",
"Continue", "Continue", "Continue", "Continue", "Stop 7 days before surgery",
"See below graphic", "Stop 2 days before surgery", "Review medical indication - Surgery should be deferred until patient on single antiplatelet (i.e. Aspirin OR Clopidogrel; if not possible discuss with sugeon, anaesthetist and cardiologist about plan.  Ideally continue at least aspirin"
)), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame"
))

structure(list(DM = c("Type 2", "Type 2", "Type 2", "Type 2",
"Type 2", "Type 2", "Type 2", "Type 2", "Type 2", "Type 2", "Type 2",
"Type 2", "Type 2", "Type 2", "Type 1", "Type 1", "Type 1", "Type 1",
"Type 1", "Type 1", "Type 1", "Type 1", "Type 1", "Type 1", "Type 1",
"Type 1", "Type 1", "Type 1", "Type 2", "Type 2", "Type 2", "Type 2",
"Type 2", "Type 2", "Type 2", "Type 2", "Type 1", "Type 1", "Type 1",
"Type 1", "Type 1", "Type 1", "Type 1", "Type 1", "Type 2", "Type 2",
"Type 2", "Type 2", "Type 2", "Type 2", "Type 2", "Type 2", "Type 2",
"Type 2", "Type 1", "Type 1", "Type 1", "Type 1", "Type 1", "Type 1",
"Type 1", "Type 1", "Type 1", "Type 1"), Time = c("AM", "AM",
"AM", "AM", "AM", "AM", "AM", "PM", "PM", "PM", "PM", "PM", "PM",
"PM", "AM", "AM", "AM", "AM", "AM", "AM", "AM", "PM", "PM", "PM",
"PM", "PM", "PM", "PM", "AM", "AM", "AM", "AM", "PM", "PM", "PM",
"PM", "AM", "AM", "AM", "AM", "PM", "PM", "PM", "PM", "AM", "AM",
"AM", "AM", "AM", "PM", "PM", "PM", "PM", "PM", "AM", "AM", "AM",
"AM", "AM", "PM", "PM", "PM", "PM", "PM"), Class = c("Long and Intermediate acting",
"Long and Intermediate acting", "Long and Intermediate acting",
"Long and Intermediate acting", "Long and Intermediate acting",
"Long and Intermediate acting", "Long and Intermediate acting",
"Long and Intermediate acting", "Long and Intermediate acting",
"Long and Intermediate acting", "Long and Intermediate acting",
"Long and Intermediate acting", "Long and Intermediate acting",
"Long and Intermediate acting", "Long and Intermediate acting",
"Long and Intermediate acting", "Long and Intermediate acting",
"Long and Intermediate acting", "Long and Intermediate acting",
"Long and Intermediate acting", "Long and Intermediate acting",
"Long and Intermediate acting", "Long and Intermediate acting",
"Long and Intermediate acting", "Long and Intermediate acting",
"Long and Intermediate acting", "Long and Intermediate acting",
"Long and Intermediate acting", "Pre-Mixed", "Pre-Mixed", "Pre-Mixed",
"Pre-Mixed", "Pre-Mixed", "Pre-Mixed", "Pre-Mixed", "Pre-Mixed",
"Pre-Mixed", "Pre-Mixed", "Pre-Mixed", "Pre-Mixed", "Pre-Mixed",
"Pre-Mixed", "Pre-Mixed", "Pre-Mixed", "Rapid or Short acting",
"Rapid or Short acting", "Rapid or Short acting", "Rapid or Short acting",
"Rapid or Short acting", "Rapid or Short acting", "Rapid or Short acting",
"Rapid or Short acting", "Rapid or Short acting", "Rapid or Short acting",
"Rapid or Short acting", "Rapid or Short acting", "Rapid or Short acting",
"Rapid or Short acting", "Rapid or Short acting", "Rapid or Short acting",
"Rapid or Short acting", "Rapid or Short acting", "Rapid or Short acting",
"Rapid or Short acting"), Name = c("Abasaglar", "Lantus", "Levemir",
"Toujeo", "Tresiba", "Insulatard", "Humulin I", "Abasaglar",
"Lantus", "Levemir", "Toujeo", "Tresiba", "Insulatard", "Humulin I",
"Abasaglar", "Lantus", "Levemir", "Toujeo", "Tresiba", "Insulatard",
"Humulin I", "Abasaglar", "Lantus", "Levemir", "Toujeo", "Tresiba",
"Insulatard", "Humulin I", "Humulin M3", "Novomix 30", "Insuman Comb 15/25/50",
"Humalog Mix 25/50", "Humulin M3", "Novomix 30", "Insuman Comb 15/25/50",
"Humalog Mix 25/50", "Humulin M3", "Novomix 30", "Insuman Comb 15/25/50",
"Humalog Mix 25/50", "Humulin M3", "Novomix 30", "Insuman Comb 15/25/50",
"Humalog Mix 25/50", "Novorapid/Fiasp", "Humalog", "Apidra",
"Humulin S", "Actrapid", "Novorapid/Fiasp", "Humalog", "Apidra",
"Humulin S", "Actrapid", "Novorapid/Fiasp", "Humalog", "Apidra",
"Humulin S", "Actrapid", "Novorapid/Fiasp", "Humalog", "Apidra",
"Humulin S", "Actrapid"), Plan = c("Usual dose at usual time",
"Usual dose at usual time", "Usual dose at usual time", "Usual dose at usual time",
"Usual dose at usual time", "Usual dose at usual time", "Usual dose at usual time",
"Usual dose at usual time", "Usual dose at usual time", "Usual dose at usual time",
"Usual dose at usual time", "Usual dose at usual time", "Usual dose at usual time",
"Usual dose at usual time", "Usual dose at usual time", "Usual dose at usual time",
"Usual dose at usual time", "Usual dose at usual time", "Usual dose at usual time",
"Usual dose at usual time", "Usual dose at usual time", "Usual dose at usual time",
"Usual dose at usual time", "Usual dose at usual time", "Usual dose at usual time",
"Usual dose at usual time", "Usual dose at usual time", "Usual dose at usual time",
"Half usual morning dose taken with a sugary drink at 7am", "Half usual morning dose taken with a sugary drink at 7am",
"Half usual morning dose taken with a sugary drink at 7am", "Half usual morning dose taken with a sugary drink at 7am",
"Half usual morning dose taken with a light breakfast at 7am",
"Half usual morning dose taken with a light breakfast at 7am",
"Half usual morning dose taken with a light breakfast at 7am",
"Half usual morning dose taken with a light breakfast at 7am",
"Half usual morning dose taken with a sugary drink at 7am", "Half usual morning dose taken with a sugary drink at 7am",
"Half usual morning dose taken with a sugary drink at 7am", "Half usual morning dose taken with a sugary drink at 7am",
"Half usual morning dose taken with a light breakfast at 7am",
"Half usual morning dose taken with a light breakfast at 7am",
"Half usual morning dose taken with a light breakfast at 7am",
"Half usual morning dose taken with a light breakfast at 7am",
"Omit breakfast dose", "Omit breakfast dose", "Omit breakfast dose",
"Omit breakfast dose", "Omit breakfast dose", "Half usual morning dose taken with a light breakfast at 7am",
"Half usual morning dose taken with a light breakfast at 7am",
"Half usual morning dose taken with a light breakfast at 7am",
"Half usual morning dose taken with a light breakfast at 7am",
"Half usual morning dose taken with a light breakfast at 7am",
"Omit breakfast dose", "Omit breakfast dose", "Omit breakfast dose",
"Omit breakfast dose", "Omit breakfast dose", "Usual morning dose taken with a light breakfast at 7am, oral fluids until 11am, omit lunchtime dose",
"Usual morning dose taken with a light breakfast at 7am, oral fluids until 11am, omit lunchtime dose",
"Usual morning dose taken with a light breakfast at 7am, oral fluids until 11am, omit lunchtime dose",
"Usual morning dose taken with a light breakfast at 7am, oral fluids until 11am, omit lunchtime dose",
"Usual morning dose taken with a light breakfast at 7am, oral fluids until 11am, omit lunchtime dose"
)), row.names = c(NA, -64L), class = c("tbl_df", "tbl", "data.frame"
))

A: Shiny does not support multiple outputs with the same name. Have a look at this.
In your case, both the tabs are using px_name and dob. In your server code, you could try something like:
output$dob1 <- output$dob2 <- renderText({input$dob})

And then in the UI refer to these separate output IDs in the tabs.
Hope this helps.


text:
Q: Use of Laplace transform to solve a differential eqn Use Laplace transform to solve:
$u_x = 2 u_t + u , u(x,0)=2e^{-3x}; $  $ u$ bounded for $x>0,t>0.$
$\frac{\bar{\partial{u}}}{\partial{x}}= 2 [s \bar{u}(x,s)-u(x,0)]+\bar{u}$
$\frac{\bar{\partial{u}}}{\partial{x}}=2[s\bar{u}-2e^{-3x}]+\bar{u}$
$\frac{\bar{\partial{u}}}{\partial{x}}=\bar{u}(2s+1)+2e^{-3x}$
$\bar{u}=\hat{u}x(2s+1)+\frac{2}{-3}e^{-3x}+B$
I dont know what comes next?

A: Consider
$${{u}_{x}}=2{{u}_{t}}+u$$  $$u\left( x,0 \right)=2{{e}^{-3x}}$$
hence
$${{U}_{x}}=2\left( sU-u\left( 0,x \right) \right)+U$$
Where U is the laplace transform of u w.r.t t.  Therefore
$${{U}_{x}}-\left( 2s+1 \right)U=-4{{e}^{-3x}}$$
Using an integrating factor one obtains
$$\frac{\partial }{\partial x}U{{e}^{-\left( 2s+1 \right)x}}=-4{{e}^{-3x}}{{e}^{-\left( 2s+1 \right)x}}$$
Solving yeilds
$$U=\frac{2}{\left( 2+s \right)}{{e}^{-3x}}+A\left( s \right){{e}^{\left( 2s+1 \right)x}}$$
Inverting we obtain
$$u\left( x,t \right)=\frac{1}{2\pi i}\int\limits_{C}^{{}}{\frac{2{{e}^{-3x}}{{e}^{st}}}{\left( 2+s \right)}+A\left( s \right){{e}^{\left( 2s+1 \right)x}}{{e}^{st}}ds}$$
where the contour is the Bromwich contour.  Residue calculus yields
$$u\left( x,t \right)=2{{e}^{-3x-2t}}+\frac{1}{2\pi i}\int\limits_{C}^{{}}{A\left( s \right){{e}^{\left( 2s+1 \right)x}}{{e}^{st}}ds}$$
Note
$$u\left( x,0 \right)=2{{e}^{-3x}}+\frac{1}{2\pi i}\int\limits_{C}^{{}}{A\left( s \right){{e}^{\left( 2s+1 \right)x}}ds}\Rightarrow \frac{1}{2\pi i}\int\limits_{C}^{{}}{A\left( s \right){{e}^{\left( 2s+1 \right)x}}ds}=0$$
And so A=0.  Therefore $$u\left( x,t \right)=2{{e}^{-3x-2t}}$$.


text:
Q: ASP.NET MVC entity framework alternative I am new to ASP.NET mvc.
Is there a good alternative for entity framework in for MVC?

A: You can use any ORM you want with MVC.
A popular choice is nHibernate, though there are many many more.

Other popular alternatives (some commercial) are:

*

*Castle ActiveRecord

*LLBLGen

*LINQ to SQL

*SubSonic
StackOverflow uses their own in-house (now open sourced), micro-ORM, Dapper.


text:
Q: Remove already existing pairs from dataset I have a dataset containing two columns ("from" & "to") representing interactions between actors. My problem is that each interaction is represented from the perspective of each actor, meaning the pair from A to B  is also present as from B to A. Usually, duplicates can be identified and removed via the unique() or distinct() but in this case I did not find a solution. Any suggestions? Here is some of my data:
structure(list(from = c("anti-government protesters", "anti-government protesters",
"human rights organisations", "human rights organisations", "MDCT supporters",
"Movement for Democratic Change", "Movement for Democratic Change",
"Movement for Democratic Change", "Movement for Democratic Change",
"nurses", "nurses", "opposition", "opposition", "opposition",
"opposition supporters", "opposition supporters", "opposition supporters",
"opposition supporters", "opposition supporters", "ordinary citizens",
"ordinary citizens", "youth activists", "youth activists", "youth activists"
), to = c("Movement for Democratic Change", "opposition supporters",
"nurses", "ordinary citizens", "opposition supporters", "anti-government protesters",
"opposition", "opposition supporters", "youth activists", "human rights organisations",
"ordinary citizens", "Movement for Democratic Change", "opposition supporters",
"youth activists", "anti-government protesters", "MDCT supporters",
"Movement for Democratic Change", "opposition", "youth activists",
"human rights organisations", "nurses", "Movement for Democratic Change",
"opposition", "opposition supporters"), n = c(1L, 1L, 1L, 1L,
1L, 1L, 12L, 16L, 12L, 2L, 2L, 5L, 5L, 5L, 1L, 1L, 6L, 3L, 3L,
1L, 1L, 1L, 1L, 1L)), class = c("grouped_df", "tbl_df", "tbl",
"data.frame"), row.names = c(NA, -24L), groups = structure(list(
    from = c("anti-government protesters", "anti-government protesters",
    "human rights organisations", "human rights organisations",
    "MDCT supporters", "Movement for Democratic Change", "Movement for Democratic Change",
    "Movement for Democratic Change", "Movement for Democratic Change",
    "nurses", "nurses", "opposition", "opposition", "opposition",
    "opposition supporters", "opposition supporters", "opposition supporters",
    "opposition supporters", "opposition supporters", "ordinary citizens",
    "ordinary citizens", "youth activists", "youth activists",
    "youth activists"), to = c("Movement for Democratic Change",
    "opposition supporters", "nurses", "ordinary citizens", "opposition supporters",
    "anti-government protesters", "opposition", "opposition supporters",
    "youth activists", "human rights organisations", "ordinary citizens",
    "Movement for Democratic Change", "opposition supporters",
    "youth activists", "anti-government protesters", "MDCT supporters",
    "Movement for Democratic Change", "opposition", "youth activists",
    "human rights organisations", "nurses", "Movement for Democratic Change",
    "opposition", "opposition supporters"), .rows = structure(list(
        1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L,
        14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L), ptype = integer(0), class = c("vctrs_list_of",
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -24L), .drop = TRUE))

A: You could sort the values of from and to rowwise and put them back to df.
df[1:2] <- t(apply(df[1:2], 1, sort))

Then unique() or distinct() will work to remove duplicated rows.
unique(df[1:2])

# Or with dplyr:
df %>% distinct(from, to)

                             from                             to
1      anti-government protesters Movement for Democratic Change
2      anti-government protesters          opposition supporters
3      human rights organisations                         nurses
4      human rights organisations              ordinary citizens
5                 MDCT supporters          opposition supporters
7  Movement for Democratic Change                     opposition
8  Movement for Democratic Change          opposition supporters
9  Movement for Democratic Change                youth activists
11                         nurses              ordinary citizens
13                     opposition          opposition supporters
14                     opposition                youth activists
19          opposition supporters                youth activists

You could also sum up the values of n by each pair of from and to.
aggregate(n ~ from + to, df, sum)

# Or with dplyr:
df %>% count(from, to, wt = n)

                             from                             to  n
1      anti-government protesters Movement for Democratic Change  2
2      human rights organisations                         nurses  3
3  Movement for Democratic Change                     opposition 17
4      anti-government protesters          opposition supporters  2
5                 MDCT supporters          opposition supporters  2
6  Movement for Democratic Change          opposition supporters 22
7                      opposition          opposition supporters  8
8      human rights organisations              ordinary citizens  2
9                          nurses              ordinary citizens  3
10 Movement for Democratic Change                youth activists 13
11                     opposition                youth activists  6
12          opposition supporters                youth activists  4


text:
Q: Source code of books made with TeX/LaTeX to learn Some time ago, reading this entry I found a nice image and a pointer to a better book entitled "Thinking Forth". To my surprise, the LaTeX sources of the book were ready to download, with pearls like:
%% There's no bold typewriter in Computer Modern.
%% Emulate with printing several times, slightly moving

\newdimen\poormove
\poormove0.0666pt
\newcommand{\poorbf}[1]{%
\llap{\hbox to \poormove{#1\hss}}%
\raise\poormove\rlap{#1\hss}%
\lower\poormove\rlap{#1\hss}%
\rlap{\hbox to \poormove{\hss}\hbox{#1}}%
#1}

%\let\poorbf=\textbf
\renewcommand{\poorbf}[1]{{\fontencoding{OT1}\fontfamily{cmtt}\fontseries{b}\selectfont#1}}

in which it can simulate the bold stroking of a font that doesn't have it. Since reading that, I was unaware of \llap and such, but now I can use them to define boxes, etc.
So, my question is twofold:

*

*Do you know of sites that show that relatively advanced use of TeX/LaTeX in terms of useful recipes, and

*Do you know any books that offer their TeX/LaTeX source to inspect and learn (and that are worth doing so.)?

A: Believe it or not, but the source code to the TeXbook is actually freely downloadable:
TeXbook source code package

A: There are two comprehensive reference guides/recipe books for TeX:

*

*TeX by Topic by Victor Eijkhout

*TeX for the Impatient by Paul Abrahams, Kathryn Hargreaves, and Karl Berry

In both cases, the sources are also available.
As lindelof mentions, the TeXBook is also available, albeit in a form that prevents compilation (Knuth wished people to look at the source for inspiration but not to reproduce the book freely):

*

*The TeXBook by Donald Knuth

On the LaTeX side of things, resources a little more scarce from the programming point of view. The best free reference that I know of is

*

*Formatting Information by Peter Flynn

Of course there's also

*

*The Not So Short Guide to LaTeX by Tobias Oetiker

but that doesn't cover so much programming "stuff". The LaTeX sources themselves contain some useful nuggets, but the quality of the documentation ranges from excellent to non-existent in parts; this should be available in your distribution with texdoc source2e.
Other large LaTeX packages obviously have the source to their documentation available; a notable example is the memoir class:

*

*The memoir class by Peter Wilson (memman.tex is the documentation)

I'm sure there are many more books with their source available; these are just the first ones that come to mind that happen to also be able TeX and/or LaTeX.

A: Not that I'd recommend it (unless you've got a lot of time and caffeine to spare), but I learned a lot from just reading the latex.ltx file. I learned a lot not only about LaTeX but also of course about TeX. It's a heavy read though and I'd suggest reading a book about TeX first before diving into the latex.ltx file.
I wanted to know about how "optional" parameters actually worked and reading the latex.ltx file really helped me understand.

A: Another book that would definitely fit part 2 of your question is LaTeX for Complete Novices by TeX.SX member Nicola Talbot.
This later question, posted on TeX.SX, is also relevant for part 2 and worth reading.

A: I found this book by Allen B. Downey that looks really nice: Computational Modeling and Complexity Science.


text:
Q: MVC2 complex type visual studio 2010 .net framework 4 I have a stored procedure usp_getCashCommissionCustomer like this:
Select
    cw.Customercode, name, state as Province, City, Suburb,
    Balance As HMCommission, MBalance as  MTNCommission
from
    customerwallet cw
inner join
    customer cu on cw.customercode = cu.customercode
where
    iscash = 1
    and (balance + mbalance) > 0
order by
    customercode

On click on customercode I should open create view of follwing table
CREATE TABLE [dbo].[CustomerLedger]
(
    [ID] [bigint] IDENTITY(1,1) NOT NULL,
    [CustomerCode] [varchar](25) NULL,
    [TransactionType] [varchar](1) NULL,
    [Description] [varchar](30) NULL,
    [TransactionDate] [datetime] NULL,
    [Amount] [float] NULL,
    [IsProcessed] [bit] NULL
) ON [PRIMARY]

Please help me.
I am new to ASP.NET MVC 2

A: I don't know whether you are using ORM or not. If you are not any ORM then you may see an approach to fill the view using stored procedure mentioned here. IF you are using ORM such as L@S or entity framework you may get start from here.
If You want popup of view you find the tutorial here


text:
Q: Is Main/UI Thread same as System UI Thread in Android? This question is different than what's being discussed about Main thread and UI thread in Android.
By mean of System thread - the thread which handles system UI like statusbar, notifications & other ongoing system processes, say thread which handles home-button-press, recents-menu etc...
By mean of Main thread - App's thread which handles UI (forked when process launched)
I believe it's saperate thread as busy main thread of app is not hanging your device and all other than app things work fine.
My doubt is only for the purpose:
If system can manage a separate thread for it self (to do UI work) than any process/app's-main thread; then why Apps can not have multiple threads who can handle UI (No matter how complex it's for devs!!)
Please provide references as well while pointing out answers on this.

A:
By mean of System thread - the thread which handles system UI like statusbar, notifications & other ongoing system processes, say thread which handles home-button-press, recents-menu etc...

There may well be several threads involved in this.

I believe it's saperate thread as busy main thread of app is not hanging your device and all other than app things work fine.

More importantly, system UI is handled by separate OS processes, independent of the OS process for an app. As with most modern operating systems, in Android, a thread is owned by a process. Hence, by definition, separate processes have separate threads.

then why Apps can not have multiple threads who can handle UI (No matter how complex it's for devs!!)

That was an architectural decision, made close to 15 years ago, back when phone hardware was a lot more limited than it is today. Having a single "magic thread" is a common practice in constrained environments, as it avoids the overhead of constant checking for locks and other approaches to ensure thread-safety of data structures. While Google has done some things to try to improve on this (e.g., added a separate rendering thread), the core architectural limit remains, for backwards compatibility with older apps.
Also note that a fair amount of work is going into Jetpack Compose to try to allow for multi-threaded composables. Basically, since we now have a lot better hardware, Google is handling low-level synchronization for us in Compose, so composables can perhaps run on several threads without issue.


text:
Q: Plot dates on X in Matplotlib from raw numbers I'm trying to plot information I gathered in the list. It's simply statistic from chat of how many messages was sent each day by user. I'm having problem with transferring dates from my data to X axis on plot. It keeps showing as normal numbers.
list_of_records = [record1, record2, record3, ...]

where:
record = ['name', messages number, day, month, year]

Example of real data:
list_of_records = [['F', 2, 23, 9, 2018], ['A', 1, 23, 9, 2018], ['F', 2, 3, 7, 2018],
['A', 2, 3, 7, 2018], ['A', 2, 3, 7, 2018], ['F', 2, 3, 7, 2018], ['F', 2, 3, 7, 2018]

Now I was looking at:link1, link1, link1, link1
But non of it made a lot of sense to me, as they always import data from somewhere.
I'm guessing I have to import some kind of lib from matplotlib to convert number I will pull from the array to plot-friendly format of dates. Then use other sub library to plot it with dates. But how to do it? I have no clue.
It's my first time with matplot lib, so please don't be too generic in answers.
My code:
from matplotlib import pyplot as plt

list = [['F', 2, 23, 9, 2018], ['A', 1, 23, 9, 2018], ['F', 2, 3, 7, 2018], ['A', 2, 3, 7, 2018], ['A', 2, 3, 7, 2018], ['F', 2, 3, 7, 2018], ['F', 2, 3, 7, 2018], ['F', 2, 3, 7, 2018], ['A', 2, 3, 7, 2018], ['F', 2, 3, 7, 2018], ['A', 2, 3, 7, 2018], ['F', 2, 3, 7, 2018]]

plot_x_A = []
plot_y_A = []
plot_x_F = []
plot_y_F = []

for value in list:
    if value[0] == "F":
        plot_x_F.append((value[-1],value[-2],value[-3]))
        #X value - take year, month and day and pack in in tuple
        plot_y_F.append(value[1])
        #Y value - just number
    if value[0] == "A":
        plot_x_A.append((value[-1],value[-2],value[-3]))
        plot_y_A.append(value[1])

#print(plot_x_A)                 #double check myself if it looks all right
#print(plot_y_A)

plt.plot_date(plot_x_A,plot_y_A,xdate=True)
plt.show()


text:
Q: SQLPLUS TRIM and COLUMN formatting I have just executed a PL/SQL procedure and have the output:
FirstName               LastName      Role        Quote
what I am wanting to do is use trim and column formatting to output the information like below so that first and last name appear on one row and then role and quote on the next row which are to be separated by a |
FirstName LastName
|Role    | Quote     |
I am not sure how to do this and any help on this would be appreciated

A: If this is output from a PL/SQL procedure - which I assume means that it is accomplished with calls to DBMS_OUTPUT - then SQLPlus column formatting commands will have no affect on it.  You would need to modify the procedure to do the output the way you want it.
If this was the output of a SELECT statement then I believe you could use the fold_after or fold_before options on the column statement to do what you want.


text:
Q: Mocked request doing actual requests call, not mock I am mocking a get request in my unittest code using requests-mock, but when I run the code during testing, it still tries to hit the actual URL instead of returning the mocked data.
This is my code:
    try:
        response = requests.get(api_url, auth=requests.auth.HTTPBasicAuth(username, password))
        response.raise_for_status()
    except requests.ConnectionError as e:
        raise dke.CLIError(f"Could not connect to Artifactory server to get NPM auth information: {str(e)}")

This is my test code
class MyTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        m = requests_mock.Mocker()
        m.get('https://artifactory.apps.openshift-sandbox.example.com/artifactory/api/npm/auth',
              text=("_auth = base64string==\n"
                    "always-auth = true\n"
                    "email = shareduser@fake.com"))

The api_url in my code matches the URL I pass to m.get(). However, when I run the test, I do not get the value of "text" but instead I get a 401 Client Error: Unauthorized  and a response from the server indicating "Bad credentials" which tells me it actually tried to contact the server instead of returning the text I had requested in the Mock.
I'm lost. As far as I can tell, I'm using this exactly as the docs indicate. Any ideas?

A: So, it seems you can't use the request_mocker that way. It has to be a decorator or context manager.

A: I mean the context manager/decorator is just a pattern around normal code. I haven't tested it but i think you just have to call m.start()/m.stop().
It's generally used as a context manager or decorator because if you instantiate it once like that then your request history is going to include all requests across all unit tests which is very hard to make assertions about.


text:
Q: Duct hanger - place family instance Revit API i'm trying to place a family using the API (c#).
When using the NewFamiltInstace overloaded method that takes (location, symbol,host, level, structural) - i'm expecting to get the instance of the hanger family in the level i have inserted, and in the elevation of the host ( the duct).
instead - i get the duct hanger in the ground floor no matter what i'm doing, can any one understand why, and what sholud i do to get it in the desired level?
tried multiple overloaded methods, tried using the duct as a host, the level as a host etc.. the hangers always show up at the floor of ground level.
the code from my transaction:
using (Transaction trans = new Transaction(doc, "Place Family"))
{
trans.Start();

int indx = 0;
foreach (XYZ hanger_xyz in hangerCoordinates)
{

if (!hangerSymbol.IsActive)
{
hangerSymbol.Activate();
}

doc.Create.NewFamilyInstance(hanger_xyz, hangerSymbol,duct,level, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);

}

trans.Commit();
}

'''

A: figured it out.
After testing all of the 11 overloaded methods for newFamilyInstance and their required arguments, and snooping around with RevitLookUp, i  managed to get the right overloded method which is:
FamilyInstance familyInstance = doc.Create.NewFamilyInstance(face, hanger_xyz, new XYZ(0, 1, 0), hangerSymbol);

face==> as a  Referemce object (extracted it from a face Face that i got from a GeoElement that i got from the desired level's floor)
hanger_xyz==>an XYZ location
new XYZ(0,1,0)==> a direction of the family as it is when it's attached to a cielling host ( got it from revitLookUp)
hangerSymbol ==> the familysymbol.


text:
Q: How to extract a numerical value from an input string using IBM Watson conversation When using the IBM Watson conversation builder,
how do I extract the (floating point) numerical value from a sentence?
For example, suppose the user typed:
Please make a payment of €1,051.84, thanks.

How can I extract the currency amount?
Thanks

A: Numbers can now be extracted via System Entities which are available in the tooling.


text:
Q: Перекодировка .csv файла в php Доброго времени суток. Пишу обработчик .csv файла. Проблема следующая: не понимаю, как перекодировать загружаемый .csv файл с помощью скрипта Перекодировать в UTF-8. Скрипт выводит содержимое файла, но не читает кириллицу.. Довольно мало опыта в программировании, прошу помочь понять, как перекодировать. Спасибо.
<?php

    $uploaddir = "uploads/";
    $uploadfile = $uploaddir . basename($_FILES["somename"]['name']);
    (move_uploaded_file($_FILES["somename"]['tmp_name'], $uploadfile));
           //Добавление и расположение файла в нужную директорию

    $row = 1;
    if (($handle = fopen("$uploadfile", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            $row++;
            for ($c=0; $c < $num; $c++) {
                echo $data[$c] . "<br />\n";
            }
        }
       fclose($handle);
    }  // обработчик .csv файла

?>

p.s
пробовал перекодировать так, но никакой реакции. Объясните, пожалуйста, что я делаю не так):
$dir = $uploadfile;
echo mb_detect_encoding($uploadfile);
$dir = iconv(mb_detect_encoding($uploadfile), "UTF-8", $dir);


text:
Q: Dynamically created inline editable DataTable I'm creating a Dynamic data-table, which pulls data from SQL and generates both the Columns and the Rows with information based on the return Query. I'm doing this dynamically because i have 8 different grids and i don't want to create a page for each one!
I'm adding information via a modal with all the columns (also generated dynamically in the code above but not very UX friendly) and via excel file (with the same structure also).
How can I make this table editable inline? Is this possible, taking in consideration, the way I'm building this table?
Table has some flaws such as it makes two ajax requests... one for the creation of the table and another when it's created (basically the same request because it's the request that refreshes the data when I add more data or search one of the columns for specific information). So if you have tips on how i can do only one ajax request instead of making two on load feel free to share also. :)
Thank you all!
//Here is where the table is create by Ajax Request
$.ajax({
            url: '@Url.Content("~/Parametrization/Detail")',
            type: 'POST',
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            data: jsonTest,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data, textStatus, jQxhr)
            {
                if (data.data.length > 0) {
                    //Gets all columns and generates a ColumnSet
                    js = JSON.parse(data.data[0].tableColsName)
                    cols = generateDynamicColumns(js)

                    //Here is where the Header and the Modal are defined dynamically
                    cols.forEach(function (index) {
                        //Header
                        $('#tblSearch_ thead tr:eq(0)').append('' + index.name + '	');
                        //Modal
                        $('#modal-bd').append('
 ' + index.name
                            + ' <input required class="form-control" id="'
                            + index.data + '" type="' + index.type + '" />
');
                    });

                    //Here is where the search bar is defined dynamically
                    $('#tblSearch_ thead tr').clone(true).appendTo('#tblSearch_ thead');
                    $('#tblSearch_ thead tr:eq(1) th').each(function (index) {

                        $(this).html('<input class="form-control" id="search" name="title" type="' + cols[index].type + '" placeholder="Procurar ' + cols[index].name + '" />');

                        $(this).find(':input').each(function () {
                            $(this).on('keyup change', function () {
                                if (tempTable.column(index).search() !== this.value) {
                                    tempTable
                                        .column(index)
                                        .search(this.value);
                                }
                            });
                        })
                    });

                    // Here is where the table is created dynamically
                    tempTable = $('#tblSearch_').DataTable({
                        dom: "Brtip",
                        paging: true,
                        pageLength: @Model._configuration.PageSize,
                        orderCellsTop: true,
                        fixedHeader: true,
                        ajax: function (data, callback, settings) {
                            input = (function () {
                                aux = {
                                    "pageNumber": (data.start / data.length) + 1,
                                    "pageSize": data.length,
                                    "OrderFieldBy": data.columns[data.order[0].column].data + '.' + data.order[0].dir
                                }
                                data.columns.forEach(v => {
                                    str = v.search.value
                                    if (str) {
                                        aux[v.data] = str
                                    }
                                    while (str.charAt(0) === ',') {
                                        str = str.substr(1);
                                    }
                                    aux[v.data + 'Search'] = str
                                })
                                return aux
                            }).call()

                            $.ajax({
                                url: '@Url.Content("~/Parametrization/Detail")',
                                type: 'POST',
                                beforeSend: function (xhr) {
                                    xhr.setRequestHeader("XSRF-TOKEN",
                                        $('input:hidden[name="__RequestVerificationToken"]').val());
                                },
                                data: JSON.stringify(input),
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                success: function (data, textStatus, jQxhr) {
                                    callback({
                                        data: data.data,
                                        recordsTotal: data.recordsTotal,
                                        recordsFiltered: data.recordsFiltered
                                    });
                                },
                                error: function (jqXhr, textStatus, errorThrown) {
                                    fnHasFormError(jqXhr.responseJSON.message, 'errorMessages_modal')
                                }
                            });
                        },
                        columns: cols,
                        serverSide: true,
                        'bRetrieve': true,
                        processing: true,
                        responsive: true,
                        "aaSorting": [[0, 'desc']],
                        "info": true,
                        "lengthMenu": [10],
                        "bFilter": true,
                        "bLengthChange": false,
                        "pagingType": "full",
                          "buttons": [{ extend: "create", editor: editor },
                                  { extend: "edit", editor: editor },
                                  { extend: "remove", editor: editor } ],
                        language: {
                            "sProcessing": "A processar...",
                            "sLengthMenu": "Mostrar _MENU_ registos",
                            "sZeroRecords": "Não foram encontrados resultados",
                            "sInfo": "Elementos mostrados  _START_ - _END_ em _TOTAL_",
                            "sInfoEmpty": "",
                            "sInfoFiltered": "(filtrado de _MAX_ registos no total)",
                            "sInfoPostFix": "",
                            "sSearch": "Procurar:",

                            paginate: {
                                'sFirst': '',
                                'sLast': '',
                                'sPrevious': '',
                                'sNext': ''
                            },
                            aria: {
                                paginate: {
                                    first: 'First',
                                    previous: 'Previous',
                                    next: 'Next',
                                    last: 'Last'
                                }
                            }
                        }
                    });
                    table = tempTable;
                } else {
                    fnHasFormError("Não existem registos relativos a esta parametrização", 'errorMessages_modal')
                }
            },
            error: function (jqXhr, textStatus, errorThrown) {
                fnHasFormError(jqXhr.responseJSON.message, 'errorMessages_modal')
            }
        });


text:
Q: name an object in Array I'm doing multiple fetchs with Promise.all. So I receive data like this :
[
   0: {
      ...
   },
   1: {
      ...
   }
]

But I would like to name my Objects. So I can do data.myObject istead of data[0].
I would like the index to be a string that I chose.
For example, i'd like to get :
[
   "home": {
      ...
   },
   "product": {
      ...
   }
]

Is is possible ? Thanks

A: No, this is not possible. Promise.all works on iterables (like arrays), not on objects. Name your values after the Promise.all call:
const data = await Promise.all([…, …]);
const home = data[0], product = data[1];

becomes with destructuring
const [home, product] = await Promise.all([…, …]);

A: Promise.all works with an array. Arrays deal in numerically indexed (ordered) values.
You'd need to have a name stored somewhere for each promise, and then generate the object from them once the promises had resolved.
e.g.
const names = ['home', 'product'];
const promises = [fetchHome(), fetchProduct()];
const results = await Promise.all(promises);
const resultsByName = names.reduce((prev, curr, index) => {
    return {...prev, [curr]: results[index]};
}, {});

You could use a similar approach without the second array if the name was available in the resolved values of fetchHome() and fetchProduct().

A: You can destructure the array of Promise results in the Promise.all.
const [home, product, toolbar, nav] = await Promise.all([
getHome(), getProduct(), getToolBar(), getNav()
]);

Since the results are an array like anything else you can destructure arrays and even use the ...rest syntax:
const [home, product, toolbar, nav, ...otherPromises] = await Promise.all([
getHome(), getProduct(), getToolBar(), getNav(), getOtherThing1()
]);
// otherPromises will be an array that you'll have to access
// with numeric keys as before:
// eg. otherPromises[0] might be the first non-named promise
// the result of getOtherThing1()

A: Seems like you want to convert Array to an object so you can get data by calling a key.

const arr = [ { id: "home", val: "val1" }, { id: "product", val: "val2" }];
const convert = arr.reduce((a,b) => (a[b.id] ??= b,a),{});
console.log(convert);
console.log(convert.home);


text:
Q: How to include all "vue" files from directory into the build without explicitly importing them is there a way to build all .vue files in my views/ folder without importing them into my vue application directly?
What I want to achieve is a Router with dynamic route definitions which will be filled from a configuration which is a json filled with name, router path and the component name which should be lazy loaded.
My issue right now: The application does only build the files which are imported somewhere in my application. What I need: Build all files in views/ as chunk in order to be able to have a dynamic Router definition.
Thank you for your help :)

A: It's hard to give proper solution without any code provided, but I'll try
With code like this:
// route definition loaded from json
const routeDef = [
  { name: 'about', path: '/about', componentName: 'about' },
  { name: 'profile', path: '/profile', componentName: 'profile' }
]

// we can create routes like this
const routes = routeDef.map(function(def) {
  return {
    name: def.name,
    path: def.path,
    component: () => import('@/views/' + def.componentName + '.vue')
  }
})

const router = new VueRouter({
  routes: routes
})

By using import('@/views/' + def.componentName + '.vue') you are telling Webpack I want to import one of the .vue files in the views directory but which one will be known at runtime. So Webpack will bundle all file in that directory and make it available for import at runtime....
Note that what you pass into import() is really important - part of the argument must always be a static string so Webpack have at least some clue about the directory (import(def.componentName) wont work) - see the docs
Additional example - loading route definitions from server at runtime
router.js
export default createRouter() {
  return axios.get('/getRouteDefinitions').then(function(data) {

    const routes = data.routeDef.map(function(def) {
      return {
        name: def.name,
        path: def.path,
        component: () => import('@/views/' + def.componentName + '.vue')
      }
    })

    return new VueRouter({
      routes: routes
    })
  })
}

main.js
import VueRouter from `VueRouter`
import createRouter from `router.js`

Vue.use(VueRouter)

createRouter().then(function(router) {
  const app = new Vue({
    router
  })
  app.$mount("#app")
})


text:
Q: Allow changing votes on answers if the question is edited Recently I downvoted the answer because I thought it didn't answer the question.  Not very uncommon reason to downvote, isn't it?  But then the guy, who asked the question, edited his question and I realized that the answer I downvoted actually answers it and deserves an upvote instead!  But I couldn't do it.
I could do it if the answerer had edited his post.   As I understand, the rationale of changing vote after edit is the following.  If I came to the question page for the first time after the edit of the answer, I would've upvoted it instead of downvoting.
But why doesn't the same rationale hold for the cases when the question is edited?  Unless there's a good reason, I suggest to allow changing answer vote on question edits, not only on answer ones.

A: I'd also like to support this request and point out that it's a silly restriction anyways, as anybody with >= 2k rep can change their vote whenever they want simply by trivially editing the answer they want to change their vote on (e.g. shuffling some whitespace around).
At the bare minimum, just make it so anybody with >= 2k rep can change their votes at any time - if you're going to allow this anyways you might as well reduce arbitrary edits by just letting votes change.
Since there's an easy way around the voting thing, either figure out a way to prevent the workaround, or just drop the rule. Anyways I'm not sure I understand the rationale behind preventing vote changes in the first place. Perhaps stopping vote changes a few weeks after a vote is cast is more aligned with whatever the goal is there.

A: +1 for this request. As an interim, assuming you don't have enough rep to edit, you can comment on the answer you DV'ed, explaining that you'd like to reverse your vote, and request that the answerer edit his post in a minor way so you can. I don't like this solution, though -- I much prefer your feature request.
If you have enough rep to edit, go with RSolberg's answer.


text:
Q: Approximating indicator function of open sets by increasing limit of positive continuous functions on a compact Hausdorff space $X$ Let $X$ be a compact Hausdorff space. I could see by searching in the internet that for any $A\subset X$, $A$ open, we can approximate the indicator function $1_A$ by an increasing sequence of continuous functions. Any references towards this can be suggested? I infact need to approximate $1_A$ by an increasing sequence of $\underline{positive}$ continuous functions?
Any reference leads to this?
I am not sure whether its even true or not. I can see some negative answers to this here:
Approximation of indicator function of an open set by continuous functions.
What is the correct assumption needed?


text:
Q: Returning a message instead a error in case of opening a excel workbook with wrong filename Inside an excel macro I have a command that opens an external workbook:
 Workbooks.Open (directory & filename), ReadOnly:=True

I want that in the case the filename does not exist or has a different name from the specified in the macro, to present a message box with a customized message to the user (i.e. "the filename does not exist or has a different name"), instead the defined application error:
"`Runtime error 1004... Microsoft Excel cannot access...."
How can I archieve this?

A: You can try something like this:
Sub OpenFileSub()

    On Error GoTo ErrHandler
    Workbooks.Open (directory & Filename), ReadOnly:=True
    On Error GoTo 0

ErrHandler:
    MsgBox "the filename does not exist or has a different name"

End Sub

A: You can test for the existence of the file by using Dir()
Sub OpenTester()
    Dim v As String
    directory = "C:\TestFolder\"
    fiilename = "ABZ.xls"
    v = directory & fiilename

    If Dir(v) = "" Then
        MsgBox "Warning Will Robinson, warning!"
    Else
        Workbooks.Open (v), ReadOnly:=True
    End If
End Sub


text:
Q: basis of subspace $R^4$ Find a basis for the subspace of $R^4$ consisting of all vectors of the form $(a,b,c,d)$  where $c=a+6b$ and $d=a-3b$
I've sat and thought about how to even start this problem and have no idea. Suggestions please!

A: Call the subspace $W$. Then $W$ consists of all the points $(a,b,c,d)$ that are solutions to those two equations. Those two linear equations. In other words, $W$ is the set of all solutions to a particular system of linear equations. And I'm willing to bet you've previously learned how to solve systems of linear equations. So all you have to do is solve them, and give a basis for the solution set.


text:
Q: Getting started with clang, LLVM, and running existing passes I am starting to work with LLVM, clang, and passes. This is a developed field, and I quickly become overwhelmed with the wealth of information out there. I was hoping someone could shed some light on these topics, with just enough detail to understand the bigger picture and just enough information to get started. Some of the details which I think would be useful are:
Q1) What is the relationship between LLVM and clang?
Q2) I know LLVM has a large set of existing static analysis techniques are these called passes?
Q3) What code representation format do I need to use to run a pass?
Q4) How do I run passes?
I know this is a very broad question. I am just looking for someone to give me enough information so that I have a footing and can get started fiddling with these tools.


text:
Q: Code Mappings : The DELETE statement conflicted with the REFERENCE constraint I'm using nHibernate 3.3.1.4 with Code Mappings.
Have Person and Picture objects, where Person have a Picture member.
Picture have an Id (int) and Image (byte[]) members.
When uploading a new picture, I want to delete the old picture first as follows:
var person = _personRepository.Get(personId);
var picture = partner.Picutre;
_pictureRepository.Delete(picture);

However it seems my mappings are incorrect, since I get an error about "The DELETE statement conflicted with the REFERENCE constraint....."
Here is my mappings:
mapper.Class<Person>(map => map.ManyToOne(x => x.Picture, pic => pic.Cascade(Cascade.DeleteOrphans)));

mapper.Class<Picture>(map => map.Property(x => x.Image, x => x.Type(NHibernateUtil.BinaryBlob)));

A: Yuo just need to set partner.Picutre to null
var picture = partner.Picutre;
partner.Picutre = null
_pictureRepository.Delete(picture);

And here you done.