text:
Q: Is it possible to view a binary in ones and zeros? By that I mean is it possible to write a program in C, compile it and then see what it looks like in ones and zeros?

A: Use hexdump or a hex editor to view a binary in hexadecimal bytes.
Hexadecimal is simply a more compact way to view binary.  Every hexadecimal digit (0-F) represents four bits.  For example, 0xF in decimal is 15 and in binary is 1111.

A: You can use xxd:
xxd -b filename

C:\opt\bin> xxd -b ctags.exe | head
0000000: 01001101 01011010 10010000 00000000 00000011 00000000  MZ....
0000006: 00000000 00000000 00000100 00000000 00000000 00000000  ......
000000c: 11111111 11111111 00000000 00000000 10111000 00000000  ......
0000012: 00000000 00000000 00000000 00000000 00000000 00000000  ......
0000018: 01000000 00000000 00000000 00000000 00000000 00000000  @.....
000001e: 00000000 00000000 00000000 00000000 00000000 00000000  ......
0000024: 00000000 00000000 00000000 00000000 00000000 00000000  ......
000002a: 00000000 00000000 00000000 00000000 00000000 00000000  ......
0000030: 00000000 00000000 00000000 00000000 00000000 00000000  ......
0000036: 00000000 00000000 00000000 00000000 00000000 00000000  ......

Just to make this a little more programming related:
#include <stdio.h>
#include <stdlib.h>

const char *lookup[] = {
   /*  0       1       2       3       4       5       6       7 */
    "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
   /*  8       9       A       B       C       D       E       F */
    "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111",
};

int main(int argc, char *argv[]) {
    FILE *fin;
    int c;
    size_t bytes_read = 0;

    if ( argc != 2 ) {
        fputs("No filename provided", stderr);
        exit(EXIT_FAILURE);
    }

    fin = fopen(argv[1], "rb");
    if ( !fin ) {
        fprintf(stderr, "Cannot open %s\n", argv[1]);
        exit(EXIT_FAILURE);
    }

    while ( EOF != (c = fgetc(fin)) ) {
        printf("%s", lookup[ (c & 0xf0) >> 4 ]);
        printf("%s", lookup[ (c & 0x0f) ]);

        bytes_read += 1;
        if ( bytes_read % 9 == 0 ) {
            puts("");
        }
    }

    fclose(fin);

    return EXIT_SUCCESS;
}

Output:

C:\Temp> binary.exe c:\opt\bin\ctags.exe | head
010011010101101010010000000000000000001100000000000000000000000000000100
000000000000000000000000111111111111111100000000000000001011100000000000
000000000000000000000000000000000000000000000000010000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000111000000000000000000000
000000000000111000011111101110100000111000000000101101000000100111001101
001000011011100000000001010011001100110100100001010101000110100001101001
011100110010000001110000011100100110111101100111011100100110000101101101

A: You mean that you can't do compilation and translate the opcodes to binary in your head?
Actually, one of the computers I learned to program on had to have the bootstrap code toggled in via front panel switches.  You needed to enter enough code to get it to boot the loader off the 8" floppy drive and load up the OS.  You can see a picture of one here.  I really did need to know the binary for the boot loader opcodes.

A: Sure it's possible.  You could write your own viewer using the information in this post.


text:
Q: Pascal double value is not exact, how to fix this? I have been solving a programming challenge in UVA and got this problem, which is REALLY strange. Here is the flawed code:
program WTF;
begin
  WriteLn(Trunc(2.01 * 100));
  ReadLn();
end.

Obviously, I need to get 201 as Integer, but I get 200, this happens because Double somehow doesn't store the exact value... It's 2.01 = 2.00(9) for reasons unbeknownst to me, can someone explain this and provide a solution?
Edit: Yet, I figgured that using Round() instead of Trunc() fixes this... But still, why wouldn't Trunc() work?

A: Double stores numbers of the form s*2p where s and p are integers. The number 2.01 is not of the form s*2p for any integers s, p so it cannot be stored exactly in a Double.
The solution here is to round 2.01 * 100 to the nearest integer instead of truncating it. Although 2.01 is not exactly 2.01, it is only a little bit below. Rounding to the nearest integer would result in 201.

Note that if by 2.00(9) you mean 2.0099999999… repeating indefinitely, then 2.00(9)is not the Double you get when you write 2.01. The nearest Double to the real 2.01, and the number you got, is 2.0099999999999997868371792719699442386627197265625. It is of the form s * 2p: 9052235251014696 * 2-52

redpajama_set_name: RedPajamaStackExchange


text:
Q: HTML adding CRUD button which will get specific thing I have a problem with my current project. I am working on my personal project where I am using CRUD in HTML and Node.js. I faced the problem while creating Get (with given ID) button. While button Get - which gives me all data from DB - is working, the one with specific ID is not. Here I am attaching screen shots of my source code:

//Get - function from SQL Server
app.get('/people', (req, res) => {
  mysqlConnection.query('SELECT * FROM peopledb.people' , (err, rows, fields) =>{
    if(!err)
    res.send(rows);
    else
    console.log(err);
  })
})

//Get - function from SQL with given ID

app.get('/people/:id', (req, res) => {
  mysqlConnection.query('SELECT * FROM peopledb.people WHERE PplID = ?' ,[req.params.id] ,(err, rows, fields) =>{
    if(!err)
    res.send(rows);
    else
    console.log(err);
  })
})

        <form action="/people" method="GET" class="getbutton">

                <input type="submit" value="Get People from Database" class="btn btn-primary" />

        </form>

        <form action="/people/" method="GET">

                <input type="submit" value="GetUnique" class="btn btn-primary"/>
                <input type="text" placeholder="Get person by ID"/>

        </form>

I hope I explained you everything clear and understandable.
Summing up, I just want the second button to forward me to page /people/(given ID in input box). After clicking the button my URL request is: localhost:X/people/?, while it should be: localhost:X/poeple/(given ID).
Thanks a lot :)

A: It's hard to say what could exactly be wrong. First of all You should use browser's dev tools (network) and check the response of your request.


text:
Q: How can I Disable Lightbulb for Fully Qualified Usings in Visual Studio 2015? I have:
namespace My.Namespace.Admin.Presenter
{
    using System;
    using System.Collections.Specialized;
    using System.Globalization;

    using My.Framework.Utility;
    using My.Namespace.Core.Business.Admin;
    using My.Namespace.Core.Entities.Admin;

    ...
}

In Visual Studio 2015, this is flagged as an improvement by the lightbulb  IDE0001: Name Can by Simplified for

*

*My.Framework.Utility to Framework.Utility

*My.Namespace.Core.Business.Admin to Core.Business.Admin

*My.Namespace.Core.Entities.Admin to Core.Entities.Admin
I don't like the lighbulbs suggestion, how can I turn it off? There doesn't seem to be a global setting for these and clicking the IDE0001 error just performs a bing search rather than a dedicated help page.
This question deals with another issue flagged by IDE0001, but not the namespacing.

A: This can be achieved via creating a Code Analysis Ruleset
In project properties select the Code Analysis tab -

Then edit a ruleset. The IDE* rules are under the Analyzer Microsoft.CodeAnalysis.CSharp.Features:

Change IDE0001 to none (or all of them to none), and the rule isn't fired anymore.
It's not granular enough to only get rid of the namespace IDE0001, but does get rid of it along with the rest of IDE0001 "suggestions" which is good enough for my needs.
The created Ruleset can be applied to all projects as needed.


text:
Q: How to implement authentication in WebService I going to create one web service in c#.Client will send username and password.I want to authenticate the user before reaching to a web method,ie in IIS level.Is it possible create a filter in c#.Can anyone pls share the code or link.User Details are stored in MSSQL database[i want to validate such a user is existing in Database.If user is not existing,then i want to block the request,there itself. Purpose is to avoid validation of user in every web method].

A: I would recommend building a REST based webservice and sending through an API key rather than usernames and passwords.
Have a look at: REST GET requests, verbs and apikey
Then just Google REST based ASP.NET Webservices for heaps of tutorials on how to accomplish it.
Updated to show implementation
Note: I can't find the original page but this code was based off a sample somewhere.
Step 1 - Edit web.config
Insert this in the  system.serviceModel  section.
<behaviors>
  <serviceBehaviors>
    <clear />
    <behavior>

      <serviceAuthorization serviceAuthorizationManagerType="API.APIKeyAuthorization, API" />
      <serviceMetadata httpGetEnabled="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>

Step 2 - Create API Authorization Class
Change the code in IsValidAPI key to suit your actual situation. You can see mine goes to a function to test if the API key is valid.
namespace API
{
public class APIKeyAuthorization : ServiceAuthorizationManager
{
    public const string APIKEY = "APIKey";
    public const string APIKEYLIST = "APIKeyList";

    protected override bool CheckAccessCore(OperationContext operationContext)
    {
        return IsValidAPIKey(operationContext);
    }

    public bool IsValidAPIKey(OperationContext operationContext)
    {
        // if verification is disabled, return true
        if (Global.APIKeyVerification == false)
            return true;

        string key = GetAPIKey(operationContext);

        // Convert the string into a Guid and validate it
        if (BusinessLogic.User.ApiKey.Exists(key))
        {
            return true;
        }
        else
        {
            // Send back an HTML reply
            CreateErrorReply(operationContext, key);
            return false;
        }
    }

    public string GetAPIKey(OperationContext operationContext)
    {
        // Get the request message
        var request = operationContext.RequestContext.RequestMessage;

        // Get the HTTP Request
        var requestProp = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];

        // Get the query string
        NameValueCollection queryParams = HttpUtility.ParseQueryString(requestProp.QueryString);

        // Return the API key (if present, null if not)
        return queryParams[APIKEY];
    }

    private static void CreateErrorReply(OperationContext operationContext, string key)
    {
        // The error message is padded so that IE shows the response by default
        using (var sr = new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + APIErrorHTML))
        {
            XElement response = XElement.Load(sr);
            using (Message reply = Message.CreateMessage(MessageVersion.None, null, response))
            {
                HttpResponseMessageProperty responseProp = new HttpResponseMessageProperty() { StatusCode = HttpStatusCode.Unauthorized, StatusDescription = String.Format("'{0}' is an invalid API key", key) };
                responseProp.Headers[HttpResponseHeader.ContentType] = "text/html";
                reply.Properties[HttpResponseMessageProperty.Name] = responseProp;
                operationContext.RequestContext.Reply(reply);
                // set the request context to null to terminate processing of this request
                operationContext.RequestContext = null;
            }
        }
    }

    public const string APIErrorHTML = @"

    <title>Request Error - No API Key</title>

        Request Error

        A valid API key needs to be included using the apikey query string parameter

";
    }
}

API authorization is done before you even hit the web method. However this example shows the API key being passed as a querystring. Follow more examples in the link above to change this to sending it through HTTP headers. A cleaner approach, it doesn't then mess up your URL's. But that all depends on your requirements.
Update
Actually I just came across this: Microsoft ASP.NET Web API - http://www.asp.net/web-api
Try that :)


text:
Q: Navigate to page on start in .NET Maui app Seems like a simple question, but I haven't been able to find a simple answer. Essentially I want to choose which page in the app to start on based on some stored state. I added a GoToAsync call in the AppShell constructor, but this didn't work--which makes sense because the AppShell hasn't been fully constructed yet.
I found this answer, but it feels like it kind of skirts around the issue:
Maui AppShell - Navigate on Open
Where is the best place to inject some code that will run once on startup and can successfully navigate a .NET Maui app to a chosen page?

A: After playing around with overrides, it seems like overriding Application.OnStart works! Shell.Current is set at this point and navigation works.
Here's additional code that allows for asynchronous initialization and uses a Loading Page until the initialization is complete:
using MyApp.Services;
using MyApp.UI;

namespace MyApp;

public partial class App : Application
{
    ConfigurationProviderService m_configProvider;

    public App(ConfigurationProviderService configProvider)
    {
        m_configProvider = configProvider;

        InitializeComponent();

        MainPage = new LoadingPage();
    }

    protected override void OnStart()
    {
        var task = InitAsync();

        task.ContinueWith((task) =>
        {
            MainThread.BeginInvokeOnMainThread(() =>
            {
                MainPage = new AppShell();

                // Choose navigation depending on init
                Shell.Current.GoToAsync(...);
            });
        });

        base.OnStart();
    }

    private async Task InitAsync()
    {
        await m_configProvider.InitAsync();
    }
}


text:
Q: EasyMock still goes into implementation of a method mocked with addMockedMethod I am trying to write a unit-test in Java. Due to the structure of Java class, I have to come up with a way in which whenever a constructor of a class is called, a mocked object of that class is created. I want to mock 2 methods of that class.
CallToBeMocked mockCallToBeMocked = EasyMock.createMockBuilder(CallToBeMocked.class)
                .withConstructor(ArgumentA.class, ArgumentB.class, ArgumentC.class)
                .withArgs(mockArgumentA, mockArgumentB, mockArgumentC)
                .addMockedMethod("isProxied", ArgumentA.class)
                .addMockedMethod("remoteCall", String.class, ArgumentA.class, Object.class)
                .createMock();

 EasyMock.expect(mockCallToBeMocked.isProxied(mockArgumentA)).andReturn(false);
 EasyMock.expect(mockCallToBeMocked.remoteCall("ip-address", mockArgumentA, null)).andThrow(new Exception()).times(3);

The problem is that although I have clearly specified that isProxied and remoteCall methods have to be mocked and I have given appropriate expectations for those methods, it still starts going into the actual implementations of these methods.

A: It should perfectly work. So something else is going on. Here is a working example based on your code. What's different from your actual implementation?
public class PartialTest {

    public interface ArgumentA { }
    public interface ArgumentB { }
    public interface ArgumentC { }

    public static class CallToBeMocked {
        public CallToBeMocked(ArgumentA a, ArgumentB b, ArgumentC c) {

        }

        public boolean isProxied(ArgumentA a) {
            return true;
        }

        public int remoteCall(String ip, ArgumentA a, Object any) throws Exception {
            return 0;
        }
    }

    @Test
    public void test() throws Exception {
        ArgumentA mockArgumentA = createNiceMock(ArgumentA.class);
        ArgumentB mockArgumentB = createNiceMock(ArgumentB.class);
        ArgumentC mockArgumentC = createNiceMock(ArgumentC.class);

        CallToBeMocked mockCallToBeMocked = createMockBuilder(CallToBeMocked.class)
                .withConstructor(ArgumentA.class, ArgumentB.class, ArgumentC.class)
                .withArgs(mockArgumentA, mockArgumentB, mockArgumentC)
                .addMockedMethod("isProxied", ArgumentA.class)
                .addMockedMethod("remoteCall", String.class, ArgumentA.class, Object.class)
                .createMock();

        expect(mockCallToBeMocked.isProxied(mockArgumentA)).andReturn(false);
        expect(mockCallToBeMocked.remoteCall("ip-address", mockArgumentA, null)).andThrow(new Exception()).times(3);

        replay(mockCallToBeMocked);

        assertFalse(mockCallToBeMocked.isProxied(mockArgumentA));
        try {
            mockCallToBeMocked.remoteCall("ip-address", mockArgumentA, null);
            fail("Should throw");
        } catch (Exception e) { }
        try {
            mockCallToBeMocked.remoteCall("ip-address", mockArgumentA, null);
            fail("Should throw");
        } catch (Exception e) { }
        try {
            mockCallToBeMocked.remoteCall("ip-address", mockArgumentA, null);
            fail("Should throw");
        } catch (Exception e) { }

        verify(mockCallToBeMocked);
    }
}

A: If we aren't tied to EasyMock, here's a way in which the same functionality can be achieved using Mockito.
import static org.mockito.Mockito.verify;

import org.mockito.Mockito;

....

ClassToBeMocked myMock = Mockito.mock(ClassToBeMocked.class);

Mockito
    .when(myMock.isProxied(any(ArgumentA.class)))
    .thenReturn(false);

Mockito
    .when(myMock.remoteCall(any(String.class), any(ArgumentA.class), any(Object.class)))
    .thenThrow(new Exception("monkeys"));

<USE ``myMock``>

verify(myMock, times(1)).isProxied(mockArgumentA);
verify(myMock, times(3)).remoteCall("ip-address", mockArgumentA, null);


text:
Q: pgcli won't run, is giving me an odd error This should have a pgcli tag, but I don't have enough reputation to create that...
Anyway, I recently did a brew upgrade, and now pgcli won't run for me.  I'm literally up-arrowing to get the command, so I know it's the command that worked before.  It's below (though, when I run it, I'm using literals, not the environment variables).
$ pgcli --single-connection "host=$HOST_NAME dbname=$DB_NAME user=$DB_USERNAME sslcert=$DB_CRT sslkey=$DB_KEY sslrootcert=$DB_TRUST_STORE sslmode=$DB_SSL_MODE"
invalid connection option "dsn"

I've tried this w/o the "--single-connection", no change.  I replaced "pgcli" with "psql" and it worked, but then I don't have pgcli.
I've googled this error message and come up empty.  I replaced my config file with the current sample config, none of that changes anything.
The relevant log lines are below.  Note that I have executed pip install keyring before this.
2022-10-04 10:51:35,886 (39248/MainThread) pgcli.main INFO - Default pager found in PAGER environment variable: "less"
2022-10-04 10:51:35,886 (39248/MainThread) pgcli.main WARNING - import keyring failed: ModuleNotFoundError("No module named 'keyring'").
2022-10-04 10:51:35,888 (39248/MainThread) pgcli.main ERROR - traceback: 'Traceback (most recent call last):\n  File "/opt/homebrew/Cellar/pgcli/3.5.0/libexec/lib/python3.10/site-packages/psycopg/conninfo.py", line 96, in _parse_conninfo\n    return pq.Conninfo.parse(conninfo.encode())\n  File "/opt/homebrew/Cellar/pgcli/3.5.0/libexec/lib/python3.10/site-packages/psycopg/pq/pq_ctypes.py", line 905, in parse\n    raise exc\npsycopg.OperationalError: invalid connection option "dsn"\n\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File "/opt/homebrew/Cellar/pgcli/3.5.0/libexec/lib/python3.10/site-packages/pgcli/main.py", line 627, in connect\n    pgexecute = PGExecute(database, user, passwd, host, port, dsn, **kwargs)\n  File "/opt/homebrew/Cellar/pgcli/3.5.0/libexec/lib/python3.10/site-packages/pgcli/pgexecute.py", line 161, in __init__\n    self.connect(database, user, password, host, port, dsn, **kwargs)\n  File "/opt/homebrew/Cellar/pgcli/3.5.0/libexec/lib/python3.10/site-packages/pgcli/pgexecute.py", line 206, in connect\n    conn_info = make_conninfo(**conn_params)\n  File "/opt/homebrew/Cellar/pgcli/3.5.0/libexec/lib/python3.10/site-packages/psycopg/conninfo.py", line 59, in make_conninfo\n    _parse_conninfo(conninfo)\n  File "/opt/homebrew/Cellar/pgcli/3.5.0/libexec/lib/python3.10/site-packages/psycopg/conninfo.py", line 98, in _parse_conninfo\n    raise e.ProgrammingError(str(ex))\npsycopg.ProgrammingError: invalid connection option "dsn"\n\n'

I tried formatting my connection string as a URL as below, but that gives me an error that makes me think that pgcli is truncating the URL and not actually connecting the way I'm asking it to.
$ pgcli "postgresql://$HOST_NAME/$DB_NAME&user=$DB_USERNAME&sslcert=$DB_CRT&sslkey=$DB_KEY&sslrootcert=$DB_TRUST_STORE&sslmode=$DB_SSL_MODE&ssl=true"
connection failed: FATAL:  no pg_hba.conf entry for host "$DB_IP", user "$NON_DB_USER_NAME", database "$DB_NAME&user=$DB_USERNAME&ssl=true&sslcert=$ROUGHLY_HALF_OF_THE_SSL_CRT_PATH", SSL on
connection to server at "$HOST_NAME" ($DB_IP), port 5432 failed: FATAL:  no pg_hba.conf entry for host "$CLIENT_IP", user "$NON_DB_USER_NAME", database "$DB_NAME&user=$DB_USERNAME&ssl=true&sslcert=$ROUGHLY_HALF_OF_THE_SSL_CRT_PATH", SSL off

Does anyone know what to do?  Where to look?  I've read the FAQ, I've googled, I've looked in the error log...  I don't know what to try next.
Thank you very much.


text:
Q: How to disable chrome's "save password" popup in selenium webdriver (python) I want to disable the "save password" popup in chrome in my selenium test whenever it appears. I found a way through ChromeOptions(), but can't find the argument or preference necessary to make the popup disappear.
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("argument")

A: prefs = {"credentials_enable_service": False,
         "profile.password_manager_enabled": False}
options.add_experimental_option("prefs", prefs)

Works for me

A: The below options will disable "save password" pop-ups. But this is in C#.
options.AddUserProfilePreference("credentials_enable_service", false);
options.AddUserProfilePreference("profile.password_manager_enabled", false);

You can find the relevant options for python here

A: To disable the save password popup in Google Chrome within your Selenium Tests you can use the following piece of code block:
from selenium import webdriver

chrome_opt = webdriver.ChromeOptions()
prefs = {"credentials_enable_service": False,
     "profile.password_manager_enabled": False}
chrome_opt.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(chrome_options=chrome_opt, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get("https://google.com")

A: None of the answers above are working in my case , did anything change in this regard ?
I dont get a warning on the console either...
 prefs = {"credentials_enable_service":False,"profile.password_manager_enabled":False,"profile.default_content_setting_values.notifications" : 2}

A: The selected answer is incorrect because it redefines the value of prefs and uses , instead of : to set the individual values.
The answer by user ItZzMJ works correctly. In my case, like this:
prefs = {"credentials_enable_service": False,
         "profile.password_manager_enabled": False}
options.add_experimental_option("prefs", prefs)


text:
Q: How can I determine programmatically whether on multi-core, hyperthreading or multi-processor? I know how to get the processor type, perhaps that's the only way, but I'm actually looking for a way to determine from an application whether it's running on a multi-core processor or on a hyper-threading single-core processor.
(background: the hosting providers of some of my clients are very vague about what resources they make available through VMWare images. This application is supposed to run on multi-core, but has seen detrimental performance since its last "move". Normally, on multi-core, one core spikes on one thread, and not the other. On this "multi-core", both processors spike, even on single-threaded applications.)

A: System.Environment.ProcessorCount Which will also include hyperthreaded processors. Which Vmware may or may not expose. Chances are higher that it will be exposed if the the processor is VT enabled AND you are using a baremetal enabled hypervisor technology.
If you have XP-SP3/WIN2k3 or above You can use WMI to pull out:
Win32_ComputerSystem.NumberOfProcessors returns physical count

Win32_ComputerSystem.NumberOfLogicalProcessors returns logical count

If the values are the same then chances are your system does not have HT or does not have it enabled.
You can start exploring how to pull out WMI info in .NET from this tutorial.


text:
Q: How can a Google Drive file not have "any content stored on Drive"? I have a Google Form that logs all of its responses in a Google SpreadSheet I own on my Google Drive Account. The SpreadSheet of responses shows up in the "My Drive" section of Google Drive when accessed on a computer.
I'm currently writing an Android application that downloads that SpreadSheet and parses it for certain data.
I'm at the point where I've found the File and I'm able to get the File's Title, Description, and ExportLinks. However, when I try to get the File's DownloadUrl, I get a NullPointerException.
According to this part of the https://developers.google.com/drive/web/manage-downloads API ("file.getDownloadUrl())"), if there is no download url, the "The file doesn't have any content stored on Drive"
How can a SpreadSheet on my Drive with over 100 responses not have any content stored on Drive?

A: Content here refers to binary content.  Google Spreadsheets (and the other Google Docs types) are not stored as binary content.  You can get it in a binary format like csv using the ExportLinks.  Alternatively, you can use the Spreadsheet-specific APIs like app script to interact with the spreadsheet contents.


text:
Q: XamDataChart with unknown number of series I am using an Infragistics XamDataChart and want to bind a collection in my view model to the chart's Series property, since I don't know in advance how many line charts I will need to display.
From what I can gather from old posts in the Infragistics support forums, the Series property is read only and thus doesn't support binding directly.  A solution is offered here but it seems like overkill for such a simple goal (maybe to me it just seems simple).
Has anyone here done any work with the Infragistics xamDataChart and MVVM?  The ultimate goal is to be able to have a collection in my view model that contains a variable number of 'series' that I can just bind to the chart.  Now I can probably do this if I just write some code behind for my xaml, access the DataContext (viewModel) and listen to the collection property, directly adding/removing series to the chart as necessary, but I was looking for a more MVVM way.
Thanks.

A: Since the Series collection of the XamDataChart is read-only, in order to be able to generate the Series dynamically,based on you VeiwModel, you should use helper class, similar to the approach that Graham Murray has suggested in the thead that you have referred. I have created a sample applicaiton, that show how you can create similar appraoch for binding the series of the XamDataChart to collection of your ViewModel. You can download the sample from here:
http://users.infragistics.com/Samples/SeriesBinder.zip
Sincerely,
Krasimir


text:
Q: Как получить значения из адресной строки страницы LinkedIn? Сделал верификацию через LinkedIn на своём сайте, используя react-linkedin-login-oauth2, теперь мне надо взять email пользователя из адресной строки или каким нибудь другим доступным путём, как мне это сделать?
Вот как сделана кнопка LinkendIn:
import React, { useState } from 'react';
import { useLinkedIn } from 'react-linkedin-login-oauth2';
import linkedin from 'react-linkedin-login-oauth2/assets/linkedin.png';

function LinkedInPage() {
  const { linkedInLogin } = useLinkedIn({
    clientId: '772g7w8l61n0ao',
    redirectUri: `${window.location.origin}/linkedin`,
    scope: 'r_liteprofile r_emailaddress' ,
    onSuccess: (code) => {
      console.log(code);
    },
    onError: (error) => {
      console.log(error);
    },
  });

  return (
    <img
      onClick={linkedInLogin}
      src={linkedin}
      alt="Sign in with Linked In"
      style={{ maxWidth: '180px', cursor: 'pointer' }}
    />
  );
}

export default LinkedInPage

Вот что в адресной строке https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=772g7w8l61n0ao&redirect_uri=https://example.com/linkedin&scope=r_liteprofile%20r_emailaddress&state=DGUw7vLfKRoj5YeoY30F

Вот слева кнопка, а справа окно которое появляется при нажатии, мне нужно взять email, если есть место куда всё это сохраняется?

A: Чтобы получить query параметры у ссылки, можно воспользоваться new URL и его полем searchParams:

const url = new URL("https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=772g7w8l61n0ao&redirect_uri=https://example.com/linkedin&scope=r_liteprofile%20r_emailaddress&state=DGUw7vLfKRoj5YeoY30F");

const queryParams = url.searchParams;

for (const [key, value] of queryParams) {
  console.log(key, value);
}


text:
Q: knowing next value from auto increment field mysql java I want to know the next value of auto increment field
I wanted to test this :
select max(contactid) from contact

and I add 1
but I realized that it can give me an error
for exemple
if I insert one record and I delete it
so if I insert after the field will increase by two
how can I achieve that ?
thank you

A: There are multiple solutions to this problem:
1. (Preferable) Stop trying to predict auto-increment values
This is the more typical case, and basically is using auto-increment as designed. This assumes that you don't actually need the auto-increment value before you insert. What you can do is:
DROP TABLE IF EXISTS t;
CREATE TABLE t (id INT UNSIGNED NOT NULL auto_increment, x INT NOT NULL, PRIMARY KEY(id));
INSERT INTO t (x) VALUES (100);
SELECT LAST_INSERT_ID();

The call to SELECT LAST_INSERT_ID() will return the ID that was just generated for your INSERT.
2. Set up an ID generation table specifically to generate IDs
You can create a table with just an auto-increment column, like so:
DROP TABLE IF EXISTS id_generator;
CREATE TABLE id_generator (id INT UNSIGNED NOT NULL auto_increment, PRIMARY KEY(id));

You can then generate a new, unique ID with:
INSERT INTO id_generator (id) VALUES (NULL);
SELECT LAST_INSERT_ID();

And use that ID to insert into the table you're actually working with. As long as all generated IDs come from this ID generation table, there will be no conflicts. However there is a cost to generating these IDs, and auto-increment is not very efficient at it.
3. Use an external ID generation scheme
This is more or less similar to solution 2, but doesn't use MySQL at all for the ID generation. You can use something like a UUID/GUID scheme which generates a string, or you could use something like Snowflake to generate integer IDs.

A: You should use LAST_INSERT_ID like this:
SELECT LAST_INSERT_ID()

It will return the last value of AUTO_INCREMENT ID field.
More details here: http://goo.gl/RkmR5

A: This will give you the next id value that will be inserted:
SELECT LAST_INSERT_ID() + 1;


text:
Q: Bubble sort melhorado Apesar de ter seguido o pseudocódigo corretamente, o programa não está ordenando o array corretamente. Por quê?
#include <bits/stdc++.h>

void bubbleSortM( int A[], int n )
{
  int i,j,aux;
  bool troca;

  for(i=1; i<n; i++)
  troca = 0;

  for(j=n-1; j>=i ;j--)
{
if(A[j-1] > A[j])
  {
 aux= A[j-1];
 A[j-1] = A[j];
 A[j] = aux;
 troca = 1;
   }
}
 if( !troca )
  {
return;
  }
  return;
}
void printVetor(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);

}

int main()
{
int A[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(A)/sizeof(A[0]);

bubbleSortM(A, n);

printf("Vetor ordenado: \n");
printVetor(A, n);
}

A: Primeiro, atente-se a identação do seu programa, que está horrível. Ela ajuda os outros (e também você mesmo) a entendê-lo. Se você tivesse feito isso, veria que falta um { depois do primeiro for e o } correspondente antes do fim da função, e que por causa disso, ele não faz nada do que você queria.
Além disso, é boa prática em C a declarar as variáveis somente quando serão usadas no menor escopo possível. C não é Pascal que exige que as variáveis sejam declaradas no início da função.
Um outro detalhe é bits/stdc++.h é um cabeçalho do C++, e não do C. Para o C, use stdio.h e stdbool.h.
E também há um return sobrando no final de bubbleSortM que é desnecessário, vez que é a última coisa da função.
Seu programa corrigido fica assim:
#include <stdio.h>
#include <stdbool.h>

void bubbleSortM(int A[], int n) {
    for (int i = 1; i < n; i++) {
        bool troca = 0;

        for (int j = n - 1; j >= i; j--) {
            if (A[j - 1] > A[j]) {
                int aux = A[j - 1];
                A[j - 1] = A[j];
                A[j] = aux;
                troca = 1;
            }
        }
        if (!troca) {
            return;
        }
    }
}

void printVetor(int A[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", A[i]);
    }
}

int main() {
    int A[] = {12, 11, 13, 5, 6, 7};
    int n = sizeof(A) / sizeof(A[0]);
    bubbleSortM(A, n);
    printf("Vetor ordenado: \n");
    printVetor(A, n);
}

Veja aqui funcionando no ideone.


text:
Q: PDF version 1.3 Add stamp I am using larval and want to add stamp on pdf documents.
My PDF files version is 1.3 and I am using FPDI package but it is not able to add PDF stamp on 1.3 version. It is working well other version. which is the best package to do this? Please suggest me

A: We offer an add-on for FPDI which allows you to process PDF documents which uses compressed cross-references and streams (introduced in PDF 1.5) here (not free).
Otherwise you have to remove the compressed cross-reference and streams (possible e.g. through the optimization process of Acrobat).


text:
Q: @ManagedProperty initialization I want to store the selected value of the first attribute managedabean "refCont" in a second attribute of the managed bean and then I'll post. but the value will show that after the second selection knowing that the value displayed is the one selected for the first time. I do not know what's sake
.xhtml
<h:outputText value="* Contact" />
<h:selectOneMenu   id="contact" value="#{reclamationMB.refCont}"  onchange="lazyload()">
    <c:set value="#{reclamationMB.refCont}" target="#{contactMB}" property="refContt" />
    <f:ajax  listener="#{contactMB.affichReclContact}" />
    <f:selectItem itemLabel="Select One"  noSelectionOption="true" itemValue="---" />
    <f:selectItems value="#{contactMB.contactsClient}" noSelectionValue="" var="contact" itemValue="#{contact.refCont}" itemLabel="#{contact.nomCont}" />
    <f:selectItems itemLabel="Autre" itemValue=""></f:selectItems>
</h:selectOneMenu>

first ManagedBean:
 @RequestScoped
    public class ReclamationMB extends AbstractMB implements Serializable {
        private int refCont;//ref contact recuperé pour la creation de la  reclamation
        .....
//getter and setter

Second Mnaged bean
 @RequestScoped
    public class ContactMB extends AbstractMB implements Serializable {
    @ManagedProperty("#{reclamationMB.refCont}")
            private int refContt;
            .....
    //getter an setter
    public void affichReclContact(AjaxBehaviorEvent event){
            contact=service.AffichContact(refContt);
            setContact(contact);
    }

A: The problem is that JSTL's <c:set> is a view build time tag handler, and not a view render time UI component, so your problem is a classical one: when you expect it to set the value, it is no longer there in the component tree. Moreover, it has run when there was no <h:selectOneMenu> tag at all.
Of course, if <h:selectOneMenu> implemented ActionSource, just like <h:commandButton>, you could have nested JSF <f:setPropertyActionListener> for the reason of setting the bean property with the needed values, as in <f:setPropertyActionListener target="#{contactMB.refContt}" value="#{reclamationMB.refCont}">. But you can't do that.
Basically you can do two things:

*

*Use PrimeFaces <p:remoteCommand> tag, which can hold the abovementioned action listener to set the needed value, and call it in onchange method. There are a bunch of such examples here on Stack Overflow and in excellent PrimeFaces' documentation.

*Make use of bean injection, instead of just bean property injection. In the former case, the expression reclamationMB.getRefCont() will always yield the right result in the holder bean, provided that reclamationMB is the variable to hold the injected bean by @ManagedProperty.


text:
Q: Angular 7 routing ignore path I have an Angular 7 application, running .Net Core on the back end.
I have the following routes defined:
const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'login', component: LoginComponent },
  { path: 'about', component: AboutComponent },
  { path: '**', redirectTo: 'home' }
];

In Visual Studio 2019, this is running at https://localhost:44358.
All works as expected.
But now I want to get metadata for a SAML implementation using sustainsys.saml2.aspnetcore2.
To get the metadata file, I try to enter https://localhost:44358/Saml2/ in my browser.
As expected, because  the path does not match anything defined, the default route takes over and I am routed to the home page.
I removed the final path, so I no longer had any default routing for unmatched paths, and then it worked fine to get the metadata.
My question is: Is there any way to redirect to 'home' for all unmatched paths except some configured path (or paths), which would just be ignored as if the default route were not present?

A: Rather add a path to your base-href in index.html (e.g. <base href="/app/"/>) so that the Angular Router won't pick up paths on your root, then you'll be able to keep your wildcard redirect as is and /Saml2/ won't be intercepted.
Of course, if the app is already in production and you need to preserve URLs, you might not be in a position to make this kind of change.


text:
Q: How to create a new column in R where arithmetic is applied on opposite values given a group Suppose the following data frame:

group
value1
value2

1
16
2

1
20
4

2
12
2

2
8
6

3
10
7

3
14
5

I want to create a table that divides value2 over value1. However, I want it to be the only other unique value in the same group. I've attached an image to demonstrate the process.
here is an image of what I'm trying to achieve
When that is done, the output should look something like this:

group
value1
value2
perc

1
16
2
2/20 10

1
20
4
4/16 25

2
12
2
2/8 25

2
8
6
6/12 50

3
10
7
7/14 50

3
14
5
5/10 50

(I've added the fractions in the perc column so it follows my image, I'd just like the value at the end of each row)
At the moment, I'm having a hard time with this problem, I realise it may have something to do with setdiff and selecting the only other unique value in that group (there's only two rows per group) but I'm not sure how. Any help is much appreciated. Thank you!

A: We can reverse the order of value1 then calculate the perc column.
library(dplyr)

df %>%
  group_by(group) %>%
  mutate(value3 = rev(value1),
         perc = (value2/value3)*100) %>%
  select(-value3)

# A tibble: 6 × 4
# Groups:   group [3]
  group value1 value2  perc
  <int>  <int>  <int> <dbl>
1     1     16      2    10
2     1     20      4    25
3     2     12      2    25
4     2      8      6    50
5     3     10      7    50
6     3     14      5    50

data
df <- read.table(header = T, text = "
group   value1  value2
1   16  2
1   20  4
2   12  2
2   8   6
3   10  7
3   14  5")

A: You can use lead and lag to get the cell above or below the current row. The two results can be joined together:
library(tidyverse)

data <- tribble(
  ~group, ~value1, ~value2,
  1L, 16L, 2L,
  1L, 20L, 4L,
  2L, 12L, 2L,
  2L, 8L, 6L,
  3L, 10L, 7L,
  3L, 14L, 5L
)

full_join(
  data %>%
    group_by(group) %>%
    mutate(
      frac = value2 / lead(value1),
      perc_text = str_glue("{value2}/{lead(value1)} {frac * 100}")
    ) %>%
    filter(!is.na(frac)),
  data %>%
    group_by(group) %>%
    mutate(
      frac = value2 / lag(value1),
      perc_text = str_glue("{value2}/{lag(value1)} {frac * 100}")
    ) %>%
    filter(!is.na(frac))
) %>%
  arrange(group)
#> Joining, by = c("group", "value1", "value2", "frac", "perc_text")
#> # A tibble: 6 × 5
#> # Groups:   group [3]
#>   group value1 value2  frac perc_text
#>   <int>  <int>  <int> <dbl> <glue>
#> 1     1     16      2  0.1  2/20 10
#> 2     1     20      4  0.25 4/16 25
#> 3     2     12      2  0.25 2/8 25
#> 4     2      8      6  0.5  6/12 50
#> 5     3     10      7  0.5  7/14 50
#> 6     3     14      5  0.5  5/10 50

Created on 2022-04-07 by the reprex package (v2.0.0)


text:
Q: how to get and use external html safely with python I fetch external untrusted html (export from etherpad) via python. How can I be sure, that there is no "bad code" included? I could of course just strip all  for example, but is that already all of it? Is there a library that does the work reliable?

A: I solved it by using python module bleach


text:
Q: three.js: make texture zero outside boundaries Currently there are 3 wrapping modes in three.js:
THREE.RepeatWrapping
THREE.ClampToEdgeWrapping
THREE.MirroredRepeatWrapping

Example:
var texture = new THREE.TextureLoader().load( "textures/water.jpg" );
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;

I'm using textures in shaders to do gpgpu computing and for my purpose I would like the texture to be zero outside its bounds. If you use ClampToEdge for example, looking up values outside the texture bounds will yield the color of the nearest pixel that is inside the bounds. Looking up a value at coordinates (1.3, .5) will give the color at (1., .5) since 1.3 is too large for texture coordinates
So I want this to yield zero outside the bounds, or if that is not possible I want to be able to continously set the edge to zero. What is the best way to do this?

A: In your shader check the texture coordinates
vec4 value = vec4(0);
if (texcoord.x >= 0. || texcoord.x <= 1. ||
    texcoord.y >= 0. || texcoord.y <= 1.)
  value = texture2D(someSampler, texcoord);
}


text:
Q: Change post meta numbers with images I need get post meta value "phone" and his value is "555666777" in this post, in others, can be 456654768... or whatever
My code is this:
<?php global $wp_query; $postid = $wp_query->post->ID; echo get_post_meta($postid, 'phone', true); ?>

Now, i wish this numbers don't show in html like numbers, i need this numbers are images.
I have created 0.jpg 1.jpg 2.jpg 3.jpg 4.jpg 5.jpg 6.jpg 7.jpg 8.jpg 9.jpg
It's possible change the numbers of phone value with this jpgs? I don't want that google robots or anothers can this telephone numbers.

A: A good way would be to isolate each digit using modulo and integer division, and produce an img tag out of it:
global $wp_query;
$postid = $wp_query->post->ID;
$i=intval(get_post_meta($postid, 'phone', true));
$s='';
while($i>0)
    {
    $digit=$i % 10;
    $i=(int)($i/10);
    $s="<img src='$digit.jpg' title='$digit'>$s";
    }
echo $s;

A: I think you dont need wp_query to get current post_id
global $post;

$image_str = get_post_meta($post->ID, 'phone', true);

$image_array = str_split(image_str);

$image_array_with_jpg = array();

foreach($image_array as $k=>$v){

  $image_array_with_jpg[] = $v.'.jpg';
}
 print_r( $image_array_with_jpg); // array with all your post images with .jpg extension


text:
Q: How is input data in forms saved before submitting? I have a question about input data in html forms.
How and where is data, that a user writes into an html form, saved before he submits it? Especially if it is a form with multiple tabs, where the user can switch between the different tabs and the input data is still there after switching from one to another tab.
Is there a temporary storage in the browser?
I don't mean data, which is explicitly saved in cookies or local storage. I refer to data, which has just been written into an input field by the user (and waits for being submitted).
Thanks for your help.

A: Answer
If you are developing an app, for example using React, the data will be stored in the component state until you submit. Where is this state stored? It depends, but normally on RAM.
It is more complex than it sounds. Normally there is a play between the CPU, RAM and Disk, because getting data from RAM is faster than from Disk, and the user device will normally have multiple active processes.
Also, on the web, you can use the browser cookies to persist the data (but this is not the answer of your question, the answer is RAM).
RAM vs Disk
RAM has a very fast path to the computer's CPU, or central processing unit, the brain of the computer that does most of the work. RAM is random access as opposed to sequential access. Data that's accessed sequentially includes stuff that's written to your hard disk drive, for example.


text:
Q: Multiple key aggregation in ElasticSearch I am new to Elastic Search and was exploring aggregation query. The documents I have are in the format -
{"name":"A",
     "class":"10th",
     "subjects":{
         "S1":92,
         "S2":92,
         "S3":92,
     }
}

We have about 40k such documents in our ES with the Subjects varying from student to student. The query to the system can be to aggregate all subject-wise scores for a given class. We tried to create a bucket aggregation query as explained in this guide here, however, this generates a single bucket per document and in our understanding requires an explicit mention of every subject.
We want to system to generate subject wise aggregate for the data by executing a single aggregation query, the problem I face is that in our data the subjects could vary from student to student and we don't have a global list of subject keys.
We wrote the following script but this only works if we know all possible subjects.
GET student_data_v1_1/_search
{ "query" :
    {"match" :
         { "class" : "' + query + '" }},
         "aggs" : { "my_buckets" : { "terms" :
         { "field" : "subjects", "size":10000 },
         "aggregations": {"the_avg":
                      {"avg": { "field": "subjects.value" }}} }},
          "size" : 0 }'

but this query only works for the document structure, but does not work multiple subjects are defined where we may not know the key-pair  -
{"name":"A",
     "class":"10th",
     "subjects":{
         "value":93
     }
}

An alternate form the document is present is that the subject is a list of dictionaries -
    {"name":"A",
     "class":"10th",
     "subjects":[
         {"S1":92},
         {"S2":92},
         {"S3":92},
     ]
}

Having an aggregation query to solve either of the 2 document formats would be helpful.
======EDITS======
After updating the document to hold weights for each subject -
        {
class": "10th",
   "subject": [
 {
   "name": "s1",
   "marks": 90,
   "weight":30
 },
 {
   "name": "s2",
  "marks": 80,
   "weight":70
 }
   ]}

I have updated the query to be -
{
  "query": {
    "match": {
      "class": "10th"
}
  },
  "aggs": {
    "subjects": {
      "nested": {
        "path": "scores"
      },
      "aggs": {
        "subjects": {
          "terms": {
            "field": "subject.name"
      },
      "aggs" : { "weighted_grade": { "weighted_avg": { "value": { "field": "subjects.score" }, "weight": { "field": "subjects.weight" } } } }
      }
    }
  }
}
      },
      "size": 0
    }

but it throws the error-
{u'error': {u'col': 312,
u'line': 1,
u'reason': u'Unknown BaseAggregationBuilder [weighted_avg]',
u'root_cause': [{u'col': 312,
u'line': 1,
u'reason': u'Unknown BaseAggregationBuilder [weighted_avg]',
u'type': u'unknown_named_object_exception'}],
u'type': u'unknown_named_object_exception'},
u'status': 400}

A: To achieve the required result I would suggest you to keep your index mapping as follows:
{
  "properties": {
    "class": {
      "type": "keyword"
    },
    "subject": {
      "type": "nested",
      "properties": {
        "marks": {
          "type": "integer"
        },
        "name": {
          "type": "keyword"
        }
      }
    }
  }
}

In the mapping above I have created subject as nested type with two properties, name to hold subject name and marks to hold marks in the subject.
Sample doc:
{
  "class": "10th",
  "subject": [
    {
      "name": "s1",
      "marks": 90
    },
    {
      "name": "s2",
      "marks": 80
    }
  ]
}

Now you can use nested aggregation and multilevel aggregation (i.e. aggregation inside aggregation). I used nested aggregation with terms aggregation for subject.name to get bucket containing all the available subjects. Then to get avg for each subject we add a child aggregation of avg to the subjects aggregation as below:
{
  "query": {
    "match": {
      "class": "10th"
    }
  },
  "aggs": {
    "subjects": {
      "nested": {
        "path": "subject"
      },
      "aggs": {
        "subjects": {
          "terms": {
            "field": "subject.name"
          },
          "aggs": {
            "avg_score": {
              "avg": {
                "field": "subject.marks"
              }
            }
          }
        }
      }
    }
  },
  "size": 0
}

NOTE: I have added "size" : 0 so that elastic doesn't return matching docs in the result. To include or exclude it depends totally on your use case.
Sample result:
{
  "took": 25,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 3,
    "max_score": 0,
    "hits": [

    ]
  },
  "aggregations": {
    "subjects": {
      "doc_count": 6,
      "subjects": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [
          {
            "key": "s1",
            "doc_count": 3,
            "avg_score": {
              "value": 80
            }
          },
          {
            "key": "s2",
            "doc_count": 2,
            "avg_score": {
              "value": 75
            }
          },
          {
            "key": "s3",
            "doc_count": 1,
            "avg_score": {
              "value": 80
            }
          }
        ]
      }
    }
  }
}

As you can see the result contains buckets with key as subject name and avg_score.value as the avg of marks.
UPDATE to include weighted_avg:
{
  "query": {
    "match": {
      "class": "10th"
    }
  },
  "aggs": {
    "subjects": {
      "nested": {
        "path": "subject"
      },
      "aggs": {
        "subjects": {
          "terms": {
            "field": "subject.name"
          },
          "aggs": {
            "avg_score": {
              "avg": {
                "field": "subject.marks"
              }
            },
            "weighted_grade": {
              "weighted_avg": {
                "value": {
                  "field": "subject.marks"
                },
                "weight": {
                  "field": "subject.weight"
                }
              }
            }
          }
        }
      }
    }
  },
  "size": 0
}


text:
Q: run schedule task before windows service starts I want to run a schedule task before a specified windows service (Service A). Service A starts automatically.
What is the best approach to take? Do I need to convert the schedule task into a service (Service B) and configure Service A to depend on Service B?
Thanks

A: Services can't depend on scheduled tasks, so you can't do it that way.
Making a service depend on another may not do what you need, either; That just makes sure that service B is running when service A is started. If you need your custom task to finish its operations first, that won't help you.
What you can do is set the service to Manual start, and have your task start the service after doing what ever else it must do.


text:
Q: Implicit derivative of $e^y$ I am confused about this problem of finding the derivative of $e^y$ when differentiating with respect to $x$. The whole problem is to differentiate $y = x \, e^y$ with respect to $x$ but I get stuck on $\frac{d}{dx}(e^y)$.
I use the chain rule and end up with
$(e^y)(y)(\frac{dy}{dx})$, derivative of the outside times inside times derivative of the inside, but when I look up online to check my answer it seems that $\frac{d}{dx}(e^y) = (e^y)(\frac{dy}{dx})$. I'm confused where my extra $y$ went?
Any help would be greatly appreciated.

A: $$\frac{\ d}{\ dx}e^y$$
First take the derivative like you "normally would":
$$e^y$$
Then take the derivative of the stuff substituted "inside", the stuff where an $x$ would usually be:
$$\frac{\ d}{\ dx} y=\frac{\ dy}{\ dx}$$
Multiply them together.
$$e^y • \frac{dy}{dx}$$
Summarized mathemetically,
$$\frac{du}{dx}=\frac{du}{dy}•\frac{dy}{dx}$$
Where here $u=e^y$.

A: You can see it more clearly if you write it down this way:
$$\frac{d}{dx}e^{y}=\frac{d}{dx}e^{y(x)} = (e^{y(x)})'$$
So just apply the chain rule:
$$(e^{y(x)})' = y'(x)e^{y(x)} = \frac{dy}{dx}e^y$$


text:
Q: Using multipart/form-data Form I am writing an Application to Upload Image files in to the server.
I am declaring a form giving the type as enctype="multipart/form-data">
I have declare few hidden variables also inside this form. When I am trying to get the Values of these hidden variable inside a Servlet it comes as "Null".
If I remove the enctype, I could retrieve the correct values of the variable.
JSP Form :

    <FORM name="form1" enctype="multipart/form-data"><!-- T1787NM -->

                <input type=hidden name="stringurl" value="<%=stringurl%>">
                <input type=hidden name="savetype" value="<%=ACTION%>">
                <INPUT type="hidden" name="iReq" value="<%=iReq%>">
                 <INPUT type="File" name="FileUpload" id="fileInput">
    </FORM>

Servlet :

String stringurl=(String) req.getParameter("stringurl");
other code..

I want to know how to access these variables in Servlet. Thanks in Advance.

A: You need to write following code in servlet
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
    } else {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<?> items = null;
        String stringUrl = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        Iterator<?> itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            if (item.isFormField()) {
                System.out.println("Form Field");
                String parameterName = item.getName();
                if(parameterName.equals("stringurl")) {
                    stringUrl = item.getString();
                }
            } else {
                // upload file logic here
            }
        }
    }

likewise you need to get all other form fields using if else ladder.
Also you have to add commons-fileupload.jar, commons-logging.jar and commons-io.jar to project build path.


text:
Q: how to get 1 minute price data of a specific time and date from yfinance? I wanna know how can i get 1 minute gold price data of a specific time and date interval (such as an 1 houre interval in 18th october: 2021-10-18 09:30:00 to 2021-10-18 10:30:00) from yfinance or any other source in python?
my code is:
gold = yf.download(tickers="GC=F", period="5d", interval="1m")

it seems it`s just possible to set period while i wanna set specific date and time intervals.
thanks

A: Your call to yfinance returns a Pandas DataFrame with datetime as the index. We can use this to filter the dataframe to only entries between our start and end times.
import yfinance as yf
from datetime import datetime

gold = yf.download(tickers="GC=F", period="5d", interval="1m")

start = datetime(2021, 10, 18, 9, 30, 0)
end = datetime(2021, 10, 18, 10, 30, 0)

filtered = gold[start: end]

Outputs
                                  Open         High  ...    Adj Close  Volume
Datetime                                             ...
2021-10-18 09:30:00-04:00  1770.099976  1770.099976  ...  1767.599976    1035
2021-10-18 09:31:00-04:00  1767.900024  1769.099976  ...  1768.500000     467
2021-10-18 09:32:00-04:00  1768.599976  1769.300049  ...  1769.199951     428
2021-10-18 09:33:00-04:00  1769.300049  1770.199951  ...  1769.099976     750
2021-10-18 09:34:00-04:00  1769.199951  1769.300049  ...  1767.800049     549
...                                ...          ...  ...          ...     ...
2021-10-18 10:26:00-04:00  1770.300049  1770.500000  ...  1769.900024     147
2021-10-18 10:27:00-04:00  1769.800049  1769.800049  ...  1769.400024     349
2021-10-18 10:28:00-04:00  1769.400024  1770.400024  ...  1770.199951     258
2021-10-18 10:29:00-04:00  1770.300049  1771.000000  ...  1770.099976     382
2021-10-18 10:30:00-04:00  1770.300049  1771.000000  ...  1770.900024     180

[61 rows x 6 columns]

A: Edit 2021-10-25
To clear my answer. Question was:

i wanna set specific date and time intervals. thanks

All you need is in the code documentation.
So start and end could be date or _datetime
        start: str
            Download start date string (YYYY-MM-DD) or _datetime.
            Default is 1900-01-01

Example code:

Note: something wrong with timezones, i've tryed to pass correcth timezone with start and end but lib didn't handle it correctly and I was finish with convert it manually)

import pandas as pd
import yfinance as yf
import pendulum
pd.options.display.max_rows=10  # To decrease printouts
start = pendulum.parse('2021-10-18 09:30').add(hours=7)  # My tz is UTC+03:00, original TZ UTC-04:00. So adds to my local time 7 hours
end = pendulum.parse('2021-10-18 10:30').add(hours=7)  # Same
print(start)
print(yf.download(tickers="GC=F", interval="1m", start=start, end=end))

Result and you can pass whatever datetime ranges you want:
2021-10-18T16:30:00+00:00
[*********************100%***********************]  1 of 1 completed
                                  Open         High          Low        Close  \
Datetime
2021-10-18 09:30:00-04:00  1770.099976  1770.099976  1767.400024  1767.800049
2021-10-18 09:31:00-04:00  1767.900024  1769.099976  1767.800049  1768.500000
2021-10-18 09:32:00-04:00  1768.599976  1769.300049  1768.199951  1769.199951
2021-10-18 09:33:00-04:00  1769.300049  1770.199951  1768.900024  1769.099976
2021-10-18 09:34:00-04:00  1769.199951  1769.300049  1767.599976  1767.800049
...                                ...          ...          ...          ...
2021-10-18 10:25:00-04:00  1769.900024  1770.400024  1769.800049  1770.300049
2021-10-18 10:26:00-04:00  1770.300049  1770.500000  1769.900024  1769.900024
2021-10-18 10:27:00-04:00  1769.800049  1769.800049  1769.099976  1769.400024
2021-10-18 10:28:00-04:00  1769.400024  1770.400024  1769.400024  1770.199951
2021-10-18 10:29:00-04:00  1770.300049  1771.000000  1769.900024  1770.099976

                             Adj Close  Volume
Datetime
2021-10-18 09:30:00-04:00  1767.800049       0
2021-10-18 09:31:00-04:00  1768.500000     459
2021-10-18 09:32:00-04:00  1769.199951     428
2021-10-18 09:33:00-04:00  1769.099976     750
2021-10-18 09:34:00-04:00  1767.800049     549
...                                ...     ...
2021-10-18 10:25:00-04:00  1770.300049     134
2021-10-18 10:26:00-04:00  1769.900024     147
2021-10-18 10:27:00-04:00  1769.400024     349
2021-10-18 10:28:00-04:00  1770.199951     258
2021-10-18 10:29:00-04:00  1770.099976     382

[60 rows x 6 columns]

PS: with start and end you do not have limitation to the last 7 days, but still have limit to the last 30 days:
1 Failed download:
- GC=F: 1m data not available for startTime=1631980800 and endTime=1631998800. The requested range must be within the last 30 days.

Original
this lib has a lack of documentation. But this is python and as result it some kind of self-documented.
Read definition of download function here
https://github.com/ranaroussi/yfinance/blob/6654a41a8d5c0c9e869a9b9acb3e143786c765c7/yfinance/multi.py#L32
PS this function have start= and end= params that I hope help you


text:
Q: Entity Framework model or viewmodel for listing data? Just imagine that I have a model with 20 fields and I have 1000 records now but my database is growing up every day, then I want to list them in a razor page and show all of them but just 5 of fields needed.
I just want to know is it OK if I return the model with all fields to my view and choose the fields I need in my view or I should create a viewModel with that fields I just need ? I am worried about the performance.

A: Definitely create a viewmodel to expose just the fields you need. Don't expose any fields that you don't need for both performance and possibly security reasons.

A: Of course you could filter your data on server side or client side. But the best approach is filtering data on server side to keep your server load and  network traffic as less as possible. It also makes your application more responsive and with better performance. Use IQueryable Interface for server side filtering (check here for more information).
One side effect of using server side filtering is having better security.

A: For small numbers like this, it really doesn't matter. Performance wise, you won't see much of a difference. I also would not worry about security.
What I would worry about is organization of your code. Do you want to couple your views to your database models? If that's ok with you, than go for it!
Edit:
I still think the decision to return the model or not should not be based on potential performance hits, but instead about your code organization.
When you are talking about displaying a larger set of records, then you'll need a way to display them (i.e. some grid with paging ...), I would sugguest you consider keeping an IQueryable all the way. There are producs that can take an IQueryable and provide paging, sorting, searching on your data.
Grid.Mvc
Telerik

A: With the viewModel you can encapsulate your properties by only passing the fields that are required on the page. When you work with a large amount of fields then yes there might be a performance gain in using the ViewModel. And by using the ViewModal you keep your application clean and all the logic separated. :)


text:
Q: Audit all insert, delete, update and select statements on a schema in Oracle 12.2 I cannot understand how to create a Unified Audit policy in order to audit all INSERT, UPDATE, DELETE and SELECT statements performed on all the objects within a specific schema.
The goal is to track the tables and views involved in a specific PL/SQL procedure for a reverse engineering task.
For what I understood from the documentation, the only option is to specify each table/view to track within the policy. Is there an "audit all objects within a schema" construct for the create audit policy statement?

A: There is no "audit all objects" setting. In unified auditing, do the following:
-- create the policy
create audit policy my_policy actions all on hr.regions;
alter audit policy my_policy actions all on hr.locations;
...

-- enable the policy
audit policy my_policy;

if you have a schema with a lot of tables, you can use SQL to build your script with something like this:
select 'alter audit policy hr_policy actions all on '||owner||'.'||table_name||';'
  from dba_tables
 where owner in ('HR','OE');

A: You described traditional auditing. For unified auditing the parameter audit_trail has no meaning and is actually not considered by Oracle. As mentioned earlier, with unified auditing you have to create an audit policy.
Oracle does not write to SYS.AUD$ with unified auditing. It writes to audsys.aud$unified or spillover files on the OS (if the DB is not accessible). Your data is visible through the view unified_audit_trail, which selects from audsys.aud$unified and v$unified_audit_trail (spillover files).
To audit all insert,update,delete,select on a table scott.t1 you would use something like
create audit policy T1_AUDIT
       ACTIONS select on scott.t1,
               insert on scott.t1,
               update on scott.t1,
               delete on scott.t1;

audit policy T1_AUDIT;

A: Creating a policy is not necessary
AUDIT SELECT TABLE, UPDATE TABLE, INSERT TABLE, DELETE TABLE BY hr, oe;

will do the job

A: The following AUDIT statements are not limited only to 1 schema, but to all.
AUDIT ALL BY USER_NAME BY ACCESS;
AUDIT SELECT TABLE, UPDATE TABLE, INSERT TABLE, DELETE TABLE BY USER_NAME BY ACCESS;
AUDIT EXECUTE,PROCEDURE BY USER_NAME BY ACCESS;

Keep in mind that your audit_trail has to be set to DB,EXTENDED
Check your current audit_trail setting with:
SHOW PARAMETER AUDIT;

If it's not set to DB,EXTENDED   , you have to set it with:
alter system set audit_trail=db,extended scope=spfile;

In order the change of audit_trail take effect, you have to restart your DB instance.
You will find audit records in SYS.AUD$ afterwards.


text:
Q: Need to simplify this long javascript line You can see that the below function contain a long line of code...
I want to simplify this...
One idea would be to use multiple variable but I don't want to do so...
Any idea on how can I simplify this?
function updateStatusBar() {
  var text = textarea.value;
  statusBar.value = "Words: " + (text.split(/\b\S+\b/g).length - 1) + "  Characters: " + text.replace(/\n|[" "]/g, "").length + " / " + text.replace(/\n/g, "").length;
}

A: You can use other functions to break down functionality:
function updateStatusBar() {
    var text = textarea.value;
    statusBar.value = "Words: " +  getWordCount(text) + "  Characters: " + getCharCount(text);
}

function getWordCount(text) {
    return (text.split(/\b\S+\b/g).length - 1);
}

function getCharCount(text) {
    return text.replace(/\n|[" "]/g, "").length + " / " + text.replace(/\n/g, "").length;
}


text:
Q: asp mvc 5 Attribute routing not firing I'm trying to use the attribute routing in a new project, but I can't get it to work.
Here is what I have so far :
[RoutePrefix("Product")]
public class ProductController : Controller
{

    [Route("{id}/{title}", Name = "Product Details")]
    public ActionResult Index(int id = 0, string title = "")
    {
        Product p = Product.Get(id);

        return View(p);
    }
}

And here is my RouteConfig.cs :
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        //routes.MapRoute(
        //    "Product Details",
        //    "Product/{id}/{title}",
        //    new { controller = "Product", action = "Index", id = UrlParameter.Optional, title = UrlParameter.Optional }
        //);

        routes.MapRoute(
            name: "DefaultIndex",
            url: "{controller}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

    }
}

If I remove the Routing attributes and uncomment the first route in my RouteConfig.cs it works fine, but I'd like to stick with route attributes.
Any idea why it's not working correctly ?
The URL I want to use is : http://www.mydomain.com/Product/12345/ProductName
EDIT, here is my Application_Start()
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleMobileConfig.RegisterBundles(BundleTable.Bundles);

}

A: Looks like its treating the {id} as an action.
Try this:
[Route("{id:int}/{title}", Name = "Product Details")]

Or this
[Route("Product/{id}/{title}", Name = "Product Details")]


text:
Q: Why does using REPLACE function on CLOB cause increase in CACHE_LOBS...? I have a requirement to use the built in REPLACE function on a CLOB variable as part of a larger PL/SQL process. I'm using Oracle 11g R2 and the function works OK, in that it does the replace as required, but as the procedure runs (there are around 2.5 millions records to process), it slows down badly - as in:

*

*first 20,000 records: ~12 minutes

*second 20,000 records: ~24 minutes

*third 20,000 records: ~37 minutes

*fourth 20,000 records: ~52 minutes

*etc...

Checking V$TEMPORARY_LOBS during operation shows that the value for CACHE_LOBS increases with every row processed - my assumption is that this implies that memory associated with LOBS (CLOBS in this case) is not getting released once it has been used...?
Stepping through the code using PL/SQL debugger reveals that the value for CACHE_LOBS increases by 2 for every call to the REPLACE function. The function calls are along the lines of:
clobRTFText         CLOB;
...
dbms_lob.createtemporary(clobRTFText, TRUE, dbms_lob.call);
...
clobRTFText := REPLACE(clobRTFText, '<CR>', '\par ');  <== Causes CACHE_LOBS to increase by 2
...
dbms_lob.freetemporary(clobRTFText); <== Doesn't seem to cause CACHE_LOBS to decrease

It's as though the third line of code above is creating further CLOB variables on the fly. Is that because there is some kind of implicit type conversion occurring due to the REPLACE function expecting a VARCHAR2 parameter? I've tried using dbms_lob.copy instead of "clobRTFText := REPLACE...etc", but it actually was worse (i.e. CACHE_LOBS increased even quicker). Whatever the reason, the call to dbms_lob.freetemporary doesn't seem to make any difference to the value of CACHE_LOBS.
I've gone through the PL/SQL Semantics for LOBs section of the Oracle documentation - it mentions the way CLOB and VARCHAR2 variables can be used in built-in functions but I can't find anything about doing so potentially causing extra memory usage.
Does anyone have any ideas why this is happening or how I could do it (i.e. use REPLACE with a CLOB) without it failing to releasing memory (assuming that is indeed what is happening)?
Thanks

A: Why do this procedurally? It seems a declarative approach fulfills the requirements.
UPDATE clob_table SET clob_column = REPLACE(clob_column, '<CR>', '\par ');
You can supply whatever WHERE clause that suits you.


text:
Q: Python Frequency Distribution (FreqDist / NLTK) Issue I'm attempting to break a list of words (a tokenized string) into each possible substring. I'd then like to run a FreqDist on each substring, to find the most common substring. The first part works fine. However, when I run the FreqDist, I get the error:
TypeError: unhashable type: 'list'

Here is my code:
import nltk

string = ['This','is','a','sample']
substrings = []

count1 = 0
count2 = 0

for word in string:
    while count2 <= len(string):
        if count1 != count2:
            temp = string[count1:count2]
            substrings.append(temp)
        count2 += 1
    count1 +=1
    count2 = count1

print substrings

fd = nltk.FreqDist(substrings)

print fd

The output of substrings is fine. Here it is:
[['This'], ['This', 'is'], ['This', 'is', 'a'], ['This', 'is', 'a', 'sample'], ['is'], ['is', 'a'], ['is', 'a', 'sample'], ['a'], ['a', 'sample'], ['sample']]

However, I just can't get the FreqDist to run on it. Any insight would be greatly appreciated. In this case, each substring would only have a FreqDist of 1, but this program is meant to be run on a much larger sample of text.

A: I'm not completely certain what you want, but the error message is saying that it wants to hash the list, which is usually a sign it's putting it in a set or using it as a dictionary key.  We can get around this by giving it tuples instead.
>>> import nltk
>>> import itertools
>>>
>>> sentence = ['This','is','a','sample']
>>> contiguous_subs = [sentence[i:j] for i,j in itertools.combinations(xrange(len(sentence)+1), 2)]
>>> contiguous_subs
[['This'], ['This', 'is'], ['This', 'is', 'a'], ['This', 'is', 'a', 'sample'],
 ['is'], ['is', 'a'], ['is', 'a', 'sample'], ['a'], ['a', 'sample'],
 ['sample']]

but we still have
>>> fd = nltk.FreqDist(contiguous_subs)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/nltk/probability.py", line 107, in __init__
    self.update(samples)
  File "/usr/local/lib/python2.7/dist-packages/nltk/probability.py", line 437, in update
    self.inc(sample, count=count)
  File "/usr/local/lib/python2.7/dist-packages/nltk/probability.py", line 122, in inc
    self[sample] = self.get(sample,0) + count
TypeError: unhashable type: 'list'

If we make the subsequences into tuples, though:
>>> contiguous_subs = [tuple(sentence[i:j]) for i,j in itertools.combinations(xrange(len(sentence)+1), 2)]
>>> contiguous_subs
[('This',), ('This', 'is'), ('This', 'is', 'a'), ('This', 'is', 'a', 'sample'), ('is',), ('is', 'a'), ('is', 'a', 'sample'), ('a',), ('a', 'sample'), ('sample',)]
>>> fd = nltk.FreqDist(contiguous_subs)
>>> print fd
<FreqDist: ('This',): 1, ('This', 'is'): 1, ('This', 'is', 'a'): 1, ('This', 'is', 'a', 'sample'): 1, ('a',): 1, ('a', 'sample'): 1, ('is',): 1, ('is', 'a'): 1, ('is', 'a', 'sample'): 1, ('sample',): 1>

Is that what you're looking for?


text:
Q: Internet Explorer 11 fantastically lying about pixels On http://quizdash.co.uk/  Internet Explorer got HUGE error: it scaling site content to all screen, but in develepment panel, it say that content not scaled and has original size.
http://storage2.static.itmages.com/i/16/0201/h_1454300006_8737908_ad9e854b85.png
Of course, scale option=100%.
Other browsers show site correctly.
Is this undocumented feature of modern IE? Can I with css/html make IE do not scale site?

A: It's not an error in IE or an undocumented feature.
In your vendor.css, the following CSS appears:
@-ms-viewport{width:10in;zoom:1;initial-scale:1;max-zoom:1}

@-o-viewport{width:10in;zoom:1;initial-scale:1;max-zoom:1}

@viewport{width:10in;zoom:1;initial-scale:1;max-zoom:1}

That's causing the page to scale with the viewport. The only browsers that support @viewport are IE and Opera Mini, so the page will only scale in those browsers. As far as the CSS is concerned, the page is displaying correctly in IE, not the other browsers, so your assertion that the other browsers are showing the site correctly is wrong. However I cannot comment on whether IE is "lying" about computed pixel sizes because I don't know how or if viewport scaling should affect computed values.
If you don't want the page to scale with the viewport, don't use @viewport.


text:
Q: Probability question - how many cycles before all items are chosen I have a container of 100 yellow items.
I choose 2 at random and paint each of them blue.
I return the items to the container.
If I repeat this process, on average how many cycles will I make before all 100 items are painted?
It is obviously 50 (100/2) if there is no replacement. But in this case, the items are returned to the container, so the same item could be chosen often.
What if we choose 3?

A: You could calculate the exact figure for the expected number using recursion and find the mean is about $258.32$ with a standard deviation of about $62.59$.
Alternatively, if you took the balls one at a time, this would be the Coupon Collector's Problem, with an expected value of $100H_{100} \approx 518.74$: you then need to halve this as you are taking items two at a time, so giving about $259.37$.  The actual answer differs from this for two reasons: your pair of items are distinct, reducing the number needed, but this is slightly offset by the possibility that the first item of the final pair is the last that needs to be painted.

A: If you choose 1 item each time, then the expected time until the items are all painted is $n \ln(n)$; This is the coupon collector problem.
http://en.wikipedia.org/wiki/Coupon_collector%27s_problem
If you take 2 at random each time it should take about half that time, because you speed up the process by a factor of two, so about $\frac{n \ln(n)}{2} $.

A: By inclusion-exclusion, the probability that all items have been painted after $m$ batches of $b$ items each have been painted is
$$
\sum_{k=0}^{100}(-1)^k\binom{100}k\left(\frac{\binom kb}{\binom{100}b}\right)^m\;.
$$
Thus the expected number of cycles required is
\begin{align}
\sum_{m=0}^\infty\left(1-\sum_{k=0}^{100}(-1)^k\binom{100}k\left(\frac{\binom kb}{\binom{100}b}\right)^m\right)
&=
\sum_{m=0}^\infty\sum_{k=0}^{99}(-1)^{k+1}\binom{100}k\left(\frac{\binom kb}{\binom{100}b}\right)^m
\\
&=
\sum_{k=0}^{99}(-1)^{k+1}\binom{100}k\frac1{1-\frac{\binom kb}{\binom{100}b}}\;.
\end{align}
For $b=2$, this is
$$
\sum_{k=0}^{99}(-1)^{k+1}\binom{100}k\frac1{1-\frac{k(k-1)}{9900}}=\\
\frac{4422524992331899897840584824409871573709079567200239855874554436668439024460525976895}{17120632903554452293765076229371169353453854260451613330736867261419928839179604592}\\\approx258.32\;,
$$
in agreement with Henry's answer. For $b=3$, it is
$$
\sum_{k=0}^{99}(-1)^{k+1}\binom{100}k\frac1{1-\frac{k(k-1)(k-2)}{970200}}\approx171.51\;,
$$


text:
Q: Angular 2: Implementing HTTP POST Request In my Angular 1.x application I am doing following on a form submit.
$scope.submit = function() {
    console.log('Saving Form Data..');
    $scope.selection_array = [];
    for ( var j = 0; j < $scope.checkboxlist.length; j++ ){
        if ($scope.checkboxlist[j].selected) {
            console.log($scope.checkboxlist[j]);
            $scope.selection_array.push($scope.checkboxlist[j].key);
        }
    }

    if ($scope.selection_array.length>0) {
        $http({
            method : 'POST',
            url : BASE_URL + '/user/selection',
            headers : {
                'Content-Type' : 'application/json'
            },
            params : {
                access_token : localStorage.getItem("access_token")
            },
            data : $scope.selection_array
        }).success(function(response) {
            console.log('response=>' + response);
            $window.alert('Your items have been saved successfully');
        }).error(function() {
            console.log('failure in updaing');
            $window.alert('Error saving items. Please try again');
        });
    } else {
        $window.alert('Please select one or more items');
    }
}

What I am doing here is, getting the selected items from a checkbox list and save that list to database by calling backend service call. Now I need to convert this code to Angular 2.
TRIED
In my service.ts file I use following.
saveUserInterests(selected_interests) {
    console.log(selected_interests);

    var headers = new Headers();
    headers.append('Content-Type', 'application/json');

    var params = new URLSearchParams();
    params.set('access_token', localStorage.getItem('access_token'));

    return this.http.post('http://localhost:8080/user/interests',
        JSON.stringify(selected_interests),
        {
            headers: headers,
            search: params
        }).map(res => res.json());
}

Then I call this service as below in my interst.ts file.
private selected_interests;

onSubmit() {
    console.log('Inside onsubmit');
    var selected_interests = [];
    for (var j = 0; j < this.interests.length; j++) {
        if (this.interests[j].selected) {
            console.log(this.interests[j]);
            selected_interests.push(this.interests[j].key);
        } else {
            console.log('else');

        }
    }
    this.selected_interests = selected_interests;
    console.log(this.selected_interests);

    this.dataService.saveUserInterests(this.selected_interests).subscribe(
        (res) => {
            console.log('response=>' + res);
            alert('Your items have been saved successfully');
        },
        (error) => {
            console.log('failure in updaing');
            alert('Error saving items. Please try again');
        });
}

This gives following error on console log.
Rx.js:10982 Uncaught EXCEPTION: Error during evaluation of "ngSubmit"
ORIGINAL EXCEPTION: TypeError: Cannot read property 'subscribe' of undefined
ORIGINAL STACKTRACE:
TypeError: Cannot read property 'subscribe' of undefined

Any suggestions are highly appreciated

A: For the HTTP part, here is the way to do in Angular2:
constructor(private http:Http, private window:Window) {
}

submit() {
  var selectionArray = (...)

  var headers = new Headers();
  headers.append('Content-Type' : 'application/json');

  var params = new URLSearchParams();
  params.set('access_token', localStorage.getItem('access_token'));

  this.http.post(BASE_URL + '/user/selection',
         JSON.stringify(selectionArray),
         {
           headers : headers,
           search: params
         }).map(res => res.json())
         .subscribe(
           (data) => {
             console.log('response=>' + response);
             this.window.alert('Your items have been saved successfully');
           },
           (error) => {
             console.log('failure in updaing');
             this.window.alert('Error saving items. Please try again');
         });
}

See these links for more details:

*

*http://restlet.com/blog/2016/04/08/interacting-efficiently-with-a-restful-service-with-angular2-and-rxjs-part-1/

*Angular2 - How to inject window into an angular2 service


text:
Q: Running wrapper file continuously for using JFR to monitor ActiveMQ performance I have an issue about continuously running Java Flight Recorder to monitor memory usage and other performance statistics of ActiveMQ.

*

*Wrapper configuration file (wrapper.conf) is under this directory with nearside (wrapper, activemq, libwrapper.so) files;
../apache-activemq-5.12.1/bin/linux-x86-64/wrapper.conf

*I added the lines below to run JFR;
 wrapper.java.additional.13=-XX:+UnlockCommercialFeatures
 wrapper.java.additional.14=-XX:+FlightRecorder
 wrapper.java.additional.15=-XX:FlightRecorderOptions=defaultrecording=true,disk=true,repository=../jfr/jfrs_%WRAPPER_PID%,settings=profile
 wrapper.java.additional.16=-XX:StartFlightRecording=filename=../jfr/jfrs_%WRAPPER_PID%/myrecording.jfr,dumponexit=true,compress=true

*When I run wrapper file, expected output 'myrecording.jfr' is generated under specified path in wrapper.conf. But the problem is, I also want it to be happen automatically (without running wrapper file by hand).
What might be the possible solution for that?


text:
Q: how to print String one after another in java I want to know that I want to print string one after another but in a particular time interval.
Everything is fine.
I want to know that when second string print override the first one and third override the second and so on..
How can I do this?
This is my code :
public class StringTest {

  public static void main(String args[]) {

    String arr[] = { "mahtab", "hussain", "yasir", "azmi", "saif" };

    int l = arr.length;

    for (int i = 0; i < arr.length; i++) {
      System.out.print(arr[i]);
      try {
        Thread.sleep(5 * 1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}

A: You can simply do this with the carriage return \r.
System.out.print(arr[i]+"\r")

A: Use this
  for (int i = 0; i < arr.length; i++) {
  System.out.print(arr[i]);
  try {
    Thread.sleep(5 * 1000);
    for(int j=0;j<arr[i].length;j++){
        System.out.print("\b");
    }
  } catch (InterruptedException e) {
    e.printStackTrace();
  }

A: To remove the last character from the screen, you can use System.out.print("\b")


text:
Q: Factorization algorithm for a semiprime of 29-digits I'm looking for the fastest prime factorization algorithm for a semiprime of 29-digits.
There are many factorization algorithms there, so as far as I know (my background is not maths:)the key factor is the length of the number to be factorized. In this case, it has only 29 digits.
Many thanks

A: For a 29 digit semiprime number, elliptic curve factorization will suffice.
For larger semiprime numbers (around 92 digits and beyond) of a general form, the general number field sieve is the fastest factorization algorithm available.
As a practical matter, just download a program called YAFU, probably from SourceForge, for whatever platform you have. YAFU will factor semiprime numbers for you intelligently, starting with elliptic curve, and switching over to GNFS if needed. YAFU relies on GGNFS and ECM, so download those too as compiled binaries, and supply the paths to the folders the executables are in, in the yafu.ini configuration file, and you should be good to go. The configuration is straightforward, there is a ggnfs_dir and a ecm_path setting you have to set. Also choose how many threads to dedicate to the process. YAFU factors a 100 digit semiprime number (like the RSA-100 challenge number) in about an hour on my machine.
To run YAFU, simply run the yafu-Win32.exe or whatever on the command line and then type:
factor(YOUR_NUMBER_HERE)
So, to factor the RSA-100 number, you would type:
factor(1522605027922533360535618378132637429718068114961380688657908494580122963258952897654000350692006139)
For a number of your size, 29 digits, I imagine it will take a few seconds.
If you are interested in learning the GNFS, first start by reading the Wikipedia on it to get a general overlay of the algorithm. When I was trying to learn it, I read a lot of C code, but the problem with that code is it was meant for performance, not readability. Anyways, I ended up writing an implementation of the GNFS in C#. The goal, beyond learning the GNFS, was to make the code readable, not performance, so people could read it to learn the algorithm, like I wish I had when I was learning. If you are interested, my code is on my GitHub. I also have uploaded a number of whitepapers that I read and referenced in order to help me write the application. The address is https://github.com/AdamWhiteHat/GNFS


text:
Q: How to unmarshal from interface{} to interface{} in Go There are multiple nodes in my system which communicate through RPC. I am trying to send a map[string] interface{} to another node through RPC. Sender uses json.Marshal and receiver uses json.Unmarshal to get the map.
Let us say at the sender side, map contains [1] => 2 where 2 is of type uint32.
The problem is Unmarshal tries to find the type of underlying data and converts 2 to float64 type according to its default behavior as specified here https://blog.golang.org/json-and-go. Later, casting float64 to uint32 causes panic.
I refered to How to unmarshal json into interface{} in golang? . But for this, we need to know the type of data. In my case data can be of any type so I want to keep it as interface{}. How do I unmarshal from interface{} to interface{}?

A: Unfortunately using the encoding/json package you can't, because type information is not transmitted, and JSON numbers by default are unmarshaled into values of float64 type if type information is not present. You would need to define struct types where you explicitly state the field is of type uint32.
Alternatively you may opt to use encoding/gob which does transmit and preserve type information. See this example:
m := map[string]interface{}{"1": uint32(1)}

b := &bytes.Buffer{}
gob.NewEncoder(b).Encode(m)

var m2 map[string]interface{}
gob.NewDecoder(b).Decode(&m2)
fmt.Printf("%T\n%#v\n", m2["1"], m2)

Output (try it on the Go Playground):
uint32
map[string]interface {}{"1":0x1}

The downside of gob is that it's Go-specific unlike the language and platform independent JSON.


text:
Q: Is there a noticable difference between OB SATA bandwidth vs PCI-e SATA Controller Main Question : Would I see any benefit (I/O bandwidth-wise) to purchasing a separate (non-raid) PCI-e controller card to plug SATAII drives into vs on-board SATAII slots?
I'd be plugging at least four drives into whichever solution I go with.
Context :
For portability reasons, I'm running a fileserver in a VM (the physical machine is dedicated explicitly for running this VM), serving files from a number of virtual disks each located on its own physical hard-drive. The host has its own dedicated drive, and the VM is also on its own physical, software-raid-mirrored drive. Occasionally I'll see some slowdowns in the I/O for reading/writing files to/from the server and I'm suspecting the fact that right now all of this is being done over the PCI bus. (Limited to 100Mb/s vs 150Mb/s for SATA).
I was willing to tolerate being limited to 100Mb/s via the PCI bus, but I'm starting to want something faster.
The machine that is running all this is a little old (P4, no PCI-e slot) so I'm considering an upgrade. I'd like whatever solution I end up going with (just a new board with >4 SATAII connections or a new board and a PCI-e controller card with 4 SATAII connections) to have as much bandwidth as possible for the disks, without getting into enterprise-level controller cards etc.

A: No, you won't see any benefit. In fact there might be a very slight performance decrease if you use the PCI-e SATA controller.

A: Third-party SATA controllers usually are for hardware RAID configurations and people who don't have enough SATA ports on their motherboard.  Unless you need the advanced RAID features (or if you have enough ports on your motherboard), don't bother.
When I say "advanced" I don't mean non-standard RAID levels.  I just mean that it removes most of the software-related overhead by using RAID (which is even present to some extent with onboard systems).

A: Is there a noticable difference between OB SATA bandwidth vs PCI-e SATA Controller?
tl;dr: rarely but it is possible. Onboard devices have only 2 or 4 GByte/s bandwidth which you can saturate while some PCIe slots are directly CPU attached with much more bandwidth.
On board SATA on Intel motherboards these days are fed from the chipset which is connected to the CPU by the DMI bus. DMI 3.0 has the same bandwidth as PCIe 3.0 x4 just a hair below 4GByte/s. Not only the SATA devices are fed from this connection but everything else on the MB as well, including M.2 (max 4 GByte/s), USB 3.1 Gen 1 (5 Gbit/s) and Gen 2 (10 Gbit/s) controllers, and some PCI Express slots as customer Intel CPUs only have 16 PCI Express lanes on the CPU, the rest is supplied by the chipset.
Now you can see where the trouble is and motherboard makers know this as well because using a single M.2 slot typically disables two SATA ports. The M.2 slot itself uses at most one SATA lane but the trouble is when that's not used because you are using a PCIe based M.2 drive which singlehandedly eats enough bandwidth to consume the bandwidth of the entire DMI bus.
So on an LGA 1151 based consumer board if

*

*A PCIe M.2 SSD is used

*The SATA controller is in a CPU-fed PCI Express slot (your motherboard manual will tell you which one it is, sometimes you can configure your slots to be like x8 + x8 or x8 + x8 + x4)

then the SATA controller will be faster. Otherwise, you are fighting for the same DMI bus bandwidth so it doesn't matter. Do note, however, this is mostly theoretical, even the fastest SSDs currently do not eat more than 2.5GByte/s so unless you try to do something like copying from a Samsung 960 Pro to four SATA SSDs in RAID-0 you won't hit the bandwidth cap.
On an LGA 2011v3 motherboard the situation is even more interesting. The X99 chipset only supports DMI 2.0 which is half the speed, that is 2GByte/s and since a single plain SATA disk can consume .5GByte/s if you want to go above four SATA disks then going with a PCI Express controller will be faster because on these motherboards typically two x16 and one x8 slot (or in rarer cases, five x8) is fed directly from the CPU as most LGA 2011v3 chips except for the 6800K and the 5820K have 40 PCI Express lanes.
Finally, if you are using an older board with Z97 or older chipset which only supports DMI 2.0 at 2GB/s then again a single M.2 slot (some Z97 boards had M.2 slots) or four SATA disks will consume the available bandwidth and then the CPU fed slot card will be faster again.


text:
Q: nginx denies all requests to a virtual host . requests are coming from a nginx tcp forwarder Summary - need to add whitelist ips to the mysite1.example.com. now when they are added it doesn't work as every request is coming as originated from the load balancer server.
Im working on a setup with a front seating Nginx host with a upstream backend to loadbalance all tcp packets on port 443 to backend servers.
nginx config of Loadbalancer server running nginx - server C is as below
stream {
        upstream stream_backend {
                hash $remote_addr consistent;
                server 10.15.15.3:443;   ## server A
                server 10.15.15.9:443;   ## server B
        }

        server {
                listen     443;
                proxy_pass stream_backend;
                proxy_timeout 5s;
                proxy_connect_timeout 5s;
        }
}

server A and server B has below nginx.conf. they are identical servers with apps.
it has two virtual hosts running in each. they are working fine.
http {

    server {
        server_name mysite1.example.com;
        listen *:443 ssl;
        listen [::]:443 ssl;

        allow 123.45.85.220; # this seems not working
        deny all; # only this is working

        location ^~ /static/ {
            ...
        }
        ...

        ssl_certificate        file.pem;
        ssl_certificate_key    file.key;
    }

    server {
        server_name mysite2.example.com;
        listen *:443 ssl;
        listen [::]:443 ssl;

        location /somethin {
            ...
        }
        location /something2{
            ...
        }

        ssl_certificate        file.pem;
        ssl_certificate_key    file.key;
    }
}

what I need is to whitelist only few ips to the  virtual host  mysite1.example.com.
the issue I face is that the nginx running on Server  A and B see the load balancer Ip as the client Ip. so when tried adding allow IP; deny all. doesn't work for any host as it has the load balancer IP on all requests as the client IP.
Can someone guide me on adding proxy IP configs to achieve the above mentioned setup running fine.
Setup is complete except for the IP whitelist issue.
p.s SSl termination happens at the back-end servers , server A and Server B
I've searched through the web and found these helpful but still couldn't figure out how to get it all working.
https://stackoverflow.com/questions/40873393/nginx-real-client-ip-to-tcp-stream-backend
https://www.cyberciti.biz/faq/nginx-redirect-backend-traffic-based-upon-client-ip-address/

A: This is happening because your nginx load balancer makes a new TCP connection to your nginx web servers, causing the original client IP address to be lost.
You can solve this using the PROXY protocol. This protocol sends the original IP address information when the new connection is opened so that your web servers can be aware of it.
To set it up, you need to make the following changes:

*

*On the load balancer, set proxy_protocol on;:
stream {
    server {
        proxy_pass somewhere;
        proxy_protocol on;

*On the web server, accept the PROXY protocol, and enable the Real IP functionality for the load balancer's IP address.
server {
    listen 443 ssl http2 proxy_protocol;
    listen [::]:443 ssl http2 proxy_protocol;
    real_ip_header proxy_protocol;
    set_real_ip_from <load balancer's IP>;

There are additional tweaks you can make to the PROXY protocol which you can find in the nginx documentation but this should get you started and solve the immediate problem.

A: My approach would be:
Filter in the load balancer using SNI:
Basically: SNI allows the proxy to see the domain name, without terminating TLS. Here is a guide. And here are the nginx docs to combine it into a solution.
If you can do this, you can then deny based upon $ssl_preread_server_name.
if ( $ssl_preread_server_name ~* mysite1.example.com && $remote_addr !~* <whitelisted_ip> ) {
           return 404;

The real_ip module also seems like a good solution.
Edit
The PROXY protocol would actually be better than real_ip.
But this would still mean, that your backend servers get hit by requests that they'd end up blocking. The SNI solution catches them at the load-balancer.

A: seems like your proxy not passing the real IP
try to add this parameter
proxy_set_header X-Real-IP $remote_addr;

can you check the access logs which ip there ?


text:
Q: Convert datetime to string/varchar in SQL Server I have a view in SQL Server which uses dates to determine which tables to access data from. The problem is it only seems to work when given the date as a varchar like '20120423'.
So I am trying to dynamically create this date with GETDATE() instead of having to use the typed out version. When I run the top SELECT statement it returns '20120423' like I would expect but when I try to compare the two values they are not equal and the IF statement prints 'VALUES ARE NOT THE SAME'.
SELECT
    '''' +CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) +''''

IF '''' +CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) +''''  = '20120423'
BEGIN
    PRINT 'VALUES ARE THE SAME'
END
ELSE
BEGIN
   PRINT 'VALUES ARE NOT THE SAME'
END

I'm kind of lost as to where to go from here. Thanks for any help.
EDIT:
With the answers given then these two queries should be the same even though they are treated differently by my view.
SELECT *
FROM DatesView
WHERE Timestamp > CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112)

SELECT *
FROM DatesView
WHERE Timestamp > '20120423'

The top one looks through all tables where the bottom one correctly only searches the necessary tables.

A: You're getting thrown off by the quote marks, just remove them they are unnecessary.
SELECT CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112)

IF CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112)  = '20120423'
BEGIN
    PRINT 'VALUES ARE THE SAME'
END
ELSE
BEGIN
   PRINT 'VALUES ARE NOT THE SAME'
END

A: Delete the first two '. Try this.
You are comparing '20120423'=20120423
SELECT '' +CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) +''

IF '' +CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) +''  = '20120423'
BEGIN
    PRINT 'VALUES ARE THE SAME'
END
ELSE
BEGIN
   PRINT 'VALUES ARE NOT THE SAME'
END

A: You are adding apostrophes to the string, so your comparison is literally (replacing the string delimiters with brackets):
if ['20120423']  = [20120423]

I think you want:
IF CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112) = '20120423'

and/or
SELECT CONVERT(VARCHAR(8), DateAdd(YY,-2,GETDATE()), 112)