text:
Q: Failure accessing ST LIS3DSH accelerometer CTRL_REG_4 I'm writing to ask if someone has ever encountered a quite weird behaviour of LIS3DSH.
to properly use such sensor, a number of registers must be configured via the spi bus. I implemented a routine to do so, which writes the registers in sequence and reads them back to check the operation result. The function gets stuck on the very first register it tries to configure, which determines the active channels and the data rate: CTRL_REG_4. This register, as others, is declared R/W; but, whatever I send into it, I read a 'zero' back (which according to the documentation is not even the default value anyway).
After spending long looking for a bug in my spi R/W functions, I skipped that register and noticed that others work just as expected, so I tend to believe there's something wrong with that specific memory location.
Can anybody read from it?


text:
Q: Change a list to a string with specific formatting Let's say that I have a list of names:
names = ['john', 'george', 'ringo', 'paul']

And need to get a string output like:
john', 'george', 'ringo', 'paul

(Note that the missing quote at the beginning and at the end is on purpose)
Is there an easier way to do this than
new_string=''
for x in names:
    new_string = new_string + x + "', '"

I know something like that will work, however the real names list will be very very (very) big and was wondering if there is a nicer way to do this.

A: You can simply use str.join:
>>> names = ['john', 'george', 'ringo', 'paul']
>>> print("', '".join(names))
john', 'george', 'ringo', 'paul
>>>

A: may be bad way to do it, just wana share it :
>>> names = ['john', 'george', 'ringo', 'paul']
>>> print(str(names)[2:-2])
john', 'george', 'ringo', 'paul

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot get @Ajax.ActionLink to work in a partial view, get "Cannot resolve" error I am using MVC3, ASP.NET 4.5, C#, Razor.
I have successfully got the Ajax.ActionLink working from my main page which contains a table and records with each containing a link. The Ajax.ActionLink "replaces" the record in all  cells within the  element. I use a partial view to do this replacing in:
col1	col2

However col1 should retain the Ajax.Actionlink as it will be required again, so my partial view should be:
@Ajax.ActionLink("Delete",...)	col2

But I get a

"cannot resolve symbol ActionLink"

error.
Am I missing a reference in the partial view. I did try System.Web.MVC.Ajax, but this failed.
Thanks for any help.
EDIT1:
Seems no issue with:
@Html.ActionLink(...)

EDIT2:
Full ActionLink code:
                    @Ajax.ActionLink("Delete",
                                 "AjaxDelete",
                                 "Order",
                                 new {id = ViewBag.id},
                                 new AjaxOptions {
                    UpdateTargetId = ViewBag.rowname,
                    InsertionMode = InsertionMode.Replace,
                    HttpMethod = "GET"
                                 });

A: The error message is misleading. The compiler cannot create an anonymous type from a dynamic property as it has no idea what type it is.
Add an (int) cast to ViewBag.id to make the anonymous field strongly typed.
Also do the same same for Viewbag.rowname (string I assume?)
e.g.
 @Ajax.ActionLink("Delete",
               "AjaxDelete",
               "Order",
               new {id = (int)ViewBag.id},
               new AjaxOptions {
               UpdateTargetId = (string)ViewBag.rowname,
               InsertionMode = InsertionMode.Replace,
               HttpMethod = "GET"
               });


text:
Q: how use kinect(openni) in opencv - linux(ubuntu14) I trying to use kinect on OPENCV and I realized that openni is the best library for kinect
but I could not find the latest version of it(Because the site is closed)
and i am using openni1.5.4 nite1.5.2 sensorkinect5.1.2.1 and opencv2.4.9 in ubuntu14.04LST
kinect installed correctly and i can run sample project from openni folder
now i want to use openni in opencv project, like this

VideoCapture sensor1;
  sensor1.open(CV_CAP_OPENNI);

but It doesn't work and I noticed this error can be from cmake variable so i remake opencv build files with

cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D WITH_TBB=ON -D BUILD_NEW_PYTHON_SUPPORT=ON -D WITH_V4L=ON -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON -D BUILD_EXAMPLES=ON -D WITH_QT=ON -D WITH_OPENGL=ON  -D WITH_OPENNI=ON ..

and in terminal i can see

OpenNI:                      YES (ver 1.5.4, build 0)
  --     OpenNI PrimeSensor Modules:  YES (/usr/lib/libXnCore.so)

but when i use

cout << cv::getBuildInformation();

in my project , i get this

OpenNI:                      NO
      OpenNI PrimeSensor Modules:  NO

Where is the problem and What is the solution?
I thank you in advance

A: Finally the problem was solved
i installed libfreenect like this

mkdir -p ~/Developer/Work
  cd ~/Developer/Work
  git clone https://github.com/OpenKinect/libfreenect
  cd libfreenect
  git checkout tags/v0.3.0

*

*NOTE: Tested with libfreenect stable release v0.3.0

*Build and install:

cd ~/Developer/Work/libfreenect mkdir build cd build cmake .. -D BUILD_OPENNI2_DRIVER=ON  make sudo make install
      cd  ~/Developer/Work/libfreenect
  mkdir build
  cd build
  cmake .. -D BUILD_OPENNI2_DRIVER=ON
  make
  sudo make install

*

*Add to library path:

sudo nano /etc/ld.so.conf.d/custom.conf

Add

/usr/local/lib/ /usr/local/lib/OpenNI2-FreenectDriver/

And

sudo ldconfig

Test with glview:

sudo glview

in cmake i use BUILD_OPENNI2_DRIVER=ON but i didn't install openni2 , i use openni1.5.4
and Be sure to use a computer not VMware  (i couldn't get stream on VMware)


text:
Q: Running node-cron blocks my terminal until I CTRL + C I writing a script to execute some POST methods using Axios. To execute it, I'm using node-cron and creating a job to execute it.
However, when I "node script.js", I see that my terminal isn't available, like it is still running or in a infinite loop.
The schedule task is working good, but I'm worried about the terminal thing. I'm not sure if when you create a task, it will run until the machine is rebooted or when you end the task using CTRL + C.
I'm not DEV, so this is the code that I did:
const axios = require('axios');
const cron = require('node-cron');

let channelID = 'ID-HERE';

// let slackAPItopic = "https://letsdeel.slack.com/api/conversations.setTopic";
// let tokenSlack = 'token-here';
// let slackAPIsendMessage = "https://slack.com/api/chat.postMessage";

const postInTopic = async (displayID) => {

    await axios.post(
        `https://letsdeel.slack.com/api/conversations.setTopic`,
        {
            channel: channelID,
            topic: 'Shift Watcher from .JS:' + ' ' + '<@' + displayID + '>'

        },
        {
            headers: {
                'Authorization': "Bearer token-here"
            }
        }
    );

};

const privateMessage = async (displayID) => {
    await axios.post(
        `https://slack.com/api/chat.postMessage`,
        {
            channel: displayID,
            text: "Hi! Just a reminder that you are on Shift Watch - From .JS"
        },
        {
            headers: {
                'Authorization': "Bearer token-here"
            }
        }
    );
};

var cronFirstHour = cron.schedule('0 1 * * 1,2,3,4,5', () => {

    let displayID = 'OADHWAD23';
    postInTopic(displayID);
    privateMessage(displayID);

},{
    scheduled: true,
    timezone: "Atlantic/Azores"
}
);

Is it happening because that's how node-cron works? Like, a forever task? I was expecting to see the cron in the crontab or anything like.
I'm developing in MacOS at the moment, but the plan is moving to AWS. Or should I make it list like a service in Linux?
About the script: It will set the topic in Slack and send a message at the same time in a specific scheduled hour.


text:
Q: how to add items to listview through alert dialog box I am stuck in a project. I need to add items to my ListView through alert dialog box. like 1st item will act as a heading and when it is selected a dialog box will open and the value will be added as sub item of that ListView. I will attach pictures just the I want them to be. Please if anyone can help.
below is the picture of ODK app.


text:
Q: For Loops with Scrapy Hey y'all I have been trying to learn scrapy, and am working on my first project right now. I have written this code to try to scrape NFL player news from http://www.rotoworld.com/playernews/nfl/football/?rw=1. I tried to set up a loop to get each container from the site, but when I run the code it isn't scraping anything. The code runs fine, even pus out a csv file when I ask it too. It just isn't scraping what I think I am telling it to scrape. Any help would be great! Thanks
import scrapy
from Roto_Player_News.items import NFLNews

class Roto_News_Spider2(scrapy.Spider):
    name="PlayerNews2"
    allowed_domains = ["rotoworld.com"]
    start_urls = ('http://www.rotoworld.com/playernews/nfl/football/',)

    def parse(self,response):

        containers= response.xpath('//*[@id="cp1_pnlNews"]/div/div[2]')

        def parse(self, response):

            for container in containers:
                def parse(self, response):
                    item=NFLNews()
                    item['player']= response.xpath('//div[@class="pb"][1]/div[@id="cp1_ctl00_rptBlurbs_floatingcontainer_0"]/div[@class="report"]/text()')
                    item['headline'] = response.xpath('//div[@class="pb"][1]/div[@id="cp1_ctl00_rptBlurbs_floatingcontainer_0"]/div[@class="report"]/p/text()').extract()
                    item['info'] = response.xpath('//div[@class="pb"][1]/div[@id="cp1_ctl00_rptBlurbs_floatingcontainer_0"]/div[@class="impact"]/text()').extract()
                    item['date'] = response.xpath('//div[@class="pb"][1]/div[@id="cp1_ctl00_rptBlurbs_floatingcontainer_0"]/div[@class="info"]/div[@class="date"]/text()').extract()
                    item['source'] = response.xpath('//div[@class="pb"][1]/div[@id="cp1_ctl00_rptBlurbs_floatingcontainer_0"]/div[@class="info"]/div[@class="source"]/a/text()').extract()

                    yield item

A: Your defined xpaths do not look good. Try this instead. It should fetch you the content you wish to scrape. Just do the copy and paste.
import scrapy

class Roto_News_Spider2(scrapy.Spider):
    name = "PlayerNews2"

    start_urls = [
        'http://www.rotoworld.com/playernews/nfl/football/',
    ]

    def parse(self, response):
        for item in response.xpath("//div[@class='pb']"):
            player = item.xpath(".//div[@class='player']/a/text()").extract_first()
            report = item.xpath(".//div[@class='report']/p/text()").extract_first()
            date = item.xpath(".//div[@class='date']/text()").extract_first()
            impact = item.xpath(".//div[@class='impact']/text()").extract_first().strip()
            source = item.xpath(".//div[@class='source']/a/text()").extract_first()
            yield {"Player": player,"Report":report,"Date":date,"Impact":impact,"Source":source}


text:
Q: PWA launch icon
*

*Is it possible to create & submit an PWA launcher icon to a website marketplace?

*The launcher icon should work like a "Add to home screen" PWA function.

What I am trying to achieve is a PWA store making it easy for users to Add an icon to their homescreen for launching a PWA website. Please advice.

A: If you mean that in your web marketplace, you want to get the icons of submitted PWA then, you can get the PWA launch icons from either the link tags:
<link rel="icon" sizes="192x192" href="nice-highres.png"> (recommended)
<link rel="icon" sizes="128x128" href="niceicon.png">
<link rel="apple-touch-icon" sizes="128x128" href="niceicon.png">
<link rel="apple-touch-icon-precomposed" sizes="128x128" href="niceicon.png">

or from the manifest.json icons section:
{
  "short_name": "Maps",
  "name": "Google Maps",
  "icons": [
    {
      "src": "/images/icons-192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "/images/icons-512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": "/maps/?source=pwa",
  "background_color": "#3367D6",
  "display": "standalone",
  "scope": "/maps/",
  "theme_color": "#3367D6"
}

A: You can set the icon to be displayed according to sizes on home screen in manifest.json file.
https://developers.google.com/web/fundamentals/web-app-manifest/
"icons": [
{
  "src": "/images/icons-192.png",
  "type": "image/png",
  "sizes": "192x192"
},
{
  "src": "/images/icons-512.png",
  "type": "image/png",
  "sizes": "512x512"
}
]

A: This is posible neither in iOS nor in Android:
Regarding the icons

*

*Android depends on the manifest.json file at the root of your domain to handle the information about the PWA.

*iOS: You may be able to change the icon and launch screen at the top of the page holding the link to the PWA, but this will not help you in any way, because Safari iOS does not allow you to generate a bookmark programmatically.

Regarding the actual link saved to the desktop

*

*Android Chrome checks the status of both the manifest and the certificate in the site before popping up the option to save a PWA to the Home Screen. If the popup appears in your site it will be for your PWA, not for the linked PWA.

*iOS does not have a way to programmatically add bookmarks. This seems to be on purpose, as a security measure. The only way to add the bookmark to the desktop is using the Safari Share button. Safari does validate your certificate at that moment before downloading the custom icon.

I understand that Android now lets you install PWAs from the Play Store, but the process to publish them there is convoluted.
What you can do

*

*Provide great information for users on how to install the PWAs listed in your site.

*Provide code to generate an install popup system in iOS for the developers publishing in your store, branded. We had to do that screen for this website and it took quite some time to get it right.


text:
Q: Include js after bootstrap 4 bundle file I'm trying to include js files after the bootstrap.bundle.js. i have this in my view
 $this->registerJsFile('https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js', ['depends' => [yii\bootstrap4\BootstrapAsset::className()]]);
 $this->registerCssFile('https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css', ['depends' => [yii\bootstrap4\BootstrapAsset::className()]]);

but when i view source. it still shows above it. any idea how to fix this? thanks

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.js"></script>

<script src="/yii2/frontend/web/assets/949bae38/yii.js"></script>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18/dist/sweetalert2.all.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mhayes-twentytwenty/2.0.0-beta.1/jquery.twentytwenty.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>

<script src="/yii2/frontend/web/assets/949bae38/yii.validation.js"></script>

<script src="/yii2/frontend/web/assets/949bae38/yii.activeForm.js"></script>

<script src="//cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>

<script src="/yii2/frontend/web/assets/536f059b/js/bootstrap.bundle.js"></script>

A: yii\bootstrap4\BootstrapAsset only loads bootstrap.css file. The bootstrap.bundle.js is loaded by yii\bootstrap4\BootstrapPluginAsset.
You only need to change the Asset class in that call like this:
$this->registerJsFile(
    'https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js',
    ['depends' => [yii\bootstrap4\BootstrapPluginAsset::className()]]
);


text:
Q: how to do Good SDK 3.1.0 integration with Xcode 8.3.2? I have installed xcode v8.3.2 and trying to integrate good sdk v3.1.0, but I am unable to do so. When I went through release notes I found that this latest version will not support to Xcode 8.3 and later versions. But one of my colleagues is able to use the latest version of good sdk with Xcode 8.3.1 without any issue. How can we resolve this?

A: As you need to install Xcode and good sdk in the applications folder on the system.This is the way it worked for me.


text:
Q: Encrypt string in ASP decrypt in Java I have below ASP code to encrypt and decrypt in asp. It works fine. I want string to be encrypted in asp and decrypt it in java.
set obj=Server.CreateObject("System.Security.Cryptography.RijndaelManaged")
Set endocde = Server.CreateObject("System.Text.endocdeEncoding")

un = endocde.GetBytes_4("Test Encryption")
obj.key = endocde.GetBytes_4("SomeRandomKey")
obj.iv =  endocde.GetBytes_4("SomeRandomIv")

set enc=obj.CreateEncryptor()
uncUn=enc.TransformFinalBlock((un),0,lenb(un))
eUn=endocde.GetString((uncUn))

set dec=obj.CreateDecryptor()
byted=dec.TransformFinalBlock((uncUn),0,lenb(uncUn))
sd=endocde.GetString((byted))

I tried encrypted string to be decrypted using below code in java but doesnt work. I tried sending encrypted data in UTF8/Base64 but doesnt work. Please help.
String iv = "sameIVasASP";
String key = "sameKeyasASP";

IvParameterSpec iv = new IvParameterSpec(iv.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "Rijndael");
Cipher cipher = Cipher.getInstance("Rijndael/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] decode = Base64.getDecoder().decode(<encrpted string>);
System.out.println( new String(cipher.doFinal(decode)).getBytes("UTF-8"));

A: How to encode/decode UTF-8 string to base64 in c#:
byte[] bytes = Encoding.UTF8.GetBytes("string-to-encode");
string base64 = Convert.ToBase64String(bytes);

How to encode/decode UTF-8 string to base64 in Java
Java8 version:
byte[] decodedBytes = Base64.getDecoder().decode(base64encodedstring);

Pre-Java8 example (with Base64 class of Commons Codec):
byte[] decodedBytes = Base64.decodeBase64(encodedBytes);

(In Java you have many option to do that (not just these), if you are using at least Java8, there is a built in class for that, for previous versions I usually use the Base64 class in Apache Commons Codec)


text:
Q: How can I to add a RichTextBox on the Evolus Pencil form? I have to add a simple RichTextBox-control on the form of Evolus Pencil.
i.e. "a big field for input" with a vertical scroll, in which is possible to insert a rich Text Formated-text, and all this will be correctly displayed on the mockup of the form.

A: The Common Shapes stencil collection included with Pencil has a Rich Text element that allows you to enter multi-line rich text content from within Pencil. The Sketchy GUI and Native UI collections contain scrollbar elements that you can add to the page alongside the rich text element.
Allowing people to edit the text content or scroll with the scrollbar once the mockup has been exported is not possible with Pencil, as the exported content is just static images (or vector images if you export to svg or pdf).


text:
Q: asp.net Core 2 Custom Model Binder with complex model I have a problem building a Custom-Model-Binder in asp.net core 2.
I read this Tutorial but that's not what I need.
I have a build an Example and put on github
I have a simple Person Class like that:
public class Person
{
    public int ID { get; set; }

    [Required]
    public string Firstname { get; set; }

    [Required]
    public string Surename { get; set; }

    [Required]
    [DisplayFormat(DataFormatString = "{0:dd.MMM.yyyy}")]
    public DateTime DateOfBirth {get;set;}

    [Required]
    public Country Country { get; set; }
}

public class Country
{
    public int ID { get; set; }

    public string Name { get; set; }

    public string Code { get; set; }
}

When I add a new Person I can select the country with a HTML select tag. But the value of the select tag is the country id and I want the binder to lookup in the database and put the right country to the model.
The create method in the Controller looks like this:
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("ID,Firstname,Surename,DateOfBirth")] Person person, int Country)
    {
        ViewData["Countries"] = _context.Countries.ToList();

        if (ModelState.IsValid)
        {
            _context.Add(person);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(person);
    }

I also implement an IModelBinder to bind the data:
 public class PersonEntityBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        // here goes the fun

        // looking for the countryId in the bindingContext

        // binding everything else except the CountryID

        // search the Country by countryID and put it to the model

        return Task.CompletedTask;
    }
}

The question is, how can I do this like I wrote in the comments in the Binder?
Anyone an Idea or a best practice solution?
regards Chris

A: First, this is a bad use of a custom model binder. Data access should happen in the controller, as that's the controller's responsibility. Second, don't use [Bind]. Like seriously. Just don't. It's awful, and it kills kittens.
Create a view model like:
public class PersonViewModel
{
    public string FirstName { get; set; }
    public string Surname { get; set; }
    public DateTime DateOfBirth { get; set; }
    public int CountryID { get; set; }
}

Then, have you action accept this instead (no more need for [Bind]):
public async Task<IActionResult> Create(PersonViewModel model)

Then, inside your action, map the posted values to a new instance of Person and fill the Country property by looking it from the database:
 var person = new Person
 {
     FirstName = model.FirstName,
     Surname = model.Surname,
     DateOfBirth = model.DateOfBirth,
     Country = db.Countries.Find(model.CountryID)
 }

Then, save person, as normal.


text:
Q: Skimage RANSACRegressor At least 2 input points needed scikit-image : 0.19.3
code to reproduce error:
from skimage.measure import LineModelND, ransac
import numpy as np

pts = np.array([[579,298],
 [604,276],
 [354,241],
 [156,240],
 [124,157],
 [625,105]])

model, inliers = ransac(pts, LineModelND, min_samples=4,residual_threshold=2, max_trials=1000)

error: At least 2 input points needed. at file skimage/measure/fit.py line 92
I haven't faced the same error with other points

A: The RANSAC procedure could not identify 2 or more inliers in the data. The scikit-image implementation does not present a warning in this situation. You can either increase the residual_threshold or decrease the min_samples to "fix" this behavior.
Scikit-learn's RANSAC implementation of RANSAC might help you out. Here, the min_samples and residual_threshold inputs are optional.
from sklearn.linear_model import RANSACRegressor
X = pts[:,0].reshape(-1,1)
y = pts[:,1].reshape(-1,1))
reg = RANSACRegressor(random_state=None,
                      min_samples=None,
                      residual_threshold=None
                     ).fit(X,y)


text:
Q: Making a PHP server to read a java based client public class Client {
/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
    Socket sock = new Socket();
    sock.connect(new InetSocketAddress(InetAddress.getLocalHost(), 43594));

    DataOutputStream out = new DataOutputStream(sock.getOutputStream());
    DataInputStream in = new DataInputStream(sock.getInputStream());

    out.writeByte(255);
    out.writeLong(133713371337L);

    System.out.println("Response: " + in.readByte() + ", " + in.readLong());

    sock.close();
}

and the PHP server meant to read and write back to the java client:
<?php
require 'Stream.php';
$stream = new Stream();

$address = '127.0.0.1';
$port = 43594;
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
socket_bind($sock, 0, $port) or die('Could not bind to address');
socket_listen($sock);
echo "Server listening on port " . $port . "...";
$client = socket_accept($sock);

$data = socket_read($client, 1, PHP_BINARY_READ);
$byte_array = unpack('C*', $data);
$stream->setStream($byte_array);
$b2 = $stream->readUnsignedByte();

$l1 = socket_read($client, $stream->readQWord());
echo $b1 . " " . $l1;
socket_write($client, 0);
socket_write($client, $stream->writeQWord(2148000000));

The stream class being used: http://pastebin.com/p1vc9aPG
I'm trying to write a client in java that contacts, sends and reads data to/from the server. The server is written in PHP and ran via cli, while the client is written in java. Please help if you can, there probably aren't many people who can help with this issue.
The protocol is already established and I'm just trying to implement it in PHP. I can't seem to read/write back to the java client from the PHP page.
The client side in Java is defined how I want it to be. What I'm looking for is the equivalent server in PHP and I can't seem to get it to work.

A: First, you should call .flush() after you write to the socket in your Java code. The data won't get sent to the server otherwise.
Then, communications between network endpoints is just about agreement on the protocol used. There is nothing language specific here...

A: I've actually written this the other way around, the client was a PHP web app and the server was a java daemon under jsvc.
The first consideration should be defining a transfer protocol, since the types and object representations of the two languages are different and they might be running on hardware with different numeric representations.  I'd recommend JSON or XML.
After that your server probably needs to be able to handle multiple connections, so threading or non-blocking socket I/O will be needed.


text:
Q: Other intersection of common tangents Core question

Suppose I have two conics, $A$ and $B$. In general these have four common tangents. Let $p$ be the point of intersection of two of these tangents, and $q$ the intersection of the other two.
Can I compute the coordinates of $q$ as rational functions of the coordinates of $A,B,p$?
Dual problem
If you prefer, you might consider the dual problem: two conics $A,B$ intersect in four points. Let $p$ be a line through two of them. Find rational coordinate functions describing $q$, the line through the other two. But subsequently I'll stick to the first formulation for the sake of consistency.
Coordinates, rational functions, homogeneous coordinates
When I wrote about rational functions of coordinates, here is what I had in mind: assume $p\in\mathbb{RP}^2$ is given in homogeneous coordinates. The conics are best considered in their dual representation, i.e. a line $g$ is tangent to $A$ if $g^T\cdot A\cdot g=0$ with $A$ being some symmetric non-zero matrix, possibly singular in the case of a degenerate conic. If it is of any relevance, you may assume you have the primal matrix, too, to describe the conic as a set of incident points. For non-degenerate conics that would be just the inverse.
So taking all the entries of the coordinate vector and the matrices as variables, is it possible to find a coordinate vector for $q$ such that all the entries of it are polynomials in these variables? Using homogeneous coordinates takes care of the division you'd have with rational functions. If you know homogeneous coordinates, think polynomial functions, else also consider rational functions.
Rationale
Many geometric operations that lead to a single solution (as opposed to multiple algebraically equivalent solutions) can avoid operations such as square roots, leaving only basic arithmetic operations which are compatible with a rational formulation of the operation. This is what makes me think a rational formulation might be possible.
I'd like to avoid case distinctions, and I'd like to avoid using random elements which lead to additional non-degeneration requirements. The best solution I have so far fails to avoid these, see below. If you can make an argument why case distinctions cannot be fully avoided, then solutions making minimal use of these will be great, too.
This operation is problematic because its definition depends on $p$ being an intersection of two tangents (i.e. $p^TAp=p^TBp=0$). If there exists some nice generalization which does what I describe for these intersections of common tangents and some other well-defined one-to-one mapping for all (or at least most) other points in the plane, then describing that generalization might in fact be easier.
Motivation and background
I first thought of this problem in the context of Properties of hyperbolic conics? There intersections of common tangents serve as foci of conics in hyperbolic geometry, and pairs of foci might have interesting properties regarding reflections in the conic.
Of particular interest is the case where $$B=\begin{pmatrix}1&0&0\\0&1&0\\0&0&0\end{pmatrix}$$ which is the dual fundamental conic of Euclidean geometry, which factors into the complex conjugate ideal circle points $[1:\pm i:0]$. With that conic fixed, the pairs of points $p,q$ will be foci of the conic $A$, so the task is that of finding one focus, given the other. That specific problem can be generalized to $q$ being the reflection of $p$ in the center of the symmetry of the conic, even if $p$ is not a focus. But I don't see how such a formulation would generalize to $B$ being non-degenerate. Perhaps there is another way to think about this specific Euclidean problem which leads to a natural projective generalization.
What I have so far
Here is what I have so far. Pick a random line $r$ through $p$, distinct from the common tangents. Compute $C=(r^TBr)A-(r^TAr)B$ which ensures that $r^T\cdot C\cdot r=0$. Geometrically speaking, find a linear combination of the conics such that the random line is a tangent, too. Since linear combinations share the original common tangents, there are now three tangents through $p$ to $C$. Which means $C$ must be degenerate, factoring in a pair of points, with $p$ being one of them, and $q$ being the other. Therefore $C$ is of rank $2$ or less, and can be written as $p\cdot q^T+q\cdot p^T$, which can be solved for the coordinates of $q$. If $p$ has only non-zero coordinates, then one easy way to extract $q$ would be taking the diagonal elements of $C$ and dividing each by the corresponding coordinate of $p$.
Having to choose a random line $r$ makes this ugly. It requires an additional check to ensure that $r$ is not one of the common tangents, because in that case $C$ would not be uniquely defined. Splitting the matrix to extract the individual points is easy for a concrete example, but hard when done with variables for input, because the fact that the matrix is supposed to be singular is not apparent in that formulation using variables.
Concrete example
To demonstrate the problem and my approach above, here is one specific example:
$$A=\begin{pmatrix}-1&0&0\\0&4&1\\0&1&1\end{pmatrix}\qquad
B=\begin{pmatrix}1&0&0\\0&1&0\\0&0&0\end{pmatrix}\qquad
p=\begin{pmatrix}2\\1\\1\end{pmatrix}$$
I'm picking
$$r=\begin{pmatrix}0\\1\\-1\end{pmatrix}$$
which satisfies $r^T\cdot p=0$. Then I compute
$$C=(r^TBr)A-(r^TAr)B=A-3B=\begin{pmatrix}-4&0&0\\0&1&1\\0&1&1\end{pmatrix}$$
Taking the elements on the diagonal and dividing them by the coordinates of $p$ I obtain
$$q=\begin{pmatrix}-4/2\\1/1\\1/1\end{pmatrix}=\begin{pmatrix}-2\\1\\1\end{pmatrix}$$
as the second point. The corresponding geometric situation, with $p,q$ as foci of the hyperbola $3x^2-y^2+2y=4$, is this:

A: I've made some progress. If $p,q$ form a pair of intersections in the sense of the question, then
$$pq^T+qp^T=\lambda A+\mu B$$
since the pencil of (dual) conics spanned by $A,B$ will contain that pair of points as one of three degenerate cases. So $C=pq^T+qp^T$ is linearily dependent from $A$ and $B$, which can be written as
$$\operatorname{rank}\begin{pmatrix}
2p_1q_1 & 2p_2q_2 & 2p_3q_3 & p_1q_2+p_2q_1 & p_1q_3+p_3q_1 & p_2q_3+p_3q_2 \\
A_{11} & A_{22} & A_{33} & A_{12} & A_{13} & A_{23} \\
B_{11} & B_{22} & B_{33} & B_{12} & B_{13} & B_{23}
\end{pmatrix}<3$$
You can check this condition by verifying that each of the $3\times3$ minors of this matrix is zero. There are $\binom63=20$ such minors, so there are $20$ equations to satisfy simultaneously. Each equation is linear in $q$, so it can be seen as a scalar product with $q=(q_1,q_2,q_3)^T$. Scalar product between two vectors being zero can geometrically be interpreted as a line-point incidence, so the coefficients of each equation encode a line. $20$ lines lead to $\binom{20}2=190$ possible points of intersection. After removing common terms from the homogeneous coordinates of these points of intersection, and normalizing signs, $115$ distinct points remain, unless I made a mistake in my Sage computation. These are quadratic in $p$ and linear in $A$ and $B$.
If $p$ is a point of intersection of common tangents, then all $115$ of these formulas will lead to different multiples of the same point $q$. Some of them may be the null vector, though. So I've gotten rid of the random choice $r$ mentioned in my question, but not of the case distinction needed to avoid hitting one of the null solutions of any single formula. I still hope for some input on that.


text:
Q: How to correctly free a PDO instance for example:
$db = new PDO();
// some code using $db here
// and next, i want to free this var and close all connection and so on
$db = NULL; // or how correctly?

Is that correct way to free all SQL results and connections?

A: you could do that, but often not necessary. if created in a function and no other vars are using it, $db will release its contents when it goes out of scope (usually at the end of the function). if $db is a global, it will be released when the script ends.


text:
Q: C++ : meta-data information in source code. To see through AST After parsing, I want to get a meta-data of the source code's field, or method.
The purpose of this is to collect info of the source code after parsing.
In java, I used annotation.
After parsing, I find user-defined annotation on class, field, or method.
Under code is example.
@BizObject //By this annotation I could understand this class is related with bissness.
public class biz ... {
    @DI //this field needs Dependency Injection.
    public Logger logger;
}

By parsing, I want to collect user-specified meta-info of the source.
How user write the meta-data on the source code?? like java annotation.
I know in C++ there is no direct attribute for this purpose.
I just wondering how to mark meta-data indirectly using other things.

A: Self response.
I solved this problem by using attribute specifier.
It is similar to Java's annotation.
http://en.cppreference.com/w/cpp/language/attributes
http://www.codesynthesis.com/~boris/blog/2012/04/18/cxx11-generalized-attributes/
https://gcc.gnu.org/onlinedocs/gcc/Attribute-Syntax.html
By using attribute specifier and CDT parser, I could get meta data related syntax's node.
CDT parser support GNU.


text:
Q: have knitr output figures in different formats Let's say I have a long report that produces a lot of figures which knitr makes as pdfs and it works really well with LaTeX. At the end of the project, my co-authors would like to have also raster based figures. One option would be to convert everything using ImageMagick. Another option would be to specify for each chunk dev = c("jpg", "pdf"), but given the number of figures, this could be cumbersome.
Is there a global switch to make knitr produce figures in pdf and other formats at the same time?

A: I think in the preamble
opts_chunk$set(dev = c("pdf", "jpg"))

should do. Within a R-chunk of course.


text:
Q: Cron Job - Delete old files, but keep files from the first of the month I'm currently running successful mysql backups, and, on some sites, I'm deleting files older that 7 days using this command
find  /path/to/file -mtime +7 -exec rm -f {} \;

What I'd like to do, because I'm paranoid and would still like some archived information, is delete files older than 31 days, but maintain at least one file from each previous month, perhaps spare any file that was created on the 1st of the month.
Any ideas?

A: You can also write a script to contain something like this using xargs:
find /path/to/files -mtime +7| xargs -i rm {};
then  add the script to your cron job

A: The grep is almost right, it only has one space too many. This works (at least for me, I use Debian):
rm `find /path/to/file -type f -mtime +7 -exec ls -l {} + | grep -v ' [A-S][a-z][a-z]  1 ' | sed -e 's:.* /path/to/file:/path/to/file:g'`

A: You can create a file with these commands:
SRC_DIR=/home/USB-Drive
DATE=$(/bin/date "+%4Y%2m%2d%2H%2M")
TIME_STAMP=$(/bin/date --date 'now' +%s)
TIME_CAL=$[$TIME_STAMP-2592000+25200] #last day, 25200 is my GMT+7hour
TIME_LAST=$(/bin/date --date "1970-01-01 $TIME_CAL sec" "+%4Y%2m%2d%2H%2M")
/bin/touch -t ${TIME_LAST} /tmp/lastmonth
/usr/bin/find -P -H ${SRC_DIR}  ! -newer /tmp/lastmonth -type d -exec rm -r {} \;

You can modified last command based on what you want to delete, in this case I want to delete sub-folders in SRC_DIR. With the 'time attribute' more than 1 month ago.

A: Kind of ugly, but you can try parsing the output of ls -l
rm `find /path/to/file -type f -mtime +7 -exec ls -l {} + | grep -v ' [A-S][a-z][a-z]  1  ' | sed -e 's:.* /path/to/file:/path/to/file:g'`

Or write a script to get the list then run rm on them one at a time.


text:
Q: Background Location Updates are stopping with background task issue identified in debugger I've been using background location updating since iOS 9 with no problems and this issue just showed up now in iOS 13.  The debugger console identifies this issue when the app enters the background: "Can't end BackgroundTask: no background task exists with identifier 3 (0x3), or it may have already been ended. Break in UIApplicationEndBackgroundTaskError() to debug."
Here's how boilerplate code for location updates in the background:
First, the code in the AppDelegate:
if CLLocationManager.authorizationStatus() == .notDetermined {
   locationManager.requestAlwaysAuthorization()
   locationManager.allowsBackgroundLocationUpdates = true
}

The info.plist:
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
    <string>"MY APP" is optimized to run in the background as well as when your using it directly.  For best results, choose ALWAYS.</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>"MY APP" is optimized to run in the background.  Please choose ALLOW.</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Please choose ALLOW WHILE USING APP.  "MY APP" needs to use your location to get its altitude data.</string>
    <key>UIBackgroundModes</key>
    <array>
        <string>location</string>

As far as I can tell there's nothing that should be causing this issue.  And why it's just started makes no sense.

A: Apple has improved the way of asking for user's location permission in order to make it more user friendly in iOS 13.
There's nothing wrong with your code and you shouldn't change anything (as you are already using requestAlwaysAuthorization() and allowsBackgroundLocationUpdates.)
Basically what is happening is: until iOS 12, the user would be asked for permission on location and could choose to Always allow, Allow once and to not allow at all.
In iOS 13, the options are Allow when is use, allow once, and not allow.
Then, iOS itself will ask for the "Always" permission when it judges necessary (aka, when your app enter in background and tries to perform some action that needs the location info).


text:
Q: JavaFX 8 QuantumRenderer high CPU usage I have a JavaFX APP containing two listviews displaying incoming customer orders (using a custom cellfactory) received from my server. I also have a few tableview displaying information from a Postgres database (this are spread across a few tabs inside a tabpane).
The user has to take an order (by clicking on it), and enter a few information inside textboxes.
The application was initially written an deployed using Java7. I had no problem whatsoever.
But recently I decided to switch to Java8. I modified my code to use lambdas and added a few extras stuff to the app:

*

*a timeline to check and display orders status every minute, inside a textflow;

*modified the customcellfactory class to use an external CSS, with setId instead of setStyle;

*...

Now, the application is running fine but, after 2-3 hours of uptime it becomes sluggish. Since is hard for me simulate the behavior inside a profiler I used jstack, top -H, and matching pid with nid to find out what is happening.
This way I found out that the culprit was QuantumRenderer with 95+% CPU usage:
  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
30300 utilizat+  20   0 5801608 527412  39696 S  95,1  6,5  60:57.34 java

"QuantumRenderer-0" #9 daemon prio=5 os_prio=0 tid=0x00007f4f182bb800 nid=0x765c runnable [0x00007f4eeb2a1000]
   java.lang.Thread.State: RUNNABLE
    at com.sun.prism.es2.X11GLDrawable.nSwapBuffers(Native Method)
    at com.sun.prism.es2.X11GLDrawable.swapBuffers(X11GLDrawable.java:50)
    at com.sun.prism.es2.ES2SwapChain.present(ES2SwapChain.java:186)
    at com.sun.javafx.tk.quantum.PresentingPainter.run(PresentingPainter.java:107)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
    at com.sun.javafx.tk.RenderJob.run(RenderJob.java:58)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at com.sun.javafx.tk.quantum.QuantumRenderer$PipelineRunnable.run(QuantumRenderer.java:125)
    at java.lang.Thread.run(Thread.java:745)

The machine running the application is using a 64Bit version of Lubuntu.
I can't figure out where should I look to find out what is the problem...

A: It seems your renderer is using the X11 pipeline (Java2D?) which could be the cause of high CPU usage (software acceleration). Does your graphics card supports hardware acceleration?
Try getting more information with -Dprism.verbose=true if your graphics card does support hardware acceleration you might want to try to force it with -Dprism.forceGPU=true, also try enabling the OpenGL pipeline to increase Java2D performance with
-Dprism.order=es2,es1,sw,j2d (you could also try with the old Java2D flag
-Dsun.java2d.opengl=true but I think that won't affect prism).
I would also recommend taking a look at the OpenJFX performance tips and tricks checklist I've seen high CPU usage in nodes that was somewhat fixed with the usage of Node.setCache(true) and its CacheHints when using any kind of animation (with the downside that this uses more memory).
Also, take a look at how you are updating your UI from your worker threads. It's important to do minimum work in the FX UI Thread and update it from your workers correctly and only when necessary, take a look at this other question to learn more about the javafx.concurrent.Task class and its correct usage to update the UI from worker threads.
This seems much more like a software acceleration issue and Dprism.verbose should let you know more but following the other suggestions never hurts! Hope this helps!


text:
Q: FizzBuzz in Dlang I'm trying to get fizzbuzz working in D but I have no idea for the life of me what the problem is. I have tried reversing the logic and it does write both words when it is not appropriate, but when it is it just writes nothing.
Here's a screenshot of what the output looks like: http://puu.sh/p67Hd/2a5a598b1b.png
import std.stdio;

void main() {
    for (uint i = 0; i < 100; i++) {
        if (i%5 && i%3) write(i);
        if (!i%3) write("Fizz");
        if (!i%5) write("Buzz");
        writeln();
    }
}

A: The reason is the operator precedence in D.
The if(!i%3) will actually be interpreted as if((!i)%3), which results in either 0%3 (which is false), or 1%3 (which is true). !n will result in 1 if n is 0, otherwise it will always be 0. Because it's going from 0 to 100, (!i) % 3 will only be true once at the beginning. This is the reason why there is a FizzBuzz at the start of the output.
So instead your code should look like this:
import std.stdio;

void main() {
    for (uint i = 0; i < 100; i++) {
        if (i%5 && i%3) write(i);
        if (!(i%3)) write("Fizz");
        if (!(i%5)) write("Buzz");
        writeln();
    }
}

A: The ! operator has precedence over % so your if statements look like
if ((!i) % 3) write("Fizz");
if ((!i) % 5) write("Buzz");

and because all of i is non-zero (besides the first time), !i is always 0 and 0 % 5 and 0 % 3 is always 0 (false).
To fix, all you need to do is add parenthesis around the % operations
if (!(i % 3)) write("Fizz");
if (!(i % 5)) write("Buzz");


text:
Q: Entity Framework many to many relationship updating How to update the many to many navigation property?
I want to update the entity I get an error

have the same primary key value

I know there is way to split the many-many relation to two many-to-one relations, but this is the case. Update many-many relation.
I do this way to add new a entity with navigation property without problem BUT for updating there is an error. I tried to remove db.Entry(item).State = ... in update, but the problem is still there.
public class TrendChart
{
        public int Id { get; set; }
        public string Name { get; set; }

        public virtual List<ParameterMonitor> Monitors { get; set; }
}

public class ParameterMonitor
{
        public int Id { get; set; }
        public virtual List<TrendChart> Charts{ get; set; }
}

var db = new DataAccess.ApplicationDbContext();

var newTrendChart = db.TrendChart.Where(x => x.Id == trendChart.Id).FirstOrDefault();

if (newTrendChart != null)
{
    if (newTrendChart.Monitors != null)
        newTrendChart.Monitors.Clear();

    newTrendChart.Name = trendChart.Name;
    newTrendChart.Monitors = new List<ParameterMonitor>();

    foreach (var item in trendChart.Monitors)
    {
        newTrendChart.Monitors.Add(new DataAccess.ParameterMonitor { MOParameterId = item.MoParameterId });
    }

    // prevent from adding new parameter
    foreach (var item in newTrendChart.Monitors)
    {
        // here the ERROR happens
        db.Entry(item).StateSystem.Data.Entity.EntityState.Unchanged;
    }

    db.SaveChanges();
}

A: I found the solution, the point is that whenever you try to add something in intermediate table the CLEAR() function does not remove the history of items in the behind scene which we do not see, consider there are two items in the intermediate table , 1,2 and 1,3 . if you want to update the table by just 1,2 , it means the clear function remove 1,2 and 1,3 and again add 1,2. but it does not work because there is already an item 1,2 in behind scene. we need to remove() 1,3 and don't care about 1,2. Is there any other Solution.
  var tempMOList = new List<int>();
                tempMOList = newTrendChart.Monitors.Select(x=> x.MOParameterId).ToList();
                foreach (var id in tempMOList)
                {
                    var temp = newTrendChart.Monitors.Where(x => x.MOParameterId == id).FirstOrDefault();
                    if (trendChart.Monitors.Any(x => x.MoParameterId == id) == false)
                        newTrendChart.Monitors.Remove(temp);

                }

                foreach (var item in trendChart.Monitors)
                {
                    if (newTrendChart.Monitors.Any(x => x.MOParameterId == item.MoParameterId) == false)
                        newTrendChart.Monitors.Add(new DataAccess.ParameterMonitor { MOParameterId = item.MoParameterId });
                }

                //prevent from adding new parameter
                foreach (var item in newTrendChart.Monitors)
                {
                    db.Entry(item).State = System.Data.Entity.EntityState.Unchanged;
                }
    db.SaveChanges();


text:
Q: Gitlab block merge requests from feature into master Is there a way to block creating/approving merge requests from "feature/*" branches into master?
I need to allow only merge requests from "release/*" and "hotfix/*" branches.
When creating MergeRequest via GUI the default target branch is master. So human error while doing this may break a workflow and merge untested\unbuild feature into master.
Our current workflow is coding new features in "feature/*" branches. Merging several features into new "release/*" branch and CI makes a build and tests of this release. After testing this release goes on the prod server and into master.

A: Since GitLab permissions are role-based, there's no way to set permissions per branch (other than setting a branch as protected in Settings / Repository / Protected Branches, which which controls who can merge not which branch can merge ). However, you could do the following:

*

*In your GitLab CICD (if you don't have it set up already I highly recommend, its a handy tool) set up a check that runs always to determine which branch is trying to be merged ($CI_COMMIT_REF_NAME is what you want, see all GitLab default environment variables here) and if the branch name matches 'feature/*', then have the pipeline fail

*Under Settings / General / Merge Requests, under Merge Checks, check the option Pipelines must succeed.

Now, if someone attempts to create a Merge Request from a feature branch, the pipeline will fail and no one will be allowed to approve the Merge Request.


text:
Q: Posting form using javascript and json with nested objects I have an html form that has the following structure:
<input type="text" name="title" />
<input type="text" name="persons[0].name" />
<input type="text" name="persons[0].color" />
<input type="text" name="persons[1].name" />
<input type="text" name="persons[1].color" />

I would like to serialize this into the following json:
{
  "title": "titlecontent",
  "persons": [{
      "name": "person0name",
      "color": "red"
    },
    {
      "name": "person1name",
      "color": "blue"
    }
  ]
}

Notice that the number of persons can vary from case to case.
The structure of the html form can change, but the structure of the submitted json can't.
How is this done the easiest?

A: Dependencies:

*

*locutus (npm install locutus)

*jQuery

Code:
var parse_str = require('locutus/php/strings/parse_str');
parse_str($("#form ID").serialize(), var result = {});
console.log(result);

A: Hey man using jQuery and the
jQuery JSON plugin, I was able to do the following:
I had to change your html a bit:

    <input type="text" class="title" />

        <input type="text" class="name" />
        <input type="text" class="color" />

        <input type="text" class="name" />
        <input type="text" class="color" />

And then I was able to use the following code to create your JSON array:
var Directory = {};
Directory.title = $("div#Directory input.title").val();
Directory.persons = [];
$("div#Directory span.person").each(function() {
  var index = $(this).attr("class").split(" ")[1];
  Directory.persons.push({
    name: "person" + index + $(this).children("input.name").val(),
    color: $(this).children("input.color").val(),
  });
});
alert($.toJSON(Directory));

This http ://stackoverflow.com/questions/492833/getting-correct-index-from-input-array-in-jquery is also somewhat helpful. Unfortunately I couldn't replicate their selection method with your particular set of attributes.
Hope I'm not doing your homework ;) There's a space in the URL above because I don't have enough reputation points to put more than one hyperlink.
This is your final JSON:
{
  "title": "abc",
  "persons": [{
    "name": "person0englishman",
    "color": "pink"
  }, {
    "name": "person1indian",
    "color": "brown"
  }]
}


text:
Q: How to define multiple distinct controllers with distinct actions in Grails filter? I've read the post on defining multiple distinct controllers in a filter and on the post with multiple actions but can we combine the two? For example:
def filters = {
someFilterMethod(controller: 'controller1|controller2|...', action: 'controller1Action|controller2Action')
  {
    ...
  }
}

Is it possible? Alternatively, I could always rename both actions to the same name. But just wondering if its possible. Thanks.

A: Yes, you can do something like this...
class MyFilters {

    def filters = {
        someFilter(controller:'one|two|three', action:'read|delete|save') {
            before = {
                // ...
            }
        }
    }
}

A: There is no way to declaratively express something like that but it would be trivial for you to put whatever imperative logic you need inside of the filter to be more specific about which combinations of controllers and actions the filter has its effect on.


text:
Q: Search array, and if found Array
(
    [0] => Array
        (
            [product_number] => 1000000002
            [quantity] => 1
            [size] => L
        )

    [1] => Array
        (
            [product_number] => 1000000002
            [quantity] => 1
            [size] => XS
        )

    [2] => Array
        (
            [product_number] => 1000000002
            [quantity] => 1
            [size] => M
        )

)

Hello guys,
I need some help with this. I am creating a shop system.
And i am trying to add products to a basket/cart.
I need to check if the product number is in the array, if yes? then is the size the right one? - if yes, then update the right one..
if the size is not the right add a new.
If the product number isn't in the array .. add a new
I have tryed with in_array, foreach, and some stuff.. i cant get it to work. Can any of you help me ?
it is in php
Thanks a lot ;)

A: Here is my implementation:
$ShoppingBasket = Array
(
     Array
        (
            "product_number" => 1000000002,
            "quantity" => 1,
            "size" => "L"
        ),
    Array
        (
            "product_number" => 1000000002,
            "quantity" => 1,
            "size" => "XS"
        ),
    Array
        (
            "product_number" => 1000000002,
            "quantity" => 1,
            "size" => "M"
        )

);

function addItem(&$ShoppingBasket, $PN, $size)
{ //use references with & to modify the array directly
    // loop through each element of your array (mind this is an array of hashes.
    foreach ($ShoppingBasket as &$item) //reference again so it modifies the item direclty in $ShoppingBasket.
    {
        // compare if the PN and size are the same
        if ($item["product_number"] == $PN && strcmp($item["size"],$size) == 0)
        {
                $item["quantity"] ++; //increase the quantity count
                return; //end the function if we found the item.
        }
    }
    // this acts as a else close, it only executes if we haven't found anything already.
    // push a new hash in $ShoppingBasket where all the field are specified.
    array_push($ShoppingBasket, array("product_number" => $PN,"quantity" => 1,"size" => $size));
    return;
}
function removeItem(&$ShoppingBasket, $PN, $size)
{ //use references with & to modify the array directly
    for($i = 0 ; $i < count($ShoppingBasket) ; $i++)
    {//need to interate with a counter to have the position in the array
        if ($ShoppingBasket[$i]["product_number"] == $PN && strcmp($ShoppingBasket[$i]["size"],$size) == 0)
        {
               array_splice($ShoppingBasket, $i, 1);
               //splice removes 1 element from position $i
               return TRUE; //we have removed something
        }
    }
    return FALSE; // we have not removed the item
}

//little test of the function
addItem($ShoppingBasket,1000000002, "M");
addItem($ShoppingBasket,1000000002, "M");
addItem($ShoppingBasket,1000000002, "XXL");
addItem($ShoppingBasket,1000000232, "M");
print_r($ShoppingBasket);
removeItem($ShoppingBasket,1000000232, "M");
removeItem($ShoppingBasket,1000000002, "M");
removeItem($ShoppingBasket,1000000002, "XXL");
print_r($ShoppingBasket);

A: I'm not sure if you have the ability to do this, but if you do you could try the following. Key your array by your product number and use the array_key_exists() function to determine if that key is present.
if( array_key_exists( $product_number, $product_array ) )
{
    //
    // The product number was found in the array of products
    //
}

else
{
    //
    // The product number was not found in the array of products
    //
}

Reference: http://php.net/manual/en/function.array-key-exists.php


text:
Q: Splitting One Polygon By Boundary of Another using QGIS? I'm using QGIS 3.0 and attempting to calculate the number of people that fall within a buffer.  The population count is a field within my block group polygon layer.  I've attached a screenshot, the orange polygons are my block counts and the purple layer is my buffer.
At first, I created a point layer where each yellow point represented 50 people in a block group (visible in the pic below), then I randomly placed the points throughout the polygon.  I was going to just count how many dots fall within the purple polygon and multiply by 50, but my gut tells me this isn't a very accurate measure.  Or maybe it is, since population is not uniformly distributed to begin with.
I have a field in my block group layer that provides the surface area in square miles, the total population, and the population per square mile, so with all that info I should be able to more accurately clip my block group layer by the boundary extent of the purple buffer, and the output should give me only the number of people who fall within the purple.  I've tried a simply clip, but the output shows the same surface area & population as before the clip-the field info isn't updated.
I've also tried digitizing, converting the polygon to lines and digitizing to conform to the boundary of the purple buffer, but it seems like a messy and complicated process for a seemingly simple task.
Maybe I'm overcomplicating things..suggestions?

A: The output clip features are showing the original block attributes, because the clip output just gives each feature the same attributes as its source feature (virtual field values become permanent too).
To get the population for each clipped feature, based on the proportion of the original area, you could use the field calculator to create a field on the clipped output layer.
The field calculation expression would be something like:
($area / "orig_area" ) * "population"
Where $area returns the area of each feature, "orig_area" is the area of the whole block (ideally calculated on the original blocks using the same $area expression, to avoid the need for unit conversions).


text:
Q: How can I get the rendered output of a template within a template tag in django? Disclaimer: This is a follow on question from my previous question.
I'm attempting to write a template tag in Django, that will render itself within the body of a Mako Template. I'm not sure that this is achievable, but it's something that'd be extremely useful to my project, and probably a lot of other people using Mako Templates within Django.
Here is the definition of my tag:
def extends_mako(parser, token):
    # wishlist below, this code does not work but it's what I want to achieve
    template_html = ''
    while (node = parser.nodelist.pop()):
        template_html += node.render()

Is the parser object capable of rendering the entire tree up to this point? My only idea at the moment, is to use the parser object to render (and remove from the tree) every node preceding this one. I'd then pass the output to Mako to render as HTML, and use that as the output to the render function of the Node I'm defining. My hope, is that when render is called on the template, it will only need to render this one node, since my template tag has already done the compilation on everything else. The intention is to have the extends_mako tag as the final tag in the tree.
I've done some quick pdb.set_trace investigation, but I can't see anything that helps thus far.
So; Is it possible to use the parser object, passed to the template tag, to compile the template, and retrieve the final rendered output?

A: This isn't a solution specific to your problem, but might get you in the right direction. I recently took Django's "spaceless" template tag and added support to not strip the whitespace out when debugging.
Part of that template tag passes the list of template nodes collected between the {% spaceless %}{% endspaceless %} tags, which in theory, might get you the nodes preceeding your node...
from django.conf import settings
from django import template
from django.utils.html import strip_spaces_between_tags

register = template.Library()

class SmartSpacelessNode(template.Node):
    def __init__(self, nodelist):
        self.nodelist = nodelist

    def render(self, context):
        content = self.nodelist.render(context)
        #from here, you can probably delete the nodes after you've rendered
        #the content to a variable, then render your tag
        return content if settings.DEBUG else strip_spaces_between_tags(content.strip())

@register.tag
def smart_spaceless(parser, token):
    nodelist = parser.parse(('end_smart_spaceless',))
    parser.delete_first_token()
    return SmartSpacelessNode(nodelist)

Hope that helps you out.


text:
Q: If $\lim_{n\to\infty} n^2|x_{n+1} - x_n| = 0$, then sequence of real numbers $x_n$ converges. Is the following true?

If $\lim_{n\to\infty} n^2|x_{n+1} - x_n| = 0$, then sequence of real numbers $x_n$ converges.

I suspect it to be true. If the "if" part is true, then $|x_{n+1}-x_n|$ has to go to zero "faster" than $n^2$. It is true that we have counterexample where $\lim |x_{n+1} - x_n| = 0$ but $x_n$ does not converge. For example, $x_n = \sum_{k=1}^n \frac{1}{k}$. But in this case, $\frac{1}{k}$ does not decrease to zero that fast.
How should I prove the claim, if it's true?

A: The claim is true. Just show that the sequence $x_n$ is Cauchy. Do this by first arguing that there exists $C>0$ such that
$$|x_{k+1}-x_{k}| < \frac C{k^2}$$
for all $k$. Next, observe that if $m>n$, then
$$|x_m-x_n|\le \sum_{k=n}^{m-1}|x_{k+1}-x_k|\le\sum_{k=n}^\infty \frac C{k^2}.$$
Finally use the fact that the RHS tends to zero as $n\to\infty$.


text:
Q: Bootstrap v4 columns won't float with flex enabled Using Bootstrap v4 the css float directive will not work on columns if $enable-flex: true; is set within Bootstrap's SCSS variables. This is due to the way flex works.
How can the same effect be achieved with flex?

A: Reverse container's row direction
One option is to float everything inside a row to the right. We can add this to the containing element (such as a row) to achieve this:
flex-direction:row-reverse;
-webkit-flex-direction: row-reverse; /* Safari 6.1+ */

EDIT: Ended up making a mixin and class for this in a Bootstrap-y way if anyone is interested (use .row-reverse like row):
@mixin make-row-reverse($gutter: $grid-gutter-width) {
  @if $enable-flex {
    display: flex;
    flex-wrap: wrap;
    flex-direction: row-reverse;
  } @else {
    @include clearfix();
    > * {
      float: right;
    }
  }
  margin-left:  ($gutter / -2);
  margin-right: ($gutter / -2);
}

// Row reverse
//
// A row with a reversed render direction.

@if $enable-grid-classes {
  .row-reverse {
    @include make-row-reverse();
  }
}

Order the individual elements
Another option would be to specify the order the columns should be in inside the container using the order directive. Set this on one of the contained columns to make it the second column in the row:
order: 2;

Self alignment
I'm putting this here purely because I think this is the way it should be done, but this is not working for me as intended. There is also an align-self directive for flex where passing flex-end to it would cause the element to render at the opposide side of the flex column or flex row. Be great if anyone has anymore information on this, but this didn't work for my use case. Perhaps this might help someone else though.


text:
Q: Gradient of generalized logarithm From Boyd and Vandenberghe Chapter 11; a generalized logarithm $\psi$ for a proper cone $K$ is any function that satisfies these two properties. 1) $\nabla^2 \psi(y) \prec 0$ for any $y \in K$, and 2) for a constant $s > 0$ and all $y \succ_K 0$: $\psi(sy) = \psi(y) + \theta \log y$, where $\theta$ is the degree of $\psi$.
The text then goes on to say that generalized logarithm satisfies the following property: $\nabla \psi(y) \succ_{K^*} 0$ (i.e., the gradient of the generalized log is contained in the dual cone).
How do I prove the above? Are there any references for the above property? I have looked in Rockafellar.


text:
Q: How should I pass an array of strings to a C library using P/Invoke? I'm trying to P/Invoke from a C# application into a C library, sending over a struct that contains an array of strings. I do have control over the C library, and can change things if needed.
This is a one-way street: From C# to C, I don't need to observe modifications made to the struct on the C side (I'm also passing it by value instead of by reference, though I might change that later - first trying to solve the immediate problem).
My C struct looks like this at the moment:
// C
struct MyArgs {
    int32_t someArg;
    char** filesToProcess;
    int32_t filesToProcessLength;
};

In C#, I've replicated the struct as such:
// C#
public struct MyArgs
{
    public int someArg;

    [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.LPStr)]
    public string[] filesToProcess;

    public int filesToProcessLength;
}

And then pass it to the library:
// C#
[DllImport("myLib.so", EntryPoint = "myFunction", CallingConvention = CallingConvention.Cdecl)]
internal static extern bool myFunction(MyArgs args);

var myArgs = new MyArgs {
    someArg = 10,
    filesToProcess = new string[] { "one", "two", "three" }
};
myArgs.filesToProcessLength = myArgs.filesToProcess.Length;

Console.WriteLine(myFunction(myArgs));

Where I'm trying to consume it:
// C
bool myFunction(struct MyArgs args) {
    printf("Files to Process: %i\n", args.filesToProcessLength);
    for (int i = 0; i < args.filesToProcessLength; i++) {
        char* str = args.filesToProcess[i];
        printf("\t%i. %s\n", i, str);
    }
    return true;
}

This basically crashes the app. I get an output that says Files to Process: 3 but then the app just stops. If I change the for-loop to not try to access the string, it counts through the loop - so it seems I get some sort of access violation.
If I change my code to accept an array as part of the function arguments, it works:
// C
bool myFunction(struct MyArgs args, char** filesToProcess, int32_t filesToProcesLength) {
    printf("Files to Process: %i\n", filesToProcessLength);
    for (int i = 0; i < filesToProcessLength; i++) {
        char* str = filesToProcess[i];
        printf("\t%i. %s\n", i, str);
    }
    return true;
}

// C#
[DllImport("myLib.so", EntryPoint = "myFunction", CallingConvention = CallingConvention.Cdecl)]
internal static extern bool myFunction(MyArgs args, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)] filesToProcess, int filesToProcessLength);

My initial thought is that because within a struct, I use ByValArray, which might be a pointer to a string array (so essentially a char***?), but even if I change the type to char*** in the struct and do a char** strArray = *args.filesToProcess, I get the same result/non-working crash.
As I am mostly a C# developer with some C knowledge, I am a bit at a loss here. What would be the best way to P/Invoke a collection of strings into a C library within a struct? As said, I can change the C library however I want, just prefer to keep it in a struct instead of adding a function argument.
If it matters, this is on Linux, using gcc 9.3.0, and this is just plain C, not C++.
Updates:

*

*sizeof(args) is 24

*Taking the addresses:

*

*&args = ...560

*&args.someArg = ...560

*&args.filesToProcess = ...568

*&args.filesToProcessLength = ...576

*So args.filesToProcess is a single pointer to something - will try to dig to see what it's pointing to

Update 2: Looking at a memory dump taken with this code, it seems that the C# side isn't sending the Array in a way that I want it, I assume the ByValArray is the problem here.
  0000  6f 6e 65 00 00 00 00 00 00 00 00 00 00 00 00 00  one.............
  0010  50 44 fc 00 00 00 00 00 61 00 00 00 00 00 00 00  PD......a.......
  0020  53 00 79 00 73 00 74 00 65 00 6d 00 2e 00 53 00  S.y.s.t.e.m...S.
  0030  65 00 63 00 75 00 72 00 69 00 74 00 79 00 2e 00  e.c.u.r.i.t.y...
  0040  43 00 72 00 79 00 70 00 74 00 6f 00 67 00 72 00  C.r.y.p.t.o.g.r.
  0050  61 00 70 00 68 00 79 00 2e 00 4f 00 70 00 65 00  a.p.h.y...O.p.e.
  0060  6e 00 53 00 73 00 6c 00 00 00 98 1f dc 7f 00 00  n.S.s.l.........

So I'm getting the first array element, but after that it's just random garbage (it changes with every run) - so the C side is tentatively OK, but the C# side isn't.
Update 3: I've experimented a bit more and changed the C# side from a string array to an IntPtr and Marshal.UnsafeAddrOfPinnedArrayElement(filesToProcess, 0). On the C side, I now get the C# array, though of course, with the C# stuff to it and wrong encoding, but at least it shows that it's indeed a marshaling problem on the C# side.
  0000  90 0f 53 f7 27 7f 00 00 03 00 00 00 6f 00 6e 00  ..S.'.......o.n.
  0010  65 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  e...............
  0020  90 0f 53 f7 27 7f 00 00 03 00 00 00 74 00 77 00  ..S.'.......t.w.
  0030  6f 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  o...............
  0040  90 0f 53 f7 27 7f 00 00 05 00 00 00 74 00 68 00  ..S.'.......t.h.
  0050  72 00 65 00 65 00 00 00 00 00 00 00 00 00 00 00  r.e.e...........
  0060  90 0f 53 f7 27 7f 00 00 27 00 00 00 20 00 4d 00  ..S.'...'... .M.

I get the key issue: If I wanted to pass an array by value, the struct size is dynamic per call, and that's probably an issue. But passing a ByValArray seems to not be correct either. Probably would need to either use a fixed-size array, an IntPtr to an array, or forgo the struct and pass it as a function argument.
But as always, if someone has a better plan, I'm all ears :)

A: You can't use structures like that because a structure has to have a compile-time size, and by definition your structure doesn't have that.
You can either manually serialize your data in a Marshal.AllocHGlobal() buffer in C# and then deserialize it in C++, or use the function call marshaller like this:
// C++
// extern "C" __declspec(dllexport)
bool myFunction(char **filesToProcess, int filesToProcessLength)
{
    printf("Files to Process: %i\n", filesToProcessLength);
    for (int i = 0; i < filesToProcessLength; i++)
    {
        char *str = filesToProcess[i];
        printf("\t%i. %s\n", i, str);
    }
    return true;
}

// C#
    [DllImport("dlltest.dll", EntryPoint = "myFunction", CallingConvention = CallingConvention.Cdecl)]
    internal static extern bool myFunction(
        [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr, SizeParamIndex = 1)]
        string[] files,
        int count);

    static void Main(string[] args)
    {
        Console.WriteLine(myFunction(new string[] { "one", "two", "three" }, 3));
    }

A: You can't use a variable size array in a struct, you have to marshal the whole thing manually, or use arguments which is much easier, especially in the (C# to C)-only way.
If you want to use a struct for some reason, then you can do it like this:
C side (I'm using Windows, you may have to adapt):
struct MyArgs {
    int32_t someArg;
    char** filesToProcess;
    int32_t filesToProcessLength;
};

// I pass struct as reference, not value, but this is not relevant
// I also use __stdcall which is quite standard on Windows
extern "C" {
    __declspec(dllexport) bool __stdcall myFunction(struct MyArgs* pargs) {
        printf("Files to Process: %i\n", pargs->filesToProcessLength);
        for (int i = 0; i < pargs->filesToProcessLength; i++) {
            char* str = pargs->filesToProcess[i];
            printf("\t%i. %s\n", i, str);
        }
        return true;
    }
}

C# side:
static void Main(string[] args)
{
    var files = new List<string>();
    files.Add("hello");
    files.Add("world!");

    var elementSize = IntPtr.Size;
    var my = new MyArgs();
    my.filesToProcessLength = files.Count;

    // allocate the array
    my.filesToProcess = Marshal.AllocCoTaskMem(files.Count * elementSize);
    try
    {
        for (var i = 0; i < files.Count; i++)
        {
            // allocate each file
            // I use Ansi as you do although Unicode would be better (at least on Windows)
            var filePtr = Marshal.StringToCoTaskMemAnsi(files[i]);

            // write the file pointer to the array
            Marshal.WriteIntPtr(my.filesToProcess + elementSize * i, filePtr);
        }

        myFunction(ref my);
    }
    finally
    {
        // free each file pointer
        for (var i = 0; i < files.Count; i++)
        {
            var filePtr = Marshal.ReadIntPtr(my.filesToProcess + elementSize * i);
            Marshal.FreeCoTaskMem(filePtr);
        }
        // free the array
        Marshal.FreeCoTaskMem(my.filesToProcess);
    }
}

[StructLayout(LayoutKind.Sequential)]
struct MyArgs
{
    public int someArg;
    public IntPtr filesToProcess;
    public int filesToProcessLength;
};

// stdcall is the default calling convention
[DllImport("MyProject.dll")]
static extern bool myFunction(ref MyArgs args);


text:
Q: How to debug keyboard on Linux I want to debug my keyboard and figure out what would happen after I press a key.
Is there any debug tools or solutions to track the keyboard events or handlers?
I searched the Internet and only found one useful answer (Debug/fix a key autorepeat issue?)
For example, I press a Volume control key, how does it trigger an event and control the driver to turn up/down?
And how do I track the control flow of it?
I'm using arch Linux on my laptop, so any solution for Linux is welcome.

A: You can observe raw USB events from the keyboard input device. Assuming you can find your keyboard here: ls /dev/input/by-id/*kbd, you can read events directly from that file.
An example where fmbtuinput.py prints human readable events:
sudo python fmbtuinput.py -p /dev/input/by-id/*kbd
This works for other USB input devices, too.


text:
Q: Do I need a rebuild for Java here? I have a ClassA that is being used my many components and libraries in various areas of a project.
Now I need to add an extra member to this class but since it will not be needed/used by other areas it does not feel proper to extend the class.
If I add the member to ClassA instead of extending would I have any issues? Would everything need to be rebuild?

A: Adding a new member preserves binary compatibility, see also Chapter 13. Binary Compatibility of the Java Language specification.
Obviously you need to rebuild the modified class, but not classes which are using the modified one.

A: Unless your existing contacts and interactions between ClassA and other classes BREAK, there should be no issue. But if you change signature of a method that is used by other classes you could get a runtime error while locating the old version of method as it does not exist anymore.

A: If you change your Class A, obviously a rebuild is necessary. To minimize the impact you can extend the class A and use the subclass for your work. The other components and libraries will continue to keep using your Class A, while your code should now refer to the sublcass which has the added member.
Again, it depends on how you define your objects.


text:
Q: Notification Builder (this) problems android I have this object:
public  void timerDistraction(final View view) {

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
       @Override
       public void run() {
         //Do something after time
           Toast.makeText(getApplicationContext(),
                   "Button is clicked", Toast.LENGTH_LONG).show();

            Notification notification = new Notification.Builder(this)
              .setContentTitle("Basic Notification")
              .setContentText("This is my example of basic notification")
              .setSmallIcon(R.drawable.ic_launcher).build();
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            NotificationManager notificationManager = getNotificationManager();
            notificationManager.notify(0, notification);
            Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notificationSound);
            r.play();

     }
     }, 5000);

And the line
Notification notification = new Notification.Builder(this)

Has an error, presumably because of the (this)
Can anyone point me in the right direction. I've tried changing it to the function or null, but no progress. If I have just the notification code itself, without the delay, it works.

A: When you are in the Runnable, this became the Runnable and not the context of your Activity. Since you must pass a context as parameter, it triggers an error. To get the correct context, you can use the same way as the one you used for the Toast:
Notification notification = new Notification.Builder(getApplicationContext());

In this case, you will effectively pass your Activity context and not your Runnable.


text:
Q: Como uma classe pode também ser um método em Ruby? Veja a classe Integer:
Integer.class
=> Class

Parece também que ela é um método, ao mesmo tempo que é uma classe:
Integer 10.5
=> 10

Como isso é possível em Ruby? Onde esse método está definido? Que mecanismos o Ruby utiliza para saber se estou chamando o método ou a classe?

A:
Como isso é possível em Ruby?

Assim:
class C
  attr_accessor :x
  def initialize(x)
    @x = x
  end
end

# N.B.
def C(x)
  C.new(x)
end

repl.it: https://repl.it/repls/CurvyTerrificRegister.

Onde esse método está definido?

Isso é um método do objeto main. A classe deste objeto é Object. Esta classe inclui o módulo Kernel. Documentação do método.

Que mecanismos o Ruby utiliza para saber se estou chamando o método ou a classe?

Chamadas de método são sempre a passagem de mensagens:

*

*C.new(42) = enviar a mensagem new para o objeto C.

*C(42) = enviar a mensagem C para o objeto main.
(Eu pessoalmente acho isso confuso. Eu não usaria isso.)


text:
Q: How to order non-integer records in MySql? I'm trying to order some MySQL records by DESC order and get the last record added.
These are my records and they're all stored as strings:
1/2017
1/2018
2/2017
2/2018
3/2017

I want to get the value 1/2018.   The records are based on the current year
and the last record added was 1/2018 and the next will be 2/2018 and so on.
this is my query:
SELECT NoControl FROM cita ORDER BY NoControl DESC LIMIT 1

but I'm getting 3/2017 as the last record.

A: If you have ever the same pattern  m/yyyy you could use some string manipulation function  eg:
SELECT NoControl
FROM cita
ORDER BY right(NoControl,4), DESC left(NoControl,1) DESC  LIMIT 1

But you should avoid of store date values as string ..
or convert the string as  a proper date
SELECT NoControl
FROM cita
ORDER BY str_to_date(NoControl,'%m/%Y') DESC LIMIT 1

A: Use SUBSTRING_INDEX to extract the first and second part, CAST as integer and sort:
SELECT str
FROM testdata
ORDER BY
    CAST(SUBSTRING_INDEX(str, '/', -1) AS UNSIGNED) DESC,
    CAST(SUBSTRING_INDEX(str, '/',  1) AS UNSIGNED) DESC
LIMIT 0, 1

SQL Fiddle


text:
Q: XML Parsing in Swift 2 (Xcode 7) I am needing help parsing XML from a URL. I have read on this a lot and cannot figure out how to get this. All the examples I have found are a little ambiguous with the examples and how to grab the info from parsed XML data.
How would I parse this XML
<menu>
    <menuitems>
        <item price="$10">Pizza</item>
        <item price="$5">Salad</item>
        <item price="$3">Bread</item>
    </menuitems>
</menu>

This is the tutorial I was going off of but I couldn't understand how this tutorial was accessing the data in the arrays and dictionary.
http://www.theappguruz.com/blog/xml-parsing-using-nsxmlparse-swift
In Xcode 7 (Swift 2), how would I parse and access this info. I know this is not how it would be accessed but I am looking for something like the code below.
print ("\(item[0].data)") // Pizza //
print ("\(item[0].price)") // $10 //

Here is the code from the tutorial but I couldn't figure out how to access all the data parsed from the URL. How would I edit this code to fit my structure?
import UIKit
import Foundation

class ViewController: UIViewController, NSXMLParserDelegate

    {

    var parser = NSXMLParser()
    var posts = NSMutableArray()
    var elements = NSMutableDictionary()
    var element = NSString()
    var title1 = NSMutableString()
    var date = NSMutableString()

func beginParsing()
{
    posts = []
    parser = NSXMLParser(contentsOfURL:(NSURL(string:"http://images.apple.com/main/rss/hotnews/hotnews.rss"))!)!
    parser.delegate = self
    parser.parse()
}

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
{
    element = elementName
    if (elementName as NSString).isEqualToString("item")
    {
        elements = NSMutableDictionary()
        elements = [:]
        title1 = NSMutableString()
        title1 = ""
        date = NSMutableString()
        date = ""
    }
}

func parser(parser: NSXMLParser, foundCharacters string: String)
{
    if element.isEqualToString("title") {
        title1.appendString(string)
    } else if element.isEqualToString("pubDate") {
        date.appendString(string)
    }
}

func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
{
    if (elementName as NSString).isEqualToString("item") {
        if !title1.isEqual(nil) {
            elements.setObject(title1, forKey: "title")
        }
        if !date.isEqual(nil) {
            elements.setObject(date, forKey: "date")
        }
        posts.addObject(elements)

    }

    }

}

A: It looks like that parser code was borrowed from something else. If this really is your XML, think it's simpler than that. The only trick in your case is that price is not an element, but rather just an attributeDict of the item element. And I might create my own custom type, Item to capture the name and price of an item.
Anyway, you might end up with something like:
struct Item {
    let name: String
    let price: String
}

var itemName: String?
var itemPrice: String?
var items: [Item]!

func parserDidStartDocument(parser: NSXMLParser) {
    items = []
}

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
    if elementName == "item" {
        itemPrice = attributeDict["price"]
        itemName = ""
    }
}

func parser(parser: NSXMLParser, foundCharacters string: String) {
    itemName?.appendContentsOf(string)
}

func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
    if elementName == "item" {
        items.append(Item(name: itemName!, price: itemPrice!))
        itemName = nil
        itemPrice = nil
    }
}

When I do that, and print items, I get:

[MyApp.ViewController.Item(name: "Pizza", price: "$10"),
  MyApp.ViewController.Item(name: "Salad", price: "$5"),
  MyApp.ViewController.Item(name: "Bread", price: "$3")]


text:
Q: Cannot write a subset of features back to the source Geopackage or File Geodatabase At QGIS 2.18.16, I have a Geopackage point layer with a selection subset.  I need to write the selected records to the same Geopackage as a new layer, with a new name.
When I attempt to Save As... the new layer, QGIS responds with this error:

It appears that QGIS thinks that I'm trying to overwrite the original layer, when I'm actually trying to create a new layer that is a subset of the original.
Interestingly, the same error occurs if I attempt the same with a File Geodatabase; that is, I try to write a subset of records as a new Feature Class to the original FGDB.
A Google search turned up the same error, but in that case the user was trying to overwrite the source layer.
I expect that QGIS should be able to write a subset of a layer's records to the source Geopackage or File Geodatabase under a new name.  How can I accomplish this without the error?
As a workaround, I can write the subset to a different Geopackage (or FGDB), and then copy that to the original Geopackage (or FGDB).

A: I had success with QGIS 3.0.1 this way:

*

*Open a layer from .gpkg database

*Select some features

*Edit - Copy Features

*Edit - Paste Features as.. New Vector Layer

Use an existing .gpkg as a target file but give a new name for the target layer

The new layer is created into the existing GeoPackage


text:
Q: Remove time between audio files I have an HTML5 <audio> element that I change the src to every minute with the following code:
$(Audio)[0].src = newBlobURL;
$(Audio)[0].load();
$(Audio)[0].play();

There is a brief stop between the previous audio and the next audio. Both audio files are in wav format and are stored in Blob URLs.
How can I remove the stop between audio files? This problem can be heard more on i-OS safari but it can be reproduced on most browsers.

A: The delay is likely from loading the new audio file. Try loading all of your audio at once when the page is loaded. Then you can play them one at a time without loading each one in real time.
Run all of the source and load all at once when the page loads.
$(Audio)[0].src = newBlobURL;
$(Audio)[0].load();


text:
Q: Parse two files input in for/while loop I have two files with two different values. I want to run a command in loop which needs input from both file. Let me give the example to make it simple.
File1 contents:
google
yahoo

File2 contents:
mail
messenger

I need output like the below
google is good in mail
yahoo is good in messenger

How can I use a for/while loop to achieve the same?
I need a script to:
$File1 needs to replace first result in File1 and $File2 needs to replace first result in File2
/usr/local/psa/bin/domain --create domain $File1 -mail_service true -service-plan 'Default Domain' -ip 1.2.3.4 -login $File2 -passwd "abcghth"

A: The standard procedure (in Bash) is to read from different file descriptors with the -u switch of read:
while IFS= read -r -u3 l1 && IFS= read -r -u4 l2; do
    printf '%s is good in %s\n' "$l1" "$l2"
done 3<file1 4<file2

A: While loop is possible but there is easy way
paste File{1,2} -d% | sed 's/%/ is good in /'

- % can be any symbol
But if you insist on loop you can use ones offered by gniourf_gniourf or simply dumb underlined
mapfile -t A < File1
mapfile -t B < File2

if [ ${#A[*]} -lt ${#B[*]} ]
then
  L=${#A[*]}
else
  L=${#B[*]}
fi

n=-1
while [ $[++n] -lt $L ]
do
  printf "%s is good in %s\n" "${A[$n]}" "${B[$n]}"
done


text:
Q: Mostrar array por JOptionPane y recoger resultado tengo un problemilla. Quiero mostrar un array en un JOptionPane, lo hago asi.
String[] continentes = { "ANorte", "ASur", "Africa", "Europa", "Asia", "Oceania" };
JOptionPane.showMessageDialog(null, Arrays.toString(continentes));

Asi, muestro el array por el JOptionPane, pero el problema, es cuando quiero que me ingrese uno de esos valores, u otro, ya me encargare yo de hacer una excepcion.
Pare recoger un dato de un JOptionPane, suelo hacer esto:
String aux= JOptionPane.showInputDialog("Introduce algo");

Y ahora, aux, tiene un string con lo que ha introducido, pero si pongo:
String aux = JOptionPane.showMessageDialog(null, Arrays.toString(continentes));

Me da este error,

Type mismatch: cannot convert from void to String[]

y no se como solucionarlo. Quiero que me aparezca un cuadrado para introducir un nombre y poder recogerlo.
Doy las gracias a todos, seguramente sera un fallo muy simple, pero no he encontrado nada.

A: showMessageDialog no retornara nada (puesto su firma indica que el return type es Void.) recuerda que showMessageDialog es unicamente para mostrar un mensaje. lo que deseas hacer es un showInputDialog con Opciones, por tanto:
Tomando como Referencia el Tutorial de Oracle Con respecto a Jdialogs link aqui
tenemos que:
showInputDialog es lo que deseamos utilizar. dada tu necesidad tenemos opciones:

String[] continentes = { "ANorte", "ASur", "Africa", "Europa", "Asia", "Oceania" };

String[] continentes = {"ANorte", "ASur", "Africa", "Europa", "Asia", "Oceania"};
/*
   JOptionPane.showInputDialog( <Ventana padre>,
   "mensaje a desplegar",
   "titulo de la ventana",
    Tipo de JoptionPane,
    Icono,
    Opciones,
    Opcion default);
*/
Object selection = JOptionPane.showInputDialog(null,"Elija un Continente",
"Seleccion",JOptionPane.QUESTION_MESSAGE,null,continentes,null);
//si se cierra la ventan o le da cancel el objecto selection es nulo por tanto verificar eso
if(Objects.isNull(selection)){
    System.out.println("opcion invalida!");
}else{
    System.out.printf("opcion elegida: %s",selection);
    System.out.println();
}

y esto se vera asi:

Consideraciones importantes: JOptionPane.showInputDialog retorna un Object por tanto se debe verificar que no sea nulo y cuando se utilize sea String (que es muy probable pero no esta garantizado.)


text:
Q: ¿Como integrar siris famework de Go con ReactJs? En un proyecto ya esta definido que vamos a usar Golang para el Backend y su framwork Siris, pero para el Frontend se va a usar react. No he visto antes esa integracion.

A: Estaba viendo que Siris utiliza los metodos HTTP, como GET, POST, UPDATE, DELETE, hay un cliente http muy fácil de usar y muy efectivo llamado Axios
https://github.com/axios/axios
la documentación es muy clara
veo que siris en main se encuentra este metodo
  // Method GET: http://localhost:8080/profile/anytypeofstring
    app.Get("/profile/{username:string}", profileByUsername)

en axios vas a usar algo así
axios.get('/profile?username=nombre')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

como utiliza promesas te devolverá una respuesta del servidor, o un error.
hace poco construí una aplicación con vuejs, axios y go funciona excelente. saludos


text:
Q: Generate a 2D boolean array from tuples How can I generate a 2D boolean array using a list of tuples that shows the indices of the True values?
For example I have the following list of tuples:
lst = [(0,1), (0, 2), (1, 0), (1, 3), (2,1)]

What I do is, I first generate an array of False's:
arr = np.repeat(False, 12).reshape(3, 4)

Then, iterate over the list to assign True values:
for tup in lst:
    arr[tup] = True
print(arr)
array([[False,  True,  True, False],
       [ True, False, False,  True],
       [False,  True, False, False]], dtype=bool)

It seems like a common use case to me so I was wondering if there is a built-in method for this, without the loops.

A: zip(*...) is a handy way of 'transposing' a list of lists (or tuples). And  A[x,y] is the same as A[(x,y)].
In [397]: lst = [(0,1), (0, 2), (1, 0), (1, 3), (2,1)]

In [398]: tuple(zip(*lst))    # make a tuple of tuples (or lists)
Out[398]: ((0, 0, 1, 1, 2), (1, 2, 0, 3, 1))

In [399]: A=np.zeros((3,4),dtype=bool)  # make an array of False

In [400]: A[tuple(zip(*lst))] = True  # assign True to the 5 values

In [401]: A
Out[401]:
array([[False,  True,  True, False],
       [ True, False, False,  True],
       [False,  True, False, False]], dtype=bool)

A: You can use multidimensional indexing for this:
>>> lst = np.array(lst)
>>> arr = np.repeat(False, 12).reshape(3, 4)
>>> arr[lst[:,0], lst[:,1]] = True
>>> arr
array([[False,  True,  True, False],
       [ True, False, False,  True],
       [False,  True, False, False]], dtype=bool)

A: Here's an approach using NumPy's linear indexing that works for tuples of any lengths intended to generate multi-dimensional arrays -
# Convert list of indices to a 2D array version
idx = np.array(lst)

# Decide on the shape of output array based on the extents, then initialize
shp = idx.max(0)+1
out = np.zeros(shp,dtype=bool)

# Using np.put insert 1s in out at places specified by linear indices version
np.put(out,np.ravel_multi_index(idx.T,shp),1)

Sample input, output -
In [54]: lst
Out[54]: [(0, 1, 3), (0, 2, 2), (1, 0, 0), (1, 3, 1), (2, 1, 3)]

In [55]: out
Out[55]:
array([[[False, False, False, False],
        [False, False, False,  True],
        [False, False,  True, False],
        [False, False, False, False]],

       [[ True, False, False, False],
        [False, False, False, False],
        [False, False, False, False],
        [False,  True, False, False]],

       [[False, False, False, False],
        [False, False, False,  True],
        [False, False, False, False],
        [False, False, False, False]]], dtype=bool)


text:
Q: arduino gets response 301 when making a HTTPS GET request I am making a simple arduino app that send a GET request to a HTTPS site. The code I'm using is exactly the same as the code in the MKRGSM library examples (GsmSslWebClient). But for whatever reason I always get the same response when connecting to a HTTPS site: "301 moved permanently". I kind of know what that means, I am aware that you are supposed to just make another request to the location specified in the header. But I don't know what I have to change to be able to address a https site. I'm sorry for my ignorance and I do know that in the example it clearly states that it connects to http://www.arduino.cc/asciilogo.txt but why is it then any different than the normal http example?
I would also point out here, that I have tried changing port to 80 and client settings, to work for unprotected http which works just fine. So its just the https that doesn't work.
this is the code:
/*
  Web client

 This sketch connects to a website using SSL through a MKR GSM 1400 board. Specifically,
 this example downloads the URL "http://www.arduino.cc/asciilogo.txt" and
 prints it to the Serial monitor.

 Circuit:
 * MKR GSM 1400 board
 * Antenna
 * SIM card with a data plan

 created 8 Mar 2012
 by Tom Igoe
*/

// libraries
#include <MKRGSM.h>

#include "arduino_secrets.h"
// Please enter your sensitive data in the Secret tab or arduino_secrets.h
// PIN Number
const char PINNUMBER[]     = SECRET_PINNUMBER;
// APN data
const char GPRS_APN[]      = SECRET_GPRS_APN;
const char GPRS_LOGIN[]    = SECRET_GPRS_LOGIN;
const char GPRS_PASSWORD[] = SECRET_GPRS_PASSWORD;

// initialize the library instance
GSMSSLClient client;
GPRS gprs;
GSM gsmAccess;

// URL, path and port (for example: arduino.cc)
char server[] = "arduino.cc";
char path[] = "/asciilogo.txt";
int port = 443; // port 443 is the default for HTTPS

void setup() {
  // initialize serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Starting Arduino web client.");
  // connection state
  bool connected = false;

  // After starting the modem with GSM.begin()
  // attach the shield to the GPRS network with the APN, login and password
  while (!connected) {
    if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &&
        (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) {
      connected = true;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, port)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.print("GET ");
    client.print(path);
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(server);
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.available() && !client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    for (;;)
      ;
  }
}

and this is the output:
Starting Arduino web client.
connecting...
connected
HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Thu, 19 Nov 2020 20:24:07 GMT
Content-Type: text/html
Content-Length: 178
Connection: close
Location: https://www.arduino.cc/asciilogo.txt
Strict-Transport-Security: max-age=500; includeSubDomains
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block

<title>301 Moved Permanently</title>

301 Moved Permanently

nginx

disconnecting.

It is also possible that I'm just stupid and the answer is clear as day, but if somebody could please tell me exactly what to do, maybe even put an example, that would be greatly appreciated.
I haven't really tried much except changing the setting to see if they work for normal http and some other libraries that worked even worse. Sadly that's all I could find on the internet since I'm not that skilled to be messing with libraries on my own. I am using arduino mkr gsm 1400.
Be sure to call me out if I missed to mention any detail that could help solving this issue
Thanks to anybody that can help me in advance.