text:
Q: importing system in python - import packages When I have the following packages:
src
   /__main__.py
   /dir1
        /__init__.py
        /main_code1.py
        /service.py
        /config.py
   /dir2
       /__init__.py
       /maincode2.py
   /dir3
       /__init__.py
       /maincode3.py

What is the difference between using the following statement in the file __main__.py
import dir1

&
from dir1 import *

&
from dir1 import main_code1

The second question is: How to import maincode3.py (present in dir3) to the maincode.py script present in dir1? I am searching for way without changing sys.path list.

A: import dir1

Imports dir1's __init__.py. You can access whatever is there using dir1.my_var_from_dir1_init. You cannot access the modules, only what's on dir1's __init__.
from dir1 import *

Imports the modules specified on the __all__ variable defined on dir1's __init__.py. If there isn't such variable, then it imports all of dir1's modules. You can access them directly, like main_code1.myvar.
from dir1 import maincode

Assuming it's a typo and you actually have a maincode module or class, it imports the maincode module/class from dir1. You can access it directly like mentioned above.
Note that each option imports dir1's __init__.py, implicitly or explicitly. If you import the modules on __init__.py, then using import dir1 will allow you to use dir1.module.

To import dir3's maincode3 to maincode.py, simply use from dir3 import maincode3. Just be careful with circular imports, which will generate an import error. You can also take a look on relative imports.

A: *

*import dir1 will import dir1/__init__.py file.

*from dir1 import *: all modules inside dir1 will be imported. Access "main_code1" without using the "dir." before.

*from dir1 import main_code1 will only import the main_code1 module.

If the __main__.py file is importing all the other modules, then you can access dir3.maincode3.py from dir1.main_code1.py simply doing something like:
import dir3.maincode3


text:
Q: Facebook Graph API - getting daily spend per ad set I'm trying to get the daily spend per ad set for all our ad accounts. We're spending lots of money with Facebook and Finance wants to see where it is going.
Basically, I'm looking each day to get the spend per ad set for yesterday. The problem is, there are lots of ad sets.
I'm trying to do this in two parts. First get the ad set IDs from the Graph API. Then get the spend using the Marketing API.
1. Graph API (v.2.4)
I'm getting a list of all the ad sets we have. I cannot do this in one call, as there are to many results (over nine pages).
GET/v2.4/me/adaccounts?fields=name,adcampaign_groups{id,name,campaign_group_status,account_id,adcampaigns{id,name}}

2. Marketing API
To get the spend for yesterday, I'm making a call to the Marketing API for each ad set. This is the PHP code I'm using:
// Get spend for yesterday
$adSet = new \FacebookAds\Object\AdSet($adSetId);
$params = array(
    'date_preset' => InsightsPresets::YESTERDAY,
);
/** @var Cursor $insights */
$insights = $adSet->getInsights(array('spend'), $params);
$insights->rewind();
$spend = 0;
if ($insights->current() != false) {
    $spend = $insights->current()->getData()['spend'];
}

Since I have lots of ad sets, I'm hitting my trotting limit long before I get the data I need.
Is there any way to get this information in one call? If not, can I get the spend data from the Marketing API in less calls?
I'm happy to update to Graph API v2.5 if it helps.
I'm using composer libraries:
facebook/php-sdk-v4: ~5.0
facebook/php-ads-sdk: 2.4.*

Thanks.

A: There is no need to do this on the adset level. With calls to the Ad Insights API what you can do is specify a specific aggregate for the data at a defined object level. Given that you have fetched your ad accounts from the /me/adaccounts endpoint you should then be able to do the following:
1. Graph API Request
The following request in the Graph API explorer, or via cURL (both provided) should return you the spend for the entire account:
1a. Graph URL
https://graph.facebook.com/<VERSION>/act_<ACCOUNT_ID>/insights?fields=spend&level=account&date_preset=yesterday&access_token=<ACCESS_TOKEN>
1b. cURL
curl -G \
-d 'level=account' \
-d 'fields=spend' \
-d 'date_preset=yesterday' \
-d 'access_token=<ACCESS_TOKEN>' \
https://graph.facebook.com/<VERSION>/act_<ACCOUNT_ID>/insights

2. Marketing API SDK
$account = new AdAccount('act_<Ad_ACCOUNT_ID>');

$params = array(
  'level' => 'account',
  'date_preset' => InsightsPresets::YESTERDAY,
  'fields' => 'spend',
);

$account->getInsights(array(), $params);

I believe that the above should help you. I have tested with the 1a & 1b and it works perfectly but haven't fully tested with 2.

A: The parameter that you are looking for is "time_increment" equals 1.
Here is the docs https://developers.facebook.com/docs/marketing-api/insights/v2.5

redpajama_set_name: RedPajamaStackExchange


text:
Q: Build-timeout Plugin in Jenkins: how long is 'too long'? I would like to take advantage of this plug-in but the 'Abort the build if it's stuck' option doesn't set any timer and the description of the plug-in doesn't say how long is the timer, it just says: 'This plugin allows you to automatically abort a build if it's taking too long'
My question is how long is that? 1 hour, less/more?
Can I set up my own time?
Is that timer for the overall job or every line in the batch file has that timer?

A: I upgraded my jenkins installations recently to 1532 and noticed on jobs that the radio to set time has gone missing. I may file this as a bug.
This is what it should look like on your jobs:
https://github.com/jenkinsci/build-timeout-plugin/pull/14#issuecomment-24114825

A: I just upgraded to Jenkins 1535 and with that a new upgrade of the plug-in was available.  That upgrade fixed the problem I was having.  The timeout time is now available.

A: Build-timeout plugin has multiple options (taken from help documentation of Build Timeout Plugin)

*

*Absolute time. Use this if you know exactly how much time your build should  not exceed in advance

*Elastic time. Use this option if you want Jenkins to decide on the time. It basically averages out on the last n builds and will stop a
  build if it exceeds given percentage. If you do not know in advance
  how much time your build takes, use this option

*Likely Stuck. Use Jenkins' Executor.html#isLikelyStuck() heuristics based approach to detect build is suspiciously taking for a long time

In your case, option two seems to be best initially.


text:
Q: Ext JS 3 FitLayout is not extending element to its container I have tried to add panels etc. to TabPanel, but for some reason even I have set added Panels (these elements contains other elements, for example one element contains EditorGridPanel) layout to FitLayout, only visible thing is line at the top of the container, so its not really fitted well and as I would have expected it to be fitted in container.
How can I debug this, because there are no JavaScript errors?
Creation of panel :
function getPanel() {

    var panel = new Ext.Panel({
        layout:'fit'
    });

    var grid = new Ext.grid.EditorGridPanel({
        title: 'mytitle',
        bodyStyle: 'padding: 5px',
        store: store,
        cm: cm,
        frame: true,
        clicksToEdit: 1,
        bbar: [{
            xtype: 'button',
            handler: function() {
                store.save();
            }
        }]
    });

    panel.add(grid);
    return panel;
}

Creation of TabPanel
var tabs = new Ext.TabPanel({
    activeTab: 0,
    plain:true,
    autoScroll: true,
    defaults:{autoScroll: true}
});

var panel = getPanel();
tabs.add(panel);

window = new Ext.Window({
    width: 500,
    height: 450,
    layout: 'vbox',
    modal: true,
    closeAction: 'hide',
    buttons: [],
    items: [tabs]
});

A: Ok, problem was with window element, I had to put fit layout to container Window.
window = new Ext.Window({
    width: 500,
    height: 450,
    layout: 'fit',
    modal: true,
    closeAction: 'hide',
    buttons: [],
    items: [tabs]
});


text:
Q: How to set an App Store link correctly? I fear that I must link to the App Store of the users country. How could I do that automatically?
For example, the link I've got from Apple is this:
http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=99999999999&mt=8

It opens up iTunes but fails loading the app. They say it takes up to 24h until it's there. So that is the link I can give anyone, no matter if from US, India, Australia or Holland? I'm confused because sometimes Google throws me at URLs like this one:
http://itunes.apple.com/us/app/id308928075?mt=8

These URLs show an app description in the web browser, and obviously they're localized. This one is for us, but you could enter any country code for /us/ to see the special description.
So is it intelligent to link to the first, very long URL (itunes.apple.com/WebObjects/MZStore...) or is it better to link to the US page of the app description online?

A: You're correct that the web links are localised. However, if you click 'View in iTunes' from that link or indeed launch any link that opens iTunes then the user is taken to the product on the correctly localised version of the store. I've just tested it with the web link you give above — clicking 'View in iTunes' took me to your product on the UK store, with UK pricing.
The direct to iTunes link you supply doesn't work, but you seem not to have substituted your product id for the 99999999999 placeholder.
I'm not sure which you'd consider better; Apple seem to be pushing the web preview URLs, based on the new behaviour of right clicking and selecting 'Copy Link' while in iTunes itself. Also, the type of link that you expect to open iTunes, with your product id substituted (ie, http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=308928075&mt=8) now appears to go to the web preview rather than to open iTunes. As a quick tip, this appears to be the 'international' version:
http://itunes.apple.com/app/id308928075?mt=8

i.e. just remove the 'us'. My browser still went to the US listing based on the price and reviews, but I'll bet it does something to at least get the display language correct.


text:
Q: Using react-leaflet-geosearch in React Leaflet: cannot read property addControl Trying to add react-leaflet-geosearch to my leaflet map and I get the error:

Cannot read property 'addControl' of undefined

I do not know what the problem seems to be:
My code:
render() {
    const prov = OpenStreetMapProvider();
    const GeoSearchControlElement = SearchControl;
    return (
      <>

          <MapContainer
            style={{ height: "100%", width: "100%" }}
            center={position}
            zoom="0"
            scrollWheelZoom={true}
          >
            <TileLayer
              attribution='© OpenStreetMap contributors'
              url="https://api.mapbox.com/styles/v1/


text:
Q: Submitting a POST with headers and parameters I need to connect to an API but all the examples they give to connect are using CURL. I need to implement it in C#. I have narrowed it down to needing to use the httpclient class, but i cant seem to find any examples or tutorials that explain exactly what i need. Here is the CURL query they say to use. Can anyone point me in the right direction of how to convert it into c#?
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXX' -d '{
  "grant_type": "password",
  "client_id": XXXXX,
  "username": "XXX.XXXXXX@XXXXXXXXX.com",
  "password": "XXXXXXXXXXXXX|XXXXXXXXXXXXX"
}' 'https://XXXXXXXXXXXX/XXXXXXXX/XXXXX/XXXXXX/authorize'
Thanks in advance :)

A: You can use the HttpClient class as following
 using (var client = new HttpClient())
            {

                client.BaseAddress = new Uri("http://yourdomain.com");
                client.DefaultRequestHeaders.Accept.Clear();

                //this line is optional in case you are using basic authentication
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                                                        "Basic",
                                                        Convert.ToBase64String(
                                                            System.Text.ASCIIEncoding.ASCII.GetBytes(
                                                               string.Format("{0}:{1}", "username", "password"))));

                var content = new FormUrlEncodedContent(new[]
                            {
                                new KeyValuePair<string, string>("", "login")
                            });
                HttpResponseMessage response = client.PostAsync("http//yourdomain.com", content).Result;
                if (response.IsSuccessStatusCode)
                {
                    var _result = response.Content.ContentToString();

                }
            }


text:
Q: Retrieve nested mapping in Solidity Pls, help to figure out how to retrieve the nested mapping in the Solidity.
string tokenURI;
uint256 tokenId;

There is Solidity mapping:
mapping(uint256 => mapping(address => string);

How to get all tokenURI based on address? I need to print them out using Python.
I created loop but it doesn't work:
uint256[] public tokens; // numbers 0,1,2 etc
address[] public clients; // addresses
string[] public uris;
function getNftUri() public {
         for (uint256 i = 0; i < tokens.length; i++){
             uint256 t = tokens[i];
             for (uint256 j = 0; j < clients.length; j++){
                 address client = clients[j];
                 if (client == msg.sender){
                     uris.push(nftCollection2[t][client]);
                 }
             }
         }
         //return uris;
}

A: Soldity mappings are not iterable, so you'll need to duplicate the values in an array to be able to get all values by a key.
mapping(address => mapping(uint256 => string)) tokenURIs;

// this way you can query `tokenURIsByAddress[owner]` to get all token URIs by an address
// `push()` to this array to add items
// as well as remove items from the array
mapping(address => string[]) tokenURIsByAddress;

You can also make use of some existing library for iterable mappings that does exactly the same thing as described in my code comment above.


text:
Q: Kind of apps (universal vs. apple silicon) If I look at my application list in System Information some apps have a 'kind' of Universal and others 'Apple Silicon'.  What's the distinction?
Thanks!

A: The Mach-O executable format supports multiple architectures in the same executable file, such as aarch64, x86_64, ppc, and so on. Such a file is usually referred to as a "fat binary" or "Universal application" in the Apple marketing jargon, as it allows a single binary file to be easily shipped and executed on different platforms.
This has helped Apple during the PowerPC->Intel transition in the '00s, and the same concept is now being reused to smoothen the x86_64->AArch64 transition.
"Apple Silicon" is just a marketing term Apple uses to refer to the AArch64-based chips they design in-house (both mobile and desktop). You may consider it as a synonym for "AArch64".
Going back to your question, the kind field displayed in System Information->Software->Applications shows you for which platforms the applications installed on your computer have been built.
An "Apple Silicon" application will only contain code built for AArch64, an "Intel" one will only run under x86_64, and a "Universal" app will contain code for both of them.
You may also use the lipo tool from XCode to inspect what architectures a given Mach-O binary contains:
$ lipo -detailed_info /Applications/Firefox.app/Contents/MacOS/firefox
Fat header in: /Applications/Firefox.app/Contents/MacOS/firefox
fat_magic 0xcafebabe
nfat_arch 2
architecture x86_64
    cputype CPU_TYPE_X86_64
    cpusubtype CPU_SUBTYPE_X86_64_ALL
    capabilities CPU_SUBTYPE_LIB64
    offset 4096
    size 41728
    align 2^12 (4096)
architecture arm64
    cputype CPU_TYPE_ARM64
    cpusubtype CPU_SUBTYPE_ARM64_ALL
    capabilities 0x0
    offset 49152
    size 91232
    align 2^14 (16384)
$ lipo -detailed_info /bin/ls
Fat header in: /bin/ls
fat_magic 0xcafebabe
nfat_arch 2
architecture x86_64
    cputype CPU_TYPE_X86_64
    cpusubtype CPU_SUBTYPE_X86_64_ALL
    capabilities 0x0
    offset 16384
    size 59536
    align 2^14 (16384)
architecture arm64e
    cputype CPU_TYPE_ARM64
    cpusubtype CPU_SUBTYPE_ARM64E
    capabilities PTR_AUTH_VERSION USERSPACE 0
    offset 81920
    size 75440
    align 2^14 (16384)

As you see, both Firefox and the system-provided ls have both been built and shipped as fat binaries.


text:
Q: How to hide copy process of Visio to RichTexbox all. I've created a project that displays contents from a Visio document by copying the content and pasting the content as an image on a rich textbox in a C# winform. The problem is that when the copying process begins, Visio opens up for a few seconds and then my program copies the content. While I do want that to happen, I do not want Visio visible during the process. Is there a way to accomplice what is done while hiding Visio?
Here's the code:
public partial class FrmVisio : Form
{
    public FrmVisio()
    {
        InitializeComponent();
    }

    private void cboContent_SelectedIndexChanged(object sender, EventArgs e)
    {
    }

    private void FrmVisio_Load(object sender, EventArgs e)
    {
        cboContent.Items.Add("PFD-001_Control of Documented Information Process _(R4)");
        cboContent.Items.Add("PFD-002_Management_Review_Process_(R1)");
        cboContent.Items.Add("PFD-003 Control of Non-conformance Process Flow(R1)");
        cboContent.Items.Add("PFD-004_Internal Audit Process _(R1)");
        cboContent.Items.Add("PFD-008_Risk & Opportunity Process _(R1)");
        cboContent.Items.Add("PFD-010_Change_Control_Process_Flow_Diagram_(R1)");
        cboContent.Items.Add("PFD-011_Determine_Requirements_for_Products_Services_(R2)");
    }

    private void btnOpenWord_Click(object sender, EventArgs e)
    {
        if (cboContent.SelectedItem == null)
            MessageBox.Show("Please select a document", "No Document Selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        else
        {
            var item = cboContent.SelectedItem.ToString();

            MessageBox.Show("IMPORTANT! PLEASE READ: MS Visio allows you to create shapes and diagrams. However, those things, if edited, will not be saved on the " +
                "QMS unless you export the allocated document as a PDF in the same folder and overwrite the default PDF given. DO NOT CHANGE THE FILE NAMES OR THEIR LOCATIONS! Otherwise, the link to the documents and the QMS will be broken", "PLEASE READ!", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            Process.Start(@"C:\Program Files (x86)\IMS Global\Quality Management System Application\QMS\QMS\QMS\" + item + @".vsd");
        }
    }

    /// <summary>
    /// Show the preview of the Visio Document
    /// </summary>
    public void DisplayVsio()
    {
        //TODO: Find Better Alternative to Show Visio Documentation.
        //TODO: If not possible, edit widgets in windows form.
        if(cboContent.SelectedItem == null)
        {
            MessageBox.Show("Please select a document", "No Document Selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else
        {
            var item = cboContent.SelectedItem.ToString();
            Visio.Application appObject = new Visio.Application();

            Microsoft.Office.Interop.Visio.Document doc = appObject.Documents.Open(@"C:\Program Files (x86)\IMS Global\Quality Management System Application\QMS\QMS\QMS\" + item + @".vsd");
            doc.Application.ActiveWindow.Selection.SelectAll();
            doc.Application.ActiveWindow.Selection.Copy();
            richTextBox1.Paste();

            appObject.Quit();
        }
    }

    private void btnShow_Click(object sender, EventArgs e)
    {
        richTextBox1.Clear();
        DisplayVsio();
    }
}

A: Change:
Visio.Application appObject = new Visio.Application();
to:
Visio.Application appObject = new Visio.InvisibleApp();


text:
Q: Image corrupted after zooming I am reading color frame from Kinect V2 sensor using Microsoft Kinect SDK v2. I am copying the frame data in a byte array, which is later on converted into EmguCV Image. Below is the snippet from the code-
// A pixel buffer to hold image data from the incoming color frame
private byte[] pixels = null;
private KinectSensor kinectSensor = null;
private ColorFrameReader colorFrameReader = null;
public KinectForm()
{
    this.kinectSensor = KinectSensor.GetDefault();
    this.colorFrameReader = this.kinectSensor.ColorFrameSource.OpenReader();
    this.colorFrameReader.FrameArrived += this.Reader_ColorFrameArrived;
    // create the colorFrameDescription from the ColorFrameSource using Bgra format
    FrameDescription colorFrameDescription = this.kinectSensor.ColorFrameSource.CreateFrameDescription(ColorImageFormat.Bgra);
    // Create a pixel buffer to hold the frame's image data as a byte array
    this.pixels = new byte[colorFrameDescription.Width * colorFrameDescription.Height * colorFrameDescription.BytesPerPixel];
    // open the sensor
    this.kinectSensor.Open();
    InitializeComponent();
}

private void Reader_ColorFrameArrived(object sender, ColorFrameArrivedEventArgs e)
{
    using (ColorFrame colorFrame = e.FrameReference.AcquireFrame())
    {
        if (colorFrame != null)
        {
            FrameDescription colorFrameDescription = colorFrame.FrameDescription;
            if (colorFrame.RawColorImageFormat == ColorImageFormat.Bgra)
                colorFrame.CopyRawFrameDataToArray(pixels);
            else
                colorFrame.CopyConvertedFrameDataToArray(this.pixels, ColorImageFormat.Bgra);

            //Initialize Emgu CV image then assign byte array of pixels to it
            Image<Bgr, byte> img = new Image<Bgr, byte>(colorFrameDescription.Width, colorFrameDescription.Height);
            img.Bytes = pixels;

            imgBox.Image = img;//Show image in Emgu.CV.UI.ImageBox
        }
    }
}

The converted image is corrupted after zooming more than 25%. Please see below screenshots-
50% Zoom -

25% Zoom -

12.5% Zoom -

A: The < TColor> should be Bgra, you can confirm from the "pixels" bytes array.
edit:
As the intensity of the Kinect's color frame is 0, the image won't be visible, so I added this code to solve the issue, I hope there is a better (faster) way to solve it.
private void FixIntensity(byte[] p)
    {
        int i = 0;
        while (i < p.Length)
        {
            p[i+3] = 255;
            i += 4;
        }
    }


text:
Q: How to fire and forgot a HTTP request? Is it possible to fire a request and not wait for response at all?
For python, most internet search results in

*

*asynchronous-requests-with-python-requests

*grequests

*requests-futures
However, all the above solutions spawns a new thread and wait for response on each of the respective threads. Is it possible to not wait for any response at all, anywhere?

A: You can run your thread as a daemon, see the code below; If I comment out the line (t.daemon = True), the code will wait on the threads to finish before exiting. With daemon set to true, it will simply exit. You can try it with the example below.
import requests
import threading
import time
def get_thread():
    g = requests.get("http://www.google.com")
    time.sleep(2)
    print(g.text[0:100])

if __name__ == '__main__':
    t = threading.Thread(target=get_thread)
    t.daemon = True  # Try commenting this out, running it, and see the difference
    t.start()
    print("Done")

A: I don't really know what you are trying to achieve by just firing an http request. So I will list some use cases I can think of.
Ignoring the result
If the only thing you want is that your program feels like it never stops for making a request. You can use a library like aiohttp to make concurrent request without actually calling await for the responses.
import aiohttp
import asyncio

async def main():
    async with aiohttp.ClientSession() as session:
        session.get('http://python.org')

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

but how can you know that the request was made successfully if you don't check anything?
Ignoring the body
Maybe you want to be very performant, and you are worried about loosing time reading the body. In that case yo can just fire the request, check the status code and then close the connection.
def make_request(url = "yahoo.com", timeout= 50):
    conn = http.client.HTTPConnection(url, timeout=timeout)
    conn.request("GET", "/")
    res = conn.getresponse()
    print(res.status)
    conn.close()

If you close the connection as I did previously you won't be able to reuse the connections.
The right way
I would recommend to await on asynchronous calls using aiohttp so you can add the necessary logic without having to block.
But if you are looking for performance, a custom solution with the http library is necessary. Maybe you could also consider very small request/responses, small timeouts and compression in your client and server.


text:
Q: Cannot read property slug of undefined I'm working with next.js and wordpress. I have set up my api.js. And whenever I tried to access the [slug] from another component, It shows - Typerror: Cannot read property 'slug' of undefined.
Assuming, I have another page called Test, if I try to access the post from the component with next link
<Link href={`/articles/${node.slug}`}>

{post.name}

</Link>

It shows the Typerror: Cannot read property 'slug' of undefined
My codes works fine in the same component it was created in, but whenever I try to access it from another component with the next link; it shows the error.
I hope It's well understood.
Here's my code:
api.js:
const API_URL = process.env.WP_API_URL;

async function fetchAPI(query, { variables } = {}) {
  const headers = { 'Content-Type': 'application/json' };

  const res = await fetch(API_URL, {
    method: 'POST',
    headers,
    body: JSON.stringify({ query, variables })
  });

  // error handling work
  const json = await res.json();
  if (json.errors) {
    console.log(json.errors);
    console.log('error details', query, variables);
    throw new Error('Failed to fetch API');
  }
  return json.data;
}

export async function getAllPosts(preview) {
    const data = await fetchAPI(
      `
      query AllPosts {
        posts(first: 20, where: {orderby: {field: DATE, order: DESC}}) {
          edges {
            node {
              id
              date
              title
              slug
            }
          }
        }
      }
      `
    );

    return data?.posts;
}

export async function getAllPostsWithSlug() {
    const data = await fetchAPI(
      `
      {
        posts(first: 10000) {
          edges {
            node {
              slug
            }
          }
        }
      }
    `);
    return data?.posts;
};

export async function getPost(slug) {
    const data = await fetchAPI(
      `
      fragment PostFields on Post {
        title
        excerpt
        slug
        date
        featuredImage {
          node {
            sourceUrl
          }
        }
      }
      query PostBySlug($id: ID!, $idType: PostIdType!) {
        post(id: $id, idType: $idType) {
          ...PostFields
          content
        }
      }
    `,
      {
        variables: {
          id: slug,
          idType: 'SLUG'
        }
      }
    );

    return data;
};

[slug].js:

{postData.title}

export async function getStaticPaths() {
    const allPosts = await getAllPostsWithSlug();

    return {
        paths: allPosts.edges.map(({ node }) => `/articles/${node.slug}`) || [],
        fallback: true
    };
}

export async function getStaticProps({ params }) {
    const data = await getPost(params.slug);

    return {
        props: {
            postData: data.post
        }
    };
}

GraphQL query
query AllProfiles {
  businessProfiles(where: {orderby: {field: AUTHOR, order: ASC}}) {
    edges {
      node {
        date
        title
        slug
        link
        uri
   }
}

Note: I shorten the codes due to stackoverflow validations. Now, the problem is whenever I try to access the path from another component, it shows the error I mentioned above.
I am using Next link for the routing and all.
Anyway to fix it? Please, guide me.
Thank you all.

A: using the graphql query from above
query AllProfiles {
  businessProfiles(where: {orderby: {field: AUTHOR, order: ASC}}) {
    edges {
      node {
        date
        title
        slug
        link
        uri
      }
    }
  }
}

assuming you're targeting that query for the slug in Link and your function looks as follows
export async function getAllProfiles() {
    const data = await fetchAPI(`
query AllProfiles {
  businessProfiles(where: {orderby: {field: AUTHOR, order: ASC}}) {
    edges {
      node {
        date
        title
        slug
        link
        uri
      }
    }
  }
}
`);

 return data?.posts;
}

Then, you'll want to isolate slug. How? Make a standalone getProfileSlug component.
import { getAllProfiles } from '@lib/api';
import Link from 'next/link';

const resolveProfileSlugs = async ({ ...props }) => {
    const data = await getAllProfiles();
    return data !== null &&
        data.posts !== null &&
        data.posts.edges !== null &&
        data.posts.edges.length > 0 ? (
        data.posts.edges.map(slugs => {
            return slugs !== null &&
                slugs.node !== null &&
                slugs.node.slug !== null &&
                slugs.node.title !== null ? (
                <>
                    <Link href={`/articles/${slugs.node.slug}`} passHref key={slugs.node.id}>

                            {slugs.node.title}

                    </Link>
                </>
            ) : (

{'Slug or Title Null'}

            )
        })
    ) : (

            {
                'data from getAllProfiles either null, undefined, and/or has an edges.length = 0'
            }

    );
};

export default resolveProfileSlugs;

I use next/typescript for all my wpgraphql projects. Feel free to poke around my most recent repo -- https://github.com/DopamineDriven/drisdell-consulting-services


text:
Q: Display each character in a different color Angular JS I would like to display each character in a word with different color in Angular JS. i tried using  tag in js file but html is not parsing it. Let me know the best way i can do it.  T

A: The quickest way would probably be to split the word into different spans containing just one letter:
let letters = word.split('')
             .map(letter => `<span color="your_color">${letter}</span>`)


text:
Q: Is it possible to store the fields of one Array as a new array? In my CakePHP app, I'm pulling in the results of a table called 'Timesheets'. This table has an athlete_id and a few split times for a race. I need to do some calculations on one athlete's times compared to another athlete (for instance, calculate the difference between the fastest finish time and slowest).
I thought the best way to do this would be to store every athletes 'finish' in a new array, then run the min() function on it. For the life of me, I can't get this to work...
Do you think I am approaching this the wrong way, or am I just missing something?
foreach ($timesheet['Run'] as $run):
    <tr<?php echo $class;?>>
        <?php echo $run['athlete_id'];?>
        <?php echo $run['start'];?>
        <?php echo $run['split1'];?>
        <?php echo $run['split2'];?>
        <?php echo $run['split3'];?>
        <?php echo $run['split4'];?>
        <?php echo $run['split5'];?>
        <?php echo $run['split6'];?>
        <?php echo $run['finish'];?>

   endforeach

A: Assuming you are fetching the timetable with order by finish asc from the database, you could do something like this (omitting splits for brevity):
$fastest = $previous = $timesheet['Run'][0]['finish'];
foreach ($timesheet['Run'] as $run):

        <?php echo $run['athlete_id'];?>
        <?php echo $run['finish'];?>
        <?php echo $previous - $run['finish'];?>
        <?php echo $fastest - $run['finish'];?>

    $previous = $run['finish'];
endforeach

This should give rows like this:
id | finished_in | to_previous  | to_best
1  | 120         | 0            | 0
2  | 121.5       | -1.5         | -1.5
3  | 121.8       | -0.3         | -1.8
4  | 122.6       | -0.8         | -2.6
...

Another option would be to wrap the returned array into an Object or maybe an ArrayIterator and do the calulcations inside, encapsuling $fastest and $previous and whatever else you might want to calculate.

A: I'll assume you have the appropriate  tags around the foreach and a ';' after endforeach.
So the question becomes can you access $timesheet['Run'][0]['athlete_id']? You might use print_r() to make sure that $timesheet is in the form you think it is.

A: I would look into using something like usort.  You can define a callback function to sort your $timesheet['Run'] array by the 'finish' key.  In the end, the first entry in your array, if defined correctly, will have the shortest finish time.
For example:
function cmp($a, $b)
{
   if ($a['finish'] == $b['finish'])
   {
      return 0;
   }

   return ($a['finish'] < $b['finish']) ? -1 : 1;
}

usort($timesheet['Run'], "cmp");

A: I recommend either doing the calculation and sorting in the controller and in SQL.

A: In my opinion you need to change the way you store your data.
try to create table containing id, event_id, athlete_id and time, that would make your application more flexible and calculation easier.


text:
Q: How to Install Selenium as a Unix daemon? How to put the following commands to run in the background as a service on Ubuntu?
Start the hub
java -jar selenium-server-standalone-2.48.2.jar -role hub &

Start the nodes
java -jar selenium-server-standalone-2.48.2.jar -role node  -hub http://localhost:4444/grid/register &

Whenever I close my ssh session can not access the selenium grid service even putting '&' character at the end of each command. Would someone give me a help?

A: I've tried to make selenium-server-standalone running as a service, but it failed to launch browser (I've tried chrome and firefox).
So it is better to do as Mahsum Akbas says.
Here is an example of how you could make it as a service:
bash - Start Java jar by service (linux)...
But it will not launch real browsers.
I was using jenkins service to launch real browser, but it failed too.
I had success in launching tests using headless browser. But there was the problem with some tests were failing.
And also, you could try this
EDITED: I've achieved it in such way using systemd:
sudo vim /etc/systemd/system/selenium-server-hub.service

[Unit]
Description=Selenium Server Standalone hub
StartLimitIntervalSec=5
After=syslog.target

[Service]
Type=simple
Restart=always
RestartSec=8
User=spacer
ExecStart=/bin/bash -c "export DISPLAY=:10 && /usr/bin/java -jar /home/spacer/seleniumserver/selenium-server.jar -role hub"
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target

sudo vim /etc/systemd/system/selenium-server-hub.service
[Unit]
Description=Selenium Server node
StartLimitIntervalSec=0
After=selenium-server-hub.target

[Service]
Type=simple
Restart=always
RestartSec=8
User=spacer
ExecStart=/bin/bash -c "export DISPLAY=:10 && /usr/bin/java -Dwebdriver.chrome.driver=/bin/chromedriver -jar /home/spacer/seleniumserver/selenium-server.jar -role node -hub 'http://192.168.0.101:4444/grid/register/'"
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target

I connect to my linux server through RDP and it opens display :10. Your display could be different.
You could check your displays by command:
ps e | grep -Po " DISPLAY=[\.0-9A-Za-z:]* " | sort -u

PS: Chrome and Firefox are starting, even though chromedriver could not be started when I was launching selenium-server hub and node from terminal as usual.

A: you can use nohup command. so, you can redirect output to nohup file and there will not be kill session after disconnect ssh.
nohup java -jar selenium-server-standalone-2.48.2.jar -role hub &
nohup java -jar selenium-server-standalone-2.48.2.jar -role node  -hub http://localhost:4444/grid/register &


text:
Q: LINQ group by null issue I am working on LINQ query where I need all the questions where each question may or may not have sub-question.
I am getting group by null/ exception issue as some parent question doesn't have child question. I am doing left join followed; group by parent question
(from question in Context.Questions.Where(question => question.ConsultationId == ConsultationId)
                   join questionHierarchy in Context.QuestionHierarchy on question.Id equals questionHierarchy.ParentQuestionId into qs
                   from childQuestion in qs.DefaultIfEmpty()
                   group childQuestion by question into g
                   select new
                   {
                       g.Key,
                       g
                   }).ToList();

A: found the answer
(from question in Context.Questions.Where(question => question.ConsultationId == ConsultationId)
                   join questionHierarchy in Context.QuestionHierarchy on question.Id equals questionHierarchy.ParentQuestionId into qs
                   from childQuestion in qs.DefaultIfEmpty()
                   group childQuestion by question into groupQuestions
                   select new
                   {
                       groupQuestions.Key,
                       childQuestions = groupQuestions.DefaultIfEmpty() == null? null : groupQuestions
                   }).ToList();

A: If you want something like "questions with their sub-questions" cnsider using GroupJoin? instead of an inner join followed by a GroupBy
In small steps:
IQueryable<Question> questions = dbContext.Questions.Where(...)
IQueryable<QuestinoHierarch> subQuestions = Context.QuestionHierarchy;

var questionsWithTheirSubQuestions = questions.GroupJoin(  // GroupJoin the questions
    subQuestions,                                          // with the subQuestions
    question => question.Id,           // from every question take the Id
    subQuestion => subQuestion.ParentQuestionId,
                                       // from every subQuestion take the ParentQuestionId,
    (question, subQuestions) => new    // take the question with all matching subQuestions
    {                                  // to make one new object:
        // select only the question items you plan to use
        Title = question.Title,
        Priority = question.Priority,
        ...

        // select only the subQuestions that you want (or all)
        // for example only the answered sub questions:
        SubQuestions = subQuestions
             .Where(subQuestion.Type = QuestionType.Answered)
             .Select(subQuestion => new
             {
                  // again: select only the subQuestion properties you plan to use
                  Name = subQuestion.Name,
                  Date = subQuestion.Date,
                  ...
             })
             .ToList(),
    });

TODO: if desired, make one big statement.


text:
Q: IEEE two column format This should be a quick answer that I can't seem to find again.  A while ago, I found out that I can use a one line addition in the preamble to format the document to the IEEE standard. It wasn't a reference to a style sheet or something else, but was integrated into TexLive. What is it again?

A: IEEEtran forms part of both MiKTeX and TeX Live, and should therefore be included in your distribution by default. As such, using
\documentclass{ieeetran}

should suffice to format your document according to IEEE's standard.
For manual installation, files are also available for download on the IEEEtran homepage.


text:
Q: In a finite group we have $abc\cdots z = z\cdots cba$ . Is it abelian? In a group we have $abc\cdots z = z\cdots cba$ then is it an abelian group?
It's proven for $3$ members here:
In a group we have $abc=cba$. Is it abelian?
And I do not find a way to try an inductive proof (If it's right for three members then it's right for n members).

A: Following the question in the link I'll try to show the case where:
$abcd=dcba$ for all $a,b,c,d\not=1$ in $G$. It is $a'=a^{-1}$ and
\begin{align}abcd=dcba \iff \\ abcda'b'c'd'=1 \\ \iff abcd(cba)'d'=1 , \\ \ \text{ for } d=cba \\ abc(cba)'=1 \iff \\ abca'b'c'=1 \iff \\ abc(ba)'c'=1, \\ \text{ for } c=ba \\ aba'b'=1 \checkmark \end{align}


text:
Q: C++11 std::begin doesn't work with int[] passed into template function I've got an issue: no matching function for call to 'begin(int*&)'
The only hint I've found on it is that compiler might not know the size of array at compile time, but I believe that's not my case.
Here is what I've got:
template <typename T>
void heapSort(T array[]) {
  size_t length = std::end(array) -  std::begin(array);
  if (length == 0) {
    return;
  }
  Heap<T> heap(array);
  for (size_t i = length - 1; i >= 0; --i) {
    array[i] = heap.pop();
  }
}

int main() {
  int array[] = {9, 8, 10, 99, 100, 0};
  for (auto i = 0; i < 6; ++i) {
    std::cout << array[i] << " ";
  }
  std::cout << std::endl;
  heapSort(array);
  for (auto i = 0; i < 6; ++i) {
    std::cout << array[i] << " ";
  }
  std::cout << std::endl;
}

What's the problem? How can I solve it?

A: void heapSort(T array[]);

is just alternative syntax for
void heapSort(T* array);

You can't pass an array by value, so you need to take it by reference (and possibly let the compiler deduce its size):
template<typename T, size_t N>
void heapSort(T (&array)[N]);

Note that this way you'll get a different instantiation for each array of distinct size. It might lead to some code bloat if you've got a large number of arrays. I'd consider using a std::vector instead.

A: Like jrok said, T array[] is just a synonym for a pointer T* array which looses any information about the actual array type.
If you really want to use a compile time array, it's actually
template<typename T,std::size_t N> void heapSort(T (&array)[N])

(And that's in the end what std::begin and std::end do, too.)

A: The other problem is that size_t is always non-negative, so your loop for (size_t i = length - 1; i >= 0; --i) will never terminate. Try replacing with:
for (size_t i = length; i > 0; --i) {
  array[i - 1] = heap.pop();
}


text:
Q: Target adjacent element in Jquery I am using the code below to change the plus sign to minus and vice versa. This works fine if there is only one element on the page.
I have a page with multiple .handler classes and i am looking to target the #plus id next to each handler. Any ideas?
jQuery(".handler").click(function(){
   jQuery("#plus").html(function(_, html) {
        return jQuery.trim(html) == '+' ? '-' : '+';
    });
});

HTML

 + <?php echo $term->name; ?>

<?php

$rp = new WP_Query( $args );
if ($rp->have_posts())
while ( $rp->have_posts() ) {
$rp->the_post();

$name       = get_field('fl_profile_name');
$location   = get_post_meta(get_the_id(), 'fl_country', true);

?>
<li data-location="<?php echo $location; ?>"><a href="<?php the_permalink();?>"><?php echo $name; ?>

<?php
}
?>

A: First change the ID to class since you have multiple elements with the same properties

 + <?php echo $term->name; ?>

then use a descendant selector to find the plus element which is within the clicked handler
jQuery(".handler").click(function () {
    var $plus = jQuery(this).find(".plus").html(function (_, html) {
        return jQuery.trim(html) == '+' ? '-' : '+';
    });
    $('.plus').not($plus).html('+')
});


text:
Q: Visual Studio says im trying to insert NULL into the "id" record of the "Cars_details" table I am writing a program for a university class, and i got stuck. Im having 2 tables, and i want to insert data into them with one text.
Cars

*

*id INT NOT NULL PRIMARY KEY, IDENTITY(1,1)

*userId INT NOT NULL  FOREIGN KEY Users(id)

Car_Details

*

*id INT NOT NULL PRIMARY KEY, FOREIGN KEY Cars(id)

*name varchar(250) NOT NULL

*body_type VARCHAR(250) NOT NULL,

*fuel_type VARCHAR(250) NOT NULL,

*motor_power VARCHAR(250) NOT NULL,

*manufacture_year INT NOT NULL

It is saying that I am trying to insert NULL value for the id record in the Car_Details table. Down below i wrote my method, how did i try to do it.
Tried doing it with transaction, but that did not work also.
public int Insert(Record record)
{
        SqlCommand command = new SqlCommand();
        command.CommandType = System.Data.CommandType.Text;
        //command.CommandText = @"INSERT INTO Cars(userId)
        //                        VALUES ((SELECT id FROM Users WHERE id = Users.id));
        //                        INSERT INTO Car_Details(id, name, body_type, fuel_type, motor_power, manufacture_year)
        //                        VALUES ((SELECT TOP 1 id FROM Cars),@name, @body_type, @fuel_type, @motor_power, @manufacture_year);";

        command.CommandText = "SET XACT_ABORT ON BEGIN TRANSACTION DECLARE @CarID int
  INSERT INTO Cars(userID) VALUES((SELECT id FROM Users WHERE id = Users.id))" +
            "SELECT @CarID = scope_identity()" +
            "INSERT INTO Car_Details VALUES(@CarID, @name, @body_type" +
            "@fuel_type, @motor_power, @manufacture_year)" +
            "COMMIT";
                    //SqlParameter p_id = new SqlParameter();
                    //p_id.ParameterName = "@id";
                    //p_id.SqlDbType = System.Data.SqlDbType.Int;
                    //p_id.Direction = System.Data.ParameterDirection.Input;
                    //p_id.Value = (record as CarRecord).Id;
                    //command.Parameters.Add(p_id);

        SqlParameter p_name = new SqlParameter();
        p_name.ParameterName = "@name";
        p_name.SqlDbType = System.Data.SqlDbType.Char;
        p_name.Direction = System.Data.ParameterDirection.Input;
        p_name.Value = (record as CarRecord).Name;
        command.Parameters.Add(p_name);

        SqlParameter p_body_type = new SqlParameter();
        p_body_type.ParameterName = "@body_type";
        p_body_type.SqlDbType = System.Data.SqlDbType.VarChar;
        p_body_type.Direction = System.Data.ParameterDirection.Input;
        p_body_type.Value = (record as CarRecord).Body_type;
        command.Parameters.Add(p_body_type);

        SqlParameter p_fuel_type = new SqlParameter();
        p_fuel_type.ParameterName = "@fuel_type";
        p_fuel_type.SqlDbType = System.Data.SqlDbType.VarChar;
        p_fuel_type.Direction = System.Data.ParameterDirection.Input;
        p_fuel_type.Value = (record as CarRecord).Fuel_type;
        command.Parameters.Add(p_fuel_type);

        SqlParameter p_motor_power = new SqlParameter();
        p_motor_power.ParameterName = "@motor_power";
        p_motor_power.SqlDbType = System.Data.SqlDbType.Int;
        p_motor_power.Direction = System.Data.ParameterDirection.Input;
        p_motor_power.Value = (record as CarRecord).Motor_power;
        command.Parameters.Add(p_motor_power);

        SqlParameter p_manufactrue_year = new SqlParameter();
        p_manufactrue_year.ParameterName = "@manufacture_year";
        p_manufactrue_year.SqlDbType = System.Data.SqlDbType.Int;
        p_manufactrue_year.Direction = System.Data.ParameterDirection.Input;
        p_manufactrue_year.Value = (record as CarRecord).Manufacture_year;
        command.Parameters.Add(p_manufactrue_year);

        command.Connection = getConnection();

        int affectedRows = command.ExecuteNonQuery();
        command.Connection.Close();

        return affectedRows;
}

A: There is missing IDENTITY (1,1) clause on primary key fields. In your current scenario you need to use IDENTITY definition or specify your primary key value in code and then pass it to SQL command.
Here you can find more info: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property?view=sql-server-2017
There is also OUTPUT INSERTED.[PK column name] clause:
https://www.sqlservercentral.com/articles/the-output-clause-for-insert-and-delete-statements
With OUTPUT clause you need to use reader to get reply from it.
Probably you need to use this approach if you are working in pending (uncommited) transaction.


text:
Q: Ubuntu on a USB stick - mount options to reduce writes I'd like to have Ubuntu installed on a USB stick, that I could plug in (almost) any computer and boot from it, and that I could use (almost) normally, as if it was installed on that computer. I'd also like to have a data partition on it that could be used by (almost) any computer, mostly to store some portable apps, just in case.

My main concern is to increase the lifetime of my drive, but without making it too unstable.
To do that, I have to choose the right options in /etc/fstab for my partitions.
Currently, I'm thinking about these:

*

*/: ext4, defaults,lazytime,commit=60,errors=remount-ro

*/media/data: FAT32, defaults,lazytime,check=strict
So lazytime should be better than the often proposed noatime or the default relatime, since, as I understand it, it's applied to creation, access and modification times, it's POSIX compliant (contrary to relatime), and it reduces the amount of write cycles by storing times in RAM and writing them from time to time.
Combined with commit=60, it should reduce writes enough to compensate the journal of ext4, that I want to keep to have a stable system.
Do you think those options are good enough?
Do you see other options I could use to reduce writes but keep a stable system?

My current setup:

*

*USB stick: SanDisk Ultra Fit (32 Go)

*OS: Xubuntu 16.04 i386

*installation: full install (from a Live USB built with Rufus)

*drivers: none proprietary

*file systems:

*

*partition table: GPT

*

*2: ESP, /boot/efi, 128 Mio, FAT32, [boot,esp]

*3: ABP, 128 Mio, HFS+

*4: BBP, 2 Mio, [bios_grub]

*5: swap, 512 Mio

*6: root, /, 24 Gio, ext4, defaults,errors=remount-ro,lazytime,commit=60

*1: data, /media/data, ~3.6 Gio, FAT32, defaults,lazytime,check=strict

*RAM:

*

*/tmp, tmpfs, defaults,nosuid,nodev,noexec,mode=1777

*swap:

*

*vm.swappiness=5

*swap partition: 512 Mio, for emergency

*zRAM

*swap files:

*

*/var/swap/hib.swp: same size as RAM, for hibernation, generated by a script at startup

*/var/swap/opt.swp: if needed, generated by a script

*overprovisioning: ~5.6%

*

*built-in: ~1.2 Gio (apparently)

*added: 512 Mio

*scheduler: deadline

A: I have made a lot of installed systems into USB flash drives, and I think such systems can work quite well. You have found some mount options, that I have not found (and not used). I am looking forward to future reports from you :-)

See this link about my systems, and the tweaks that I suggest,
help.ubuntu.com/community/Installation/UEFI-and-BIOS#Final_system_tweaks
I think it is important to get a fast USB 3 flash drive (and I think there are better drives for this purpose than the Ultra Fit),
help.ubuntu.com/community/Installation/FromUSBStick#Notes_about_speed
I think that the lifetime of good USB pendrives is rather good now, but still, it is important to backup all important files at regular intervals.

An alternative is a persistent live drive with a casper-rw partiiton, and if you wish you can add a home-rw partition,
help.ubuntu.com/community/mkusb/persistent
A persistent live drive is more portable, but cannot be updated and upgraded like an installed system (the kernel and drivers cannot be upgraded). But an installed system is often portable enough.


text:
Q: How to set a list to remove duplicates and to show only last entry by date? I have created a program which collects:

*

*HWID

*public IP Address

*Date and time when program is launched

Program is designed to append those values, each in "Environment.NewLine" and result looks like this:

Next step was to separate those entries, so I can have them in 3 different listBoxes and here is the class code I used :
public DB_List(string fajl) //Fajl u Listu pretvaranje
{
    newFajl = fajl;
}
public Tuple < List < string > , List < string > , List < string >> ListSeparator()
{
    string[] FajlA = File.ReadAllLines(newFajl);
    List < string > one = new List < string > ();
    List < string > two = new List < string > ();
    List < string > three = new List < string > ();
    {
        for (int i = 0; i < FajlA.Length; i += 3)
        {
            one.Add(FajlA[i]);
            two.Add(FajlA[i + 1]);
            three.Add(FajlA[i + 2]);
        }
    }
    return Tuple.Create(one, two, three);
}

Code in main Form :
private void Form1_Load(object sender, EventArgs e)
{
    string a = (@"data\blabl.txt");
    DB_List liste = new DB_List(a);
    var Lista = liste.ListSeparator();
    listBox1.DataSource = Lista.Item1; // HWID
    listBox2.DataSource = Lista.Item2; // cpuIP
    listBox3.DataSource = Lista.Item3; // cpuTime
}

The result is this :
Final :
In the screenshot I've selected what I would like to be displayed.
Basically, I would like:

*

*duplicates to be removed from ListBox1 and ListBox2 ( latest entry to be displayed )

*In ListBox3 - only latest date to be displayed according to the index of  listBox1.DataSource and listBox2.DataSource

A: You want your lists to show only changes, right?
then your data structure is wrong.
It has to be something like
public List<Tuple<string,string, string>> ListSeparator()
        {
            string[] FajlA = File.ReadAllLines(newFajl);
            var results =new List<Tuple<string, string, string>>();

                for (int i = 0; i < FajlA.Length; i += 3)
                {
                    results.add(new Tuple<string, string, string>(FajlA[i], FajlA[i + 1], FajlA[i + 2]);
             }

            return results;
        }

Then on your load you can get distinct data and use them like this:
string a = (@"data\blabl.txt");
    DB_List liste = new DB_List(a);
    var Lista = liste.ListSeparator().Distinct();
    listBox1.DataSource = Lista.Select(l => l.item1).tolist ; // HWID


text:
Q: dnsutils points to public IP of client machine, not server I am logged in via SSH to a remote machine, which is a Raspberry Pi 4. I am trying to use dnsutils to extract the public IP of the remote machine. However, it is returning the public IP of the client machine that I am physically using. I am using a shell script to do this. The specific command that I am using is
public_ip="$(dig +short myip.opendns.com @resolver1.opendns.com)"

I am using SSH via a Windows 11 machine. Not that it matters, but I am using the Visual Studio Code remote - SSH extension package. I have also tried SSH via Windows PowerShell and it's still returning the public IP of the client machine.

A: It's highly unlikely opendns is discovering the IP address of your SSH client if you are executing dig on your remote machine.
The most likely thing is that your client's public IPv4 address is the same as your remote machine's public IPv4 address.  This would happen if the two are in the same physical location or otherwise on the same LAN (perhaps through a VPN).
This is due to Network Address Translation introduced in the late 1990s to slow down IPv4 address exhaustion.  This means that your home or office router will take one IP address for the whole LAN and and make it appear as if everything on your LAN is just one machine with that single IP address.

Incase it isn't obvious to future readers, requesting myip.opendns.com from the DNS server resolver1.opendns.com (or any of the resolver*.opendns.com servers) will result in an A name DNS record with the DNS client's IP address as seen by the DNS server.


text:
Q: Seeking algorithm for optimal 2D spacing of agents among fixed locations I'm designing a program where each of N agents is assigned a value K. There are N fixed locations, each with coordinates (x,y), and each location is assigned one agent.
What algorithm could I use to distribute all agents among the locations such that the linear distance between the agents with the highest values of K is maximized? (Specifically between the agents in the highest quintile of K values.)
If it matters, N will likely fall in the range of 10-30.

A: Google tells me that (30 choose 6) = 593775 so if you can work out a formula that tells you how good each possible choice of K fixed locations from N is, you can probably afford to evaluate it for all possible choices.
Here is a heuristic for larger parameter values. Calculate all distances between pairs of points and sort them into increasing order. Read out pairs from this in order and merge groups of points linked by each pair, using Union-Find to keep track of the groups of points created in this way. Stop when one of the groups reaches the required size, and that group is your answer.


text:
Q: Conditional expectation of insurance payment I'm trying to solve the following problem:
An insurance policy is written to cover a loss, $X$, where $X$ has a uniform distribution on $(0, 1000)$. At what level must a deductible be set in order for the expected payment to be $40\%$ of what it would be with no deductible?
$X$ = total loss
$D$ = deductible
$Y$ = insurance payment
I know that the insurance payment should be:
$$Y = \begin{cases}
  0, & \text{for } X \leq D , \\
  X - D, &\text{for } X > D.
\end{cases}
$$
So then the expected insurance payment is:
$$E[Y] = E[X - D|X >D] \cdot P[X>D]$ $
So that gives us:
$$E[Y] = \frac{1000+D}{2}\cdot\frac{1000-D}{1000}$$
After this I'm stuck.

A: With no deductible, the expected payment is $500$. $\frac{40}{100} \times 500 =200$. Let $d$ be the deductible. $\int\limits_{d}^{1000}\frac{(x-d)}{1000}dx=200$ so $\frac{(1000-D)^{2}}{2000}=200$, I hope I am not mistaken!

A: Your mean excess loss function is set up wrong. By definition, E[X-d|X>d]=the average payment that exceeds the deductible d given that the loss exceeds the deductible.
The original set up: (1000+d)/2 is interpreted as the value of the loss that exceeds the deductible from the insured's point of view. "The insured must incur this amount of loss in order to receive the average payment"
The correct excess loss function: (1000-d)/2. This is the expected value of the loss that exceeds the deductible from the insurer's point of view. For this example, there exists possible payments from 0 to (1000-d), uniformly distributed. The expected value of this uniform distribution is ((1000-d)+0)/2.
In summary, the theoretical set up is correct:

*

*E[X-d|X>d]*P[X>d]=E[Y]

*To solve the problem: ((1000-d)/2)*((1000-d)/1000)=(0.4)*500

Note: mich95 sets up the problem correctly as well. If integrating (x-d) * f(x) is more intuitive, go for it. But in general, I hope this post addresses the problem with where the original equation went wrong.


text:
Q: Asp.Net Core 2.2 UseUrls is ignored I have the following code in my Asp.Net Core 2.2
public class Program
{
    public static void Main(string[] args)
    {
        var urls = new string[] { "https://localhost:3045" };
        CreateWebHostBuilder(args, urls).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args, string[] bindingUrls) =>
        WebHost.CreateDefaultBuilder(args)
            .ConfigureServices(services => services.AddAutofac())
            .ConfigureKestrel(opt =>
            {
                opt.AddServerHeader = false;
            })
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseUrls(bindingUrls)
            .UseStartup<Startup>();
}

However when I debug the site is launched on https://localhost:44326/ why is used in launchSettings.json
Why is that happening?

A: .UseUrls(bindingUrls) will configure Kestrel url.
dotnet core always sits in Kestrel behind IIS/IIS Express as a proxy. The url you get is the configuration for your IIS Express.
This url can be changed in your project settings or launchSettings.json
If you would like to just run on Kestrel user the cli command dotnet run or dotnet watch run


text:
Q: Windows, FindResource error 1814 I have a problem embedding custom binary data into a Windows executable. The problem might also be with linking the resource or retrieving it, I don't know. Anyway the FindResource returns NULL and error code is 1814.
All the examples I've found include using an IDE of some sort or another, for creating the resource and building/making the executable. I need it to be done automatically by calling nmake on the makefile.
I'm doing it on 64bit Windows 7 using personal edition of MS Visual Studio / C++ installed in default directories(s).
Here's the setup I put together (all the files in the same directory; nmake also called from this directory):

*

*File: custom.data.txt with the follofing contents:
My own personal custom data.

Note that I'm only using text resource for this example. In reality I'll be using custom data in no particular format.

*File: custom.h with the following contents:
#define IDR_RCDATA1 101

*File: custom.rc with the following contents:
IDR_RCDATA1 RCDATA "custom.data.txt"

Edit: if #include "custom.h" is added to custom.rc, the example works as expected:
#include "custom.h"
IDR_RCDATA1 RCDATA "custom.data.txt"

*File: example.cpp with the following contents:
#include "custom.h"
#include <windows.h>
#include <fstream>
#include <iostream>

using namespace std;

int main(int argc, char* argv[]) {

    HRSRC myResource = FindResource(NULL, MAKEINTRESOURCE(IDR_RCDATA1), RT_RCDATA);

    if(myResource == NULL) {
        DWORD WINAPI errorCode = GetLastError();
        cout << "Could not find resource! Error code: " << errorCode << "." << endl;
        return 0;
    }

    unsigned int myResourceSize = SizeofResource(NULL, myResource);
    cout << "Resource size: " << myResourceSize << endl;

    if(myResourceSize > 0) {

        HGLOBAL myResourceData = LoadResource(NULL, myResource);
        void* pMyBinaryData = LockResource(myResourceData);

        std::ofstream f("C:\\Users\\draver\\win_custom_resource\\extracted_resource.txt", std::ios::out | std::ios::binary);
        f.write((char*)pMyBinaryData, myResourceSize);
        f.close();

        BOOL bResult = UnlockResource(myResource);
        bResult = FreeResource(myResource);
    }

    return 0;
}

*File makefile with the following contents:
NAME = example

CC = "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64\cl.exe"
RC = "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\RC.exe"
RESOURCE_NAME = custom

all : link

link : compile
    $(CC) $(NAME).obj $(RESOURCE_NAME).res

compile : resource
    $(CC) -c $(NAME).cpp /EHsc

resource :
    $(RC) $(RESOURCE_NAME).rc

clean :
    del *.obj
    del *.exe
    del *.res
    del extracted_resource.txt

*File setup.bat that I'm calling before nmaking, with the following contents:
call "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64

The produced executable (example.exe) contains the "My own personal custom data." string (verified via a dump) as expected, but fails to retrive it when run.
The output is
    Could not find resource! Error code: 1814.

What am I doing wrong?
Edit: see the edit above (3. File: custom.rc) which solves the problem.

A: (Answered in the comments. See Question with no answers, but issue solved in the comments (or extended in chat) )
@Roger Rowland wrote:

Did you #include "custom.h" in your custom.rc file?
Well you need it because otherwise, it will not know that IDR_RCDATA1 is 101, and then FindResource will fail (as it did). What happens if you do #include it?


text:
Q: pymongo error operation failure I'm currently using celery with django, i have
pymongo ver 1.11
mongodb ver 1.8
I'm getting following error, i'm not able to figure out what is the error.
[2011-09-23 02:06:59,544: WARNING/MainProcess] File "/usr/local/lib/python2.6/dist-packages/pymongo/database.py", line 293, in command
[2011-09-23 02:06:59,560: WARNING/MainProcess] msg, allowable_errors)
[2011-09-23 02:06:59,560: WARNING/MainProcess] File "/usr/local/lib/python2.6/dist-packages/pymongo/helpers.py", line 126, in _check_command_response
[2011-09-23 02:06:59,561: WARNING/MainProcess] raise OperationFailure(msg % response["errmsg"])
[2011-09-23 02:06:59,561: WARNING/MainProcess] pymongo.errors
[2011-09-23 02:06:59,561: WARNING/MainProcess] .
[2011-09-23 02:06:59,561: WARNING/MainProcess] OperationFailure
[2011-09-23 02:06:59,561: WARNING/MainProcess] :
[2011-09-23 02:06:59,561: WARNING/MainProcess] command SON([('findandmodify', 'messages'), ('query', {'queue': 'celery'}), ('remove', True)]) failed: exception: nextSafe(): { $err: "using a newer index version: { v: 1, key: { queue: 1 }, ns: "kombu_def...", code: 13658 }

A: I think its to do with MongoDB indexes are using version 1 which relates to mongodb >= 2.0
see: http://www.mongodb.org/display/DOCS/Index+Versions


text:
Q: Can I change Apache's port number to 'not 80' when I connected it with Tomcat? I connected Apache with Tomcat, so the server can run both jsp and php files.
It worked, but I don't want to show the port number, just like any other web sites.
So I changed Tomcat's to 80, and Apache's to 8080.
I checked both servers are on, and accessable, but php files didn't work.
So I tried to make it run, and figured out that only when Apache uses the port number 80, mod_jk works.
Is there good way to running Tomcat at 80, and making Apache to run only php files?
Or, can I make it to access Tomcat's ROOT project when I accessed to Apache and only php files be run from Apache?
Thank you.

A: You don't have to change Apache's and Tomcat's ports. You can configure Apache as a reverse proxy for the specific domain, so it can handle and pass the requests to Tomcat.
For example:
   ProxyRequests Off

    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    ProxyPass / http://domain.tld:8080/
    ProxyPassReverse / http://domain.tld:8080/


text:
Q: Symfony 3: make TextareaType field optional I have a form with one optional field (remark). By default all are mandatory fields. I wanted to make 'remark' field optional. I have tried a lot of solutions. It seems none is working. How can I make it optional?
Here is my code
RequestItem.php
/**
 * RequestItem
 *
 * @ORM\Table(name="request_item")
 * @ORM\Entity(repositoryClass="InventoryBundle\Repository\RequestItemRepository")
 */
class RequestItem
{
  /**
     * @var string
     *
     * @ORM\Column(name="remark", type="text", nullable=true)
     */
    private $remark;

RequestItemType.php
class RequestItemType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('item', EntityType::class, array(
              'class' => 'InventoryBundle:Item',
              'choice_label' => 'name',
              'expanded' => false,
              'multiple' => false,
            ),
              array('attr' =>array('class' =>'form-control', 'style' =>'margin-bottom:15px; width:100px')))
            ->add('date', DateType::class, array('attr' =>array('class' =>'form-control', 'style' =>'margin-bottom:15px')))
            ->add('quantity', TextType::class,array('attr' =>array('class' =>'form-control', 'style' =>'margin-bottom:15px; width:75px')))
            ->add('client', TextType::class,array('attr' =>array('class' =>'form-control', 'style' =>'margin-bottom:15px; width:200px')))
            ->add('remark', TextareaType::class, array('attr' =>array('class' =>'form-control', 'style' =>'margin-bottom:15px', 'required' => false), 'empty_data'  => null))
        ;
    }

I put 'required' => false to remark field.
new.html.twig
{% extends 'base.html.twig' %}

{% form_theme form _self %}

{% use 'form_div_layout.html.twig' with form_label as base_form_label %}
{% block form_label %}
  {{ block('base_form_label') }}
    {% if required %}
      *
    {% endif %}
{% endblock %}

{% block body %}

Request Item creation

    {% if is_granted("ROLE_SUPER_ADMIN") %}

    {% if app.session.flashBag.has('warning') %}

            {% for msg in app.session.flashBag.get('warning') %}
                {{ msg }}
            {% endfor %}

    {% endif %}

    {{ form_start(form) }}
        {{ form_widget(form) }}
        {{ form_row(form.remark, {'required': false}) }}
        <input type="submit" value="Create" class="btn btn-primary" />
    {{ form_end(form) }}

    Back to the list
    {% else %}

Please login

    {% endif %}
{% endblock %}

I add {{ form_row(form.remark, {'required': false}) }} in the twig file.
The page source view for the remark field

  Remark
          *
    <textarea id="request_item_remark" name="request_item[remark]" required="required" class="form-control" style="margin-bottom:15px" ></textarea>

The textarea field is required.
I have also tried by adding in new.html.twig file
{% extends 'base.html.twig' %}

{% form_theme form _self %}

{% block textarea_widget %}

    {% set required=required|default('not required') %}
    {{ block('form_widget_simple') }}

{% endblock %}

It is strange, the textarea field becomes input text field and it is still required.

  Remark
          *

        <input type="text" id="request_item_remark" name="request_item[remark]" required="required" class="form-control" style="margin-bottom:15px"  />

The table structure
CREATE TABLE `request_item` (
  `id` int(11) NOT NULL,
  `item_id` int(11) DEFAULT NULL,
  `date` date NOT NULL,
  `quantity` int(11) NOT NULL,
  `client` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `remark` longtext COLLATE utf8_unicode_ci
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

A: Don't place required in attr, it should be on top level in options.
...
 ->add('remark', TextareaType::class, array('required' => false, 'attr' =>array('class' =>'form-control', 'style' =>'margin-bottom:15px'), 'empty_data'  => null))
...

Otherwise if you set this element required through attributes, and required option won't have sense.


text:
Q: Is it always required to call an object all the way through the chain (or in order)? I'm trying to look through reddit's API. I have seen a fiddle where they grab the image url from the site. However, I'm confused as to how they are getting the objects themselves. In theireach()statement, they used data.data.children and item.data.url, however I cannot find a data object right after another data object in the json here http://www.reddit.com/r/pics.json. I also do not see item.data.url. if I look from the very beginning (the two first objects are "kind" and "data"). What does this mean?

A: Given the code in the fiddle:
$.getJSON("http://www.reddit.com/r/pics/.json?jsonp=?", function(data) {
    $.each(data.data.children, function(i,item){
        $("<img/>").attr("src", item.data.url).appendTo("#images");
    });
});

data and item are both function parameters, and their names have no relation to any named key within the JSON.
The parameter data represents the entire JSON structure, but as it's just a parameter whose name is not significant I shall call it foo instead to disambiguate it from the contents of that structure, hence foo.data refers to the child element named data within the first level of the JSON.
The item parameter represents each element in the array foo.data.children, so item.data.url for the first item would be equivalent to data.children[0].data.url within the JSON.

A: The structure of the JSON returned is:
{
    data: {
        after: "",
        before: null,
        children: [
            {
                data: {
                    url: ""
                }
            },
            ...
        ],
        modhash: ""
    },
    kind: "Listing"
}

The name of the result variable is called data in the callback function parameters. So to get to the children you need to type:
data.data.children;

Next, in the $.each loop, each entry from the children array is assigned to an item variable in that callback function. It is from there where you drill down to the url. property (item.data.url).
You could name these whatever you want if data.data is confusing.


text:
Q: Brace auto formatting on separate lines If I enter some simple code such as:
public void Hello()

and then press enter and type a {, I get:
public void Hello()
{ }

I would like the result to be either:
public void Hello()
{                   // no added '}'

or:
public void Hello()
{
}                   // the '}' on a new line

I've looked around Tools -> Options -> Text Editor -> C# -> Code Style and Tools -> Options -> Text Editor -> C# -> Formatting but cannot seem to find how to make the above changes.

A: Install Productivity Tools 2015
Auto brace completion is one of the many features it has to offer


text:
Q: Tab Completion feature in unix shell development i am developing a shell using unix system programming (robbins and robbins) how can i add this feature and also how can i add history feature too (history feature like in BASH- when i press up key it shows the previous typed command )

A: You can use GNU readline.  It has both these features.
EDIT: Like Christopher says, you should look at the documentation and come back if you have specific questions.


text:
Q: specialization on const member function pointers I am trying to specialize some utility code on const member functions, but have problems to get a simple test-case to work.
To simplify the work i am utilizing Boost.FunctionTypes and its components<FunctionType> template - a MPL sequence which should contain the tag const_qualified for const member functions.
But using the test-code below, the specialization on const member functions fails. Does anybody know how to make it work?
The test-code prints out (using VC8 and boost 1.40):

non-const
  non-const

Expected output is:

non-const
  const

The test-code itself:
#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/function_types/function_type.hpp>
#include <boost/mpl/contains.hpp>

namespace ft  = boost::function_types;
namespace mpl = boost::mpl;

template<typename F>
struct select
{
    template<bool IsConst /* =false */>
    struct helper {
        static void f() { std::cout << "non-const" << std::endl; }
    };

    template<>
    struct helper</* IsConst= */ true> {
        static void f() { std::cout << "const" << std::endl; }
    };

    typedef ft::components<F> components;
    typedef typename mpl::contains<components, ft::const_qualified>::type const_qualified;
    typedef helper<const_qualified::value> result;
};

typedef boost::function<void (void)> Functor;

template<typename MF>
Functor f(MF f)
{
    return boost::bind(&select<MF>::result::f);
}

class C
{
public:
    void f1() {}
    void f2() const {}
};

int main()
{
    f(&C::f1)(); // prints "non-const" as expected
    f(&C::f2)(); // prints "non-const", expected "const"
}

A: While its still unclear to me why the approach via function_types::components<> doesn't work, i realized that there is a simpler approach with Boost.FunctionTypes to specialize on const member functions:
The classification meta functions like is_member_function_pointer<> optionally take a tag parameter ...
template<typename F>
struct select
{
    /* ... helper-struct as before */

    typedef ft::is_member_function_pointer<F, ft::const_qualified> const_qualified;
    typedef helper<const_qualified::value> result;
};

A: I have not tested it, but shouldn't
typedef mpl::contains<components, ft::const_qualified> const_qualified;

be
typedef typename mpl::contains<components::type, ft::const_qualified>::type const_qualified;


text:
Q: Typescript TypeGuard not working on class properties I think title and example code says all:
private x: IJobOverview | IJobRecursive;
method1()
{
    const o = this.x;
    if (isJobOverview(this.x))
        this.x;                   //o is IJobOverview or IJobRecursive !!WHY?
    if (isJobOverview(o))
        o;                        //o is IJobOverview
}

Is this bug? Did I do something wrong?
My Typescript version is 2.2.
Updated:
I get error:

(74,61): error TS2339: Property 'tagIds' does not exist on type
  'IJobOverview | IJobRecursive'

.
Extended code:
if (isJobOverview(this.x))
  this.x.tagIds;               //line 47

I compile with WebPack (Javascript services)


text:
Q: How can I get a legend in my plot? How can I get a legend from the Elev_Avg component of polydatx?
I tried using ax.legend(), but I got this error:
No handles with labels found to put in legend.
Plot
f, ax = plt.subplots(1, figsize=(8, 8))
polydatx.plot(ax = ax, column = 'Elev_Avg', cmap='OrRd', scheme='quantiles', label='elev')
segdatx.plot(ax = ax)
ax.grid(False)
ax.legend()

A: You have to tell the computer what to put in the legend.  Then you will get it :)
For example, if what you are plotting are two columns ['s1', 's2'] from a pandas dataframe df, then this is what you would do to get the plot and legend:
ax.plot(df.loc[:,['s1', 's2']], marker='o')
ax.legend(['s1', 's2'])
plt.show()

A: According matplotlib document (matplotlib)
 the handles is optional, but for some reason most people get that error message. What I did was
handles, labels = ax.get_leggend_handles_labels()
ax.legend(handles, labels). It seems to work for me.


text:
Q: How to handle App Signing and uploading to PlayStore for a startup I am aware of how the process goes but I am unsure how to approach it when uploading for some other people. I was hired to make an app and to help them get it on the play store, when I sign it, what is the usual approach to the key and the password/ aliases? Are there any guidelines that people usually follow when making them eg length of the password, name of the alias and so on? Should I give them the key as well, where is the key usually stored?

A: The keys are stored in a keystore. Make sure to create a new keystore and there create a key called "key0" (my IDE shows this as the standart name IDK). Make sure to give them the keystore name & password, as well as the "key0" and its password.
Then, you can simply give them the keystore file. Make sure to tell them to back it up.
When they want to make a new release, they will browse to the keystore that you gave them and will be able to sign the new release with the passwords and keyname you gave them.


text:
Q: Align ggplot2 plots vertically With the code found at https://gist.github.com/low-decarie/5886616
A dual dendodogram tile plot can be produced:
dual_dendogram_tile_plot(as.matrix(USArrests),  main="USA Arrests")

The problem: Align the vertical dendogram with the tile plot area.
(and/or improve the alignment of the horizontal dendogram)
This question relates to:
left align two graph edges (ggplot)
Specifying ggplot2 panel width
Plot correlation matrix into a graph

A: Here's an example to align more basic grobs,
library(ggplot2)
library(grid)
library(gtable)

p <- qplot(1,1)
g <- ggplotGrob(p)

panel_id <- g$layout[g$layout$name == "panel",c("t","l")]
g <- gtable_add_cols(g, unit(1,"cm"))

g <- gtable_add_grob(g, rectGrob(gp=gpar(fill="red")),
                     t = panel_id$t, l = ncol(g))

g <- gtable_add_rows(g, unit(1,"in"), 0)
g <- gtable_add_grob(g, rectGrob(gp=gpar(fill="blue")),
                     t = 1, l = panel_id$l)

grid.newpage()
grid.draw(g)

and with your grobs

A: The answer from @baptiste helped me get a better understanding of the gtable structure and how to modify it. Below I post just my modified variant as code snippet for (my own) reuse.
It is using find_panel() to get the panel extent, and pipes %>% the modifications directly into grid.draw. The piping considerably simplified playing around with the gtable_* functions, as it allows to easily uncomment single lines and check the effect on the final plot.
library(ggplot2)
library(grid)
library(gtable)
library(dplyr)

p <- ggplot(tribble(~x,~y,~a,~b,
                    1, 1, "a1","b1",
                    1, 1, "a2","b1",
                    1, 1, "a2","b2"),
           aes(x=x,y=y)) +
  geom_point() +
  facet_grid(vars(a),vars(b))

g <- ggplotGrob(p)
panels_extent <- g %>% find_panel()
g %>%
  # Add red box to the very right, by appending a column and then filling it
  gtable_add_cols(widths = unit(1,"cm"), pos = -1) %>%
  gtable_add_grob(rectGrob(gp=gpar(fill="red")),
                  t = panels_extent$t, b = panels_extent$b,
                  l = -1, r = -1) %>%
  # Add green box to the top, by prepending a row and then filling it
  # Note the green box extends horizontally over the first panel as well
  # as the space in between.
  gtable_add_rows(heights = unit(1,"cm"), pos = 0) %>%
  gtable_add_grob(rectGrob(gp=gpar(fill="green")),
                  t = 1, b = 1,
                  l = panels_extent$l, r = panels_extent$l+1) %>%
  {grid.newpage();grid.draw(.)}


text:
Q: Optimising algorithm of self-organising sequence of numbers implemented on circular doubly linked list Few days ago I asked you in order to pick the best data structure for my problem. In that time I also explained my problem and decribed it:
Self-organising sequence of numbers with big amount of operations on it - best data structure
I have implemented it, but unfortunately it can not pass few test's. Here is my code:
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int allCharCounter = 0;

struct List_node{
    int value;
    struct List_node *next;
    struct List_node *prev;
};

//inserting at first
void insert(List_node** start, int v){
    List_node* newNode = new List_node;
    newNode->value = v;

    if(*start == NULL){

        newNode->next = newNode;
        newNode->prev = newNode;
        *start = newNode;
    }else{
        newNode->next = *start;
        newNode->prev = (*start)->prev;
        (*start)->prev->next = newNode;
        (*start)->prev = newNode;
    }
}

//getting input
int getNumber(){
    int c = getchar_unlocked();
    int value = 0;
    for(; (c < 48 || c > 57); c = getchar_unlocked());

    for(; c > 47 && c < 58 ; c = getchar_unlocked()){
        value = 10*value+c-'0';
        allCharCounter++;
    }
    return value;
}

int main(){

    int numberOfOperations = getNumber();
    struct List_node* list = NULL;

    //counter of numbers
    int numbersInSeq = 0;

    //passing values to list
    while(!feof(stdin)){
        int number = getNumber();
        insert(&list, number);
        numbersInSeq++;
    }

    if(list !=NULL){

        while(numberOfOperations-- != 0){
            int c = list->value;

            //insert - X
            if(c & 1){
                List_node* newNode = new List_node;
                newNode->value = c-1;

                newNode->prev = list;
                newNode->next = list->next;
                list->next->prev = newNode;
                list->next = newNode;

                numbersInSeq++;
                int moveNext = c%numbersInSeq;
                //int movePrev = numbersInSeq - moveNext;

                for(int i = 0; i < moveNext; i++){
                    list = list->next;
                }
            }else{
                //remove - R
                c = list->next->value;
                List_node* tmp = list->next;

                list->next = tmp->next;
                list->next->prev = list;
                tmp->next = NULL;
                tmp->prev = NULL;
                free(tmp);

                numbersInSeq--;
                int moveNext = c%numbersInSeq;
                //int movePrev = numbersInSeq - moveNext;
                //moving my list (POS)
                for(int i = 0; i < moveNext; i++){
                    list = list->next;
                }
            }

        }
        //printing output
        for(int i = 0; i < numbersInSeq; i++){
            fprintf(stdout, "%d",list->value);
            if(i != numbersInSeq-1){
                fprintf(stdout, "%c",' ');
            }
            list = list->next;
        }

    }else{
        //in case of empty list return -1
        fprintf(stdout, "%d", -1);
    }
    fprintf(stdout, "%c",'\n');
    fprintf(stdout, "%d",allCharCounter);

}

This code uses circular doubly linked list, output is always correct, but as I said before it was too slow for some test's. You also may see that by mistake I implemented moving the list(POS) only using next. So I came up with this:
int moveNext = c%numbersInSeq;
int movePrev = numbersInSeq - moveNext;
if(moveNext < movePrev){
    for(int i = 0; i < moveNext; i++){
        list = list->next;
    }
}else{
    for(int i = 0; i < movePrev; i++){
        list = list->prev;
    }
}

Injected right after incrementing and decrementing numbersInSeq in both X and R methods. Variable moveNext is a number of iterations that is needed to move pointer to desired place by using next. So the diffrence of it and numbersInSeq is movement by prev. Because of that I know what is more efficient, moving it using next or prev.
I have tested it on example with 50 digits and output was correct. Number of iterations was smaller:

*

*w/o - 13001

*with - 570
Not only it haven't passed even one more test there, but also it was too slow for another test(Although I don't know exactly what was in there, but I can tell you that file with its size is around 34mb).
Maybe you can see what I missed here/wrote badly/don't know about structure. Is it possible to optimise somehow my code to be faster?

A: *

*Please review your previous question. The answer you marked as correct is incorrect in fact: all you need is a single-linked circular list, since you always traverse forward and never backward.

*Obviously, operators new and delete (it is free in your case) in the code impacts performance the most. Basically, memory allocation is slow and you should avoid it in case you want to pass some performance tests.
There are variety of techniques to avoid memory allocations. The most simple would be to maintain another free_list with free list elements.
So instead of new you should write a function:

*

*If free_list is NULL

*

*return new List_node // allocate

*else

*

*n = free_list

*free_list = n->next

*return n // reuse previously allocated node

And instead of delete or free you should write a function:

*

*node_to_free->next = free_list

*free_list = node_to_free // i.e. put node to free to the free list

Those two changes should give you significant performance boost. If it will be not enough to pass the test, come for more suggestions on SO ;)


text:
Q: mongoose sort latest document entry in db and update I want to sort the latest document matching the query then set paid property to true.
Payment.update({orderRef: paidRef} , {$set:{paid:true}}, {new: true}, function(err, doc){ });

A: Use findOneAndUpdate() because you only want to update one.
like :
findOneAndUpdate({
 orderRef: paidRef,
}, {
  $set: { paid : true },
}, {
  new: true,
  sort: { date: -1 },
});

with date a field where the creation date is stored


text:
Q: Can you create a Google map in a virtual element I am wondering it is possible to create a working Google map in a virtual element which can then be pasted into any page at any time.
So here is my JS when targeting an element which already exists on the page.
var mapLatLong = new google.maps.LatLng(51.5174456, -0.1305081);
var markerLatlng = new google.maps.LatLng(51.5170951, -0.1367416);

var mapOptions = {
    zoom: 16,
    center: mapLatLong,
    mapTypeId: google.maps.MapTypeId.ROADMAP
}

var map = new google.maps.Map($('#map_canvas'), mapOptions);

var contentString = '
'+
                        '
'+
                        '
'+
                        '
BrocklebankPenn
'+
                        '
'+
                            '
5th floor, 58-60 Berners Street,
London,
W1T 3NQ,
United Kingdom
'+
                            '
+44 (0)20 3137 7034
'+
                        '
'+
                    '
';

var infowindow = new google.maps.InfoWindow({
    content: contentString
});

var marker = new google.maps.Marker({
    position: markerLatlng,
    map: map,
    title: 'BrocklebankPenn'
});

google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
});

infowindow.open(map,marker);

What I want to do is something like this:
this.mapCanvas = document.createElement('div');
this.mapCanvas.setAttribute('id', 'map_canvas');

var mapLatLong = new google.maps.LatLng(51.5174456, -0.1305081);
var markerLatlng = new google.maps.LatLng(51.5170951, -0.1367416);

var mapOptions = {
    zoom: 16,
    center: mapLatLong,
    mapTypeId: google.maps.MapTypeId.ROADMAP
}

var map = new google.maps.Map($(this.mapCanvas), mapOptions);

var contentString = '
'+
                        '
'+
                        '
'+
                        '
BrocklebankPenn
'+
                        '
'+
                            '
5th floor, 58-60 Berners Street,
London,
W1T 3NQ,
United Kingdom
'+
                            '
+44 (0)20 3137 7034
'+
                        '
'+
                    '
';

var infowindow = new google.maps.InfoWindow({
    content: contentString
});

var marker = new google.maps.Marker({
    position: markerLatlng,
    map: map,
    title: 'BrocklebankPenn'
});

google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
});

infowindow.open(map,marker);

this.$el.html(this.mapCanvas);

Basically the exact same thing but with a variable instead of #map_canvas, I have taken this approach with JS in the past but it does not seem to be working for Google maps, I get the following error:
Uncaught TypeError: Cannot set property 'position' of undefined

Which I am not sure of.
If anyone can help that would be awesome.
Cheers,
Luke.

A: Basically it's possible, Demo: http://jsfiddle.net/doktormolle/5SjnK/
The issues with your code:
var map = new google.maps.Map($(this.mapCanvas), mapOptions);

$(this.mapCanvas) is a jQuery-object, but it's expected to be an HTML-Element
this.$el.html(this.mapCanvas);

Don't set the html, you must insert the original node into the document.
But I wouldn't suggest it, there will be more issues, e.g. when you use API-methods that try to access the parentNode of the map-div or methods that need to calculate positions inside the document(both will fail before the node has been inserted into the document).
Related to pasted into any page:
It's not possible, the document where you use the map must be the same document where you load the API, the API internally uses references to the window/document where the API has been loaded. See this question: Marker drag not working in iframe under Chrome and Firefox
But as long as any page doesn't mean "any document"(regarding to your description it's always the same document) it's possible.


text:
Q: Which paypal SDK/API to use to send credit card payments to email address? Is there anyway to do the following using the Paypal APIs in PHP? I can't seem to find exactly what I need.

*

*We are a merchant - we have several businesses who list their goods on our website.

*Customers will need to pay for these goods using a credit/debit card. We don't want to force Paypal use/registration - in fact, we don't really want the customer to interact with Paypal at all.

*We'd like to create a payment form where they enter their credit card details - we would then use the API to pay this directly to the business' Paypal account using their email address.

Using the REST API I've been able to do this to an extent - the only problem with this is that it doesn't seem dynamic i.e. I can't set the Payee email address to receive the payment - it's linked to my account via the ClientID and ClientSecret. Obviously this is not what I need -  I want to pay into the account of the owner of the goods, not mine.
I've seen 'Guest Payments' mentioned but that seems to require the user being redirected to Paypal - something I'd rather avoid.
Thanks in advance.

A: I don't think the REST API is quite ready for what you're doing.  The Classic API will handle it with no problem, though.
If you don't want any interaction with PayPal at all then you'll need to use Payments Pro, which allows you to tie credit card payments directly into your own forms via HTTP request/response with PayPal (no redirect or iframe).
Each business would need to be signed up with their own Payments Pro account, and then they would Grant API Permissions through their PayPal account profile for your app to make API calls on their behalf.  Once they've done that, you just pass their email address or PayPal merchant ID into the SUBJECT parameter of API requests and it will use their account accordingly even though you're still using your own API credentials.
The Permissions API allows you to automate this and tie the grant permissions step directly into your app so business owners can do that quickly and easily from within their profile or during signup with your site.  This works with auth tokens, though, as opposed to email addresses and merchant ID's.


text:
Q: problem while changing col names with str_to_title I have a data set that looks like this:

It can be build using codes:
df<- structure(list(`Med` = c("DOCETAXEL",
"BEVACIZUMAB", "CARBOPLATIN", "CETUXIMAB", "DOXORUBICIN", "IRINOTECAN"
), `2.4 mg` = c(0, 0, 0, 0, 1, 0), `PRIOR CANCER THERAPY` = c(4L,
3L, 3L, 3L, 3L, 3L), `PRIOR CANCER SURGERY` = c(0, 0, 0, 0, 0,
0), `PRIOR RADIATION THERAPY` = c(0, 0, 0, 0, 0, 0)), row.names = c(NA,
6L), class = "data.frame")

Now I would like to change col name that are not start with number to proper case. How should I do it? I thought I could use str_to_title. I have tried many ways can not get it to work. Here is the codes that I tried:
# try1:
df[,3:5] %>% setNames(str_to_title(colnames(df[,3:5])))

#try2:
df[,3:5] <- df[,3:5]%>% rename_with (str_to_title)

# try3:
colnames(df[,3:5])<- str_to_title(colnames(df[,3:5]))

What did I do wrong? there is no error message, just the col names did not get updated. Could anyone help me identify the issue, or maybe show me a better way if you have?
Here I have small data then I can find the col number. If I want it to auto correct the col names to proper case, how can I do that?
Thanks.

A: We can use
library(dplyr)
library(stringr)
df %>%
   rename_at(3:5, ~ str_to_title(.))

-output
#         Med 2.4 mg Prior Cancer Therapy Prior Cancer Surgery Prior Radiation Therapy
#1   DOCETAXEL      0                    4                    0                       0
#2 BEVACIZUMAB      0                    3                    0                       0
#3 CARBOPLATIN      0                    3                    0                       0
#4   CETUXIMAB      0                    3                    0                       0
#5 DOXORUBICIN      1                    3                    0                       0
#6  IRINOTECAN      0                    3                    0                       0

Or using rename_with
df %>%
  rename_with(~ str_to_title(.), 3:5)


text:
Q: Unnable to acces other drives and partition due to insuficent permissions I have a Dell Inspiron 15r running both Ubuntu 13.10 and OS X mountain lion. I was trying to change my Ubuntu UID to 501 co I could read and write in the OS X home folder without root permissions.
Now when I try to access the partition it tells that I don't have the permissions necessary to view the contents of the partition. It does the same thing for other drives that I use.
I need an answer fast because school starts in two days.

A: I found a thread over on Ubuntuforums that while old, basically covers how to recover from your scenario. You'll want to return your Ubuntu uid back to its original value, which should be 1000 with sudo usermod -u 1000 your_username
This thread on superuser has some options for mounting the Mac partition as read/write, though there may be some issues with having to either disabling journaling on the Mac partition or only having root-level access to it. You might be able to get it to mount with the correct uid with an entry in fstab but I have never seen instructions for mounting HFS+ partitions via fstab.


text:
Q: Username and password iteration in python 3 I have been trying to think of a way to iterate through a username list and check each value of password from a password list. For example, there is a list of 2 usernames, admin and root, there is also a password list of 5 passwords.
For each of the usernames all passwords will have to checked.
I have been able to come up with this piece of code:
if os.path.isfile(USER_FILE) and os.path.isfile(PASS_FILE):
    with open(USER_FILE, 'r') as user_file, open(PASS_FILE, 'r') as pass_file:
        for u in user_file.read().splitlines():
            for p in pass_file.read().splitlines():
                print(f"{u}:{p}")

However, after the first username the scripts stops and the 2nd username is not checked agains all passwords in my list.
The output I am getting from the script is as follows:
./brute.py users.txt passwd.txt
admin:root
admin:admin
admin:toor
admin:123456
admin:000000000
admin:password

Any suggestion is appreciated..