text:
Q: Porting 'sh 1.11'-based code to Windows All signs seem to indicate that my script is fully operational within a Linux environment and as far as I can tell, the only thing keeping it from working in Windows is my usage of sh, which is pretty straightforward:
from sh import convert

convert(inputfile, '-resize', r, '-quality', q, '-strip', outputfile)

This translates to a bash line:
convert image.jpg -resize 350x350 -quality 80 -strip ./small/export.jpg

where the r and q variables are any given resolution or quality.

Running this in Windows of course raises an error because 'sh' is completely non-functional in Windows :( I tried replacing 'sh' with the deprecated pbs, but am not having any luck. This is what I've got so far:
import pbs

pbs.convert('-resize', r, '-quality', q, '-strip', inputfile, outputfile)

The error being raised is:
  File "C:\Python27\lib\site-packages\pbs.py", line 265, in _create
    if not path: raise CommandNotFound(program)
pbs.CommandNotFound: convert

Question:

How do I successfully pass these ImageMagick commands from my script while in a Windows environment?

A: Following Kevin Brotcke's answer, this is the hack we went with:
try:
    import sh
except ImportError:
    # fallback: emulate the sh API with pbs
    import pbs
    class Sh(object):
        def __getattr__(self, attr):
            return pbs.Command(attr)
    sh = Sh()

A: pbs.CommandNotFound error message is because pbs does not have a convert method. Instead you need to use the Command method:
import pbs
convert = pbs.Command('convert')

Now you can use it similar to sh:
convert(inputfile, '-resize', r, '-quality', q, '-strip', outputfile)

A: Sub process is your best bet. While, as you said it isn't the easiest to learn, it is really useful. I would look at this indepth tutorial. Of course, read the docs too.
As to your specific problem, sh has been around longer than pbs, so it almost certainly has more functions. Looking through the source (pbs.py), I found no function named convert(). Also, you changed the arguments you called from sh to pbs (you didn't put an inputfile). Finally, there is no function named convert() in sh.py from the git repo, so I suspect you are confusing it with convert from something else.
Beyond that, you should be able to use pbs and subprocess in conjunction.

A: You could use stdlib's subprocess module, to run the command on Windows:
#!/usr/bin/env python
from subprocess import check_call

check_call(r'c:\path\to\ImageMagick\convert.exe image.jpg -resize 350x350 -quality 80 -strip small\export.jpg')

It is important to provide the full path with the file extension otherwise a different convert command may be chosen.
check_call() raises an exception if convert exits with non-zero status. You could use subprocess.call() and check the status manually instead.


text:
Q: Button Inside Gridview Inside Update Panel Not Working I'm just starting to use Update Panels in my solutions, so I'm slowly getting familiar with them.  I have a GridView that has a delete button associated with each row displayed. When I click on the delete button, it's OnClick event should displays a panel which acts as semi-modal confirmation box (done as a lightbox) to delete the record associated with the relevant row.  However, when I click the button, the panel doesn't show because all of it is in a Update Panel. Works fine without the update panel
Any ideas?
Here's a stripped down version of my code:

<form id="form1" runat="server">
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:GridView ID="GridView1" runat="server" DataSourceID="DataSourceGridView1">
                <Columns>
                    <asp:templatefield HeaderText="Name">
                        <ItemTemplate><asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("MyFieldName") %>' /></ItemTemplate>
                    </asp:templatefield>
                    <asp:TemplateField HeaderText="Delete">
                        <ItemTemplate><asp:LinkButton ID="LinkButtonDelete" runat="server" OnClick="LinkButtonDelete_Click"></asp:LinkButton></ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
            <asp:SqlDataSource ID="DataSourceGridView1" runat="server" ConnectionString="<%$ ConnectionStrings:MyString %>" SelectCommand="MySelectCommand" SelectCommandType="StoredProcedure"></asp:SqlDataSource>
        </ContentTemplate>
    </asp:UpdatePanel>
    <asp:Panel runat="server" ID="PanelConfirmMessage" Visible="false">

Are you sure you want to continue?

        <asp:Button runat="server" ID="ButtonYes" Text="Yes" OnClick="ButtonYes_Click" />
        <asp:Button runat="server" ID="ButtonNo" Text="No" OnClick="ButtonNo_Click" />
    </asp:Panel>
    <asp:Panel runat="server" id="PanelConfirmLightBox" Visible="false"></asp:Panel>
</form>

A: To post back your gridview template field control from update panel you can add the control to the Trigger collection in the code behind on the DataBind event of the item.
So try add this OnDataBinding of LinkButton :
   protected void PostBackBind_DataBinding(object sender, EventArgs e)
{
   LinkButton lb = (LinkButton) sender;
   ScriptManager sm = (ScriptManager)Page.FindControl("scriptmanagerId");
   sm.RegisterPostBackControl(lb);
}

<asp:ScriptManager ID="scriptmanagerId" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:GridView ID="GridView1" runat="server">
                <Columns>
                    <asp:templatefield HeaderText="Name">
                        <ItemTemplate><asp:TextBox ID="TextBox1" runat="server" Text='<%#Eval("name") %>' /></ItemTemplate>
                    </asp:templatefield>
                    <asp:TemplateField HeaderText="Delete">
                        <ItemTemplate><asp:LinkButton ID="LinkButtonDelete" runat="server" Text="Delete" OnClick="LinkButtonDelete_Click" OnDataBinding="LinkButtonDelete_DataBinding"></asp:LinkButton></ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </ContentTemplate>
    </asp:UpdatePanel>

A: Thanks all for you help.  I was provided an answer through the help of someone else.  The answer was simple. All I had to do was place the confirmation inside the update panel along with everything else.
Shortened version with fix:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:GridView ID="GridView1"...>
            <Columns>....</Columns>
        </asp:GridView>
        <asp:SqlDataSource ...></asp:SqlDataSource>

        <asp:Panel runat="server" ID="PanelConfirmMessage" Visible="false">
        ...
        </asp:Panel>
        <asp:Panel runat="server" id="PanelConfirmLightBox" Visible="false"></asp:Panel>
    </ContentTemplate>
</asp:UpdatePanel>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Event Receiver issue with updating Splistitem fields only when i save as a document from Office Word? I have a problem with updating Splistitem fields only when i save as via Office Word a document to Sharepoint in my Event receiver.
it's works when i add the document from Sharepoint.
here is my Code :
public override void ItemAdded(SPItemEventProperties properties)
{
    base.ItemAdded(properties);
    properties.ListItem["Status"] = "Approved";
}


text:
Q: web3 getTransaction receiver I have tried using web3.eth.getTransaction to retrieve the receiver address. However, the return result "to: 0x55d398326f99059fF775485246999027B3197955" is the token address instead of the receiver address. The receiver suppose is "0xdd7dac811ad166b30e97c37bc450d7851e5c6971". Anyone got faced this issue before?
below is my source code:
let provider = new Web3.providers.HttpProvider('https://bsc-dataseed2.binance.org/');

let web3 = new Web3(provider);

let testing = await web3.eth.getTransaction('0x12bc57ac6f0056588af06b033848b453c3ed0ee4f3a1cc8a7550a617d82ac1e5')

console.log(testing)
Response return:

{
  blockHash: '0x0ff3577a6d5f755ee01c3b24b8146ad424ca501ebb4d046ae978e02ac3ddda1c',
  blockNumber: 22335057,
  from: '0x0EdeF9ef3088a71bdAf43b5dE9E113789d5f58BF',
  gas: 51115,
  gasPrice: '5050000000',
  hash: '0x12bc57ac6f0056588af06b033848b453c3ed0ee4f3a1cc8a7550a617d82ac1e5',
  input: '0xa9059cbb000000000000000000000000dd7dac811ad166b30e97c37bc450d7851e5c69710000000000000000000000000000000000000000000000056bc75e2d63100000',
  nonce: 6,
  to: '0x55d398326f99059fF775485246999027B3197955',
  transactionIndex: 18,
  value: '0',
  type: 0,
  v: '0x93',
  r: '0x2d426a97974e354c526be2a0ca680da98a33b7c7fe166aa2edecd616ff376f8f',
  s: '0x7cdf297d1f1f2c8ba62d591857d1f0c5e65ba0e440fe5448527df42ee323f3c9'
}

A: You need to use getTransactionReceipt and decode logs get the receiver's address.

<script src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.8.0/web3.min.js"></script>
<script>
async function getReceipt() {
    let provider = new Web3.providers.HttpProvider('https://bsc-dataseed2.binance.org/');

    let web3 = new Web3(provider);

    let receipt = await web3.eth.getTransactionReceipt('0x12bc57ac6f0056588af06b033848b453c3ed0ee4f3a1cc8a7550a617d82ac1e5')

    let data = web3.eth.abi.decodeParameters(
        [
            { type: 'address', name: 'receiver' },
        ],
        receipt.logs[0].topics[2]
    );

    console.log(data.receiver)
}

getReceipt();
</script>


text:
Q: How to do Hybrid Encryption in NodeJS in given below steps? Steps for Encryption
1) Generate a 16 digits random number. Say RANDOMNO.
2) Encrypt RANDOMNO using RSA/ECB/PKCS1Padding and encode using Base64. Say encryptedKey.
3) Perform AES/CBC/PKCS5Padding encryption on request payload using RANDOMNO as a key and iv-initialization vector. Say encrypted_data.
4) Now client may choose to send IV in request from one of the below two options.
a. Send Base64 Encoded IV in the "iv" tag. (Recommended Approach)
b. Send IV as a part of encrypted data itself.

bytes[] iv = IV
bytes[] cipherText = symmetrically encrypted Bytes (step3)
bytes[] concatB = iv + cipherText
encryptedData= B64Encode(concatB)

Please can someone help me on the above?. I tried my level best to find the solution.
I tried the bellow query, I am not sure that this is wrong or right
var request = require("request");
var crypto = require('crypto');
var fs = require('fs');

var object = {name : "Test", age : '28'}

var keyProfile = crypto.createPublicKey(fs.readFileSync(__dirname + '/publickey.txt'));
  var packetData = Buffer.from(JSON.stringify(object));

var randomno = 'SwAW1D8kbcXVrq31'//Randomly generated string of length 16 (OR 32).
  var encryptedKey = crypto.publicEncrypt({ key: keyProfile, padding: crypto.constants.RSA_PKCS1_PADDING }, Buffer.from(randomno)).toString('base64');

  // Symmetric encryption
  var iv = crypto.randomBytes(16);
  var cipher = crypto.createCipheriv('aes-128-cbc', randomno, iv);
  var encryptedData = cipher.update(packetData, 'utf8', 'base64');
  encryptedData += cipher.final('base64');
  console.log(encryptedData)

A: var request = require("request");
var crypto = require('crypto');
var fs = require('fs');
var object = {name : "Test", age : '28'}
var keyProfile = crypto.createPublicKey(fs.readFileSync(__dirname + '/publickey.txt'));
var packetData = Buffer.from(JSON.stringify(object));

var randomno = 'SwAW1D8kbcXVrq31'//Randomly generated string of length 16.
var encryptedKey = crypto.publicEncrypt({ key: keyProfile, padding: crypto.constants.RSA_PKCS1_PADDING }, Buffer.from(randomno)).toString('base64');
var iv = crypto.randomBytes(16);
var cipher = crypto.createCipheriv('aes-128-cbc', randomno, iv);
var encryptedData = cipher.update(packetData, 'utf8', 'base64');
encryptedData += cipher.final('base64');
return encryptedData


text:
Q: How can viewControllerWithRestorationIdentifierPath:coder: find an existing instance? The docs on viewControllerWithRestorationIdentifierPath:coder: say:

Your implementation of this method should create (or find) the
  corresponding view controller object and return it... It is not always
  necessary to create a new view controller object in your
  implementation of this method. You can also return an existing view
  controller object that was created by another means. For example, if
  the view controller had already been loaded from a storyboard file,
  you would return that object rather than create a new one. [My italics.]

This has always seemed like complete nonsense to me. This is a class method! We don't have any access to any instances at this moment — unless we create one. I'd be grateful if someone can explain to me how on earth a class method can find or know about "the view controller that has already been loaded from a storyboard file".
EDIT: To earn the bounty you must show me an actual case, from your own app, of the class method viewControllerWithRestorationIdentifierPath:coder: being used to "return an existing view controller object that was created by another means."

A: The most common example of this I can think of is any of the view controllers that are owned by the App Delegate.  This is traditionally a tab bar controller or a navigation controller in traditional apps, but sometimes it can be something completely custom, which is when this functionality might be useful.
Since the UIApplication is pretty much a singleton and has one delegate, it means your App Delegate has global state, which makes it accessible from anywhere, including in class methods with: [[UIApplication sharedApplication] delegate].
Of course, any singleton is accessible from anywhere and a common pattern (but one I personally dislike) is to have a NavigationManager singleton which manages any global view controller transitions, so in this case you'd be able to access the existing instances as well.


text:
Q: Confused, Is raspberry pi a real device for learning embedded linux or just for hobby? and sorry i couldn't think of a better title, please read this so you can understand what i am asking:
I already bought the Pi, but as i see it has a fully featured pc like OS, what i'm seeking to learn is embedded Linux programming with Cortex-A to make devices similar to smart fridges smart thermostats drones etc.
In non of the above the user notices that it has Linux unless they check datasheets etc.
how can i learn to do programming like that? its just learning not doing it for hobby or only making things work. do devices like the ones i mention have an os like linux and run the app when being powered with some modifications? im not looking for bare-metal im looking for linux programming, and only experience i have in embedded is AVR and Arduino which are kind of different.
my friend already told me that these devices are just like pi with some modifications to run the app on start, but i saw on some website someone telling that raspberry pi is just embedded-PC and not good for learning!

A: The Raspberry Pi is an embedded Linux system.  It is running on an ARM and will give you some of the ideas of embedded design.  Whether it is "embedded enough" is a question of how far you want to go.
There are effectively two halves of embedded Linux programming.  In many situations, the developer will wear both hats, but the required knowledge can be slightly different.

*

*Systems programming.  This is the part about getting a bootloader working, the kernel building, and driver development.

*Application programming.  This is writing the actual application that the system is designed for.  This uses the system APIs and userland programming techniques.

The Raspberry Pi is especially well suited for learning the application programming role.  All of the booting and kernel building stuff is done for you, and you can get right to what you need to do.  Some people will deride it as working on a mini-PC, but that is intentional.  It is made to be easy to work with.
On the other hand, Raspberry Pi can also be a platform for learning the systems development side.  This requires a decent amount of hardware knowledge, the ability to read datasheets, and a good understanding of both the processor and Linux boot process.  This is a lot of stuff to learn! But you can take it in pieces since you have a working example.  To learn this stuff, you really need to understand what the developers of the platform have done.  To really get it, you have to do parts of it yourself.  It seems like reinventing the wheel, and it is, but it is you doing the reinventing, and you will learn things in the process.
As an aside, I find some professional developers to be very snobby about using "hobby" boards to learn.  I've done professional Linux systems development, and I'm going to tell you it's silly to think that way. We live in a time with amazing access to learning resources.  Learn where you can.


text:
Q: PHP output buffering displaying first 2 values together I am trying to get my PHP script to print its data in realtime using output buffering. For example, I have attached code for a loop that counts to 50, with a sleep delay of 1.  I would expect it to display and count it like such [echo 0, sleep 1, echo 1, sleep 1, echo 2, sleep 1, echo 3, sleep 1, echo 4, sleep 1, ... etc]. (counting like a human) However, for the initial 2 values (value 0 and 1), they appear together immediately. There is no buffer delay between the first 2 values, and they are outputted together. It doesnt echo 0 then delay 1 sec, then echo 1, delay 1... etc. It outputs value 0 and value 1, and works how I would expect it to after the initial 2 values.

Why is it outputting the first 2 values of the loop together?
<?php
header('Content-Encoding: none;');
    set_time_limit(0);
for($i=0;$i<50;$i++)
    {
    if (ob_get_level() == 0){ob_start();}
        echo $i."<br/>";
        echo str_pad('', 4096);
        ob_flush();
        flush();
        sleep(1);
    ob_end_flush();
    }
?>


text:
Q: Web browser can access webpages but games can't access servers that are not in my LAN The title tells everything: I can access websites using the browser, connect to servers within my LAN network, but I can't connect to servers that are not connected to my router.
I use:
   computer 1) wired connection - Windows 7
   computer 2) wireless connection - Ubuntu 13.10

This issue occurs on both machines.
The games I tried this on: Minecraft, Starmade, Ghost recon online and Sprial knights.

A: As this is happening across two different computers, I suggest it might be a ports issue. Make sure the ports for the games you want to play are open.
This site is a good place to start if you don't know what to do, and this page is useful in working out which ports each game requires.
Alternatively, it could possibly be a firewall issue if both your systems are running the same software (But I can't help with that without more information)


text:
Q: Exchange online retention policy not sure which policy is active We have Microsoft Online Exchange Business Plan One, and by default my retention policy is set to "Default MRM Policy". This policy is shown below and in this image:

Default MRM Policy
This policy contains the following retention tags
1 Month Delete
1 Week Delete
1 Year Delete
5 Year Delete
6 Month Delete
Default 2 year move to archive
Junk Email
Never Delete
Personal 1 year move to archive
Personal 5 year move to archive
Personal never move to archive
Recoverable Items 14 days move to archive

From this I am not able to make out which retention policy is applicable (1 week, 1 month, 1 year, etc.)
I would appreciate any clarification on this. I have checked different tutorials but they don't show clearly which policy tag is active.

A: You only have 1 policy that includes multiple tags in the policy.
So - all those tags are active.  They all do different things.  They are mix of mailbox and personal tags.  mailbox tags can be assigned from the server, such as the Archive and Deleted items (which you don't have b/c you can't set it unless you create or re-name the default policy).  Personal tags are assigned by the user in Outlook / OWA and no mailboxes/folders have them applied by default.


text:
Q: How to enable unison to login with ssh from systemd service unit? I have a pdf-sync.path file for systemd runnin in user-space (systemctl --user enable pdf-sync.path). Whenever there is a change in the folder that I defined in the path file I want to synchronize that folder with a folder on a remote server via ssh. Thus I created the pdf-sync.service file providing these informations:
[Unit]
Description=PDF Sync

Problem is that unison does not seem to find my private key in ~/.ssh
[Service]Aug 27 15:51:07 sputnik3arch env[28873]: ssh_askpass: exec(/usr/lib/ssh/ssh-askpass): No such file or directory
Aug 27 15:51:07 sputnik3arch env[28873]: Permission denied, please try again.
Aug 27 15:51:07 sputnik3arch env[28873]: ssh_askpass: exec(/usr/lib/ssh/ssh-askpass): No such file or directory
Aug 27 15:51:07 sputnik3arch env[28873]: Permission denied, please try again.
Aug 27 15:51:07 sputnik3arch env[28873]: ssh_askpass: exec(/usr/lib/ssh/ssh-askpass): No such file or directory
Aug 27 15:51:07 sputnik3arch env[28873]: Permission denied (publickey,password).
Aug 27 15:51:07 sputnik3arch env[28873]: Fatal error: Lost connection with the server

ExecStart=/usr/bin/unison pdf_mobile_sync

How will I enable unison to login via ssh from the systemd unit?


text:
Q: Given a DFA with multiple Final states. How can I find its compliment? It is not possible to have multiple start state in DFA but how can I achieve Compliment operation on DFA having multiple Final states?
I try Complimenting the language of given DFA but how multiple final states can be converted to multiple starting states

A: As pointed out in the comments, finding a DFA for compliment of the language of another DFA is quite straightforward: you simply make all accepting states non-accepting, and vice-versa. The resulting DFA may not be minimal for the language it accepts, but it is still a DFA.
You might be thinking of how to find a DFA for the reversal of a language of another DFA. This is a little more involved and encounters the issue you suggest: by reversing the direction of all transitions, making the initial state accepting and making accepting states initial, you get an automaton that works, but it has multiple initial states. This is not allowed for DFAs. Happily, we can make an NFA-lambda easily by adding a new state q0' and adding empty/lambda/epsilon transitions from it to the otherwise initial states. Now we have an NFA-lambda for the reversal of the language and we can obtain a DFA by determinizing this using a standard algorithm.


text:
Q: autoresizingMask not working as expected for UITableView.tableHeaderView's subview I'm adding a header view to my UITableView and want to add a subview to it having some margins.
class ViewController: UIViewController {

    private let tablewView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        tablewView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(tablewView)
        [
            tablewView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
            tablewView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
            tablewView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            tablewView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
        ].forEach{ $0.isActive = true}

        let headerView = UIView(frame: CGRect(x: 0, y: 120, width: 200, height: 100))
        headerView.backgroundColor = .blue

        let subView = UIView(frame: CGRect(x: 10, y: 10, width: 180, height: 80))
        subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        subView.backgroundColor = .yellow
        headerView.addSubview(subView)

        tablewView.tableHeaderView = headerView
    }
}

The problem is that the right margin isn't preserved when the header is resized (when the table view is laid out). As you can see on the image, the right margin is missing:

If I'm using the same view without UITableView, then the margin is preserved as expected.
Is it a UIKit bug? Are there any workarounds?
I know that I can try AutoLayout solutions from here Is it possible to use AutoLayout with UITableView's tableHeaderView? but they're looking a bit hacky. autoresizingMask is supposed to work, after all.

A: In Cocoa programming as in comedy, timing is everything.
Add the subview in a one-time implementation of viewDidLayoutSubviews and all will be well. The subview will appear correctly, and will continue working if the table view is resized (e.g. due to rotation of the interface).
So, cut these four lines:
    let subView = UIView(frame: CGRect(x: 10, y: 10, width: 180, height: 80))
    subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    subView.backgroundColor = .yellow
    headerView.addSubview(subView)

And instead:
var didLayout = false
override func viewDidLayoutSubviews() {
    guard !didLayout else { return }
    didLayout.toggle()
    if let h = tablewView.tableHeaderView {
        let subView = UIView(frame: h.bounds.insetBy(dx: 10, dy: 10))
        subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        subView.backgroundColor = .yellow
        h.addSubview(subView)
    }
}


text:
Q: How to mark 90 percentile in gnuplot How to mark 90 percentile in gnu plot. sample needed
plot [][] "fle.txt" using 1:2 with lines

This is how i plot the graph i want to mark the 90% in the graph
this is my data set
time(seconds)  frequency  cumulativeFrequency
10             2          2
11             6          8
12             8          16
13             10         26
14             7          33
15             5          38
16             5          43
17             4          47
18             2          49

A: I can't see any way to do this in gnuplot by itself, but it's not hard to do using python --
# percent90.py
import sys
def to_num(iterable):
    for line in iterable:
        columns = line.split()  # split into columns
        if not columns:  # empty line
            continue
        try:
            yield float(columns[1])  # This is a good number -- Yield it and keep going
        except ValueError:  # Not a number on the line
            pass            # just keep going -- do nothing
        except IndexError:
            print line

with open(sys.argv[1]) as fin:
     data = sorted(to_num(fin))

top_10 = data[int(len(data)*0.9):]  #top 10 percent of the data
print(top_10[0])

which you can call something like:
python percent90.py path/to/datafile

This will tell you where to place your mark.  As for marking it, I would probably do something like this in gnuplot:
YVAL = `python percent90.py path/to/datafile`
set arrow 1 from graph 0,first YVAL to graph 1,first YVAL ls 1 nohead front

A: If you just want to compute the 90% point of the data, this could be done with the stats or plot command and gnuplot's internal variables, then draw a line as mgilson suggested:
#!/usr/bin/env gnuplot

set terminal png
set output 'test.png'

# 'every ::1' skips header
stats 'fle.txt' every ::1

mark = (STATS_max_y - STATS_min_y)*0.9 + STATS_min_y

set arrow 1 from graph 0,first mark to graph 1,first mark ls 1 nohead front

plot 'fle.txt' every ::1

This script produces this output:


text:
Q: How to echo these foreach arrays properly? Working on a project, am pretty new to PHP and don't know how to do this in a better way.
    $item_thumbnails = array(
        "https://brkcdn.com/v2/images/shop/thumbnails/f7dd8e95-551f-5e1f-92f1-2ea6c29e61ca.png",
        "https://brkcdn.com/v2/images/shop/thumbnails/9fd1ea9d-cfd0-525a-963f-0c3438c5dc34.png"
    );

    $item_names = array(
        "brick-luke's Fedora",
        "Golden Bok"
    );

    $item_urls = array(
        "https://www.brick-hill.com/shop/20/",
        "https://www.brick-hill.com/shop/10267/"
    );

    $item_values = array(
        "30.000",
        "100.000"
    );

    $item_demands = array(
        "High",
        "Low"
    );

    foreach ($item_urls as $key => $item_url) {
    foreach ($item_thumbnails as $key => $item_thumbnail) {}
    foreach ($item_names as $key => $item_name) {}
    foreach ($item_values as $key => $item_value) {}
    foreach ($item_demands as $key => $item_demand) {}
        echo ('

            '.$item_name.'

                Value:
'.$item_value.'

                Demand:
'.$item_demand.'

        ');
    }

It only shows the latest item in the array on all tabs (if there are more).
How to fix this? Help is appreciated.

A: Something like this should work:
$item_thumbnails = array(
    "https://brkcdn.com/v2/images/shop/thumbnails/f7dd8e95-551f-5e1f-92f1-2ea6c29e61ca.png",
    "https://brkcdn.com/v2/images/shop/thumbnails/9fd1ea9d-cfd0-525a-963f-0c3438c5dc34.png"
);

$item_names = array(
    "brick-luke's Fedora",
    "Golden Bok"
);

$item_urls = array(
    "https://www.brick-hill.com/shop/20/",
    "https://www.brick-hill.com/shop/10267/"
);

$item_values = array(
    "30.000",
    "100.000"
);

$item_demands = array(
    "High",
    "Low"
);

// iterate over one array and get values from
// other arrays under the same key `$key`
foreach ($item_urls as $key => $item_url) {
    echo ('

        ' . $item_names[$key] . '

            Value:
' . $item_values[$key] . '

            Demand:
' . $item_demands[$key] . '

    ');
}

A: First of all you should improve your array structure.
$items = array(
  [
    "thumbnail" => "https://brkcdn.com/v2/images/shop/thumbnails/f7dd8e95-551f-5e1f-92f1-2ea6c29e61ca.png"
    "name" => "brick-luke's Fedora",
    "url" => "https://www.brick-hill.com/shop/20/",
    "value" => "30.000",
    "demand" => "High"
  ],
  [
    "thumbnail" => "https://brkcdn.com/v2/images/shop/thumbnails/9fd1ea9d-cfd0-525a-963f-0c3438c5dc34.png",
    "name" => "Golden Bok",
    "url" => "https://www.brick-hill.com/shop/10267/",
    "value" => "100.000",
    "demand" => "Low"
  ]
);

After that you can foreach $items variable and take data from it. See below:
<?php
foreach ($items as $item) {
?>

  <a class="image" href="<?php echo $item['url']; ?>">
    <img src="<?php echo $item['thumbnail']; ?>" onerror="this.onerror=null;this.src=<?php echo $storageUrl; ?>/error.png">

    <?php echo $item['name']; ?>

    Value:
<?php echo $item['value']; ?>

    Demand:
<?php echo $item['demand']; ?>

<?php
}
?>

Enjoy!


text:
Q: Array Not renumbering I have a situation where I have to delete a obj from an array vs .splice. What is happening is that the array is not renumbering correctly, as you can see below.
To get rid of the undefined placeholder in the array after i delete an object for the array i do a [].concat(). The problem with this is that the new array is not numbered correctly.
What is the most effective what to renumber the new array correctly with low overhead?
for (var o = 0; o < uncheckedQue[i].childNodes.length; o += 1) {
    uncheckedQue[i].removeChild(uncheckedQue[i].childNodes[o]);
    if (uncheckedQue[i].childNodes.length < 1) {
        delete uncheckedQue[i];//remove the document fragment if has no childnodes
    };
};

 uncheckedQue = [].concat(uncheckedQue);

0: DocumentFragment
2: DocumentFragment
3: DocumentFragment
4: DocumentFragment
5: DocumentFragment
6: DocumentFragment
7: DocumentFragment
length: 8

***Let me clear something up. These childNodes are contained in a document fragment that is in an array. These childNodes are not in the Dom.
Here is the outer loop. You'll notice why i use the delete, so i keep my length correct for the outer loop.
     for (var i = 0; i < uncheckedQue.length; i += 1) {
                 //
                 if (t.mucs === t.mucsstop) { break; };
                 for (var o = 0; o < uncheckedQue[i].childNodes.length; o += 1) {
                     uncheckedQue[i].removeChild(uncheckedQue[i].childNodes[o]);
                     t.mucs += 1;
                     if (uncheckedQue[i].childNodes.length < 1) {
                         delete uncheckedQue[i];//remove the document fragment if has no childnodes
                     };
                     if (t.mucs === t.mucsstop) { break; };
                 };
             };

A: childNodes is a live NodeList, so each time you remove an item, the list is shorter so you effectively skip every second node. If you want to remove all childNodes from a document fragment, the simplest way is to keep removing firstChild nodes until there are no more:
var node = uncheckedQue[i];
while (node.firstChild) {
  node.removeChild(node.firstChild);
}

Also, a NodeList is a host object, it is not an array, so calling array methods on it will throw errors.
Edit
From your code:
> for (var o = 0; o < uncheckedQue[i].childNodes.length; o += 1) {

That would be clearer in a common format:
for (var j=0; j < uncheckedQue[i].childNodes.length; j++) {

If uncheckedQue is an array of document fragments, then:
> uncheckedQue[i].removeChild(uncheckedQue[i].childNodes[o]);

is removing child nodes from a fragment. So the child node that is now at childNodes[o] is the one that was at childNodes[o + 1] before that statement was executed. So on the next iteration, the o + 1 node will be the one that was formerly at o + 2. In simple terms, it will remove every second child.
Also:
> if (uncheckedQue[i].childNodes.length < 1) {

can be:
if (!uncheckedQue[i].childNodes.length) {

since the length value of a NodeList is an unsigned integer from 0, and if length is zero then the test returns true.
To remove the fragment from the array, use Array.prototype.splice as suggested by VeXii. But note that you must adjust the index or work backwards through the array for the same reason as when deleting a member of a live NodeList.

You'll notice why i use the delete, so i keep my length correct for the outer loop.

Because the delete operator doesn't adjust the array member indexes (which are just property names), so you have a sparse array. You can either use splice and adjust the index as you go, or go backwards through the array, or compress the array at the end (which is likely the worst performing solution), e.g.
function compressArray(a) {
  for (var i=0; i<a.length; i++) {
    while (!a.hasOwnProperty(i) && a.length > i) {
      a.splice(i, 1);
    }
  }
  return a;
}

Note that the above modifies the original array. It's simpler to copy array members to a new array:
function compressArray(a) {
  for (var i=0, iLen=a.length, b=[]; i<iLen; i++) {
    if (a.hasOwnProperty(i)) {
      b.push(a[i]);
    }
  }
  return b;
}

Take your pick. Note that neither method removes members whose value is undefined or some other falsey value, only those that don't exist at all.

A: insted of delete use splice like
if (uncheckedQue[i].childNodes.length < 1) {
   uncheckedQue.splice(i,1)//remove the document fragment if has no childnodes
};


text:
Q: are there any alternatives to AppDomainSetup and CreateInstanceAndUnwrap for net-Standard2.0 Im trying to make my code compile in netStandard2.0 and cant get over this. AppDomain is supported but has limmited methods. And AppDomainSetup is not supported. i have the following code that right now is Net Framework 4.7.1 compatible. is there any alternative to make it compile on NetStandard2.0??
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = m_ApplicationBase;
setup.PrivateBinPath = m_PrivateBinPath;

setup.ApplicationName = "TemplateCompiler " + m_AppDomainCount;
setup.LoaderOptimization = LoaderOptimization.SingleDomain;
m_AppDomain = AppDomain.CreateDomain("TemplateCompiler Appdomain " +
m_AppDomainCount, null, setup);
m_AppDomain.AssemblyResolve += AppDomainAssemblyResolve;

m_RemoteLoader = (RemoteLoader) m_AppDomain.CreateInstanceAndUnwrap
(Assembly.GetExecutingAssembly().FullName, typeof(RemoteLoader).FullName);


text:
Q: bootstrap different shaped images I built this mock-up:

I was wondering if this type of gallery is possible to build with bootstrap, I did not start to code yet because I think that it will not work because of the rows.
I would like some second opinions, from people who have worked with bootstrap for longer than me.

A: I found something that actualy works!!  and it's responsive! :D

.poligono, .poligono div {
    margin: 0 auto;
    transform-origin: 50% 50%;
    overflow: hidden;
    width: 250px;
    height: 250px;
}
.poligono {
    transform: rotate(45deg) translateY(10px);
}
.poligono .los1 {
    width: 355px;
    height: 355px;
    transform: rotate(-45deg) translateY(-74px);
}
.poligono .los1 img {
    width: 100%;
    height: auto;
    -moz-transition: all 0.6s;
    -webkit-transition: all 0.6s;
    transition: all 0.6s;
}

.poligono:hover img {
    -moz-transform: scale(1.3);
    -webkit-transform: scale(1.3);
    transform: scale(1.3);
}

Projects

Cenas maradas acontecem

A: If you are asking if there is a default bootstrap for this the answer is no.
But yes this is possible with your own css.
I don't see why not you could not skew the image with something like the following:
img.tilted{
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
}

If you want this "mask like behaviour" i don't see why you couldn't put all the images on a layer bellow and put a transparent image on the top
Or you can try to css clip it like this http://www.html5rocks.com/en/tutorials/masking/adobe/


text:
Q: How to send VGA data to monitor using Visual Basic Is there a way to send vga(or any video data) to a display device via a VB application.
eg I have a desktop setup with my program running I click a play button and it send video data to a separate screen.
I have searched online and the best i can find is to get display information or to change resolution, neither of which I need.

A: 'for secondary screen
'frmplayer contain your videoplayer
if system.windows.form.screen.allscreen.count>1 then
    frmplayer.left=system.windows.form.screen.allscreen(1).bound.left
end if


text:
Q: Find specific word in input file and read the data from next row in PySpark Input File:
32535
1243
1q332|2
EOH
CUST_ID|CUST_NAME|ORDER_NO|ORDER_ITEM
1|TAM|222|ORANGE
2|AAM|322|APPLE

output
CUST_ID|CUST_NAME|ORDER_NO|ORDER_ITEM
1|TAM|222|ORANGE
2|AAM|322|APPLE

Mentioned above the input and output. I want to read input file, if found 'EOH' word in input file and convert to Dataframe from next line. Before 'EOH' rows should be ignored. Output format is given above.
sometime few rows may be added before 'EOH'.Need to pickup based on 'EOH' word.
Please share Pyspark code.

A: I don't know if this is the best approach, but here is:
from pyspark.sql.window import Window
import pyspark.sql.functions as f

df = (spark
      .read
      .format('csv')
      .option('delimiter', '|')
      .schema('CUST_ID string, CUST_NAME string, ORDER_NO integer, ORDER_ITEM STRING')
      .load(YOUR_PATH))

# Identifying which line is the header
df = (df
      .withColumn('id', f.monotonically_increasing_id())
      .withColumn('header', f.lag('CUST_ID', default=False).over(Window.orderBy('id')) == f.lit('EOH')))

# Collecting only header row to python context
header = df.where(f.col('header')).head()

# Removing all rows before header
df = (df
      .where(f.col('id') > f.lit(header.id))
      .drop('id', 'header'))

df.show()

Output:
+-------+---------+--------+----------+
|CUST_ID|CUST_NAME|ORDER_NO|ORDER_ITEM|
+-------+---------+--------+----------+
|      1|      TAM|     222|    ORANGE|
|      2|      AAM|     322|     APPLE|
+-------+---------+--------+----------+

A: If the schema is fixed as in the comment, you can pass them into from_csv
schema = """
    CUST_ID INT,
    CUST_NAME STRING,
    ORDER_NO INT,
    ORDER_ITEM STRING
"""

# if you know for sure all fields are not null then
(df
    .withColumn('value', F.from_csv('value', schema, {'sep': '|'}))
    .select('value.*')
    .where(
        F.col('CUST_ID').isNotNull() &
        F.col('CUST_NAME').isNotNull() &
        F.col('ORDER_NO').isNotNull() &
        F.col('ORDER_ITEM').isNotNull()
    )
    .show(10, False)
)

# if you unsure about the nulls, you can filter them before processing (or there are many other options)
(df
    .withColumn('tmp', F.size(F.split('value', '\|')))
    .where((F.col('tmp') == 4) & (~F.col('value').startswith('CUST_ID')))
    .withColumn('value', F.from_csv('value', schema, {'sep': '|'}))
    .select('value.*')
    .show(10, False)
)

# +-------+---------+--------+----------+
# |CUST_ID|CUST_NAME|ORDER_NO|ORDER_ITEM|
# +-------+---------+--------+----------+
# |1      |TAM      |222     |ORANGE    |
# |2      |AAM      |322     |APPLE     |
# +-------+---------+--------+----------+


text:
Q: PHP - Capture part of URL and detect URL change I am trying to achieve the above stated. Is there a way I can do the following
URL:
https://www.example.com/p/8488771-97811-test-test-test-test-test-test-test.html#/1234-567-uk_89_eu_00
How can I capture "97811" only?
As the site is also changing the link dynamically because there is a dropdown feature when user choose an item or another item, "97811" will change to automatically -
Example:
https://www.example.com/p/8488771-97812-test-test-test-test-test-test-test.html#/1234-567-uk_89_eu_00
https://www.example.com/p/8488771-97813-test-test-test-test-test-test-test.html#/1234-567-uk_89_eu_00
Thus, I need to capture and detect if there is a change in url.
I have tried with the following codes -
$_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

It is returning the full URL but I need to get only the stated number.

A: You can use the php explode function. First you can explode request_uri with delimiter '/'. It will return an array. Then you should explode again your element of the array with delimiter '-'. Hope this will help you.
You can get more about explode function here-
http://php.net/manual/es/function.explode.php


text:
Q: Examples of strict inclusion of function classes Consider the following three classes of Lipschitz functions $f:\mathbb{R}^n\to\mathbb{R}^n$:

*

*$A=\{\exists\beta,R>0:\,\langle f(x)-f(y),x-y\rangle\leq-\beta|x-y|^2\,\forall|x|,|y|>R\}$

*$B=\{\exists\alpha,\beta>0:\,\langle f(x)-f(y),x-y\rangle\leq\alpha-\beta|x-y|^2\,\forall x,y\in\mathbb{R}^n\}$

*$C=\{\exists\alpha,\beta>0:\,\langle f(x),x\rangle\leq\alpha-\beta|x|^2\,\forall x\in\mathbb{R}^n\}$
We certainly have that $A\subset B\subset C$. I'm interested in explicit examples (preferably in dimension $n=1$) which show that these inclusions are strict.

A: I will give functions which serve as counterexamples, but will only provide a sketch
for why these counterexamples work.
First, consider the function
$$
f(x) = 2\sin(x) - x.
$$
Then this function is in $B$, but not in $A$.
One can show that $f$ is not in $A$ using derivatives.
One can see that there are arbitrarily large points $x$
with $f'(x)>0$, which causes a problem in the definition of $A$.
Some intuition why the function is in $B$:
If $|x-y|$ is small, then any problems caused by the $\sin$ term
can be dealt with the constant $\alpha$.
If $|x-y|$ is large, then the $\sin$ term is irrelevant relative to the $x$ term.
For the second counterexample, the function is more complicated to describe.
We require that
$$
f(0)=0,\;
f(-n) = n,\;
f(2^{2n}) = -2^{2n},\;
f(2^{2n+1}) = -2^{2n}
$$
holds for all $n\in\Bbb N$ and we interpolate linearly between these points.
Then this function is in $C$, but not in $B$.
The function has a linear growth, but has plateaus, and the size of the plateaus grows
as $|x|$ grows.
Because of $f(x)\leq -x/2$ one can show that the function is in $C$.
However, if one chooses $x=2^{2n}$, $y=2^{2n+1}$
then one can see that there are no constants $\alpha,\beta$
such that the definition in $B$ can be satisfied.


text:
Q: Discord Guild and Members Cache So my bot is needing the Guild and its members to be cached, but I can't work out how to do it.  I'm also not sure if I would need to cache in this module (and any later ones that also need caching), or if I can cache in a central one (e.g. Config/Index) and just reference back later on.    Advice needed, please!
const Discord = require('discord.js');
const config = require('../settings/config.js');
const client = require('../index.js').client;
const Guild_ID = require('../settings/configuration').BOT_SETTINGS;
const totalUsers = client.channels.fetch('883654989271154728');
const onlineUsers = client.channels.fetch('883655041813200926');
const onlineStaff = client.channels.fetch('883655107902844978');

let guild = client.guilds.fetch('867657498827948032')
.then(guild => console.log(guild.name))
.catch(console.error);

setInterval(function() {
console.log('Getting stats update..')

var userCount = client.memberCount;
var onlineCount = guild.members.cache.filter(m => m.presence.status === 'online').size
var coderCount = client.roles.get('867673073440391188').members.size;

console.log("Total Users: " + userCount);
console.log("Online Users: " + onlineCount);
console.log("Online Staff: " + coderCount);

totalUsers.setName("Total Users: " + userCount)
.then(newChannel => console.log(`Stat channel renamed to: ${newChannel.name}`))
.catch(console.error);

onlineUsers.setName("Online Users: " + onlineCount)
.then(newChannel => console.log(`Stat channel renamed to: ${newChannel.name}`))
.catch(console.error);

onlineStaff.setName("Online Staff: " + coderCount)
.then(newChannel => console.log(`Stat channel renamed to: ${newChannel.name}`))
.catch(console.error);
}, 30000)

A: fetch returns a promise which must be resolved. Whenever using .then() to resolve promises, the result is available inside the callback function.
However the there is no need to fetch channels if you have the guild object, they will be cached.
You must either use async/await or work inside of .then(). I also recommend fetching all of your GuildMembers to cache them all (this will require the guild members intent to be enabled)
To make it easier on us I'll use async/await, wrapping your code inside an update function.
async function update() {
   try {
      const guild = await client.guilds.fetch('867657498827948032');

      const totalUsers = guild.channels.cache.get('883654989271154728');
      const onlineUsers = guild.channels.cache.get('883655041813200926');
      const onlineStaff = guild.channels.cache.get('883655107902844978');

      const guildMembers = await guild.members.fetch();

      var onlineCount = guildMembers.filter(m => m.presence.status === 'online').size;

      // Access the role via the guild object
      var coderCount = guild.roles.cache.get('867673073440391188').members.size;

      // Update channel name code...
   } catch (err) {
      console.error(err);
   }
}

setInterval(update, 30000);

Note: As this function runs every 30 seconds, and multiple data are being fetched. This is considered API spam. I recommend either refactoring your function or increasing the interval significantly


text:
Q: Modeling using Stanford NER - Output Model file size I trained my own model using also my own features. The size of my training dataset is 6M only. After modeling phase, The size of my model (.gz) is 420M,
Is this normal or something goes wrong???
Thanks

A: It's not the training dataset which impacts the size of the model serialisation. It's what/how many features you employ. But a model of 420Mb is pretty usual.
As long as you manage to classify unseen text, no worries there.


text:
Q: How to randomize points on a sphere surface evenly? Im trying to make stars on the sky, but the stars distribution isnt even.
This is what i tried:
rx = rand(0.0f, PI*2.0f);
ry = rand(0.0f, PI);
x = sin(ry)*sin(rx)*range;
y = sin(ry)*cos(rx)*range;
z = cos(ry)*range;

Which results to:
img http://img716.imageshack.us/img716/3320/sphererandom.jpg
And:
rx = rand(-1.0f, 1.0f);
ry = rand(-1.0f, 1.0f);
rz = rand(-1.0f, 1.0f);
x = rx*range;
y = ry*range;
z = rz*range;

Which results to:
img2 http://img710.imageshack.us/img710/5152/squarerandom.jpg
(doesnt make a sphere, but opengl will not tell a difference, though).
As you can see, there is always some "corner" where are more points in average. How can i create random points on a sphere where the points will be distributed evenly?

A: you can do
z = rand(-1, 1)
rxy = sqrt(1 - z*z)
phi = rand(0, 2*PI)
x = rxy * cos(phi)
y = rxy * sin(phi)

Here rand(u,v) draws a uniform random from interal [u,v]

A: You don't need trigonometry if you can generate random gaussian variables, you can do (pseudocode)
x <- gauss()
y <- gauss()
z <- gauss()
norm <- sqrt(x^2 + y^2 + z^2)

result = (x / norm, y / norm, z / norm)

Or draw points inside the unit cube until one of them is inside the unit ball, then normalize:
double x, y, z;

do
{
    x = rand(-1, 1);
    y = rand(-1, 1);
    z = rand(-1, 1);
} while (x * x + y * y + z * z > 1);

double norm = sqrt(x * x + y * y + z * z);
x / norm; y /= norm; z /= norm;

A: It looks like you can see that it's the cartesian coordinates that are creating the concentrations.
Here is an explanation of one right (and wrong) way to get a proper distribution.


text:
Q: Fitting a function that contains a numerical derivative Imagine I want to Fit a data to a simple function as following:
    f[c]=ND[Exp[c x],x,??]
FindFit[data,f[c],c]

where ND is numerical derivative.
Could you please tell me what can put instead of "??" for this function to do fitting.
Thanks a lot


text:
Q: How to replace exact string in a statment using regular expressions I have couple of insert statments like below with STRINGDECDOE()
INSERT INTO EPSG_ALIAS
   (ALIAS_CODE, OBJECT_TABLE_NAME, OBJECT_CODE, NAMING_SYSTEM_CODE, ALIAS, REMARKS)
 VALUES
   (1431, 'Datum', 6123, 7300, STRINGDECODE('Kartastokoordinaattij\ufffdrjestelm\ufffd (1966)'), NULL);

How to replace the STRINGDECODE('Kartastokoordinaattij\ufffdrjestelm\ufffd (1966)') with
e'Kartastokoordinaattij\ufffdrjestelm\ufffd (1966)'

Using Regular expression in java

A: This will work even with "quoted single quotes" in the text (ie, for instance, 'It''s working':
private static final Pattern PATTERN
    = Pattern.compile("\\bSTRINGDECODE\\(('[^']*(?:''[^']*)*')\\)");

// in code:

PATTERN.matcher(theInput).replaceAll("e$1")


text:
Q: If/else statement in foreach query in neo4j I would like to duplicate every node in my graph by using foreach loop. I try to use if/else statement to create specific kind of node - (:Node) if n:Node has 'Node' label and (:Road) if r:Road has 'Road label. How to fix this query?
MATCH p=((n:Node)-[:STARTS]-(r:Road)-[:ENDS]-(z:Node))
FOREACH (x in nodes(p) |
WITH CASE head(labels(x))
WHEN 'Node'
THEN
CREATE (:Node {name : x.name, subID : ID(x)})
ELSE
CREATE (:Road {name : x.name, subID : ID(x)}))

A: You don't need to do any FOREACH, you can just create them :
MATCH p=((n:Node)-[:STARTS]-(r:Road)-[:ENDS]-(z:Node))
CREATE (:Node {name : n.name, subID : ID(n)})
CREATE (:Road {name : r.name, subID : ID(r)})


text:
Q: refrescar tabla desde una api Angular 6 Hola no se en q estoy fallando estoy llenando una tabla desde un servicio (API) y no se por que no se actualiza bien si responde al segundo producto que agrego pero no al primero y una vez q comenzó a agregar después continua perfectamente lo mismo al eliminar (la api es php ).-

en el componente

agregarTablaEdit(dib: any)
{
this.dibServ.altaDib(this.dib).subscribe();
this.ngOnInit();
this.RefrezcarDatos();
this.router.navigate(['/dibEditClean'])
}

Miren que puevo con tres métodos con "ngOnInit" una "funcion refrezcar datos " y "enviando a otro componente y regresando" este ultimo me funciona pero me reinicia las variables cada vez inicia

 RefrezCardatos(){
this.dibServ.obtenerDib().subscribe(
result => this.DIBcompu = result);
this.dibServ.obtenerDibFecha().subscribe(
result => this.DIBFEC = result);}

en html

    {{item.caravana}}
    {{item.raza}}
    {{item.peso1}}
    {{item.peso2}}
    {{item.adpv1| number:'.3-3'}}
    {{item.peso3}}
    {{item.adpv2 |number:'.3-3'}}
    {{item.ciclicidad}}
    {{item.numero}}
    {{item.utero}}
    {{item.gdr}}
    {{item.servicio}}
    {{item.peso4}}

      <button class="btn btn-secondary mr-2" data-toggle="modal" data-target="#EditarAnimal"(click)="EditDIB(item,divFecha)" ></button>
      <button class="btn btn-warning " (click)="bajaDibTemp(item.id)"   ></button>


text:
Q: Custom INSTALL_REFERRER receiver with multiple tracking services After update google play services to 7.0.3 my custom INSTALL_REFERRER braodcast receiver got broken.
I used CampaignTrackingService (which got the update also) to forward the intent to google analytics.
in AndroidManifest.xml
    <receiver
        android:name="myapp.analytics.installReferrer.InstallReferrerBroadcastReceiver"
        android:exported="true">
        <intent-filter>
            <action android:name="com.android.vending.INSTALL_REFERRER" />
        </intent-filter>
    </receiver>

And my Custom BroadCastReceiver (and here is the problem):
    public class InstallReferrerBroadcastReceiver extends BroadcastReceiver{

private final static String TAG = InstallReferrerBroadcastReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
    // Send to Different Analytics services

    // Send to Google Analytics
    CampaignTrackingService campaignTrackingService = new CampaignTrackingService();
    // I used onHandleIntent() in google-play services 7.0.0, in 7.3.0 its gone
    campaignTrackingService.onHandleIntent(intent);
    }
}

A: Try extending CampaignTrackingReceiver instead of BroadcastReceiver. Then in your onReceive method call super.onReceive(context, intent); Also you are calling the Service from the Receiver. Analytics provides both the CampaignTrackingService and CampaignTrackingReceiver. When you are providing your own receiver implementation you should pass the call to Analytics CampaignTrackingReceiver.onReceive instead of direct call to the service. Android guarantees that your app process will not be killed before you return from onReceive but the app process might be killed before the service had started and you will loose the campaign. Analytics provided receiver will correctly do the handoff to the service to avoid this problem (it requires partial wake lock permission).


text:
Q: Finding an irrational function with horizontal asymptotes y=1 and y=5 I can't seem to find an irrational function with $2$ horizontal asymptotes $y=1$ and $y=5$.
I've looked everywhere and tried all I know, I keep getting $2$ asymptotes that the contrary of each other eg. $y=1$ and $y=-1$.
(The function can't be a composition of 2 functions and it HAS to be an irrational function)
I'd appreciate any help!
Thanks in advance.
**EDIT:
I THINK THIS IS THE CORRECT ANSWER
$$
f(x)=\frac{2x-1}{\sqrt{x^2-1}}+3
$$

A: Hint: Two strictly increasing functions taking values in $(-1, 1)$ are
$$
f(x) = \tanh x = \frac{e^{x} - e^{-x}}{e^{x} + e^{-x}},\qquad
g(x) = \frac{x}{\sqrt{1 + x^{2}}}.
$$
If $a$ and $b$ are real numbers, consider a function of the form $h(x) = a + bf(x)$ or $a + bg(x)$.

A: This is the most ''similar'' to a rational function that i can find:
$$
y=\dfrac{2x^2+3|x|x+|x|}{x|x|}
$$
If you consider irrational a function where $x$ is under a root, than subsitute $|x|=\sqrt{x^2}$ and the function is ''irrational''.


text:
Q: Can´t Connect on Plugin Registration Tool Crm dynamics 2016 (On premise) I can´t login into Plugin Registration Tool (Crm 2016 on premise), i use server IP, and the name of the server, and credential of a user with System Administrator role.
When a not use a port (like 5555 or 443), the tool show me a list of my two organizations, but i select any one, i press acept, show the list again but empty (no organizations listed).
The implementation of Crm Server listening all for the port 443 in https.
Another behavior its occurs when a disable a organization, a let enable only a default organization (in other words, a enable a single organization), in this case i cant retrieve any organizations.
I test to navigate on web service, service detection, discovery and the test are succesfully.
Anyone can help about this issue
Thanks a lot

A: Use the Organization Service URL from Developer Resources screen from within CRM.  Also make sure that your credentials are correct.

A: I test using Login Control Tester provided in CRM SDK 2016, in the "Bin" folder. I check the user and this have role permission in CRM and are Admon account of Domain, also the same user is using for the CRM´s associated services
enter image description here


text:
Q: How can access the random numbers using Random.Range( ) from different script? I'm stuck at this very simple lines of code in Unity2D using C#. Simply i just want to access a random number generated from a different script.
//Script A
void Start(){
    int rand;
    rand = Random.Range(0,4);
    myString1 = myArray[rand];
}

//Script B
public ScriptA obj;
public string[] myString2;
public string nj;
void Start(){
    myString2 = new string[] {
        "A" ,
        "B",
        "C",
        "D"
    };
    nj = myString2[obj.rand];
    guiText.text = nj;
}

Everything works just fine, my GUIText Shows, my Random no is generated perfectly in Script A, but when i does access it in Script B, it return 0 only i.e only A, even if the random generated number is 2 or 3, it prints A in GUIText.
Trust me i just sorted problems within my project,but still it doesn't behaving the way i wanted to be.
I mean seriously, GUIText shows only A, i need A,B,C & D randomly..
Plz anyone help me with these..!!

A: The variable rand is only accessible locally in void Start() for Script A.
Try this in Script A
public int rand {get; set;}
void Start(){
    rand = Random.Range(0,4);
    myString1 = myArray[rand];
}


text:
Q: PHP populate formatted date (only month and year) into drop down list, but delete duplicates Im trying to get the dates from the DB, store only the months and years of them into a var, populate the drop drown list with the results, but delete any duplicate month and year.
For example my drop down list is displaying:

*

*Jun 14

*Jun 14

*Jul 14

*Aug 14

*Aug 14

*Aug 14

*Sep 14

*Jan 15

*Feb 15

*Jun 15

*Jun 15

And I only want it do to display one month (with year) each option.
Here's my code:
            <select name="month">
                <?php
                    $sSDate = "SELECT DISTINCT eventStartDate FROM te_events GROUP BY eventStartDate ORDER BY eventStartDate ASC";
                    $qrSDate = mysql_query($sSDate) or die (mysql_error());
                    while($rowSDate = mysql_fetch_assoc($qrSDate))
                    {
                        $s_event_start_date = $rowSDate ['eventStartDate'];

                        $sGetStartDate = strtotime($s_event_start_date);
                        $sFormattedStartDate = date('M y', $s_event_start_date );

                        echo '
                        <option value="'.$sFormattedStartDate.'">
                            '.$sFormattedStartDate.'
                        </option>
                        ';
                    }
                ?>
            </select>

A: Use sql: Select distinct Year(eventStartDate), month(eventStartDate) from ...


text:
Q: Idiomatic Kotlin way to find an element to the right of a pivot that's just greater than the pivot I would like to write a computer program such that given an array of numbers and a pivot index, it returns the index of the smallest element to the right of the pivot that is just greater than the pivot.
For example: if the input is [1, 4, 7, 2, 5, 6] and the pivot is at index 1 i.e. element 4, then the output should be 4 which is the index of 5 because 5 is the smallest element to the right of 4 that is greater than 4.
The following code works
fun justGreater(nums: IntArray, pivotIndex: Int): Int {
    var result = 0
    var currBest = Int.MAX_VALUE
    for (i in pivotIndex until nums.size) {
        if (nums[i] > nums[pivotIndex] && nums[i] < currBest) {
            result = i
            currBest = nums[i]
        }
    }
    return result
}

I would like to write this idiomatically and succinctly.

A: Just a little improvement
fun IntArray.justGreater(pivotIndex: Int): Int {
    var result = 0
    var currBest = Int.MAX_VALUE
    for (i in pivotIndex until size) {
        if (get(i) > get(pivotIndex) && get(i) < currBest) {
            result = i
            currBest = get(i)
        }
    }
    return result
}

I think there is no shortcut function to decrease code

A: This returns the smallest closest value position to the right of pivot:
fun justGreater(nums: IntArray, pivotIndex: Int): Int {
    val least = nums.asList()
        .subList(pivotIndex + 1, nums.size)
        .filter { it > nums[pivotIndex] }
        .min()!!
    return nums.indexOf(least)
}

A: You can try following:
fun justGreater(nums: IntArray, pivotIndex: Int): Int {
    return nums.withIndex()
        .sortedBy { it.value }
        .first { it.index > pivotIndex && it.value > nums[pivotIndex] }
        .index
}

Another option:
fun justGreater(nums: IntArray, pivotIndex: Int): Int {
    return nums.mapIndexed { index, number -> index to number }
        .sortedBy { (_, number) -> number }
        .first { (index, i) -> index > pivotIndex && i > nums[pivotIndex] }
        .first // returns pair, so we need to get only index
}

One more option:
fun justGreater(nums: IntArray, pivotIndex: Int): Int {
    val filteredArr = nums.sliceArray(pivotIndex + 1 until nums.size)
        .filter { it > nums[pivotIndex] }
    return nums.indexOf(filteredArr.min() ?: -1) // we return -1 in case item was not found
}


text:
Q: Use of cut command in unix Suppose I have string as follwing:
Rajat;Harshit Srivastava;Mayank 123;5
Now i want result as following using cut command
Rajat
Harshit Srivastava
Mayank 123
5
I have tried but cut is not working on string containing spaces.

A: man cut would tell you:
   -d, --delimiter=DELIM
          use DELIM instead of TAB for field delimiter

   --output-delimiter=STRING
          use  STRING  as  the  output delimiter the default is to use the
          input delimiter

If you insist on using cut for changing the delimiters:
$ echo "Rajat;Harshit Srivastava;Mayank 123;5" | cut -d \; --output-delimiter=\  -f 1-
Rajat Harshit Srivastava Mayank 123 5

but instead you should use sed or tr or awk for it. Try man tr, for example.

A: Try this
echo "Rajat;Harshit Srivastava;Mayank 123;5" | sed 's/;/ /g'


text:
Q: why slider is not working in jquery? could you please tell me why slider is not working in jquery ?
i see this demo , but it callback function not fire ?
why ?
I take help from this url
http://rangeslider.js.org/
here is my code
<!DOCTYPE html>

    <link rel="stylesheet" href="style.css" />

Hello Plunker!

    <input type="range" min="10"
           max="1000"
           step="10"
           value="300" />

here is my code
https://plnkr.co/edit/cbh60dJcvHhAoqDlLo9g?p=preview
callback function not fire why ? when I slide the slider

A: From your example it's not clear whether you're loading the JS and CSS files for Range Slider, so that could be part of the problem.
Also, if you want it to show by default you need to change polyfill: true, to polyfill: false,.

$(function () {
    $('input[type="range"]').rangeslider({
        polyfill: false,

        onInit: function() {
            console.log('init')
        },

        // Callback function
        onSlide: function(position, value) {},

        // Callback function
        onSlideEnd: function(position, value) {
            console.log(value)

        }
    });
})

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rangeslider.js/2.3.2/rangeslider.min.css">

Hello Plunker!

<input type="range" min="10"
    max="1000"
    step="10"
    value="300"
/>


text:
Q: Azure AD B2C edit attributes In Azure AD B2C, I notice that into the Page UI customization for a policy, we can include some HTML code into the input field for text labels when we edit attribute (in the picture example for chekbox). Do you think it's a potential hack and Microsoft will block this behavior or is it an expected case ?

A: The ability to add HTML code in the input field for text labels/values is not intended to be a feature and not the intended approach to achieve UI customization. You should not rely on this as validation that prevents this can be added at any point.
To customize the UI today, you can provide your own page with a div container where Azure AD B2C will display its controls. You can certainly use CSS to further customize the look and feel of these fields. Check out this article for more info.
Azure AD B2C is also looking at adding support for custom JS which will give you further control over the UI. You can vote for that item in the Azure AD B2C UserVoice forum to support it and stay up to date on its progress


text:
Q: Const vector values vs pointer? In C++ I know how to pass a vector as pointer:
void my_func (vector<int>* arr)

But how can I implement:

*

*Make the vector const, ie don't allow change of arr = ...

*Make the values of the vector const, ie don't allow changes to the values of arr.
I read a lot of posts here but got too much confused about const meaning with complex DS like vector and others.

A: Both of your desires can be satisfied by tagging the argument as const:
void my_func(const vector<int> * arr)

... although unless you need to be able to pass a NULL-pointer for some reason, it's better to pass the array by-reference than by-pointer:
void my_func(const vector<int> & arr)

Note that you can have both (1) and (2), or neither, but not one-and-not-the-other.  Modifying the member-values of the vector is considered modifying the vector, so tagging the vector as const prohibits both types of modification.

A: Basically the situation is
void do_something( std::vector<int>* ptr_to_vec) {
    ptr_to_vec->push_back(42);
    (*ptr_to_vec)[0] = 5;
}

void cannot_do_something(const std::vector<int>* ptr_to_vec) {
    // both of the following will not compile
    //ptr_to_vec->push_back(42);
    //(*ptr_to_vec)[0] = 5;
}

A: Rule of thumb: const applies to the thing on its left, unless there is nothing there, then it applies to the thing on its right instead.
So...

Make the vector const, ie don't allow change of arr = ...

vector<int>* const arr will apply const to *, ie arr will be a const pointer to a non-const vector.  arr itself can't be changed to point at a different vector object, but the vector itself can have its members modified when accessed via arr.

Make the values of the vector const, ie don't allow changes to the values of arr.

const vector<int>* arr (or vector<int> const * arr) will apply const to vector, ie arr will be a non-const pointer to a const vector object. The vector's members can't be modified when accessed via arr, but arr itself can be changed to point at a different const vector object.
And then, you can combine the two, if needed:
const vector<int>* const arr (or vector<int> const * const arr) will make arr be a const pointer to a const vector object.  Neither the pointer nor the vector can be changed/modified.


text:
Q: A general statement I would like to make a general statement:
**The first statement about work places:

*

*In work places, the employees must respect their director.

*In work places, the employees must respect their directors.

Is it correct if I remove "the" here:

*In work places, employees must respect their director.

*In work places, employees must respect their directors.

**The second statement is about the way you pay the bill:

*

*when paying by card, the customers just have to hand out a small card to the cashiers instead of counting a pile of bank notes before giving to them.

*when paying by card, the customer just has to hand out a small card to the cashier instead of counting a pile of bank notes before giving to them.
Is it correct if I remove "the" here?

*when paying by card, customers just has to hand out a small card to cashiers instead of counting a pile of bank notes before giving to them.

=====
My questions for 2 statements:

*

*Which sentences are correct?

*What is the difference between the correct sentences.

Thank you so much.

A: In English, you generally must have an article, "the" or "a", before a singular noun. (Sometimes other adjectives eliminate the need for the article, like if you say "my" or "one".) Plurals do not require an article. Sometimes we put "the" in front of a plural to indicate we are talking about some specific group, but it's not required grammatically. Like you might say, "Songs make me feel cheerful." No "the", so songs in general. You might also say, "This album contains many songs by composer Fred Smith. The songs make me feel cheerful." The "the" here indicates that we are talking about a specific set of songs, namely, those by Fred Smith that are on this album, and not about songs in general.
In your first pair of sentences, you appear to be talking about all employees in any work place, so "the" is not necessary. It is not wrong here because it could be interpreted to mean "the employees who are in work places", as opposed to other kinds of employees. Employees working from home, perhaps? But if we think of all employees as being in some sort of work place, you could include "the" or not and it doesn't really change the meaning.
In the second set of sentences, if you say "the customers" that presumably means the customers identified by context, perhaps the customers using credit cards or whatever sort of cards you're talking about. Depending on the context, if you don't say "the" it may be clear that you are talking about customers using credit cards. Or it may mean that all customers must use cards and their is no other option. Which I don't think is what you mean. So again, the "the" is basically optional. Without it, the set of customers is probably still clear from context.
Whether you say "customers have to" or "the customer has to", either is valid. Arguably there could be an ambiguity either way. If you use the plural, someone might suppose you mean that all customers share the same card. If you use the singular, someone might suppose you mean that there is only one customer. But in this case, I'd think it's obvious from context that neither of those is what you mean. I presume you mean that each customer has his own card. If there really was possibility ambiguity, you could reword the sentence a little to make this clear.
Couple of side notes:
In sentence 3 you say "the customers just has to". But "customers" is plural and "has" is singular, so this is incorrect. It should be "the customers just have to".
In 1, 2, and 3, "counting a pile of bank notes before giving to them" is awkward. "Give" is usually transitive, that is, you should say what you are giving. Obviously you mean "counting a pile of bank notes before giving THE BANK NOTES to them", but the grammar is incorrect if you leave that out. If you put it in the sentence sounds repetitious. So you should say, "counting a pile of bank notes before giving the cash to them" or using some other synonym for "bank notes". Or in this case, I would just leave it out and say "... counting a pile of bank notes."


text:
Q: Map a book in elasticsearch with many levels, nested vs parent-child relationship When creating the mappings for an index that can search through multiple books, is it preferable to use nested mappings like below, or using documents with a parent-child relationship
book: {
  properties: {
    isbn:     {       //- ISBN of the book
      type: 'string'  //- 9783791535661
    },
    title:    {       //- Title of the book
      type: 'string'  //- Alice in Wonderland
    },
    author:   {       //- Author of the book(maybe should be array)
      type: 'string'  //- Lewis Carroll
    },
    category: {       //- Category of the book(maybe should be array)
      type: 'string'  //- Fantasy
    },
    toc: {            //- Array of the chapters in the book
      type: 'nested',
      properties: {
        html: {           //- HTML Content of a chapter
          type: 'string'  //- <!DOCTYPE html>...
        },
        title: {          //- Title of the chapter
          type: 'string'  //- Down the Rabbit Hole
        },
        fileName: {       //- File name of this chapter
          type: 'string'  //- chapter_1.html
        },
        firstPage: {      //- The first page of this chapter
          type: 'integer' //- 3
        },
        numberOfPages: {  //- How many pages are in this chapter
          type: 'integer' //- 27
        },
        sections: {       //- An array of all of the sections within a chapter
          type: 'nested',
          properties: {
            html: {           //- The html content of a section
              type: 'string'  //-
...

            },
            title: {          //- The title of a section
              type: 'string'  //- section number 2 or something
            },
            figures: {        //- Array of the figures within a section
              type: 'nested',
              properties: {
                html: {           //- HTML content of a figure
                  type: 'string'  //-
...

                },
                caption: {        //- The name of a figure
                  type: 'string'  //- Figure 1
                },
                id: {             //- Id of a figure
                  type: 'string', // figure4
                }
              }
            },
            paragraphs: {     //- Array of the paragraphs within a section
              type: 'nested',
              properties: {
                html: {           //- HTML content of a paragraph
                  type: 'string', //-
...

                }
                id: {             //- Id of a paragraph
                  type: 'string', // paragraph3
                }
              }
            }
          }
        }
      }
    }
  }
}

The size of an entire books html is approximately 250kB.
I would want to query things such as
- the best matching paragraph including it's nearest paragraphs on either side
- the best matching section from a single book including any child sections
- the best figure given it is inside a section with a matching title
- etc

I don't really know the specifics of the queries I would want to perform, but it is important to have a lot of flexibility to be able to try out very weird ones without having to change all of my mappings too much.

A: If you use the nested type, everything will be contained in the same _source document, which for big books can be quite a mouthful.
Whereas if you use parent/child docs for each chapters and/or sections, you might end up with smaller chunks which are more chewable...
As always, it heavily depends on the queries you will want to make, so you should first think about all the use cases you will want to support and then you'll be better armed to figure out which approach is best.
There's another approach which uses neither nested nor parent/child, and which simply involves denormalization. Concretely, you pick the smallest "entity" you want to consider, e.g. a section, and then simply create standalone documents for each section. In those section documents, you'd have fields for the book title, author, chapter title, section title, etc.
You can try each approach in their own index and see how it goes for your use cases.

A: nested is basically a way of stuffing everything into the same document. That can be useful for searching, but it makes certain things considerably harder.
Like - for example - if you're trying to find a particular chapter section - your query will return the correct document - the whole book. I would imagine that's probably not what you're looking for, and thus a parent/child relationship would be the appropriate way to go.
Or just don't bother, and treat book/chapter/section as separate types within an index which query and 'join' on demand.


text:
Q: ASP.NET: Path.Combine with relative paths I'm trying to convert "~/Uploads/Images/" to an absolute path I can create a FileStream from. I've tried VirtualPathUtility and Path.Combine but nothing seems to give me the right path. The closest I got was VirtualPathUtility.ToAppRelative, but that was just the file's location as a direct child of C:.
There must be a way to do this.

A: You are looking for the MapPath method.
// get the path in the local file system that corresponds to ~/Uploads/Images
string localPath = HttpContext.Current.Server.MapPath("~/Uploads/Images/");

Use it together with Path.Combine to create a file path:
string fileName = Path.Combine(
                      HttpContext.Current.Server.MapPath("~/Uploads/Images/"),
                      "filename.ext");
using (FileStream stream = File.OpenRead(fileName))
{
   // read the file
}


text:
Q: Connecting USB-powered Beaglebone to car's CAN bus through OBD connector using common signal ground I want to connect my Beaglebone Black, powered from USB port on my laptop, to OBD connector present in my Ford in order to see CAN traffic with can-utils.
Beaglebone operates on 3.3V, that's why I am using a logic level converter to interface to MCP2551 CAN transceiver operating on 5V.
I am using pins P9_26 and P9_24 from Beaglebone's header P9.

My DB9 to OBDII cable has the following pinout:

Questions:

*

*Is the connection presented on the schematic correct?

*Can I connect the Signal Ground from my Ford's OBDII connector with GND from Beaglebone (which I think equals GND from USB) safely?

*Is connecting grounds of these two separate circuits (car <-> Beaglebone/laptop) necessary?

*If the grounds are not connected - can it pose any danger to the car's transceiver/CAN computer or USB port in laptop?

A: You would think because of the differential nature of CAN and the fact that you are not drawing power from the OBD port, it would all work fine without the common ground reference.
But, you are then at the mercy of your 2 floating grounds. The CAN transcivier will have an upper limit of the common mode voltage it can tolerate. If at some point the disparity between your floating grounds is large enough to exceed that, you can damage your transcievers. This is not something you can control: so yes use a common ground.
Edit 1:
If however you MUST use floating grounds then consider other (more expensive) transeviers with isolated inputs.

A:

*

*Is the connection presented on the schematic correct?

Looks ok. Though to save cost, it might be a better idea to use a CAN transceiver with 3.3V supply. Example.

*Can I connect the Signal Ground from my Ford's OBDII connector with GND from Beaglebone (which I think equals GND from USB) safely?

Yes, though be aware that when you initially do so, you might get an ESD discharge (like when you touch a car with your fingers). Once both grounds have the same potential, it is harmless.

*Is connecting grounds of these two separate circuits (car <-> Beaglebone/laptop) necessary?

Yes. A car on rubber tires will have a completely different potential than your computer supply.

*If the grounds are not connected - can it pose any danger to the car's transceiver/CAN computer or USB port in laptop?

The circuits are fairly rugged and since there are no high currents, this is unlikely. However, it may be impossible to do any form of data communication without a signal ground, as the voltage reference for the signal levels could be anything.


text:
Q: Как удалить этот PPA репозиторий? В консоль выдает:

Ошибка GPG: http://ppa.launchpad.net trusty InRelease: Следующие подписи не могут быть проверены, так как недоступен открытый ключ: NO_PUBKEY C2518248EEA14886

Пробовал делать:
$ sudo add-apt-repository --remove ppa:launchpad.net

но ничего не выходит. как удалить его? я не могу до конца сделать apt-get update.
Вот все, что выводится в консоль:

Получено:42 http://ppa.launchpad.net trusty InRelease [15,5 kB]
  Игн http://ppa.launchpad.net trusty InRelease
  Игн http://ppa.launchpad.net trusty/main Sources/DiffIndex
  Игн http://ppa.launchpad.net trusty/main amd64 Packages/DiffIndex
  Игн http://ppa.launchpad.net trusty/main i386 Packages/DiffIndex
  В кэше http://ppa.launchpad.net trusty/main Translation-en
  В кэше http://ppa.launchpad.net trusty/main Sources
  В кэше http://ppa.launchpad.net trusty/main amd64 Packages
  В кэше http://ppa.launchpad.net trusty/main i386 Packages
  Игн http://ppa.launchpad.net trusty/main Translation-ru_RU
  Игн http://ppa.launchpad.net trusty/main Translation-ru
  Получено 627 kБ за 9с (68,8 kБ/c)
  Чтение списков пакетов… Готово
  W: Ошибка GPG: http://ppa.launchpad.net trusty InRelease: Следующие подписи не могут быть проверены так как недоступен открытый ключ: NO_PUBKEY C2518248EEA14886

ОС Debian 8

A: к сожалению, вы не привели всей информации, которую вам сообщила программа apt-get. там должно было быть указано и имя репозитория, с которым возникли проблемы.
судя по встречающимся в интернете упоминаниям строки C2518248EEA14886, этим ключом подписаны пакеты то ли в репозитории webupd8, то ли в репозитории vlc.
для «отключения» репозитория можно, например, закомментировать строки, в которых встречаются эти слова (webupd8 или vlc). нужные файлы можно найти, например, так:
$ grep -rlE '(webupd8|vlc)' /etc/apt/sources.list*

«закомментировать» — это вставить символ # в начало строки.

дополнение
если искомые слова не нашлись, стоит поискать слова ppa или trusty:
$ grep -rlE '(ppa|trusty)' /etc/apt/sources.list*

ввиду того, что в дистрибутиве debian не используется по умолчанию «левых» репозиториев (с того же, например, сайта ppa.launchpad.net), а trusty — кодовое имя одного из выпусков другого дистрибутива — ubuntu, таких строк у вас вряд ли много. попробуйте закомментировать их все. или выборочно, пока ошибка не исчезнет.


text:
Q: Add a new field to new shipping method in simple checkout module for Open Cart I try to configure simple checkout module v3.8.3 for Open Cart and I want to create a new shipping method with saving delivery date to new field (like the existed field 'comment').
How can I extend my files to carry out this?

A: My purpose was is to add custom shipping date and time.
I actually carried out this case by this way:
1.) In the 'admin/view/template/module/simple.tpl':
<option value="date" <?php echo $field['save_to'] == 'date' ? 'selected="selected"' : '' ?>>date</option>
<option value="time" <?php echo $field['save_to'] == 'time' ? 'selected="selected"' : '' ?>>time</option>

2.) In the 'catalog/controller/checkout/simplecheckout_customer.php':
private function get_date_value() {
$date = $this->simple->get_total_value(Simple::SET_CHECKOUT_CUSTOMER,'date');
        $simple_show_shipping_address = $this->cart->hasShipping() ? $this->config->get('simple_show_shipping_address') : 0;

        if ($simple_show_shipping_address && $this->request->server['REQUEST_METHOD'] == 'POST' && empty($this->request->post['shipping_address_same'])) {
            $date .= ' '.$this->simple->get_total_value(Simple::SET_CHECKOUT_ADDRESS,'date');
        }

        $this->simple->date = $date;
        $this->session->data['date'] = $date;
    }

    private function get_time_value() {
        $time = $this->simple->get_total_value(Simple::SET_CHECKOUT_CUSTOMER,'time');

        $simple_show_shipping_address = $this->cart->hasShipping() ? $this->config->get('simple_show_shipping_address') : 0;

        if ($simple_show_shipping_address && $this->request->server['REQUEST_METHOD'] == 'POST' && empty($this->request->post['shipping_address_same'])) {
            $time .= ' '.$this->simple->get_total_value(Simple::SET_CHECKOUT_ADDRESS,'time');
        }

        $this->simple->time = $time;
        $this->session->data['time'] = $time;
    }

3.) In the 'catalog/controller/checkout/simplecheckout.php':
$data['date'] = $this->simple->date;
$data['time'] = $this->simple->time;

4.) So after these actions I can get the values in the 'catalog/controller/checkout/success.php':
$this->session->data['date']
$this->session->data['time']


text:
Q: need SQLite3 for a portable program vb6 Is there any idea to use sqlite version 3 in vb6 like sqlite version 1 ? sqlite version 1 use ags_sqlite.dll
http://www.freevbcode.com/imagesvr_ce/184390/source/008/zully_lite_sqlite.zip

A: I would use the SQLite ODBC driver. It works pretty darn well and allows the DSN-less approach, which makes app distribution easier.
The only to look out for is that it won't allow multiple statements in one call - thus you must call them separately.


text:
Q: given the following equation system, find the max? I realise that the question is not clear, but I'm not really sure what this problem  itself is all about. I have an "algorithm and analysis" mid exam coming up.

Problem 4 (5 points)
Consider the following equation system:
        max     x1 + 4x2 + 3x3
        x1 + 4x2 + 3x3     ≤     4

I think that I can solve this using dynamic programming, but I'm not sure... It looks a lot like a knapsack problem, but I'm not sure what I would consider as the value, and what as the weight...

A: One obvious solution would be
x_1 = 0
x_2 = 1
x_3 = 0

which can be found by inspection; another one would be as follows.
x_1 = 1
x_2 = 0
x_3 = 1

A: As the expression to maximise is also the expression that is constrained to an upper limit, you obviously need to solve this equation:
        x1 + 4x2 + 3x3 = 4
As you have more than one freedom (3 variables, 1 equation, so 2 dimensions of freedom), there are an infinite number of solutions.
You can pick any value for x2 and x3, and then the corresponding x1 is:
        x1 = 4 − 4x2 − 3x3


text:
Q: How to write to the log file using Laravel 4 artisan command? So the below code pulls the data I'm looking for, and dumps it to the command line, but it won't write to the log files... any clues to how I SHOULD be doing this?
public function fire()
{
Log::info('Starting Pull', array('Start Pull' => 'Begin');
$this->line('Pulling Data From Source.');
$sites=Site::all();
foreach($sites as $site){
        Log::info('Doing Pull for', array('data Pull' => print_r($site->tag,true)));
    }
    $this->line('Completed');
     Log::info('End Pull', array('End Pull' => 'Done');
}

A: Are you sure you're looking at the right log?
Laravel 4 adds the Server API (´php_sapi_name()´) being used to run it. So if you're using Apache 2, you should see files named as:
log-apache2handler-YYYY-MM-DD.txt

When accessing your app via web interface; and
log-cli-YYYY-MM-DD.txt

When accessing your app via a command line interface (i.e. Artisan).


text:
Q: how can i write item template for a selected item of combo box in wpf i have created an item template for wpf combo box to display multiple properties of and object in a combo box item.
<ComboBox x:Name="cmbType" Grid.Column="2" Grid.Row="0" Grid.ColumnSpan="1"
        SelectedItem="{Binding Current.Type, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsEditable="False"
        ItemsSource="{Binding Types, Mode=OneWay}" DropDownClosed="cmbIncidentType_DropDownClosed" TabIndex="601">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="10" />
                    <ColumnDefinition Width="4" />
                    <ColumnDefinition Width="*" />

                </Grid.ColumnDefinitions>
                <TextBlock Grid.Column="0" Text="{Binding ID}" />
                <TextBlock Grid.Column="2" Text="{Binding Name}" />
            </Grid>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

till now its perfect it shows both id and name of a type in combo box item but now i want when i select an item it should only display name of selected item in the text area of combo box instead of displaying both ID and name.
Can anyone please help?

A: You can use a trigger to hide the ID in the ComboBox display area:
<DataTemplate>
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding ID}" Margin="0,0,4,0">
            <TextBlock.Style>
                <Style TargetType="TextBlock">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ComboBoxItem}, Path=IsSelected}" Value="{x:Null}">
                            <Setter Property="Visibility" Value="Collapsed"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBlock.Style>
        </TextBlock>
        <TextBlock Text="{Binding Name}"/>
    </StackPanel>
</DataTemplate>


text:
Q: How to throw `DbUpdateConcurrencyException` manually in .net core? I want to throw Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException in my code, but DbUpdateConcurrencyException has single constructor:
public DbUpdateConcurrencyException(
      [NotNullAttribute] string message,
      [NotNullAttribute] IReadOnlyList<IUpdateEntry> entries)

I pass null in second parameter but as [NotNullAttribute] says, it can't be null.
In my try-catch code i just catch the DbUpdateConcurrencyException and i don't mind its properties (Message or ...).
Is there any way to throw and instance from this class out of the box?
I know i can make a custom Exception but i'd rather DbUpdateConcurrencyException.

A: It seems, you are running EF core 2.2 or below, because the overloads you are looking for have been introduced in ef core 3.0. Therefore one answer will be upgrade to EF core 3.0 or newer,
If this is not an option, you can define your custom exception in the interim (I understand you'd rather avoid it but that's probably the cleanest way around it):
public class MyDbUpdateConcurrencyException : DbUpdateException
{
    public MyDbUpdateConcurrencyException(string message) : base(message, (Exception)null)
    {
    }
}

UPD As it's been pointed out in comments you can target different versions of .net core runtime with your current EF. I just wanted to point out that upgrading to EF core 3.0 might be tricky due to a few breaking changes it introduced, therefore passing an empty list (as Erik Philips suggests) will likely be a more fitting solution in your case.

A: Simply pass in a list with a null entry.
Working DotNetFiddle Example
// @nuget: Microsoft.EntityFrameworkCore -version 2.2
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Update;
public class Program
{
    public static void Main()
    {
        throw new DbUpdateConcurrencyException("message"
          , new List<IUpdateEntry> { null }  );
    }
}


text:
Q: Visual Studio Commercial Libraries I just upgraded to Visual Studio 2012. I need to be able to use different commercial components for different projects. For instance, one client might need me to use UI components from Developer Express. Another might want me to use Telerik components.
Truth is, I rarely would need to load all of them. I'd really like the ability to load just the sets of components I want without having to bear the time it takes to load all of them each time I start Visual Studio.
I was wondering if there's anyway I can create customized loading scenarios. For example, start VS with component packages a, b, and c or perhaps start it with a, b, d, and e?
Thanks for any pointers.
-- Robert


text:
Q: Google Charts - Getting default content mixed in with custom HTML for tooltip Trying to add some custom HTML tooltips to a Googlechart.
I have followed the docs as far as I can see, but I get my custom content in the centre of the original content (rather than it overriding the original content as expected).
Is there any way to customise the tooltips html with the original values, or completely override the tooltip content?
JSFiddle here
  [1]:

google.charts.load('current', {'packages':['corechart', 'bar']});
 google.charts.setOnLoadCallback(drawBarChart);
                                        function drawBarChart() {

                                            var bardata = google.visualization.arrayToDataTable([
                                                ['Genre', 'Accepted', 'Pending' , {'type': 'string', 'role': 'tooltip', 'p': {'html': true}}],
                                                ['Egg Baskets', 4325, 4324 , createCustomHTMLContent(234 , 434)],
                                                ['Cheese Wedges', 43, 434,  createCustomHTMLContent(234 , 434)],
                                                 ['Bannanasanan', 43, 434,   createCustomHTMLContent(234 , 434)]]);

                                            var view = new google.visualization.DataView(bardata);

                                            var options = {

                                                pieHole: 0.4,
                                                series: [
                                                    {color: '#b3d657', visibleInLegend: false},
                                                    {color: '#c1c2c3', visibleInLegend: false}
                                                ],

                                                legend: {
                                                    position: 'bottom',
                                                    alignment: 'left'
                                                },
                                                chartArea: {
                                                    left: 16,
                                                    top: 10,
                                                    width: '95%',
                                                    height: '80%',
                                                },
                                                isStacked: true,
                                                bar: { groupWidth: '60%' },
                                                focusTarget: 'category',
                                                tooltip: {isHtml: true},

                                            };
                                            var barChart = new google.visualization.ColumnChart(document.getElementById("container-div"));
                                            barChart.draw(view, options);
                                        }
                                        function createCustomHTMLContent(accepted, pending) {

                                            return '
' +
                                                    + '
'
                                                        + '
'
                                                             +'Custom Title'
                                                        + '
'
                                                    + '
'
                                                    + '
'
                                                        + '
'
                                                            + 'Suggested'
                                                        + '
'
                                                        + '
'
                                                              +  pending
                                                        + '
'
                                                    + '
'
                                                    + '
'
                                                        + '
'
                                                            + 'Accepted'
                                                        + '
'
                                                        + '
'
                                                            +  accepted
                                                        + '
'
                                                    + '
'
                                                + '
'
                                        }

A: the following option is causing the default and custom tooltips to be mixed together.
focusTarget: 'category'

removing the above option will allow the custom tooltip to be the only one displayed.
but in order to show the same custom tooltip for both series,
you will need to include two custom tooltip columns in the data table.
see following working snippet...

google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawBarChart);

function drawBarChart() {
  var bardata = google.visualization.arrayToDataTable([
    ['Genre', 'Accepted', {'type': 'string', 'role': 'tooltip', 'p': {'html': true}}, 'Pending', {'type': 'string', 'role': 'tooltip', 'p': {'html': true}}],
    ['Egg Baskets', 4325, createCustomHTMLContent(234, 434), 4324, createCustomHTMLContent(234, 434)],
    ['Cheese Wedges', 43, createCustomHTMLContent(234, 434), 434, createCustomHTMLContent(234, 434)],
    ['Bannanasanan', 43, createCustomHTMLContent(234, 434), 434, createCustomHTMLContent(234, 434)]
  ]);

  var view = new google.visualization.DataView(bardata);
  var options = {
    series: [
      {color: '#b3d657', visibleInLegend: false},
      {color: '#c1c2c3', visibleInLegend: false}
    ],
    legend: {
      position: 'bottom',
      alignment: 'left'
    },
    chartArea: {
      left: 16,
      top: 10,
      width: '95%',
      height: '80%',
    },
    isStacked: true,
    bar: { groupWidth: '60%' },
    tooltip: {isHtml: true},
  };
  var barChart = new google.visualization.ColumnChart(document.getElementById("container-div"));
  barChart.draw(view, options);
}

function createCustomHTMLContent(accepted, pending) {
  return '
' +
          + '
'
              + '
'
                   +'Custom Title'
              + '
'
          + '
'
          + '
'
              + '
'
                  + 'Suggested'
              + '
'
              + '
'
                    +  pending
              + '
'
          + '
'
          + '
'
              + '
'
                  + 'Accepted'
              + '
'
              + '
'
                  +  accepted
              + '
'
          + '
'
      + '
'
}