text:
Q: Can't compile because replace function improperly used? I stream in a text file, which uses semi colons to separate values.
I want to replace the semi colon with a colon, and stream out into a newly made .csv file
CURRENTLY, the program runs without an error during compiling, but when i specify an output filename,
it creates the .csv file then crashes.
I can not upload images in my post because I am a new member...
Here is the Visual Studio Output When I compile:
BEGIN
1>------ Build started: Project: export, Configuration: Release Win32 ------
1>  export.cpp
1>  Generating code
1>  Finished generating code
1>  export.vcxproj -> J:\Bar\OIL Final\export\Release\export.exe
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
END

Here is the 'guts' of the code:
string file_type = ".csv";                          //  Stores the Export

Filename Extension
    string file_path = "";                              //  Stores the
Export Filename and Path
    string filename;
bool validateExportFilename()
{
    bool valid_filename = false;                        // Holds the Bool Value which

maintains a loop until vaid file is found
    while (valid_filename == false)
    {
        std::cout << "\t\tPlease Enter A Name For These Results:\t";
        cin >> filename;

        file_path = export_folder + filename + file_type;

        ifstream check_filename;                        // Define the Input

File Stream --> using USER entered file name
            check_filename.open(file_path);                 // Open the file fresh - all
positions in memory (i.e. getline() location) will be reset.
        if (check_filename.fail())
        {
            t("FILE NAME IS VALID..."); //  TRACE MESSAGE
            valid_filename = true;
        }
        else
        {
            std::cout << "\n\t\t\t[!] ERROR - File Exists. Try again. [!]\n" << endl;   //

Notify USER of Error
                std::cout << "\n\n\t\t\t";
                // Format the pause command's screen output
            system("pause");

                    // Pause to give user the time to find the file
        }
        check_filename.close();
    }
    return 0;
}

if (inFile.is_open())
{
    while (!inFile.eof())
    {
        string line = "";
        getline(inFile, line);
        line.replace(line.begin(), line.end(), ";", ", ");
        outFile << line << endl;
    }
}

t("End Function - Replace");    //  TRACE MESSAGE

inFile.close();
outFile.close();

return 0;

Here is a sample of the data of the text file, i am trying to stream in, and turn into a CSV file:
4/09/2013;10:34:57 AM;4780;1129;63;32;19.9;17.7;13.5;12.6;OK;0;50;4.77;26; 144
4/09/2013;10:35:11 AM;4546;1117;69;30;19.8;17.7;13.7;12.5;OK;0;50;4.76;26; 143

And here is what i want to stream out to a different file, but with the extention .CSV instead of .TXT:
4/09/2013,10:34:57 AM,4780,1129,63,32,19.9,17.7,13.5,12.6,OK,0,50,4.77,26, 144
4/09/2013,10:35:11 AM,4546,1117,69,30,19.8,17.7,13.7,12.5,OK,0,50,4.76,26, 143

And here is what the debugger outputs when the program crashes:
The thread 0x1d5c has exited with code -1073741510 (0xc000013a).
The program '[10012] export.exe' has exited with code -1073741510 (0xc000013a).

Unhandled exception at 0x637B7666 (msvcr120.dll) in export.exe: Fatal program exit requested.

Call stack lists this:
msvcr120.dll!637b7666() Unknown
[Frames below may be incorrect and/or missing, no symbols loaded for msvcr120.dll]
[External Code]
>   export.exe!replaceAndExport() Line 204  C++
    export.exe!wmain() Line 79  C++

And under Autos:
-       inFile  {_Filebuffer={_Set_eback=0x00000000 <NULL> _Set_egptr=0x00000000 <NULL>

_Pcvt=0x00000000  ...} }  std::basic_ifstream >
    +       std::basic_istream >    {_Chcount=0 }
std::basic_istream >
    +       std::basic_ios >    {_Mystrbuf=0x001efb88 {_Set_eback=0x00000000
 _Set_egptr=0x00000000  _Pcvt=0x00000000  ...} ...}
std::basic_ios >
    +       _Filebuffer {_Set_eback=0x00000000  _Set_egptr=0x00000000  _Pcvt=0x00000000
 ...} std::basic_filebuf >
    -       line    ""  std::basic_string,std::allocator >
            [size]  0   unsigned int
            [capacity]  15  unsigned int
    +       [Raw View]  0x001efcd8 {...}
std::basic_string,std::allocator > *
    -       outFile {_Filebuffer={_Set_eback=0x00000000  _Set_egptr=0x00000000
_Pcvt=0x00000000  ...} }  std::basic_ofstream >
    +       std::basic_ostream >    {...}
std::basic_ostream >
    +       std::basic_ios >    {_Mystrbuf=0x001efc34 {_Set_eback=0x00000000
 _Set_egptr=0x00000000  _Pcvt=0x00000000  ...} ...}
std::basic_ios >
    +       _Filebuffer {_Set_eback=0x00000000  _Set_egptr=0x00000000  _Pcvt=0x00000000
 ...} std::basic_filebuf >
I can see the .CSV file being created, but the file remains empty at 0KB and a split second after the file is
created, the application crashes.
I feel like i may need to adjust the "read a line, swap commas in" process so i dont overflow the buffer, but
i am not a programmer so i dont really know...

A: As you've pointed out, the problem lies with the line line.replace(line.begin(), line.end(), ";", ", ");
Since you seem determined to emphasize on the fact that you're not a programmer, I will not go into detail as to why it compiles even though you're using it wrong. Instead, I will explain how this function is supposed to be used. While they are a number of variations to this function, the main purpose of string::replace is to replace a portion of one string with another string.
Simply put, I can use string::replace to change Hello World to Goodbye Cruel World by stating that I want Hello to be replaced with Goodbye Cruel. This, of course, works for not just the beginning but also any part of the string.
So that's not the function you want.
The function you want to use is present in <algorithm> called replace. replace is similar to string::replace except that instead of replacing a range, you specify the old value (in this case ';') and the new value (in this case ':') and you pass them into the function like this, replace(line.begin(), line.end(), ';', ':');. Now what replace will do is search through the range from line.begin() to line.end() for all instances of ';' and replace them with ':'.
Thank you for reading.


text:
Q: Table is not loaded using Spring boot i am creating simple spring boot application project. i have create two various controller those are student and course controller and Index controller is Index controller is a Main Page .when i ran the project index is loaded sucessfully.when i click the course link success visit to course page but course tables is not loaded and course page as link addnewcourse when i click that it will redirect to HTTP Status 404 – Not Found. i don't that what i was happing i attached the full source code on github link here https://github.com/raguram1986/SpringSecuritys
i attached the screenshot image below the folder structure.

Course Controller
 @Controller
    @RequestMapping("/Course")

    public class CourseController {

         @Autowired
            private CourseService service;

           @GetMapping("/")
            public String viewHomePage(Model model) {
                List<Course> listcourse = service.listAll();
                model.addAttribute("listcourse", listcourse);
                System.out.print("Get / ");
                return "course";
            }

            @GetMapping("/addcourse")
            public String add(Model model) {
                List<Course> listcourse = service.listAll();
                model.addAttribute("listcourse", listcourse);
                model.addAttribute("course", new Course());
                return "addcourse";
            }

            @RequestMapping(value = "/save", method = RequestMethod.POST)
            public String saveCourse(@ModelAttribute("course") Course course) {
                service.save(course);
                return "redirect:/";
            }

            @RequestMapping("/edit/{id}")
            public ModelAndView showEditCoursePage(@PathVariable(name = "id") int id) {
                ModelAndView mav = new ModelAndView("addcourse");
                Course course = service.get(id);
                mav.addObject("course", course);
                return mav;

            }
            @RequestMapping("/delete/{id}")
            public String deleteCoursePage(@PathVariable(name = "id") int id) {
                service.delete(id);
                return "redirect:/";
            }
    }

Domain
@Entity
public class Course {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;
    private String coursename;
    private int duration;

    public Course()
    {

    }

    public Course(Long id, String coursename, int duration) {

        this.id = id;
        this.coursename = coursename;
        this.duration = duration;
    }

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getCoursename() {
        return coursename;
    }
    public void setCoursename(String coursename) {
        this.coursename = coursename;
    }
    public int getDuration() {
        return duration;
    }
    public void setDuration(int duration) {
        this.duration = duration;
    }

    @Override
    public String toString() {
        return "Course [id=" + id + ", coursename=" + coursename + ", duration=" + duration + "]";
    }

}

Repository
@Repository
public interface CourseRepository extends JpaRepository<Course, Long>{

}

Service
@Service
public class CourseService
{
    @Autowired
    private CourseRepository repo;

    public List<Course> listAll() {
        return repo.findAll();
    }

    public void save(Course course) {
        repo.save(course);
    }

    public Course get(long id) {
        return repo.findById(id).get();
    }

    public void delete(long id) {
        repo.deleteById(id);
    }

}

Course.html

Course Creation

Add new

            Course ID
            Course Name
            Duration
             edit
             delete

        Course ID
        Course Name
        Duration

            Edit

            Delete

A: You have @RequestMapping("/Course") annotation on CourseController and in Course.html you trying to make request to /addcourse (i guess, please check in your browser development tool) but you need to make request to /Course/addcourse  endpoint because of annotation on controller class. So u need to change
Add new
 to
Add new

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you redirect a bare "example.com" domain to "https://example.com"? Title really says it all. I cannot get my domain to redirect from site.com to http://example.com but https://example.com works as well as https://www.example.com.
My nginx conf is as follows with sensitive paths removed. Here is a GIST link to all my nginx setup, it is currently the only enabled domain in my entire nginx configuration.
Console output on my local vs my server:
rublev@rublevs-MacBook-Pro ~
• curl -I rublev.io
^C
rublev@rublevs-MacBook-Pro ~
• ssh r
Welcome to Ubuntu 16.04.2 LTS (GNU/Linux 4.4.0-75-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  Get cloud support with Ubuntu Advantage Cloud Guest:
    http://www.ubuntu.com/business/services/cloud

78 packages can be updated.
0 updates are security updates.

Last login: Fri May 12 16:41:35 2017 from 198.84.225.249
rublev@ubuntu-512mb-tor1-01:~$ curl -I rublev.io
HTTP/1.1 200 OK
Server: nginx/1.10.0 (Ubuntu)
Date: Fri, 12 May 2017 16:41:43 GMT
Content-Type: text/html
Content-Length: 339
Last-Modified: Thu, 20 Apr 2017 20:47:12 GMT
Connection: keep-alive
ETag: "58f91e50-153"
Accept-Ranges: bytes

I am at my wits end, I truly have no idea what to do now, I've spent weeks trying to get this working.

A: LetsEncrypt is using http by default, just to be safe, it's preferable to leave the ability for it to access the well-known for the acme challenge. You also don't seem to be pointing to the right path for it, unless you changed your webroot to /home/rublev/sites/rublev.io?
I would try to rewrite your default server like this instead of redirecting directly to your https equivalent. Besides, it will allow you to test more easily this strange behavior.
server {
  listen 80 default_server;
  listen [::]:80 default_server;
  server_name rublev.io www.rublev.io;

  location / {
    return 301 https://$server_name$request_uri;
  }

  location ~ /.well-known {
    # Apparently you changed your webroot,
    # just make sure that the file is created and accessible
    root /home/rublev/sites/rublev.io/.well-known;
  }
}

Also, it's very important to know that you need either two different certificates or one that accept your domain both with and without www form. If that was not the case, that might very well be the reason of your issue. To generate a cert with both domains, you can run the following command:
sudo ./certbot-auto certonly --standalone -d rublev.io -d www.rublev.io --dry-run

I would also comment out your jenkins server and configs, just in case it's messing with your main one. Note: from this question, you can use proxy_redirect http:// $scheme://; instead of the form you're currently doing. It shouldn't affect another server, but I prefer to be sure in these weird scenarios.

Another thing, that might be the path to another solution, would be to consider picking only one form of your domain (either with or without www), and redirecting users from the "wrong" to the "right" one. This will allow you to get more consistent urls, better for SEO and people sharing your links.

A: Add the server
server {
    server_name example.com;
    return 301 https://example.com$request_uri;
}


text:
Q: run a command on a layer above my system I would like to run a command, make in fact, to install something into a "layer".
Afterwards I would like to inspect and pack the files in the layer and gzip them.
I know this is risky since the command may vary it's behaviour, but for this specific case I really need it :D
Is there something around that does that?
Thank you in advance!

A: The best option is to use a prefix as HolyBlackCat mentions in a comment. The next best option is to attempt to use a chroot envrionment, though this will be more work to accomplish cleanly. I can think of a few other approaches, but they all have far too much work involved to be able to execute them in a reasonable amount of time.


text:
Q: Does iOS support the "beforeinstallpromp" event? Chrome in Android and Desktop supports "beforeinstallpromp" event which is can show up add to homescreen banner. I'm try to use the same javascript code for my PWA in iOS but it is doesn't work.

/**
 * Clear caches
 */
function pwaClearCaches()
{
    //Clear caches
    caches.keys().then(function(names) {
        for (let name of names) {
            caches.delete(name);
        }
    });
}

var pwa_app_installed = false; //PWA is already installed
var deferredPrompt; //Link to show dialog event
$(document).ready(function(){
    if (window.location.protocol === 'http:') { //Если это HTTP протокол, а не HTTPS
        console.log(lang.t('You need HTTPS for work'));
    }

    if ('serviceWorker' in navigator) {
        /**
         * Подвешиваемся на переключение режима правки, чтобы сразу очистить кэш
         */
        $('.debug-mode-switcher').on('click', function () {
            if (!$('.debug-mode-switcher .toggle-switch').hasClass('on')) {
                //Delete service worker
                navigator.serviceWorker.getRegistrations().then(function (registrations) {
                    for (let registration of registrations) {
                        registration.unregister();
                    }
                });

                //Clear caches
                pwaClearCaches();
            }
        });
    }

    if ($.cookie('update_pwa_cache')){ //Update cache if we have cookie на обновление
        pwaClearCaches();
        $.cookie('update_pwa_cache', '', {expires: -1});
    }

    /**
     * Close window with prompt
     */
    function closePWAInstallWindow()
    {
        $("#pwaInstall").hide();
        $.cookie('not_show_pwa', '1');
    }

    let body = $('body');
    /**
     * Add to homescreen event
     */
    body.on('click', '#pwaAddToHomeScreen', function(){
        deferredPrompt.prompt(); // Show alert to install
        deferredPrompt.userChoice.then((choiceResult) => {//Wait for user choose
            if (choiceResult.outcome === 'accepted') { //Accept install
                closePWAInstallWindow();
            } else { //Cansel install
                closePWAInstallWindow();
            }
            deferredPrompt = null;
        });
        return false;
    });
    /**
     * Close intalll window
     */
    body.on('click', '#pwaCloseInstall', function(){
        closePWAInstallWindow();
        return false;
    });
});

console.log('out');

//If we not in webapp and no session that we need to install
if (!(window.matchMedia('(display-mode: standalone)').matches) && !$.cookie('not_show_pwa')) {
    /**
     * Event that app is installed
     */
    $(window).on('appinstalled', (evt) => {
        pwa_app_installed = true;
    });

    console.log('not fired');

    /**
     * Event beforeinstallprompt from browser
     */
    $(window).on('beforeinstallprompt', (e) => {
        // Prevent Chrome 67 and earlier from automatically showing the prompt
        e.preventDefault();
        // Stash the event so it can be triggered later.
        deferredPrompt = e.originalEvent;
        console.log('fired');

        var is_mobile_android = false;
        var ua = navigator.userAgent;

        if (/Android/i.test(ua) && /Chrome/i.test(ua)){ //If we in Android and it is Chrome prevent native window
            is_mobile_android = true;
        }

        if (!pwa_app_installed && !is_mobile_android){
            let body = $('body');
            body.append('
' +
                '
Please install our app

' +
                    'Add to homescreen' +
                    'No Thanks' +
                '
' +
            '
');

            setTimeout(function () { //Show our banner
                $("#pwaInstall").addClass('show');
            }, 100);
        }
    });
}

And I have manifest.json
{
    "short_name": "VaporStore",
    "name": "VaporStore & FreeVape",
    "description": "Магазин свободного пара",
    "icons": [
        {
            "src": "/storage/system/resized/xy_64x64/0f08cd435767735a778ea63fea5b5efd_e2f1b76.png",
            "type": "image/png",
            "sizes": "64x64"
        },
        {
            "src": "/storage/system/resized/xy_128x128/0f08cd435767735a778ea63fea5b5efd_b510eb77.png",
            "type": "image/png",
            "sizes": "128x128"
        },
        {
            "src": "/storage/system/original/0f08cd435767735a778ea63fea5b5efd.png",
            "type": "image/png",
            "sizes": "192x192"
        },
        {
            "src": "/storage/system/original/272d68dfbb5e80ef67f6c7abcb2391cb.png",
            "type": "image/png",
            "sizes": "512x512"
        }
    ],
    "background_color": "#ffffff",
    "theme_color": "#ff9800",
    "display": "standalone",
    "orientation": "portrait",
    "start_url": "/",
    "scope": "/"
}

And I have service worker based on workbox from Google.
Does iOS support the "beforeinstallpromp" event or not? On Android and Desktop chrome works fine.
Update 04.04.2019
The most full answer is given here:
https://www.youtube.com/watch?v=s5ASNwnBttQ
from the clip: "iOS 12.2 does not support beforeinstallprompt" (mention is made of add to home screen behavior via 'Share Screen')

A: beforeinstallprompt is not available in iOS Safari
See list at the bottom of this page
https://developer.mozilla.org/en-US/docs/Web/API/BeforeInstallPromptEvent


text:
Q: Phase Portraits for systems of ODEs I want to produce a phase portrait of the system:
x'=x(y-1) and y'=4-y^2-x^2
My code below is what I have attempted so far. My issue is the ics and duration lines, Whenever I add more points I get red errors that will not show the output of the phase portrait.
 import numpy as np
 from matplotlib import pyplot as plt
 from scipy.integrate import odeint

# Define vector field
def vField(x,t):
u = x[0]*(x[1]-1)
v = 4-(x[0])**2-(x[1])**2
return [u,v]

# Plot vector field

X, Y = np.mgrid[-np.pi:np.pi:-30j,-6:6:30j]
U, V = vField([X,Y],0)

fig, ax = plt.subplots(figsize=(10, 10))
ax.quiver(X, Y, U, V)

ics  =      [[2,4],[2,0],[1,4], [2,4],[-2,4],[-2,0],[-1,4],[-2,4],   [-2,1],[2,-1]]
durations = [[0,4],[0,8],[0,12],[0,4],[0,4],[0,8],[0,12],[0,4],   [0,12],[0,12]]
vcolors = plt.cm.autumn_r(np.linspace(0.5, 1., len(ics)))  # colors      for each trajectory

# plot trajectories
for i, ic in enumerate(ics):
t = np.linspace(durations[i][0], durations[i][1],100)
x = odeint(vField, ic, t)
ax.plot(x[:,0], x[:,1], color=vcolors[i], label='X0=(%.f, %.f)' %  (ic[0], ic[1]) )

ic_x = [ic[0] for ic in ics]
ic_y = [ic[1] for ic in ics]
ax.scatter(ic_x, ic_y, color='blue', s=20)

plt.xlabel('x')
plt.ylabel('y')
plt.xlim(-3.1,3.1)
plt.ylim(-6,6)
plt.legend()

This is what I obtain from the python code above. How do I go about completing this and finding what other points to use so that I get the final phase portrait? Thank you in advance


text:
Q: How to set backgroundcolor of more button with other tabs [Xamarin Forms]? I'm developing a application with Xamarin.Forms.Shell for Layout and Navigation. When I use more of five tabs into TabBar, it's naturally appearance the button more, that is native each platformn (Android and iOS). But, same using the customization color in xaml for Shell.Background and Shell.TabBarBackground, not works for the background of tabs into more button.
My code in Xaml APP SHELL:
 <Shell.Resources>
    <ResourceDictionary>
        <Style x:Key="BaseStyle"  TargetType="Element">
            <Setter Property="Shell.BackgroundColor"
                    Value="{x:Static core:Colors.Background}" />
            <Setter Property="Shell.ForegroundColor"
                    Value="White" />
            <Setter Property="Shell.TabBarBackgroundColor"
                    Value="{x:Static core:Colors.Background}" />
            <Setter Property="Shell.TabBarTitleColor"
                    Value="{x:Static core:Colors.Selection}" />
            <Setter Property="Shell.TabBarUnselectedColor"
                    Value="White" />
        </Style>
    </ResourceDictionary>
</Shell.Resources>

<ShellItem Route="Home">
    <ShellContent ContentTemplate="{DataTemplate core:HomePage}"/>
</ShellItem>

<TabBar Route="Tabs" Style="{x:StaticResource BaseStyle}">
    <Tab Route="TabSearch"
         Icon="ic_list_white"
         Title="Search">
        <ShellContent ContentTemplate="{DataTemplate core:SearchPage}"/>
    </Tab>
    <Tab
        Icon="ic_filter_list_white"
        Title="Filter">
        <ShellContent ContentTemplate="{DataTemplate core:FilterPage}"/>
    </Tab>

    <Tab Icon="ic_star_white"
        Title="Favourites">
        <ShellContent ContentTemplate="{DataTemplate core:FavouritesPage}"/>
    </Tab>

    <Tab Icon="ic_remove_red_eye_white"
        Title="Seen">
        <ShellContent ContentTemplate="{DataTemplate core:SeenPage}"/>
    </Tab>

    <Tab Icon="ic_shopping_cart_white" Title="{x:Static resources:Strings.MAINPAGE_MENU_PURCHASE_PACKAGES}">
        <ShellContent ContentTemplate="{DataTemplate core:PackagePurchasePage}"/>
    </Tab>

    <Tab Icon="ic_sync_white" Title="{x:Static resources:Strings.MAINPAGE_MENU_RESTORE_PURCHASES}"  >
        <ShellContent ContentTemplate="{DataTemplate core:RestorePurchasePage}"/>
    </Tab>

    <Tab Icon="ic_settings_white" Title="{x:Static resources:Strings.MAINPAGE_MENU_SETTINGS}"  >
        <ShellContent ContentTemplate="{DataTemplate core:SettingsPage}"/>
    </Tab>

    <Tab Icon="ic_help_white" Title="{x:Static resources:Strings.MAINPAGE_MENU_ABOUT}" >
        <ShellContent ContentTemplate="{DataTemplate views:AboutShell }"/>
    </Tab>
</TabBar>

and here is my tabbar with applied style:

When I clicked on more button:

I need apply the same style that appearance on my TabBar in this screen of more button.

A: You could set the color for the TabBarUnselectedColor property.
 <Shell.Resources>
    <ResourceDictionary>
        <Style x:Key="BaseStyle"  TargetType="Element">
            <Setter Property="Shell.BackgroundColor"
                Value="Black" />
            <Setter Property="Shell.ForegroundColor"
                Value="White" />
            <Setter Property="Shell.TabBarBackgroundColor"
                Value="Green" />
            <Setter Property="Shell.TabBarTitleColor"
                Value="Red" />
            <Setter Property="Shell.TabBarUnselectedColor"
                Value="Red" />
        </Style>
    </ResourceDictionary>
</Shell.Resources>


text:
Q: How to insert money data type from SQL server into currency field in crm using c# (latebound) My sample data is like this. EstOneTimeCharge is my column name with data type money in DB and new_estrecurringcharge is currency field in crm.
EstOneTimeCharge
100.20
100.50
100.70

I'm using SSIS script component to insert this record into crm.
My first code:
if (!Row.EstRecurringCharge_IsNull)
    {
        TicketEnt["new_estrecurringcharge"] = new Money (Row.EstRecurringCharge);
    }

Then I got this error:
My second code:
if (!Row.EstRecurringCharge_IsNull)
    {
        TicketEnt["new_estrecurringcharge"] = Row.EstRecurringCharge;
    }

Then I got this:

My third code:
 if (!Row.EstRecurringCharge_IsNull)
    {
        TicketEnt["new_estrecurringcharge"] = Convert.ToDecimal(Row.EstRecurringCharge);
    }

Throw same error as my second code.
Please help.
Thanks in advance.

A: You are almost there. Use both Convert.ToDecimal & new Money.
if (!Row.EstRecurringCharge_IsNull)
    {
        TicketEnt["new_estrecurringcharge"] = new Money(Convert.ToDecimal(Row.EstRecurringCharge));
    }


text:
Q: Unable to compile a JUnit test on Windows I'm trying to compile this very simple JUnit test on my Windows 10 box:
import static org.junit.Assert.assertTrue;
import org.junit.Test;

public class TestHelloWorld
{
    @Test
    public void BasicTest ()
    {
        assertTrue(true);
    }
}

However, this seemingly innocuous task has proven impervious to three to four hours of research and trial and error.
From a Cygwin terminal I see this:
javac -cp lib/hamcrest-core-1.3.jar:/lib/junit-4.12.jar:. TestHe
TestHelloWorld.java:1: error: package org.junit does not exist
import static org.junit.Assert.assertTrue;
                       ^
TestHelloWorld.java:1: error: static import only from classes and interfaces
import static org.junit.Assert.assertTrue;
^
TestHelloWorld.java:2: error: package org.junit does not exist
import org.junit.Test;
                ^
TestHelloWorld.java:6: error: cannot find symbol
        @Test
         ^
  symbol:   class Test
  location: class TestHelloWorld
TestHelloWorld.java:9: error: cannot find symbol
                assertTrue(true);
                ^
  symbol:   method assertTrue(boolean)
  location: class TestHelloWorld
5 errors

and from a CMD prompt I see this:
javac -cp C:\Users\canon\Documents\GitHub\cse1341\AssignmentTester\lib\junit.jar TestHelloWorld.java
error: error reading C:\Users\canon\Documents\GitHub\cse1341\AssignmentTester\lib\junit.jar; error in opening zip file
1 error

I honestly have no idea what I'm doing incorrectly here. I've always been on a *nix machine before, where I don't recall having any problems compiling JUnit tests when I pass in the junit and hamcrest jars to the class path using the -cp flag. Any ideas or guidance here would be much appreciated!

A: There are two thing:

*

*Java in windows using ';' to separate the jar files in classpath argument so it should be
"javac -cp lib/hamcrest-core-1.3.jar;/lib/junit-4.12.jar;. TestHeTestHelloWorld.java" in cygwin

*check if C:\Users\canon\Documents\GitHub\cse1341\AssignmentTester\lib\junit.jar is a valid jar. (you can use zip tool to check).

A: The slash before lib/junit-4.12.jar seems to be wrong.


text:
Q: Send email on every change of service status I am running a Debian server and i have setup mailutils to send an email from command line from root@localhost to an external email.
I would like to slightly modify it, so it can send emails on every service change. eg

*

*ssh new logins

*iptables restart

*fail2ban restart

*system reboot

*asterisk restart

*etc

if possible, together with the system information such as CPU, RAM, HDD status.


text:
Q: Mocking functions for acceptance testing in F# I have a function which generates random numbers. When acceptance testing, I want to replace this with one that generates known numbers.
In an object oriented language I would use dependency injection and simply wire up this component differently in the test set-up. The only way I can see to do this in a functional language is to pass the dependency through the program, from the root, until it gets to the function that needs it (is "turtles all the way down" the correct phrase here?).
Is there a better way?

A: There are numerous options - you could pass the function around, you could use a dependency injection mechanism (many of the standard .NET libraries will work in F# but you may find some F#-specific lightweight tools too) or you could even use monads to pass the state around implicitly.
However, do you need to make the choice between production and testing set-up at runtime? If no, you could just move the functions that you want to implement differently for testing into a separate file and have two different builds of your project.
This might not be as pure solution, but it is super simple (just use Random.Test.fs instead of Random.Runtime.fs) and it is nicely functional - you just provide different implementation of a single (or multiple) functions and the rest of the code uses them.

A: The only way to do it in a pure functional language is to thread the state all the way through.  F# is impure, so you can do it the typical way you do it in OO.  But I am unclear if you're asking about pragmatics or about how functional designs tackle the issue.

A: Presumably you have something like the following:
let generateRandomNumber =
    let generator = new System.Random()
    fun () -> generator.Next()

let addFiveToRandomNumber() =
    let next = generateRandomNumber()
    next + 5

where addFiveToRandomNumber is the function you'd like to test.
A good solution to your problem, and generally good practice in F#, is to disentangle your pure and impure functions:
let generateRandomNumber =
    let generator = new System.Random()
    fun () -> generator.Next()

let addFiveToGeneratedNumber generator =
    let next = generator()
    next + 5

let addFiveToRandomNumber() = addFiveToGeneratedNumber generateRandomNumber

Now the function you want to test is addFiveToGeneratedNumber, e.g. addFiveToGeneratedNumber (fun () -> 1) should always return 6. I probably wouldn't even bother testing generateRandomNumber or addFiveToRandomNumber.
So here our solution is to "pass in the dependency", but it doesn't have to come all the way from the root.


text:
Q: How to update a Gravity Forms $entry $field_id after 3rd party response? When my GravityForm is submitted it successfully posts the submitted entry data as a JSON array to a (3rd party) API. The API creates an object, assigns a random id to it and then returns the id along with the rest of the array, in the request response.
How can I retrieve the random id from the request response and save it to a hidden field in the previously submitted GravityForm entry?
This is what the 3rd party API response looks like:
{
        "url": "http://domain.com",
        "name": "companyName",
        "random_id": 4224
}


text:
Q: CLion and Yaml-cpp: how can i build yaml-cpp with clion in windows I had install yaml-cpp in linux successfully, then i want to install yaml-cpp in windows with clion. But when I build or install it, some errors happened. Such as:
 In file included from D:/github/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-linked_ptr.h:74:0,
                 from D:/github/yaml-cpp/test/gtest-1.8.0/googlemock/include/gmock/internal/gmock-port.h:53,
                 from D:/github/yaml-cpp/test/gtest-1.8.0/googlemock/include/gmock/internal/gmock-generated-internal-utils.h:44,
                 from D:/github/yaml-cpp/test/gtest-1.8.0/googlemock/include/gmock/internal/gmock-internal-utils.h:45,
                 from D:/github/yaml-cpp/test/gtest-1.8.0/googlemock/include/gmock/gmock-actions.h:46,
                 from D:/github/yaml-cpp/test/gtest-1.8.0/googlemock/include/gmock/gmock.h:58,
                 from D:\github\yaml-cpp\test\gtest-1.8.0\googlemock\src\gmock-all.cc:40:
D:/github/yaml-cpp/test/gtest-1.8.0/googletest/include/gtest/internal/gtest-port.h:1782:3: error: 'AutoHandle' does not name a type

Is there something I should modify if I want to use yaml-cpp in windows?

A: Just disable testing support during CMake configuration via -DYAML_CPP_BUILD_TESTS=OFF.
Seems bundled gtest has issues with MinGW compatibility.

A: intellij-support has solved this problem.


text:
Q: how to select entries by comparing two lists? I need to select all entries where any item of a list is in some column
here is MY_TABLE:

     COLUMN1     COLUMN2
        1        item1, item2, item3, item4
        2        item5, item6, item7, item8
        3        item9, item10, item11, item12
        4        item13, item14, item15, item16
        5        item17, item18, item19, item20

So I need something like:

    DECLARE @MY_LIST
    SET MY_LIST =  "'item1', 'item15'"
    SELECT * FROM MY_TABLE WHERE @MY_LIST IN COLUMN2

and it should return:

     COLUMN1     COLUMN2
        1        item1, item2, item3, item4
        4        item13, item14, item15, item16

MY_LIST can be an array and data in COLUMN2 we can convert into array as well.
So if there is an item in both MY_LIST and in COLUMN2 then I need this entry be selected.
Thank you very much for any response


text:
Q: Wordpress upload path incorrect after site migration I have recently migrated a Wordpress site all is fine apart from when I try and upload some new media. I get an error message saying that the upload failed because:
The uploaded file could not be moved to /var/www/vhosts/mysite.org.uk/httpdocs/wp-content/uploads.
It appears to be adding /httpdocs/ after the site url which is incorrect. Where is this defined and how can I change it?


text:
Q: What is the latency for WebRTC? So WebRTC allows you to connect clients together directly without going through the server.
I'm trying to figure out what the latency would be?
Of course it would be less than with having a server, because there's less distance that has to be traveled.
But say for example that the two WebRTC clients happen to be in my house and connected to the same network. Will WebRTC know to just communicate over LAN, or will it have to go out to the public internet?
If for example, they are both connected to 4G in the same area, would it only have to go as far as the 4G antenna or whatever?
So basically are there any shortcuts?


text:
Q: Change Lineseries thickness in WPFToolkit.Chart C# I'm trying change the line thickness in a serie dinamically created, I need turn the line more thick.
Below, follow the code to bind the created serie on chart component. It works fine, but I tryed adapt this in this code and I had no sucess.
Please help, thanks.
Style style = new Style(typeof(LineDataPoint));
style.Setters.Add(new Setter(LineDataPoint.OpacityProperty, (double)(0.0)));
style.Setters.Add(new Setter(LineDataPoint.BackgroundProperty, dadosSerie.ColorSerie));

LineSeries lineSerie = new LineSeries()
{
    Title = dadosSerie.SerieTitle,
    IndependentValueBinding = new Binding("Key"),
    DependentValueBinding = new Binding("Value"),
    DependentRangeAxis = dadosSerie.EixoY,
    DataPointStyle = style,
    ItemsSource = dadosSerie.DataSerie,
};

chtGraficos.Series.Add(lineSerie);

A: Have you tried adding a Style for the serie's Polyline instead?
It seams the style for the LineDataPoint is actually for every point on the serie.
Here is a working sample of a chart fully created on code-behind. You just have to create a window named MainWindow and add a reference on the project to System.Windows.Controls.DataVisualization.Toolkit:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var valueList = new Dictionary<string, int>();
        valueList.Add("Developer", 60);
        valueList.Add("Misc", 20);
        valueList.Add("Project Manager", 40);

        var style = new Style(typeof(Polyline));
        style.Setters.Add(new Setter(Polyline.StrokeThicknessProperty, 10d));

        var series = new LineSeries
        {
            PolylineStyle = style,
            ItemsSource = valueList,
            DependentValuePath = "Value",
            IndependentValuePath = "Key",
        };

        var lineChart = new Chart { Height = 254 };
        lineChart.Series.Add(series);

        var mainGrid = new Grid();
        mainGrid.Children.Add(lineChart);

        this.Content = mainGrid;
    }
}


text:
Q: How to read in spaces with if stream in c++ I need to read in a txt file that has 20 rows (ROWS = 20) and 40 columns (COLS = 40)
But so far when I read in the file it does not recognize the spaces. This is what I have so far:
void readMaze(string file) {
    if stream inputFile;
    inputFile.open(file);
    char input;
    for(int i = 0; i < ROWS; i++) {
       for(int j = 0; j < COLS; j++) {
           inputFile >> input;
           switch(put) {
               case 'X':
                   maze[i][j] = WALL;
                   break;
               case 'S':
                   maze[i][j] = START;
                   break;
               case 'C':
                   maze[i][j] = CHEESE;
                   break;
               case ' ':
                   maze[i][j] = SPACE;
                   break;
               default:
                   break;
           }
       }
    }
    inputFile.close();
}


text:
Q: Cannot make a static reference to the non-static field players I'm making a program in java to register players and add them in an arraylist. My method for adding players is this:
void registerNewPlayer() {
        System.out.print("Name?> ");
        String name = input.nextLine();
        System.out.print("Game?> ");
        String game = input.nextLine();
        System.out.print("Age?> ");
        int age = input.nextInt();
        Player player = new Player(name, game, age);
        players.add(player);
    }

my problem is that i don't know where to put
 ArrayList<Player> players = new ArrayList<>();

if i have it in main, the method doesn't know what players is, but if i have it in the class i get a "Cannot make a static reference to the non-static field players" exception, when i try to print it from main. What's the best way of solving this.
Update: thanks for the help, i realized that since my command loop is already running on an instanced version of my class there is actually no problem, there was only a problem when i tried to test my method outside the instanced command loop.

A: If you'd like to have it at the class level, escape the static context.
public class YourClass {
  ArrayList<Player> players = new ArrayList<>();

  public static void main(String[] args) {
    new YourClass(); // or YourClass yourClass = new YourClass();
  }

  // Create an instance of YourClass to leave the static context
  public YourClass() {
    registerNewPlayer();
  }

  public void registerNewPlayer() {
    System.out.print("Name?> ");
    String name = input.nextLine();
    System.out.print("Game?> ");
    String game = input.nextLine();
    System.out.print("Age?> ");
    int age = input.nextInt();
    System.out.print("Weight?> ");
    int weight = input.nextInt();
    Player player = new Player(name, game, age, weight);
    players.add(player);
  }
}

A: I thinik this is the best solution for your problem. I hope it helps :)

*

*Your Player class:

    public class Player {

    private static ArrayList<Player> _players = new ArrayList<Player>();

    private String name;
    private String game;
    private int age;
    private int weight;

    public Player(String name, String game, int age, int weight){
        this.name = name;
        this.game = game;
        this.age = age;
        this.weight = weight;
    }

     public static void AddPlayer(Player player){
        _players.add(player);
    }
    public static ArrayList<Player> getPlayers(){
        return _players;
    }

}

*Now you can create some players and get them as follow:

... main ...
  .
  .
  .
    Player p1 = new Player("Name1", "Game1", 20, 70);
    Player p2 = new Player("Name2", "Game2", 30, 80);
    Player p3 = new Player("Name2", "Game3", 25, 73);
    Player.AddPlayer(p1);
    Player.AddPlayer(p2);
    Player.AddPlayer(p3);
    ArrayList<Player> allPlayers = Player.getPlayers();
  .
  .
  .

Let me know if it is working for you !

A: The error you get is because you are trying to access a non-static variable (i.e. a value or object that exists only in instances of that class) from outside of such an instance. What you can do is to create an object of that class to be able to access the players through it:
public class Demo {

    private List<Player> players = new ArrayList<>();

    public static void main(String[] args) {
        Demo demo = new Demo();
        demo.registerNewPlayer();
        System.out.println(demo.players);
    }

    private void registerNewPlayer() {
        System.out.print("Name?> ");
        String name = input.nextLine();
        System.out.print("Game?> ");
        String game = input.nextLine();
        System.out.print("Age?> ");
        int age = input.nextInt();
        Player player = new Player(name, game, age);
        players.add(player);
    }
}

By creating an object of the class and executing the method as well as access the variable through it, allows you to do what you want (if I understood correctly that is).
Further reading material:
Java: when to use static methods
Type List vs type ArrayList in Java (you may have noticed that I changed the type of players to List<Player> from ArrayList<Player>)
What is the difference between public, protected, package-private and private in Java? (you may have noticed the private keyword on the list and the method)

A: Globally declare the list.
ArrayList<Player> players = new ArrayList<>();


text:
Q: Cannot access SDcard (ExternalStorageDirectoryPath points to /storage/emulated/0) I am developing a react native app for android, which allow user to write files to an external SDcard on Android Pie. I have used React-native fs and react-native fetch-blob libraries. The problem is that i can not get the correct path to my external SDcard. I have tried using  RNFS.ExternalDirectoryPath and RNFS.ExternalStorageDirectoryPath. They all give path as "/storage/emulated/0/Android/data/com.storage/files". this path does not save file in SDcard it save the file in internal memory.
I'm using Android 9 and have given permission for read and write in AndroidManifest.xml.
Any suggestion to how to write file to SD card and does android Pie support read and write to external SD Card?


text:
Q: React Navigation Issue with performance after updating libraries i ran into an issue with react navigation performance. Today i updated version of libraries that i use in my React Native Expo Project which caused that issue. Then unaware of poor navigation performance i've pushed current version of my app to git repository. When i realized that navigation stopped working smoothly i restored it to the previous version. I've deleted node_modules and package-lock.json directories and cleared npm cache, then ran npm install once again with previous version of libraries, but it didnt help at all. Even when I restored version from 2 weeks ago and installed specified version of libraries, the app still doesnt work as it used to.
Current version of package.json:
{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "eject": "expo eject"
  },
  "dependencies": {
    "axios": "^0.18.0",
    "expo": "^32.0.6",
    "prop-types": "^15.7.2",
    "react": "16.5.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz",
    "react-native-animatable": "^1.3.2",
    "react-native-datepicker": "^1.7.2",
    "react-native-elements": "^1.1.0",
    "react-native-flash-message": "^0.1.11",
    "react-native-gifted-chat": "^0.7.3",
    "react-native-google-places-autocomplete": "^1.3.9",
    "react-native-modal": "^7.0.2",
    "react-native-size-matters": "^0.2.1",
    "react-navigation": "^3.9.0",
    "react-redux": "^6.0.1",
    "redux": "^4.0.1",
    "redux-axios-middleware": "^4.0.0",
    "redux-persist": "^5.10.0",
    "redux-persist-expo-securestore": "^0.1.1",
    "redux-thunk": "^2.3.0"
  },
  "devDependencies": {
    "babel-preset-expo": "^5.1.1"
  },
  "private": true
}

Previous version of package.json:
{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "eject": "expo eject"
  },
  "dependencies": {
    "axios": "^0.18.0",
    "expo": "^32.0.6",
    "prop-types": "^15.7.2",
    "react": "16.5.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz",
    "react-native-animatable": "^1.3.1",
    "react-native-datepicker": "^1.7.2",
    "react-native-elements": "^1.1.0",
    "react-native-flash-message": "^0.1.11",
    "react-native-gifted-chat": "^0.7.3",
    "react-native-google-places-autocomplete": "^1.3.9",
    "react-native-modal": "^7.0.2",
    "react-native-size-matters": "^0.1.6",
    "react-navigation": "^3.3.2",
    "react-redux": "^6.0.1",
    "redux": "^4.0.1",
    "redux-axios-middleware": "^4.0.0",
    "redux-persist": "^5.10.0",
    "redux-persist-expo-securestore": "^0.1.1",
    "redux-thunk": "^2.3.0"
  },
  "devDependencies": {
    "babel-preset-expo": "^5.0.0"
  },
  "private": true
}

Navigation file:
import React from "react";
import { Animated, Easing, SafeAreaView } from "react-native";
import {
  createAppContainer,
  createDrawerNavigator,
  createStackNavigator,
  createSwitchNavigator
} from "react-navigation";
import AddAppsScreen from "../screens/AddAppsScreen";
import BoardScreen from "../screens/BoardScreen";
import FavoriteScreen from "../screens/FavoriteScreen";
import HomeScreen from "../screens/HomeScreen";
import AuthLoadingScreen from "../screens/AuthLoadingScreen";
import LoginScreen from "../screens/LoginScreen";
import NoticeScreen from "../screens/NoticeScreen";
import ProfileScreen from "../screens/ProfileScreen";
import SearchResultScreen from "../screens/SearchResultScreen";
import SearchScreen from "../screens/SearchScreen";
import UserDetailsScreen from "../screens/UserDetailsScreen";
import SideMenu from "./SideMenu";
import NavigationBar from "./NavigationBar";
import MessagesScreen from "../screens/MessagesScreen";
import ChatRoomScreen from "../screens/ChatRoomScreen";
import { moderateScale } from "react-native-size-matters";

const RootNavigator = createStackNavigator(
  {
    Home: {
      screen: HomeScreen
    },
    Board: {
      screen: BoardScreen
    },
    Notice: {
      screen: NoticeScreen
    },
    Profile: {
      screen: ProfileScreen
    },
    Favorite: {
      screen: FavoriteScreen
    },
    Search: {
      screen: SearchScreen
    },
    SearchResult: {
      screen: SearchResultScreen
    },
    UserDetails: {
      screen: UserDetailsScreen
    },
    AddApps: {
      screen: AddAppsScreen
    },
    Messages: {
      screen: MessagesScreen
    },
    ChatRoom: {
      screen: ChatRoomScreen
    }
  },
  {
    headerMode: "none",
    initialRouteName: "Home",
    transitionConfig: () => ({
      transitionSpec: {
        duration: 300,
        easing: Easing.out(Easing.poly(4)),
        timing: Animated.timing
      },
      screenInterpolator: sceneProps => {
        const { layout, position, scene } = sceneProps;
        const { index } = scene;

        const width = layout.initWidth;
        const translateX = position.interpolate({
          inputRange: [index - 1, index, index + 1],
          outputRange: [width, 0, 0]
        });

        const opacity = position.interpolate({
          inputRange: [index - 1, index - 0.99, index],
          outputRange: [0, 1, 1]
        });

        return { opacity, transform: [{ translateX: translateX }] };
      }
    })
  }
);

const HomeNavWrapper = createStackNavigator(
  {
    RootNavigator: {
      screen: RootNavigator
    }
  },
  {
    defaultNavigationOptions: ({ navigation }) => ({
      header: <NavigationBar navigation={navigation} />
    }),
    transitionConfig: () => ({
      transitionSpec: {
        duration: 300,
        easing: Easing.out(Easing.poly(4)),
        timing: Animated.timing
      },
      screenInterpolator: sceneProps => {
        const { layout, position, scene } = sceneProps;
        const { index } = scene;

        const width = layout.initWidth;
        const translateX = position.interpolate({
          inputRange: [index - 1, index, index + 1],
          outputRange: [width, 0, 0]
        });

        const opacity = position.interpolate({
          inputRange: [index - 1, index - 0.99, index],
          outputRange: [0, 1, 1]
        });

        return { opacity, transform: [{ translateX: translateX }] };
      }
    })
  }
);

const HomeDrawerNavigator = createDrawerNavigator(
  {
    HomeNavWrapper: HomeNavWrapper
  },
  {
    contentComponent: SideMenu,
    drawerWidth: moderateScale(280)
    // drawerPosition: "right"
  }
);

const AppNavigator = createSwitchNavigator(
  {
    AuthLoading: {
      screen: AuthLoadingScreen
    },
    Login: {
      screen: LoginScreen
    },
    HomeDrawerNavigator: {
      screen: HomeDrawerNavigator
    }
  },
  {
    // initialRouteName: "HomeDrawerNavigator"
    initialRouteName: "AuthLoading"
  }
);

const MainNavigation = createAppContainer(AppNavigator);

export default MainNavigation;

A: Problem solved,it was not related to react-navigation but to npm.
npm audit fix - fixed that issue


text:
Q: angular-ui-router share states So I have a few states set up like this:
$stateProvider.state('accounts', {
    url: "/accounts",
    templateUrl: 'tpl/accounts/index.html',
}).state('accounts.view', {
    url: "/{accountNumber:[A-Z]{3}[0-9]{3,7}}",
    views: {
        '@': {
            templateUrl: 'tpl/accounts/view.html',
            controller: 'AccountController',
            controllerAs: 'controller'
        }
    },
    resolve: {
        account: ['$stateParams', 'AccountService', function ($stateParams, accountService) {
            return accountService.get($stateParams.accountNumber);
        }]
    }
}).state('accounts.create', {
    url: '/create',
    views: {
        '@': {
            templateUrl: 'tpl/accounts/save.html',
            controller: 'AccountSaveController',
            controllerAs: 'controller'
        }
    },
    params: {
        account: null
    },
    resolve: {
        account: ['$stateParams', 'AccountProvider', function ($stateParams, provider) {
            return $stateParams.account || provider.newAccount();
        }]
    }
}).state('accounts.view.edit', {
    url: '/edit',
    views: {
        '@': {
            templateUrl: 'tpl/accounts/save.html',
            controller: 'AccountSaveController',
            controllerAs: 'controller'
        }
    }
})

and it all works fine.
Now I have the need to create some child states for both create and edit. They will use the same view and controllers, but I was wondering if I can use the same state.
For example, I will be setting up an address state which will look something like this:
.state('accounts.view.edit.address', {
    url: '/address',
    views: {
        '@': {
            templateUrl: 'tpl/accounts/save/address.html',
            controller: 'AccountAddressSaveController',
            controllerAs: 'controller'
        }
    }
})

and I will set another up for the create state like this:
.state('accounts.create.address', {
    url: '/address',
    views: {
        '@': {
            templateUrl: 'tpl/accounts/save/address.html',
            controller: 'AccountAddressSaveController',
            controllerAs: 'controller'
        }
    }
})

It isn't an issue to do this for one child state, but there are 4 others and I just thought i would ask if there is a way to share the states, like perhaps:
.state(['accounts.create.address','accounts.view.edit.address'], {
    url: '/address',
    views: {
        '@': {
            templateUrl: 'tpl/accounts/save/address.html',
            controller: 'AccountAddressSaveController',
            controllerAs: 'controller'
        }
    }
})

A: You may put your state config in a variable
var sharedState = {
    url: '/address',
    views: {
        '@': {
            templateUrl: 'tpl/accounts/save/address.html',
            controller: 'AccountAddressSaveController',
            controllerAs: 'controller'
        }
    }
}

and then simply do,
.state('accounts.create.address', sharedState)
.state('accounts.view.edit.address', sharedState)


text:
Q: Improve Feed readability Since the latest update the android app's feed font changed. While the kerning is better and I personally like the lightweight L&F, I can see it becoming a problem on contrast-weak screens and for people who's eyes aren't the best anymore.

I'd love to have the blue of the font a tad darker and "bolder" to aid readability

A: As of version 1.0.69 (coming out in the next few days) the blue-ish white background is gone everywhere, which leads to both a simpler looking design and higher contrast. Here's what the feed looks like now:


text:
Q: Finding the Equation of an Ellipse Given the Vertices and Y-Intercepts The question is as follows:

The vertices of an ellipse are $(9,0)$ and $(-9,0)$, and the $y$-intercepts of the ellipse are $5$ and $-5$. Write an equation for the ellipse.

After doing some calculations I found the foci to be $(-4\sqrt{14}, 0)$ and $(4\sqrt{14}, 0)$.
We haven't been taught to use the intercepts and put that into the formula of a generic ellipse. But what we have been taught is that given any point $P = (x, y)$ on the ellipse, $PF_1 + PF_2 = 2a$, where $F_1$ and $F_2$ are the two focal points and $a$ is distance from the center to one of the vertices on the major symmetry axis.
Using the distance formula I know that $PF_1 = \sqrt{(x + 4\sqrt{14})^2 + y^2}$ and $PF_2 = \sqrt{(x-4\sqrt{14})^2 + y^2}$.
$$ \sqrt{(x + 4\sqrt{14})^2 + y^2} + \sqrt{(x-4\sqrt{14})^2 + y^2} = 18$$
I did the following steps to simplfy to find the equation of the ellipse in the form of $hx^2 + ky^2 = m$.
$$ \sqrt{(x + 4\sqrt{14})^2 + y^2} = 18 + \sqrt{(x-4\sqrt{14})^2 + y^2} $$
After squaring both sides...
$$ (x + 4\sqrt{14})^2 + y^2 = 324 - 36\sqrt{(x-4\sqrt{14}) + y^2} + (x-4\sqrt{14})^2 + y^2 $$
$$ x^2 + 8\sqrt{14}x + 56 - 324 - (x-4\sqrt{14})^2= - 36\sqrt{(x-4\sqrt{14})}$$
$$ x^2 + 8\sqrt{14}x + 56 - 324 - (x^2 - 8\sqrt{14}x + 224)= - 36\sqrt{(x-4\sqrt{14})^2}$$
From this point I am seeing terms that I can't cancel out to get $hx^2 + ky^2 = m$ (e.g. $8\sqrt{14}x + 8\sqrt{14}x = 16\sqrt{14}$). Also, expanding the right side of the equation will lead to even larger terms because I have to multiply them by $(-36)^2$. Where am I making a mistake? Any help will be greatly appreciated.


text:
Q: Is k-means clustering supposed to behave like this? First of all, data I'm using can be found here.
My code is:
library(readxl)
prouni <- read_excel("C:/Users/e270860661/Downloads/prouni.xlsx",
                 sheet = "Formatados_para_rodar")
View(prouni)
str(prouni)

coercivo <- data.frame(prouni$mensalidade, prouni$Medicina,
prouni$nota_integral_ampla)
summary(coercivo)
coercivo$dropador <- complete.cases(coercivo)
summary(coercivo$dropador)
final <- coercivo[coercivo$dropador == TRUE,]
final$dropador <- NULL

set.seed(100)
analise <- kmeans(final, centers = 4)
str(analise)

plot(final, col = analise$cluster)

The plot I get is:
For context, "mensalidade" means "tuition", "medicina" is a dummy variable (1 for a given program being Medicine and 0 for not being Medicine) and "nota_integral_ampla" is equivalent to required SAT score to be approved in the program.
My problem is that clustering doesn't seem to be working "multivariably". The algorithm seems to have chosen tuition thresholds and classified observations considering only these thresholds. Is my intutition right or is kmeans supposed to do this? Is there a coding error?
I'm an economist by training so this is all very new to me, sorry if it's a poorly elaborated question.

A: I think what is seen is an artefact of having data in different scales, using somewhat inappropriate $k$ and potentially employing an inappropriate clustering algorithm.
As the data in the sample's dimensions are on substantially different scales, it is problematic to use the raw data directly. That is because simple Euclidean distances between data-points are potentially irrelevant if the differences in scale do not translate to difference in importance. If we think that all features are equally important the easiest way to achieve that is by using normalised data in the sense of : newfinal <- apply( final, 2, scale) where the values of the features contained on the columns of newfinal are set to have mean $0$ and variance $1$. That said, I do not think that using $k=4$ is a good choice, even with standardised data. I say that based on how the data look as well as what standard metrics for choosing $k$ like the GAP-statistics (available in cluster::clusGap) suggest. Running something like: clusGap( newfinal, kmeans, K.max = 6, B = 100) strongly suggests that $k=4$ is overkill and potentially $k=2$ is a much more reliable options. You can use other metrics too (e.g. fitting a Gaussian Mixture Model and examining the relevant AIC, BIC values) but I suspect these will also suggest $k<4$.
Check out MATLAB's tutorial on Cluster Using Gaussian Mixture Models and its relevant links. It is well written and easy to follow.  $k$-means is a special case of a GMM so this can help your understanding a lot.
Aside using $k$-means I would suggest look into a density-based approach like DBSCAN. This algorithm can be easily used by using the function dbscan::dscan. The DBSAN results suggest having two major clusters and 2-3 smaller/outlier clusters. The relevant command will be something like : analise2 <- dbscan( newfinal, eps = 1). Notice DBSCAN requires to define a smallest relevant "neighbourhood size, the parameter eps, there is very good thread here explain the role of the parameter eps in more detail.

A: Welcome to Cross Validated!
Notice that your two quantitative variables are on different scales, with mensalidade ranging from zero to ten thousand and nota_integrada ranging from 450 to 800 (say).  Since the k-means minimizes a sum of squares involving the three variables, mensalidade's variability is swallowing the variability of the other two.
Standardize both variables and give it another try. (Notice that medicina will range between 0 and 1, there is no need to standardize it too).


text:
Q: In PSTricks thickness of the contour's line of PointSymbol=o I want to change the thickness of the contour's line of PointSymbol=o in the following line:
\pstGeonode[PointSymbol={o},PosAngle=45,PointName=none, , linecolor=red,,linecolor=yellow,dotsize=0.32,](0,0){F}.

How can I do this?
Thank You!

A: With dotLW you can scale  the current linewidth:
\listfiles
\documentclass{article}
\usepackage{pst-eucl}

\makeatletter
\define@key[psset]{pstricks}{dotLW}[1]{\def\psk@dotLW{#1 }}
\psset[pstricks]{dotLW=1}
\@namedef{psds@o}{%
  CLW \psk@dotLW mul SLW
  /r2 DS CLW sub def
  \pst@gdot{0 0 DS \tx@SD \pst@usecolor\psfillcolor   0 0 r2 \tx@SD }}
\makeatother
\begin{document}
\begin{pspicture}(-3,-3)(3,3)
\pstGeonode[PointSymbol=o,PosAngle=45,PointName=none](0,0){F}
\pstGeonode[PointSymbol=o,dotscale=3,PosAngle=45,PointName=none](1,1){G}
\pstGeonode[PointSymbol=o,dotscale=3,PosAngle=45,PointName=none, dotsize=5mm](-1,-1){H}
\pstGeonode[PointSymbol=o,dotscale=3,PosAngle=45,PointName=none, dotsize=5mm,dotLW=2](-1,1){H1}
\pstGeonode[PointSymbol=o,dotscale=3,PosAngle=45,PointName=none,dotLW=0.25](1,-1){G1}
\end{pspicture}

\end{document}

A: Thank You very much!!!!
I have another questions: what is the thickness of the contour's line  when I put dotLW=1? And, without "dotLW", what is the thickness of the contour's line by default for PointSymbol=o?
Thank You!


text:
Q: Why is Enumeration in Collection Framework not defined for ArrayList objects where as it is defined for Vector objects? public static void main(String[] args) {

    ArrayList v1 = new ArrayList();
    v1.add(123);
    v1.add(153);
    v1.add(125);

    Enumeration en = v1.elements(); // This line gives error.
    v1.add(4000);
    while(en.hasMoreElements())
    {
        System.out.println(en.nextElement());
    }

    System.out.println(v1);
}

Why there is an error in case of ArrayList but not in case of Vector?

A: Because Enumeration is a legacy class.
As the Vector class.
List and Collection more generally favor the use of Iterator to iterate on elements of them.
Iterator also provides a removal operation that Enumeration doesn't have.
You can read in the Enumeration javadoc :

NOTE: The functionality of this interface is duplicated by the
  Iterator interface. In addition, Iterator adds an optional remove
  operation, and has shorter method names. New implementations should
  consider using Iterator in preference to Enumeration.


text:
Q: Is there Android support for Clojure?
Possible Duplicate:
Clojure on Android

Given Java is Android's native language and Clojure is a JVM language, is there any support for writing a program in Clojure and cross compiling it to the Android platform?


text:
Q: Please help with sed command to grab specific text I have a txt file which is an output from an api call to JIRA which creates a task.
In this file, I have this text (issue # can change):
"key":"JIRA-90"

I'd need to grab the JIRA-90 but can't seem to figure out how to do it with sed.
JIRA-90 can of course change as that is the issuetype in JIRA.

A: sed -n 's/.*"key":"\([^"]*\)".*/\1/p' < your-file

Using the usual idiom: sed -n 's/pattern/replacement/p which does a substitution and only prints the resulting pattern space if it's successful (not printing the pattern space at the end of each cycle as it would do without -n).

A: Assuming your input file contains more than 1 name-value pair, consider this:
$ awk -F'":"' '{gsub(/^[[:space:]]*"|"[[:space:]]*$/,""); f[$1]=$2} END{print f["key"]}' file
JIRA-90

That approach lets you populate an array (f[] above) with the name to value mappings and then you can just print the values by their names whenever you like.
$ cat file
        "foo":"127"
        "key":"JIRA-90"
        "bar":"hello world"

$ awk -F'":"' '{gsub(/^[[:space:]]*"|"[[:space:]]*$/,""); f[$1]=$2} END{print f["bar"], f["key"]}' file
hello world JIRA-90

$ awk -F'":"' '{gsub(/^[[:space:]]*"|"[[:space:]]*$/,""); f[$1]=$2} END{print f["foo"] * 3}' file
381

$ awk -F'":"' '{gsub(/^[[:space:]]*"|"[[:space:]]*$/,""); f[$1]=$2} END{for (i in f) print i "=" f[i]}' file
key=JIRA-90
foo=127
bar=hello world


text:
Q: Undefined variable of an object how to debug this? So i am pretty new with JavaScript, and it is realy not my cup of tea.
We have ran into some issues in a large codebase with code that looks a bit like so:
var no = {somecontent:"text"};//Just any random object
document.write(no.length);
if(no.length != 0){
    document.write("Something is in this list!");
}
if(typeof(no.length) == "undefined"){
    document.write("OH GOD WHY?! THE LIES!");
}

Minus the last write, we just had the '!= 0' check for length of something which we assumed was an array. Since it is Undefined type, it simply returns true and assumed "something is in the list". This obviously caused a lot of issues, and we are afraid that there are a lot more of these errors in the codebase. (1500 lines by now)
So now my question is. Is there any sort of java parser/checker/compiler whichever that catches this in a form of an error or warning like: "You are trying to test for X while object/parameter is "undefined"!" ?
I imagine this must be a pretty common thing to happen, expecially when the programmer is inexperienced with the language. (Comming from Java/C#) But i couldn't find any answer on this besides adding: "typeof(no.length) == "undefined"" To every if statement in the code. Which seems like overkill and probably slams performance in the ground at runtime.
Any help with this issue is greatly appreciated!
Thanks in advance,
Smileynator

A: Sounds like you are looking for a tool to automatically check large javascript files for type safety.
You may want to check out Flow,
or the blogpost 5 attempts at type safety in javascript.


text:
Q: Simple way to render inputted component inside generic component I have seen an approach to do this using ng-content, but i can't do it this time (Also, seems that this isn't the best approach for this kind of problem).
Basically, what i want is something similar to this:
@Input title: string;
@Input component: Component; <--- This

Or something as simple as this.
I just need to be able to render a component (For example, a ButtonComponent) inside this component, but i already used ng-content (I am making basically an expansible container, but it can receive any components to display on the right side).
Any tips?

A: You can use *ngComponentOutlet directive.
For example:
<ng-container *ngComponentOutlet="component"></ng-container>

Of course with this directive, you have to add input component to entryComponents array too.
Stackblitz example

A: The right way to do such a thing is to use dynamically loaded components.
In your host component you should do the following:
add a <ng-container #btnContainer> where you want the button to be rendered in your template, and place a reference to it at the component class with @ViewChild('btnContainer', {static: true}) btnContainer.
Then receive ComponentFactoryResolver on the host component's constructor (it will be injected).
 constructor(private componentFactoryResolver: ComponentFactoryResolver) { }

then somewhere else, you resolve the factory to that component, and insert it on the ng-container you added in the template.
insertButton() {
    const buttonFactory = this.componentFactoryResolver.resolveComponentFactory(ButtonComponent);
    //clear the container to be sure it is empty
    this.btnContainer.viewContainerRef.clear();
    const btnRef = this.btnContainer.viewContainerRef.createComponent(buttonFactory);

    //If you want to set some data to the ButtonComponent you do as following
    //Example: if the button has a @Input() text attribute.
    btnRef.instance.text = "I'm working";

}

Every dynamically loaded components should be added to the entryComponents array of the module it's part of. So add it as follow:
@NgModule({
  declarations: [ ... ],
  imports: [ ... ],
  bootstrap: [ ... ],
  entryComponents: [ ButtonComponent ]  <----- here
})

The docs: https://angular.io/guide/dynamic-component-loader


text:
Q: Selecionar option em select de outra maneira com AngularJS Recentemente encontrei esse exemplo no JSFiddle para selecionar determinado option em um elemento select.
Reparei que é selecionado da seguinte maneira:
HTML:
<div class="listitem" ng-repeat="Choice in Person.Choices">
     {{Choice.Name}}:
     <select
        ng-model="Choice.SelectedOption"
        ng-options="choice.Name for choice in Choice.Options track by choice.ID"></select>
    {{Choice.SelectedOption.ID}}
</div>

JSON:
{
 "Name":"Dinner",
 "Options":[{Name:"Fish",ID:1}, {Name:"Chicken",ID:2}, {Name:"Beef",ID:3}],
 "SelectedOption":{Name:"Chicken",ID:2} // Neste trecho
}

Dúvida:
Não posso criar uma variável global dentro da minha controladora dessa maneira:
$scope.selected;

E colocar o valor de ng-model do elemento select com selected e passar o valor do ID que eu quero simplesmente sem fazer da forma que esta fazendo? Ou seja, passando o valor do option que eu quero invés de um objeto JSON.
Existem outras maneiras?

A: Se entendi corretamente, sim - apenas altere
ng-model="Choice.SelectedOption"

para
ng-model="selected"

e a diretiva utilizará $scope.selected como o aspecto do modelo a sofrer binding.


text:
Q: Why can't I concatenate a value in the second part of the ISNULL statement? I've already solved this issue using a CASE statement, but I'm wondering why, when using ISNULL, can I concatenate a value to the check_expression but not the replacement_value. Here's an example:
create table name_test
(
    nm          varchar(25)
    ,mid_init   varchar(1)
    ,name_type  int
)

insert into name_test values('Joe',NULL,1)
insert into name_test values('Joe','X',2)

I have this query.
SELECT
    n1.nm, isnull(n2.mid_init+'b',n1.mid_init) as m1,
    isnull(n1.mid_init,n2.mid_init+'b') as m2
FROM
    name_test n1
    JOIN name_test n2
    on n1.nm = n2.nm and n1.name_type = 1 and n2.name_type = 2

In the first statement (m1), I use the NOT-NULL value first, concatenated with a 'b'. In the second statement (m2), I use the NULL value first, so the query should pass through to the replacement_value. It does, but only takes the first value, not the concatenated value.
Result:
nm     m1   m2
Joe    Xb   X

With a little more investigation, I see that this query:
select
    n1.nm, isnull(n2.mid_init+'b',n1.mid_init) as m1,
    isnull(n1.mid_init,'1'+ n2.mid_init+'b') as m2
from
    name_test n1
    join name_test n2
    on n1.nm = n2.nm and n1.name_type = 1 and n2.name_type = 2

returns
nm  m1  m2
Joe Xb  1

So, the ISNULL function will take the entire check_expression, but if the check_expression is null, it will only take the first part of the replacement_value.
Does anyone know why there is a discrepancy. Also, I solved it with a case - is there a better solution?

A: ISNULL inherits the data type of the first expression, while COALESCE inherits the data type according to data type precedence. (What is the point of varchar(1) anyway?)
I would do:
select n1.nm,
COALESCE(CONVERT(VARCHAR(25), n1.mid_init),'1'+ n2.mid_init+'b') as m2
from name_test n1
join name_test n2 on n1.nm = n2.nm and n1.name_type = 1 and n2.name_type = 2;


text:
Q: How to capture docker pull status I'm trying to post docker image downloading status to frontend in a real time manner. Currently it can just tell that docker pull is going on. I understand that there could be multiple layers of different sizes and the sizes of layers that haven't started downloading could be unknown. So I'm thinking about showing how many layers are there and the current downloading status of the layers that have already started downloading.
Do you know how to capture the data that's shown on terminal console when you do docker pull <image>? My program is in Python so that I would like to get the data in python code and send it to frontend. I checked the docker documentation but didn't find any api that supports this. Looks like there's no public api that supports this functionality yet.
Do you have any other approaches that may realize my goal?
Any suggestions are welcomed and appreciated!
Thank you!

A: You need a low-level pull() call for that (docs). Here's an example:
>>> import docker
>>> import json
>>> client = docker.APIClient(base_url='unix://var/run/docker.sock')
>>> for line in client.pull('busybox', stream=True, decode=True):
...     print(json.dumps(line, indent=4))
{
    "status": "Pulling from library/busybox",
    "id": "latest"
}
{
    "status": "Pulling fs layer",
    "progressDetail": {},
    "id": "e5d9363303dd"
}
{
    "status": "Downloading",
    "progressDetail": {
        "current": 8635,
        "total": 764663
    },
    "progress": "[>                                                  ]  8.635kB/764.7kB",
    "id": "e5d9363303dd"
}
{
    "status": "Downloading",
    "progressDetail": {
        "current": 764663,
        "total": 764663
    },
    "progress": "[==================================================>]  764.7kB/764.7kB",
    "id": "e5d9363303dd"
}
{
    "status": "Verifying Checksum",
    "progressDetail": {},
    "id": "e5d9363303dd"
}
{
    "status": "Download complete",
    "progressDetail": {},
    "id": "e5d9363303dd"
}
{
    "status": "Extracting",
    "progressDetail": {
        "current": 32768,
        "total": 764663
    },
    "progress": "[==>                                                ]  32.77kB/764.7kB",
    "id": "e5d9363303dd"
}
{
    "status": "Extracting",
    "progressDetail": {
        "current": 764663,
        "total": 764663
    },
    "progress": "[==================================================>]  764.7kB/764.7kB",
    "id": "e5d9363303dd"
}
{
    "status": "Extracting",
    "progressDetail": {
        "current": 764663,
        "total": 764663
    },
    "progress": "[==================================================>]  764.7kB/764.7kB",
    "id": "e5d9363303dd"
}
{
    "status": "Pull complete",
    "progressDetail": {},
    "id": "e5d9363303dd"
}
{
    "status": "Digest: sha256:c5439d7db88ab5423999530349d327b04279ad3161d7596d2126dfb5b02bfd1f"
}
{
    "status": "Status: Downloaded newer image for busybox:latest"
}

A: docker-py provides low level APIs to pull image along with streaming status. You can use this snippet to show it like a progress bar similar to docker pull command. It first shows red progress-bars for showing download status, then green status bars for extract :-)
import docker
from rich.progress import Progress

tasks = {}

# Show task progress (red for download, green for extract)
def show_progress(line, progress):
    if line['status'] == 'Downloading':
        id = f'[red][Download {line["id"]}]'
    elif line['status'] == 'Extracting':
        id = f'[green][Extract  {line["id"]}]'
    else:
        # skip other statuses
        return

    if id not in tasks.keys():
        tasks[id] = progress.add_task(f"{id}", total=line['progressDetail']['total'])
    else:
        progress.update(tasks[id], completed=line['progressDetail']['current'])

def image_pull(image_name):
    print(f'Pulling image: {image_name}')
    with Progress() as progress:
        client = docker.from_env()
        resp = client.api.pull(image_name, stream=True, decode=True)
        for line in resp:
            show_progress(line, progress)

if __name__ == '__main__':
    # Pull a large image
    IMAGE_NAME = 'bitnami/pytorch'
    image_pull(IMAGE_NAME)

Progress bar for docker pull through Python API


text:
Q: Entity Framework AsNoTracking() Infinite Navigation Property I have implementation like this:
var query = this.DbContext.Set<T>();

if (includeProperties != null && includeProperties.Any())
{
    foreach (var includeProperty in includeProperties)
    {
        if (!String.IsNullOrEmpty(includeProperty))
        {
            query = query.Include(includeProperty);
        }
    }
}

return await query.Where<T>(predicate).ToListAsync();

I'd like to make this query AsNoTracking() and I'm interested if its important where to call AsNoTracking()?
Does it make any difference if I put it here:
var query = this.DbContext.Set<T>().AsNoTracking();

or here:
return await query.Where<T>(predicate).AsNoTracking().ToListAsync();

Will both perform query .AsNoTracking() same way or not?
Also I'm interested if .Include() is also affected by any of these .AsNoTracking() or do I have to put additional .AsNoTracking() like this:
query = query.Include(includeProperty).AsNoTracking();

I'm having trouble with .Include() because I get infinite recursive navigation properties and when using Automapper I get stackoverflow, so I'm not quite sure if I'm using AsNoTracking() correctly (or AsNoTracking() doesn't affect infinite nesting of properties, although I read that somewhere, but only tracks changes in Context for further CUD operations?)
I also have these in my Context subclass:
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;

Though my main problem is inifinite navigation property references, I'd really appreciate if someone could also explain correct usage of AsNoTracking() from beginning of question (although, for example, it doesn't have anything to do with the problem).
Thank you.

A: No it's not important where to call AsNoTracking(). Basically all it does is sets ObjectQuery.MergeOption (and some other properties) on internal ObjectQuery, so it doesn't matter where to do that until actual query execution.
Yes, all Includeed entities will also not be tracked by a context.
No, LazyLoadingEnabled = false, ProxyCreationEnabled = false and AsNoTracking() will not solve all your infinite recursion problems, especially if you are using includes. Look for how to map such recursive entities with automapper correctly, doing anything on EF side will not help.


text:
Q: Weird Color Change on Linux Mint under VirtualBox Currently I have a machine that runs Linux Mint 18.1, drivers and vbox additions up-to date.
Everytime I started the machine, the background image turns into a weird colorish image.
This is how it looks like:

After some background changes it becomes normal.

However I don't want to change background everytime I open the machine.

A: This command fixed this issue for me:
gsettings set org.cinnamon.muffin background-transition fade-in
To be executed in the guest Linux Mint OS.

A: I get this too. The gamma is way too high, initially.
There seems to be another problem associated with VirtualBox, the latest Guest Additions, and 3D acceleration mode. Maybe they're related...


text:
Q: How to add Pull to refresh feature to Flutter Webview without any problem? How to add Pull to refresh feature to Flutter Webview without any problem?
I've been struggling for 2 days.
Here is the whole code but it doesn't work correctly. Could you please help?
What is the best practice to give refresh feature to webview?
This code I wrote gives an error, the application closes
.....
@override
Widget build(BuildContext context) {
WebViewController? _webviewController;
return SafeArea(
  child: Scaffold(
    appBar: AppBar(
      actions: [],
    ),
    body: RefreshIndicator(
      onRefresh: () {
        return Future.delayed(Duration(seconds: 1), () {
          _webviewController!.reload();
        });
      },
      child: Expanded(
        child: SingleChildScrollView(
          physics: AlwaysScrollableScrollPhysics(),
          scrollDirection: Axis.vertical,
          child: Column(
            children: [
              SizedBox(
                height: heights,
                child: WebView(
                  javascriptMode: JavascriptMode.unrestricted,
                  initialUrl: "https://flutter.dev/",
                  // WebviewControlleri burada tanimliyoruz
                  onWebViewCreated: (WebViewController webViewController) {
                    _webviewController = webViewController;
                  },
                  onPageFinished: (content) async {
                    var _heights = double.parse(await _webviewController!
                        .evaluateJavascript(
                            "document.documentElement.scrollHeight"));
                    heights = _heights;

                    setState(() {});
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    ),
    bottomNavigationBar: BottomAppBar(
      color: Colors.amber,
      child: Row(
        children: [
          IconButton(
            onPressed: () async {
              // Geri donecek bir sey varmi kontrol ediyoruz
              if (await _webviewController!.canGoBack()) {
                // Varsa geri donuyoruz
                _webviewController!.goBack();
              } else {
                // Yoksa ekrana mesaj gosteriyoruz
                ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text("Geri donecek bir sey yok")));
              }
            },
            icon: Icon(
              Icons.arrow_left,
              size: 50,
            ),
          ),
          IconButton(
            onPressed: () async {
              // Ileriye gidecek bir sey varmi kontrol ediyoruz
              if (await _webviewController!.canGoForward()) {
                // Varsa ileri gidiyoruz
                _webviewController!.goForward();
              } else {
                // Yoksa ekrana mesaj gosteriyoruz
                ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text("Ileri gidecek bir sey yok")));
              }
            },
            icon: Icon(
              Icons.arrow_right,
              size: 50,
            ),
          )
        ],
      ),
    ),
  ),
);

}
}


text:
Q: Не работает генератор ТСР пакетов Здравствуйте!
Делаю лабораторную работу:
Реализация генератора TCP-пакетов(на Raw сокетах) в соответствии со стандартом RFC 793.

*

*Требования к реализации

•   Приложение должно выполнять функции генерации TCP пакетов.
...
остальное не так важно...
Важно "руками" создать tcp пакет, и отправить его куда-то, допустим на 127.0.0.1 на порт 1000.
Кое-как собрал генератор пакетов... И он не работает... Не выдает ошибок при компиляции, а при работе sendto(...) WSAGetLastError() выдает ошибку 10022. Вот код:
header.h

 struct tcp_header
{
unsigned short  src_port;   // Порт отправителя
unsigned short  dst_port;   // Порт получателя
unsigned int    seq_n;      // Номер очереди
unsigned int    ack_n;      // Номер подтверждения
unsigned char   offset;     // Смещение данных (4 бита)
                    // + Зарезервировано (4 бита)
unsigned char   flags;      // Зарезервировано (2 бита)
                    // + Флаги (6 бит)
unsigned short  win;        // Размер окна
unsigned short  crc;        // Контрольная сумма заголовка
unsigned short  padding;    // Дополнение до 20 байт
};
//Также необходимо ввести структуру псевдозаголовка, которая позволит вычислять контрольную сумму в TCP и UDP пакетах.
struct pseudo_header
{
unsigned int src_addr;      // адрес отправителя
unsigned int dst_addr;      // адрес получателя
unsigned char zero ;        // начальная установка
unsigned char proto;        // протокол
unsigned short length;      // длина заголовка
//struct tcp_header tcp;
};

//-------=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
struct ip_header
{
unsigned char   ver_ihl;    // Длина заголовка (4 бита)
                // (измеряется в словах по 32 бита) +
                // + Номер версии протокола (4 бита)
unsigned char   tos;        // Тип сервиса
unsigned short  tlen;       // Общая длина пакета
unsigned short  id;     // Идентификатор пакета
unsigned short  flags_fo;   // Управляющие флаги (3 бита)
                    // + Смещение фрагмента (13 бит)
unsigned char   ttl;        // Время жизни пакета
unsigned char   proto;      // Протокол верхнего уровня
unsigned short  crc;        // CRC заголовка
unsigned int    src_addr;   // IP-адрес отправителя
unsigned int    dst_addr;   // IP-адрес получателя
};

            ip_header iph;
                tcp_header tcph;
                    SOCKET s;

//-------=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//Далее поговорим о подсчете контрольных сумм в генерируемых пакетах.
//Контрольную сумму в IP и ICMP пакетах считает следующая функция:
unsigned short rs_crc (unsigned short * buffer, int length)
{
    unsigned long crc = 0;
    // Вычисление CRC
    while (length > 1)
    {
        crc += *buffer++;
        length -= sizeof (unsigned short);
    }
    if (length) crc += *(unsigned char*) buffer;
    // Закончить вычисления
    crc = (crc >> 16) + (crc & 0xffff);
    crc += (crc >> 16);
    // Возвращаем инвертированное значение
    return (unsigned short)(~crc);
}
//Для подсчета CRC в TCP и UDP пакетах необходимо воспользоваться следующей функцией,
//которая сначала создает псевдозаголовок, а уже потом вычисляет контрольную сумму.
unsigned short rs_pseudo_crc( char *data, int data_length,unsigned int src_addr,unsigned int dst_addr,int packet_length,unsigned char proto)
{
    char * buffer;
    unsigned int full_length;
    unsigned char header_length;
    struct pseudo_header ph;
    unsigned short p_crc = 0;

    // Заполнение структуры псевдозаголовка
    ph.src_addr = src_addr;
    ph.dst_addr = dst_addr;
    ph.zero = 0;
    ph.proto = proto;
    ph.length = htons (packet_length);

    header_length = sizeof (struct pseudo_header);

    full_length = header_length + data_length;
    buffer =(char *) calloc (full_length, sizeof (char));

    // Генерация псевдозаголовка
    memcpy (buffer, &ph, header_length);
    memcpy (buffer + header_length, data, data_length);

    // Вычисление CRC.
    p_crc = rs_crc ((unsigned short*) buffer, full_length);
    free (buffer);
    return p_crc;
}
//Установки опции TOS для сокета:
int rs_set_tos (SOCKET s, unsigned char new_tos)
{
    int tos = new_tos;
    int tos_len = sizeof (tos);
    int per=setsockopt(s, IPPROTO_IP, 3, (char *)&tos, tos_len);
    if (per == SOCKET_ERROR)
    {
        cout<<"setsockopt Error "<<WSAGetLastError()<<endl;
        return WSAGetLastError();
    }
    return 0;
}
//Установка опции RAW для сокета:
int rs_set_raw (SOCKET s)
{
    unsigned int use_own_header = 1;

    // Установка опции RAW для сокета, что говорит о том
    // что мы вручную будем формировать заголовки пакетов
    if ( setsockopt (s, IPPROTO_IP, 2,//~IP_HDRINCL
        (char*)&use_own_header, sizeof(use_own_header))== SOCKET_ERROR)
    {
        cout<<"setsockopt Error "<<WSAGetLastError()<<endl;
        return WSAGetLastError();
    }
    else
                        {
                                cout<<"TCP setsockopt - OK"<<endl;
                        }

    return 0;
}

//Далее необходимо объявить структуры заголовков создаваемых пакетов.
//После этого производится заполнение заголовка IP пакета. На следующем шаге созданием RAW -сокет,
//и если нет вложений протоколов верхнего уровня в пакет IP , то отправляем его, используя следующую функцию:
int rs_send_ip (SOCKET s, ip_header iph, unsigned char * data, int data_length, unsigned short dst_port_raw)
{
    char * buffer;
    int result;
    sockaddr_in target;
    unsigned char header_length;
    unsigned int packet_length;
    memset (&target, 0, sizeof (target));
    target.sin_family = AF_INET;
    target.sin_addr.s_addr = iph.dst_addr;
    target.sin_port = dst_port_raw;

    // Вычисление длины и заголовка пакета
    header_length = sizeof (struct ip_header);
    packet_length = header_length + data_length;

    // Установка CRC.
    iph.crc = 0;

    // Заполнение некоторых полей заголовка IP
    iph.ver_ihl = RS_IP_VERSION;

    // Если длина пакета не задана, то длина пакета
    // приравнивается к длине заголовка
    if (!(iph.ver_ihl & 0x0F))
        iph.ver_ihl |= 0x0F & (header_length / 4);
    buffer =(char *) calloc (packet_length, sizeof (char));

    // Копирование заголовка пакета в буфер ( CRC равно 0).
    memcpy (buffer, &iph, sizeof (struct ip_header));

    // Копирование данных в буфер
    if (data) memcpy (buffer + header_length, data,
                data_length);

    // Вычисление CRC.
    iph.crc = rs_crc((unsigned short *) buffer,
                packet_length);

    // Копирование заголовка пакета в буфер (CRC посчитана).
    memcpy (buffer, &iph, sizeof (struct ip_header));

    // Отправка IP пакета в сеть.
    result = sendto ( s, buffer, packet_length, 0,(struct sockaddr *)&target,sizeof (target));

    if(result==SOCKET_ERROR)
        cout<<"TCP pakcet sended - Filed: "<<WSAGetLastError()<<endl;
    else
        cout<<"TCP sendto - OK"<<endl;
    printf("%s\n", buffer);

    free (buffer);
    return result;
}

int rs_send_tcp (SOCKET s, unsigned char * data, int data_length)
{
    char * buffer;
    int result;
    unsigned char header_length;
    unsigned int packet_length;

    // Вычисление длин пакета и заголовка.
    header_length = sizeof (struct tcp_header);
    packet_length = header_length + data_length;

    // Установка CRC.
    tcph.crc = 0;

    // Установка поля offset .
    tcph.offset = 0xF0 & ((header_length / 4) << 4);
    buffer =(char *) calloc (packet_length, sizeof (char));

    // Копирование заголовка пакета в буфер ( CRC равно 0).
    memcpy (buffer, &tcph, sizeof (struct tcp_header));

    // Копирование протокола более высокого уровня (данных)
    if (data) memcpy (buffer + header_length, data, data_length);

    // Вычисление CRC.
    tcph.crc = rs_pseudo_crc (buffer, packet_length, iph.src_addr, iph.dst_addr, packet_length, IPPROTO_TCP);

    // Копирование заголовка пакета в буфер (CRC посчитано).
    memcpy (buffer, &tcph, sizeof (struct tcp_header));

    // Посылка IP пакета с вложенным TCP пакетом
    result = rs_send_ip (s, iph, (unsigned char*)buffer, packet_length, tcph.dst_port);

    free (buffer);
    return result;
}

int rs_exit(void)
{
    // Закрытие библиотеки Winsock
    if(!WSACleanup ())
        cout<<"TCP WSACleanup() - OK"<<endl;
    else
        cout<<"TCP WSACleanup() Error "<<WSAGetLastError()<<endl;
    return 0;
}

//=======================================================================================
    TCP.cpp
#include <winsock2.h>
#include <ws2tcpip.h>

#include <Windows.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

using namespace std;

#include "defines.h"
#include "header.h"

/*****************************************************************/
void ShowError()
{
        LPVOID lpMsgBuf = NULL;
        FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,NULL,WSAGetLastError(),
                MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),(LPTSTR)&lpMsgBuf,0,NULL);
        CharToOem((char*)lpMsgBuf,(char*)lpMsgBuf);
        cout<<(LPCTSTR)lpMsgBuf<<endl;
        LocalFree(lpMsgBuf);
}

//*****************************************************************/

void main(){
        WSADATA            wsaData;
        //Первым шагом будет инициализация библиотеки Winsock 2.2.
        if(WSAStartup(0x0202,&wsaData)){ShowError();}
        else
        {
                cout<<"TCP WSAStartup - OK"<<endl;
                // Созлание RAW сокета.
                s = WSASocket (AF_INET, SOCK_RAW, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);

            if(s != INVALID_SOCKET){

                cout<<"TCP Raw scoket is created"<<endl;

                rs_set_tos(s, 0);
                rs_set_raw(s);

    unsigned int use_own_header = 1;

    // Установка опции RAW для сокета, что говорит о том
    // что мы вручную будем формировать заголовки пакетов
    if ( setsockopt (s, IPPROTO_IP, 2,//~IP_HDRINCL
        (char*)&use_own_header, sizeof(use_own_header))== SOCKET_ERROR)
    {
        cout<<"setsockopt Error "<<WSAGetLastError()<<endl;
    }
    else
                        {
                                cout<<"TCP setsockopt - OK"<<endl;
                        }

                char *ptr, szMessage[4068];
                strcpy(szMessage,"HHHHHHHHEEEEEEEEEEEEEELLLLLLLLLLLLLLLLLOOOOOOOOOOOOOOOOOOOOWWWWWWWWWWWWWWWWWWWW");
                ptr=szMessage;
                unsigned char data;
                data = static_cast<unsigned char>(*ptr);
                //************************************************************************

                rs_send_tcp (s, &data, strlen(ptr));

                if(closesocket(s)== SOCKET_ERROR){ cout<<"Close TCP Socket - Error"<<endl;}
                else{cout<<"TCP closesocket - OK"<<endl;}
            }
        }

        rs_exit();
        getch();
}

Подправил код... Вот тут вот // Отправка IP пакета в сеть.
    result = sendto ( s, buffer, packet_length, 0,(struct sockaddr *)&target,sizeof (target)); выявляется ошибка...

Перебрал всё заново руками, результат-меньше кода, а ошибка та же самая...:
char datagram[4096];
struct ip_header *iph = (struct ip_header *) datagram;

struct tcp_header *tcph = (struct tcp_header *) datagram + sizeof (struct ip_header);
char * data = (char *) datagram + sizeof(struct tcp_header) + sizeof(struct ip_header);
struct sockaddr_in sin;
WSADATA            wsaData;

//Первым шагом будет инициализация библиотеки Winsock 2.2.
if(WSAStartup(0x0202,&wsaData))
    {ShowError();}
else
    cout<<"\n\nTCP WSAStartup - OK"<<endl;
        // Созлание RAW сокета.
SOCKET r = WSASocket (AF_INET, SOCK_RAW, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);

if(r != INVALID_SOCKET){
        cout<<"TCP Raw scoket is created"<<endl;
}

sin.sin_family          = AF_INET;
sin.sin_port            = htons (1000);
sin.sin_addr.s_addr     = inet_addr("127.0.0.1");

memset(datagram, 0, 4096);

iph->ver_ihl                    = 5;
iph->tos                     = 0;
iph->tlen                     = sizeof (struct ip_header) + sizeof (struct tcp_header);
iph->flags_fo                     = 0;
iph->ttl                    = 255;
iph->proto                       = 6;
iph->crc                    = 0;
iph->src_addr     = inet_addr ("127.0.0.1");
iph->dst_addr     = sin.sin_addr.s_addr;

tcph->src_port          = htons (1001);
tcph->dst_port          = htons (1000);
tcph->seq_n            = 65;// random
tcph->ack_n            = 0;
tcph->offset            = 0;
tcph->flags          = TCP_SYN;
tcph->win           = htonl (65535);
tcph->crc           = 0;
tcph->padding            = 0;

iph->crc             = csum ((unsigned short *) datagram, iph->tlen >> 1);

memset(data, 0, sizeof(data));

unsigned int use_own_header = 1;
int one = 1;
const char *val = "hhhhhhh";
if(setsockopt (r,IPPROTO_IP,IP_HDRINCL,(char*)&use_own_header,sizeof(use_own_header))==SOCKET_ERROR) {
        cout<< "Setsockopt\tFAIL.\n";
}

while(1) {
       int result = sendto ( r, data, strlen(data), 0,(struct sockaddr *)&sin,sizeof (sin));
        if(result==SOCKET_ERROR)
        {
                cerr << "Sendto\tFAIL. "<<WSAGetLastError()<<endl;
        } else
                cout << " :) ";
}

A: Обратите внимание, речь именно о send.
Limitations on Raw Sockets
On Windows 7, Windows Vista, Windows XP with Service Pack 2 (SP2), and Windows XP with Service Pack 3 (SP3), the ability to send traffic over raw sockets has been restricted in several ways:
TCP data cannot be sent over raw sockets.
UDP datagrams with an invalid source address cannot be sent over raw sockets. The IP source address for any outgoing UDP datagram must exist on a network interface or the datagram is dropped. This change was made to limit the ability of malicious code to create distributed denial-of-service attacks and limits the ability to send spoofed packets (TCP/IP packets with a forged source IP address).
A call to the bind function with a raw socket for the IPPROTO_TCP protocol is not allowed.

Note  The bind function with a raw socket is allowed for other protocols (IPPROTO_IP, IPPROTO_UDP, or IPPROTO_SCTP, for example).

These above restrictions do not apply to Windows Server 2008 R2, Windows Server 2008 , Windows Server 2003, or to versions of the operating system earlier than Windows XP with SP2.
см. здесь (от Microsoft).


text:
Q: HP Fortify issue- XML External Entity Injection I solved XML External Entity Injection with DocumentBuilderFactory class using below code
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);

Now I have to resolve this XML External Entity Injection coming when I am using TransformerFactory class.
I could not find these methods in the TransformerFactory.

setXIncludeAware() and setExpandEntityReferences()

what are the alternatives for this in TransformerFactory class? is there any other way to pass HP fortify for this?
thanks in advance


text:
Q: how to use Images without path in handlebars I want to deliver image list into Handlebars view.
ArrayList<ImageIcon> images = new ArrayList<>();
for(Photos p : photos){
    ByteArrayInputStream bis = new ByteArrayInputStream(p.getImage());
    BufferedImage bim = ImageIO.read(bis);
    images.add(new ImageIcon(bim));
}

model.addAttribute("photos", images);

I'm sure that there are ImageIcon objects in this arrayList by debugging.
Then, how can I use this array in handlebars like this.
{{#each photos as |photo|}}

{{/each}}

I want to use this images without file path.

A: @GetMapping("/displayImage")
public void displayImage(@RequestParam("email")String email, HttpServletResponse response) throws IOException {
    List<Photos> list = photoService.showImages(email);

    byte[] binaryImage = list.get(0).getImage();
    response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
    response.getOutputStream().write(binaryImage);
    response.getOutputStream().close();
}


text:
Q: Deriving the formula and its error $$f''(x) \thickapprox\dfrac{1}{2h^2}[f(x+2h) - 2f(x) + f(x - 2h)]$$
I'm supposed to be deriving the above formula and establish an error formula in using them.
This is one of a series of problems like this, and I'm not quite too sure on how to get started on this. (This is in a chapter of Estimating Derivatives and Richardson Extrapolation)
Any tips/pointers?

A: Taylor expansion does the trick:
$$\begin{align*}
f(x+2h)&=f(x)+2hf^\prime(x)+2h^2 f^{\prime\prime}(x)+\frac43 h^3 f^{(3)}(x)+\cdots\\
f(x-2h)&=f(x)-2hf^\prime(x)+2h^2 f^{\prime\prime}(x)-\frac43 h^3 f^{(3)}(x)+\cdots
\end{align*}$$
Combine these two appropriately to remove the term containing $f^\prime(x)$, and move everything to the left such that the first term of the right hand side is $f^{\prime\prime}(x)$. The term(s) after that should be your error estimate.

A: Hint: $f''(x) \simeq \dfrac{f'(x+h)-f'(x-h)}{2h}.$ Try to replace $f'$ by $f$ in the definition.


text:
Q: В WebStorm введенное название тега не оборачивается автоматически скобками Столкнулся с тем, что WebStorm перестал оборачивать набираемые HTML-теги угловыми скобками и не подставляет автоматически закрывающий тег. Покопался в настройках, но так и не нашел, как вернуть этот базовый функционал.
Ввожу начало название тега -> появляется список автоподстановки -> выбираю нужный мне тип элемента -> название добавляется, но после нажатия на "Tab" слово не оборачивается в <угловые скобки>.
Обнаружил только что, что и Emmet перестал работать. Синтакс div.nav>ul>li*5>a не срабатывает. Хотя в CSS-файлах вроде как предлагает эмметовские сокращения и поддерживает их.

A: Проверьте настройки: "Settings" > "Editor" > "Emmet" - включён ли сам Emmet, нужная ли клавиша выбрана для раскрытия сокращений. Также см. https://www.jetbrains.com/webstorm/help/enabling-emmet-support.html