text:
Q: How can I login linux using C or C++ I need to programmely switch the current user to another,then the followed code should be executed in the environment(such as path,authority..) of another user.
I've find the 'chroot()','setuid()' may be associated with my case, but these functions need the root authority, I don't have root authority, but I have the password of the second user. what should I do?
I have tried shell "su - " can switch current user, can this command help me in my C++ code?
Don't laugh at me if my question is very stupid, I'm a true freshman on linux. :)
Thanks!

A: You can use the system function to execute shell commands on the operating system.

A: You could take a look at the source code of the login command, or you could try using the exec()-family functions to call on login.
EDIT: Seems like you will need root access in any case.

A: Is setuid what you're looking for?

A:
when clients connect to the server,
  the server transfer the data what they
  need,but the precondition is the
  correct username and password.

If your primary requirement is to authenticate, then try man pam. There are also some libraries allowing to auth over LDAP. Unfortunately I have no personal experience implementing neither.
Otherwise, recreating complete user environment is unreliable and error prone. Imaging a typo or endless loop but in user's ~/.profile.
I haven't done that for some time, but I would also have tried to dig in direction of "su", figuring out user shell (from /etc/passwd) and trying to exec() it as if it was a login shell (with "-"). But after that you would need somehow to communicate a command for execution to it and that's a problem: shells run differently in batch more and in interactive mode. As a possible hack, expect (man expect) comes to mind, but it is still IMO too unreliable.
I have in past used ssh under expect (to input the password), but it was breaking on customized user profiles every other time. With expect, to send a command, one has to recognize somehow that shell has finished initialization (execution of profile and rc files). But since many people customize the shell prompt and their profile/rc files print extra info, it was quite often that expect was recognizing shell prompt too soon.
BTW, depending on number of users, one can try a setup where users manually start the server under their own account. The server would have access only to the information which is only accessible to the user.

A: I think the key point here is that you can't change the user of the running process (easily). All the programs like 'su' are effectively starting a new process as the specified user.
Therefore, in your design I would recommend seperating off the functionality that needs to be done into a different executable and then investigate using execve() to start it.


text:
Q: Is this drive compatible with PS3? I am aware that 99% of HDDs that are 2.5" are compatible with the PS3 but before performing a purchase I would like to be 110% sure. I am looking into this HDD.
Western Digital Blue Portable WD7500BPVX
Is it compatible? Is there any other feature to check besides that it being 2.5" Sata hdd?

A: According to the customer reviews on Amazon they work very well. For example:

My husband bought this HDD for his PS3 Slim. It fits perfect and worked like a charm. He is happy as can be.

And another one:

Bought this hard drive to upgrade a PS3 with and everything went perfectly. Did a lot of research first and saw some pretty unfounded statements about hard drive limits on the PS3. I opted to go the route of backing up save games only (don't forget to do this separately for all users on the PS3), so the total time to swap drives was all of 5 minutes. Plus maybe another 10-15 to update firmware package and format.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS position icon to top right of table I am relatively new to CSS. I have a table on my page which has a width of 70%. I need to position a small icon just above the right side of the table so that the icon is aligned with the right margin of the table below it. How can I achieve this?
So generically this question would be how to position elements relative to the position of other elements on a page using CSS?
Thanks,
Calvin

A: Hi now you can do this easily throw Position Give to Parent Position Relative and child to give position Absolute and do top right according to your layout
Live demo
http://jsfiddle.net/srgJh/

A: In CSS you should write:
.myclass {
    position:relative;
}

or

then you can control position by "top", "left", "right", "bottom" statement. Example:

A:

...

.icon {
position:absolute;
width:10px;
height:10px;
top:0;
right:0;
}

if want the icon be outside the table write values with minus, for ex:
top:-10px; /* above the table */
right:-10px; /* on the right side the table */

A: Give This css :
.classname {
    position:relative;
}

i hope you problem will be solve

A: The guys above have answered the question, but if you want to know how it works, try looking at:
http://www.tizag.com/cssT/position.php
Also you should consider using Divs instead of tables, when creating layout of the entire page:
http://www.tizag.com/htmlT/htmldiv.php


text:
Q: Is it possible to play minecraft with multiple people on the same computer? Backstory: My friends and I go are both pc gamers and go round each overs houses (not anymore obviously) for sleepovers. Because we are on pc there aren't many games we can play together.
Problem: We are both massive Minecraft lovers and we were wondering if we are able to play Minecraft together on the same machine with different accounts with different input devices so theoretically we could play on the same server together? We have searched everywhere and didn't find much. We were wondering if we could do this through a Virtual Machine maybe? It's just the only issue is that we cannot have the same window open at the same time...

A: If you have multiple graphics cards, it is theoretically possible to pass through the mouse and keyboard as well as one GPU to the VM, and then set it up as fullscreen on a second monitor.  This worked for me in QEMU/KVM on Linux, but on Windows it may be impossible.  I used this tutorial on Ubuntu 20.04.

A: It's possible to play with two keyboards/mouses at once. However, this might be a bit too complicated to install and laggy, plus the way I do it requires a premium software, so I think it would be way easier for you to find a different solution to your predicament. However, this could help out some other people, so here it is.
The tutorial I used for this is here. I didn't get a virus in the process, so it should be safe to use the software. Nevertheless, don't be an idiot and at least be careful. I'm not responsible for anything you do!

*

*There's a great multiseat software called ASTER, which you can get here.

ASTER is a paid program: however, it does have a 30 day trial that you could try out, and there are other alternatives listed here that would work out as well. Note that you'll need Windows 10 for the the steps below.

*You'll need two sets of a keyboard and a mouse, an extra monitor, and you'll probably also need a great PC if your game is very high resolution and has good graphics that will lag you out. If you don't own an extra PC monitor, you can also use a television as your extra monitor. Having another monitor is required for the software. Also, you'll probably need at least half an hour of time on your hands.

*After you get your materials, plug everything in and make sure that your monitors are connected to the same graphics card. According to the tutorial I used, apparently ASTER crashes your system if you're using a NVIDA graphics card with Geforce Experience, and you have to uninstall Geforce Experience for this. I'm not exactly in the most trustworthy parts of the web currently, but it's your decision whether or not you want to trust them or not. I personally don't use a NVIDA graphics card.

*Download the installation software. Create a backup in case your computer crashes either using another software or by checking the box in the the bottom left hand corner of the software that says "Create a restore point". After doing this, download ASTER from the installation software by going through the instructions on the installation program, and then restart your computer. After restarting your computer, start up ASTER again, press OK when it asks to update, and then press the correct option for getting a software key.

*Press on the "Workplaces" tab and set up "Place 1" and "Place 2" by dragging the icons representing hardware for each respective player into the places you want them. If you're not sure what the icons represent, hover over them to see what you're using. For instance, if I want to set my first monitor for me and the second monitor for my friend, I'll drag one monitor into Place 1 and another into Place 2. It's very important that you make sure the icons you're dragging are the pieces of hardware you're using to play.

*If you get a warning message about sharing monitors, ignore it. There may be more keyboard icons than you actually have keyboards: these are other USB devices that you have connected to your computer. You should make sure that you have the right hardware in the right place by hovering over the icons and checking the hardware names. You wouldn't want to connect your microphone instead of your keyboard!

*Click apply, and then enable ASTER workplaces on the general setting tabs. Also, change "How to run workplaces" in the settings and change it to manual, so you won't have a problem turning it on/off.

*Click on "Enable ASTER and Reboot PC". Every time you want to turn ASTER on/off, you'll have to reboot using ASTER.

*If everything has gone well, your second monitor should've switched on and you can now login and launch your games as if the two monitors were connected to two different computers. When you're done playing, simply press the reboot button on ASTER to switch the two workplaces off. Enjoy :)

A: Yes it is possible by running 2 minecraft. But the real problem is the active windows or only one keyboards. So it isn't possible. I'm sorry to dissapoint you.


text:
Q: Can static libraries that don't rely upon the C standard library be compiled on one OS, then moved to another? I know that for full programs this is impossible because of executable file formats and syscalls, however if you had a file with:

    int add(int a, int b) {
        return a + b;
    }

Could you compile it as an object file or static library on Linux, and then use it on macOS or Windows?

A: Compiling a C code turns it into a native binary/ native image. It is specific to the processor/OS on which it is compiled (unless of course you are not using a cross compiler). The binary/object will not run on another OS.
Only in case of languages like java, C# it is possible that you can compile for one OS and run on other (without rebuilding). This is because these languages create a managed binary/object. This managed object doesn't run directly on the OS. It runs on the virtual machine (JVM for Java and CLR for C#).

A:
Can static libraries that don't rely upon the C standard library be compiled on one OS, then moved to another?

In theory; yes. Note that a compiler is just something that converts a primary language (e.g. C) into a secondary language (e.g. maybe native code for a specific OS and specific CPU; but maybe also BASIC source code or web-assembly source code or some kind of portable byte-code or anything else).
The only thing that really matters is that whatever uses the secondary language understands the secondary language.
In practice; for static libraries the secondary language includes things like object file formats and calling conventions; and "whatever uses the secondary language understands the secondary language" includes understanding the object file format, understanding the calling conventions, etc. Typically compilers are configured such that their secondary language matches whatever makes sense for the computer the compiler is running on, and because of this often you can't compile a static library on one computer and move it to another computer (with a different compiler and/or OS and/or CPU).
However, "typical" does not indicate a necessity. Cross-compilers are entirely possible.
For an example, you can port GCC (and it's tools - linker, etc) to Windows and use your cross-compiler to create static libraries that can be used by compiler's designed for (and running on) Linux; and if you do this you probably won't be able to use the cross compiler (running on Windows) to create static libraries for other compilers that are also running on Windows.


text:
Q: Setting wallpaper in android code? I have been using this code for a while now but it is not working as expected it sets the wallpaper bigger than the screen making it bigger so I scaled to so it would fit the screen and it worked fine but the thing is that when I restart the device the scaling disappears making the wallpaper bigger than the screen again so I used broadcast receiver to fix this but it works for some devices and not all of them.
(the image gets bigger in width and height so when the user scrolls between the pages the next part of the image scrolls with him -see image below for more details- )

here is my final code:
DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int height = metrics.heightPixels;
        int width = metrics.widthPixels;
        Bitmap tempbitMap = BitmapFactory.decodeResource(getResources(), tophone);
        Bitmap bitmap = Bitmap.createScaledBitmap(tempbitMap,width,height, true);
        WallpaperManager wallpaperManager = WallpaperManager.getInstance(MainActivity.this);
        wallpaperManager.setWallpaperOffsetSteps(1, 1);
        wallpaperManager.suggestDesiredDimensions(width, height);
        try {
          wallpaperManager.setBitmap(bitmap);
          } catch (IOException e) {
          e.printStackTrace();
        }

can anyone tell me another code than this one that makes the wallpaper fit the screen without scaling it and without needing to use broadcast receiver
    Thank you!!


text:
Q: How I can set params in react-router-dom with dynamic import I have read the documentation  by Tyler Macginnis react-router, but I cand find the solution for my problem.
Basically I was tried to test my routing with custom pages (:page param), but the console.log only print "path" function

DynamicImport.js to load dynamically pages
import React, { Component } from 'react';
import PropTypes from 'prop-types';

class DynamicImport extends Component {
    state = {
        component: null
    };

    async componentDidMount() {
        const { path } = this.props;
        const { default: Component } = await path().then((data) => {
            return data;
        });

        this.setState({ component: <Component {...this.props} /> });
    }

    render() {
        const { component } = this.state;
        return
{component ||
Loading...
}
;
    }
}

DynamicImport.propTypes = {
    path: PropTypes.func.isRequired
};

export const Top = () => (
    <DynamicImport path={() => import('../../containers/Top')} />
);
export const News = () => (
 <DynamicImport path={() => import('../../containers/News')} />
);
export const Show = () => (
    <DynamicImport path={() => import('../../containers/Show')} />
);
export const Ask = () => (
    <DynamicImport path={() => import('../../containers/Ask')} />
);

Routing.js to routing
import React from 'react';
import { NavLink } from 'react-router-dom';
import './Routing.css';

const Routing = () => (

                <NavLink to="/" activeClassName="active">
                    Top
                </NavLink>

                <NavLink to="/news" activeClassName="active">
                    News
                </NavLink>

                <NavLink to="/show" activeClassName="active">
                    Show
                </NavLink>

                <NavLink to="/ask" activeClassName="active">
                    Ask
                </NavLink>

);

export default Routing;

App.js initial file
import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Routing from './containers/Routing/Routing';
import { Top, News, Show, Ask } from './containers/Routing/DynamicImport';

class App extends Component {
    render() {
        return (
            <Router>

                    <Routing />

                        <Route exact path="/" component={Top} />
                        <Route path="/top/:page" component={Top} />
                        <Route path="/news/:page" component={News} />
                        <Route path="/show/:page" component={Show} />
                        <Route path="/ask/:page" component={Ask} />

            </Router>
        );
    }
}

export default App;

When render Top page and set params in URL, params doesn't exist...
import React, { Component } from 'react';

class Top extends Component {
    constructor(props) {
        super(props);
        this.state = {
            stories: []
        };
    }
    componentWillMount() {
        console.log(this.props);

    }

    render() {
        console.log(this.props);
        return
;
    }
}

export default Top;

That console.log print this...

what's wrong?

A: Resolved. I forgot pass 'props' to...
export const Top = (props) => (
    <DynamicImport path={() => import('../../containers/Top')} />
)


text:
Q: Cancel a save from save method in django models So I have django model and I want to override save so that it only saves on certain instances. Is there a way to avoid a save from happening if a condition is met? The idea is if certain conditions defined with an if statement aren't met the instance fails to be saved. so for instance if there is not enough waiters we cancel the save, or if there is not enough tables we do the same.
Here's my code:
class Service(models.Model):
    id = models.AutoField(primary_key=True)
    arrival = models.DateTimeField(auto_now_add=True)
    exit = models.DateTimeField(null=True, blank=True)
    waiter = models.ForeignKey('Waiter', on_delete=models.CASCADE)
    table = models.ForeignKey('Table', on_delete=models.CASCADE)
    total_ammount= models.DecimalField(max_digits=15, decimal_places=2)

    def save(self, *args, **kwargs):
        if self.id == None:
            time = datetime.datetime.now()

            # check for waiters
            waiters = Waiter.objects.select_related().annotate(num_Service=Count('service', filter=Q(service__exit__gt=time))).all()
            available_waiters = waiters.filter(num_Service__lt=4)
            avalable_waiters_length = len(available_waiters)
            # check for tables
            tables = Table.objects.select_related().annotate(num_Service=Count('service', filter=Q(service__exit__gt=time))).all()
            available_tables = tables.filter(num_Service__lt=1)
            avalable_tables_length = len(available_tables)
            # return exception if a problem arises
            if avalable_tables_length == 0 and avalable_waiters_length == 0:
                print("not enough waiters or tables")
            if avalable_waiters_length == 0:
                print("not enough waiters")
                return
            if avalable_tables_length == 0:
                print("not enough tables")
                return
            # assign waiter and table
            waiter_obj = random.choice(available_waiters)
            self.waiter = waiter_obj
            table_obj = random.choice(available_tables)
            self.table = table_obj

            print(time.time())
            # check if current time is open
            if datetime.time(9,0) < time.time() and time.time()> datetime.time(21, 30):
                print("The restaurant is closed")
                return

            print(time.time())
            # add timedelta to init_time
            if time.time() < datetime.time(17,0):
                print(time + datetime.timedelta(minutes=90))
                self.exit = time + datetime.timedelta(minutes=90)
            if time.time() > datetime.time(17,0):
                self.exit = time + datetime.timedelta(minutes=120)

            #finalize pre_save
            return super(Service, self).save(*args, **kwargs)

Thank you in advance :)

A: you should raise an error, like ValidationError for example


text:
Q: Module compiled with Swift 3.1 cannot be imported in Swift 3.2.3 I have a Cocoa Touch framework file which I take out regularly from my codebase. It has some helper classes which I uses in some of my projects. It was doing good before the evolution of Xcode 9.0.
When I tried that framework in a project of Xcode 9 then it shows error that the module is compiled with Swift 3.1 so I compiled the whole classes using Swift 4 and tried to use that in a application, it still shows me the above mentioned error.
If I use the same project in Xcode 8.3.2 then it works well.

A: If the issue is in one of external libraries then their recompilation is required. For that one way is:

*

*Deintegrate all the pods first:
pod deintegrate

*Run pod install again:
pod install

Also, clean XCode Derived Data & clean up your project.


text:
Q: Rails Console Error When I open Rails console, or sandbox for that matter, and I try and add new date, in this case, a user, I keep getting this same error.  I have tried everything to get it resolved, but for the life of me I cannot figure it out.  I am using Windows, so obviously I know that is one of my first problems, but its all I have for the current moment, so I will have to make due.  Here is the error message that pops up when I try and simply enter user.new(information...)... any help would be greatly appreciated, I am pulling my hair out over here.
    C:\TTS\Rails\workspace\sample_app>rails console
    DL is deprecated, please use Fiddle
    Loading development environment (Rails 4.2.0)
    irb(main):001:0> user.new(name: "Will Wagar", email: "will@wagar.com")
    NameError: undefined local variable or method `user' for main:Object
            from (irb):1
            from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.0/lib/rails/commands/console.rb:110:in `start'
            from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.0/lib/rails/commands/console.rb:9:in `start'
            from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:68:in `console'
            from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
            from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.0/lib/rails/commands.rb:17:in `<top (required)>'
            from bin/rails:4:in `require'
            from bin/rails:4:in `<main>'

A: You almost certainly want User.new (note the capital U) rather than user.new, it's a Ruby convention that classes are capitalised.
To expand, you probably want to do it in several steps:
user = User.new(name: "Will Wagar", email: "will@wagar.com")
user.valid?
user.save
etc...

So in the first one you're creating an instance of the class User and assigning it to the variable user and then in subsequent operations, you're working with the new user variable you've created.

A: I see that now, I should have mentioned in the question that I have tried it both ways, capitalized and not.  I can get a return when I try it with a capital U, but when I try and check to see if it is valid or save it, I get the same error.
irb(main):008:0> user.valid?
NameError: undefined local variable or method user' for main:Object
        from (irb):8
        from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.0/lib/rails/commands/console.rb:110:instart'
        from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.0/lib/rails/commands/console.rb:9:in start'
        from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:68:inconsole'
        from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:39:in run_command!'
        from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/railties-4.2.0/lib/rails/commands.rb:17:in'
        from bin/rails:4:in require'
        from bin/rails:4:in'


text:
Q: Controlling(play/pause) VLC from separate application I want to control(play/pause) VLC mediaplayer from my own application. How can I achieve that?
Please note: I'm developing for windows laptop using VC++ and application as well as videos are offline(i.e. internet isn't used at all).

A: The following article on Code Project may be of use to you.
VLCWrapper - A Little C++-wrapper Around libvlc
http://www.codeproject.com/Articles/38952/VLCWrapper-A-Little-C-wrapper-Around-libvlc
Or you could just use libvlc directly. I found a LibVLC Tutorial at https://wiki.videolan.org/LibVLC_Tutorial/.
I hope this helps.


text: Q: Is it possible to use BPF as a library in your own program? It seems like the debugging tools and the way instrumetnation is done should be quite general. Is it possible to have all the benefits of safe JIT'ed code in your program for, basically, the same purpose: performance monitoring and doing hot patches / configuration changes?


text:
Q: Finding a submatrix with the maximum possible sum in O(n^2) I'm trying to write a program in Java that when given an MxN matrix it will find the (contiguous) submatrix with the biggest sum of numbers. The program then needs to return the top left corner coordinates of the submatrix and the bottom right corner coordinates. The matrix can include negative numbers and both the matrix and submatrix don't need to be square.
I saw that this was discussed here: Getting the submatrix with maximum sum? and the solution there seems to be O(n^3). A friend of mine said that they had once managed to solve this problem in O(n^2). Also suggested here. Is that possible?
Is there any available code out there that solves this problem in the most efficient way?

A: You (most likely) can't solve your problem in O(n^2), at least no such algorithm is known. The optimal solution has sub-cubic complexity, but it's very hard to implement and probably slower in practice. You can read a paper about it here.
The usual algorithm used is the O(n^3) one referenced in the question you found.

A: (S)He's a friend of yours.. so just ask him/her, and do share with us too :)


text:
Q: Disable wp-cron, and run linux cron instead in multisite environment I have a multi-site environment with domain mapping.
I tried to use these two examples to make Linux cron work instead of wp-cron:

*

*https://www.lucasrolff.com/wordpress/why-wp-cron-sucks/

*https://tigr.net/3203/2014/09/13/getting-wordpress-cron-work-in-multisite-environment/
Then, I set the cron in the cPanel and all looks great, but I started getting emails containing errors from the cron job:
PHP Warning:  include_once(/my-cont/sunrise.php) [function.include-once]: failed to open stream: No such file or directory in /home/user/public_html/wp-includes/ms-settings.php on line 18
PHP Warning:  include_once() [function.include]: Failed opening '/my-cont/sunrise.php' for inclusion (include_path='.:/usr/local/php53/pear') in /home/user/public_html/wp-includes/ms-settings.php on line 18
PHP Notice:  Undefined index: HTTP_HOST in /home/user/public_html/wp-includes/ms-settings.php on line 30

To remove the "HTTP_HOST" notice, I have added to the PHP file: $_SERVER['HTTP_HOST'] = 'mydomain.com';
my-cont is my content directory's new name. I have changed wp-config.php to reflect this:
define( 'WP_CONTENT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/my-cont' );
define( 'WP_CONTENT_URL', 'http://'.$_SERVER['HTTP_HOST'].'/my-cont');

Any ideas?

A: I also have linux cron jobs running in a WordPress multisite environment and was getting the same error of HTTP_HOST.
My cron scripts load wp-load.php to gain access to WordPress core functions. When on a single site, they work fine, switch to multisite, I received the errors.
I tried the simplest and the obvious first before committing to a full debug of the WP core.
In each of my cron script I added,
 define('DOING_CRON', true);
 if (!isset($_SERVER['HTTP_HOST'])) {
      $_SERVER['HTTP_HOST'] = 'domain.com';  // replace with primary host
 }

 // then load wordpress
 require 'wp-load.php';

This action was sufficient, and my linux cron scripts resume without further incident


text:
Q: Portable temporary files with C++ (C++ standard libraries or Boost)? Is there a portable way of creating temporary files with C++ that get automatically deleted when the program terminates (regardless of whether it crashes, gets killed, or just reaches return 0; in main().).
On Unix systems, I can open a file, delete it and then keep the still existing handle. This works with FILE *, std::fstream etc.
On Windows, this appears not to work. The only way I found is using CreateFile with the FILE_FLAG_DELETE_ON_CLOSE flag.
Is there something smarter that (1) works both on Linux and Windows, (2) has the "the file is removed on when the program terminates" behaviour as on Linux. I would be fine with #ifdef code as long as the file type that I work with is the same on both systems (e.g. std::fstream or FILE *).
I know about this solution, but this appears only to work on graceful exits and would require me to either set up central handlers and manage all temporarily opened files.
Edit: Rephrased the question to "how can I get files on Windows that are automatically removed as removed-but-still-open files in Linux.

A: http://www.cplusplus.com/reference/cstdio/tmpfile/

Creates a temporary binary file, open for update ("wb+" mode, see
  fopen for details) with a filename guaranteed to be different from any
  other existing file.
The temporary file created is automatically deleted when the stream is
  closed (fclose) or when the program terminates normally. If the
  program terminates abnormally, whether the file is deleted depends on
  the specific system and library implementation.

For abnormal termination, handle std::terminate by using: http://en.cppreference.com/w/cpp/error/set_terminate
Clean up the file with std::remove and then re-throw. I haven't tested this abornmal termination stuff yet but it should work. The temporary file creation works for sure. I've used it before.
It can be wrapped in a streambuf for usage with streams.

A: Also as a partial solution you can write a class, that deletes the file on destruction. On windows you can use MoveFileExW(filepathFull, NULL, MOVEFILE_DELAY_UNTIL_REBOOT) if that fails to have the file deleted on reboot. All of this can be hidden in the class. See for example: tmpfile.h tmpFile.cpp
Alternatively you can use something like:
struct TmpFile{
    FILE* file;
    TmpFile(std::string path){
#ifdef _WIN32
        HANDLE handle = CreateFile(path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, 0,
           OPEN_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, 0);
        if(handle == INVALID_HANDLE_VALUE) throw "Error";
        int fd = _open_osfhandle((intptr_t)h, _O_APPEND | _O_RDONLY);
        if(fd == -1){ CloseHandle(handle); throw "Error"; }
        file = _fdopen(fd, "a+");
        if(f == NULL){ _close(fd); throw "Error"; }
#else
        file = fopen(path.c_str(), "w+");
        unlink(path.c_str());
#endif
    }
    ~TmpFile(){
        fclose(file);
    }
};

Check the access modifiers and adjust to your needs (especially the error handling) This has the nice properties of RAII and will delete the file even in exception cases. However some failures where the dtor is not called will leak the handle in which case the file might not be deleted on windows.
The Win32 handling is taken from here: https://stackoverflow.com/a/7369662/1930508 Check the explanations there.


text:
Q: ArcObjects: How to remove a custom layer? How is a custom layer supposed to be destructed?
I have a custom layer that implements drawing by overriding IActiveViewEvents::AfterDraw.
The problem is that sometimes when the custom layer is removed from the Scene/Table Of Contents it is still drawn!?
The FinalRelease() method is never called in my custom layer.

*

*I would expect it to be ArcScenes responsibility to delete my custom layer when it is removed?; which in turn would call my FinalRelease() method.

*If my custom layer is not in the Scene/Table Of Contents; how comes it receives IActiveViewEvents::AfterDraw calls?
I would expect ArcScene to draw only layers in the Scene/Table Of Contents.
Here is an overview of my code:
    class ATL_NO_VTABLE MyLayer :
    public ILayer,
    public IGeoDataset,
    public IGraphicsContainer3D,
    public IActiveViewEvents,
    public IPersistVariant, ....
    {

    public:
    HRESULT FinalConstruct()
    {
        return S_OK;
    }

    void FinalRelease() // newer called!
    {
        return S_OK;
    }

    // called after layer has been removed!?
    STDMETHOD(AfterDraw)(IDisplay * Display, esriViewDrawPhase phase);

    ...
    };

    HRESULT addMyLayer() // called by user clicking a button
    {
      IMyLayerPtr myLayer(CLSID_MyLayer);
      IApplicationPtr ipApp(CLSID_AppRef);
      IDocumentPtr doc;
      ipApp->get_Document(&doc)
      if(doc)
        return S_FALSE;
      ISxDocumentPtr sxdoc;
      sxdoc = doc;
      if(!sxdoc)
        return S_FALSE;
      IScenePtr scene;
      sxdoc->get_Scene(&scene);
      if(!scene)
            return S_FALSE;
      return scene->AddLayer(myLayer, VARIANT_FALSE); // I add the layer, but who removes it?
    }

Thanks in advance for any answers!
Andreas


text:
Q: Retrieve XML from URL I am having some problems retrieving a xml from url with the following code:
    private static String getAlbumArt(String artistName, String albumName){
        try{
        XMLParser xml_parser = new XMLParser();
        String xml = xml_parser.getXmlFromUrl(getAlbumURL(artistName, albumName));
        Document doc = xml_parser.getDomElement(xml);
        NodeList N = doc.getElementsByTagName("album");
        Node node = N.item(0);
        NodeList N2 = node.getChildNodes();
        System.out.println("1------");
            for (int i = 0; i < N2.getLength(); i++) {
                Node detailNode = N2.item(i);
                if (detailNode.getNodeType() == Node.ELEMENT_NODE)
                    {
                    System.out.println("2------");
                    if (detailNode.getNodeName().equalsIgnoreCase("image"))
                    {
                        String sizeVal = ((Element) detailNode).getAttribute("size");
                        String url = detailNode.getTextContent();
                        if (sizeVal.equalsIgnoreCase("large")) {
                            return url;
                        }
                    }
                    }
        }
        }
        catch (Exception e){
        }
        return null;
    }

The xml function which i call in the above code:
public String getXmlFromUrl(String url) {
    String xml = null;
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return xml;
}

getAlbumURL:
    public static String getAlbumURL(String artist, String album){
        return URL_METHOD + METHOD_GETALBUM + AMPERSAND
                + API_KEY + AMPERSAND
                + PARAM_ARTIST + artist + AMPERSAND
                + PARAM_ALBUM + album;
    }

XMLparser:
public class XMLParser {
// constructor
public XMLParser() {
}

//Get XML from URL
public String getXmlFromUrl(String url) {
    String xml = null;
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return xml;
}

//Get dom element
public Document getDomElement(String xml){
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is);

        } catch (ParserConfigurationException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (IOException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        }

        return doc;
}

//Get nod element
 public final String getElementValue(Node elem ) {
     Node child;
     if( elem != null){
         if (elem.hasChildNodes()){
             for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                 if( child.getNodeType() == Node.TEXT_NODE  ){
                     return child.getNodeValue();
                 }
             }
         }
     }
     return "";
 }

//Get element value
 public String getValue(Element item, String str) {
     NodeList nlList = item.getElementsByTagName(str).item(0).getChildNodes();
     Node nValue = (Node) nlList.item(0);
     return nValue.getNodeValue();
    }

}
Any ideas ? I seriously don't know what is wrong.. I used this before and it worked.

A: I pulled your code and tried it out. I redid the "getAlbumURL" to return a hardcoded string. I used the address you provided in the comments, it failed. However, that xml doesn't link to any album art. So I tried the proper album name, "In%20ra*i*nbows." Worked like a dream.
So first, verify that your constants are giving you what you think they should (which you already did) and second, verify your test data. Your code appears to be fine.

A: Afte DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); add these lines before the try{} block:
dbf.setIgnoringComments(true);
dbf.setCoalescing(true);


text:
Q: Java LDAP Unix Timestamp | Why Nanotime to Java date convert use Formula: (((1970-1601) * 365) - 3 + Math.round((1970-1601)/4) ) * 86400L? Can someone please explain the ldatDatetime to date code especially :
(((1970-1601) * 365) - 3 + Math.round((1970-1601)/4) ) * 86400L;

The code available is here under which converts windows nt timeformat(ldap-accountexpires time format) to Java datetime?
long nanoseconds = 132590231990000000l; //Targeted Time
long mills = (nanoseconds/10000000);
long unix = (((1970-1601) * 365) - 3 + Math.round((1970-1601)/4) ) * 86400L;
long timeStamp = mills - unix ;
Date date = new Date(timeStamp*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); // The format of your date
sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // Give a Timezone reference for formating (see comment at the bottom

String formattedDate = sdf.format(date);
System.out.println(formattedDate);

Is this only one way to do this or other available calculations too?

A: An LDAP (or Active Directory) timestamp is the number of 100-nanosecond intervals since Jan 1, 1601 UTC. The number is usually 18 digits like yours.
java.time
I recommend that you use java.time, the modern Java date and time API. for your date and time work. While the following conversion is not shorter than yours, I find it much more readable. Let's first define some constants both for use in the conversion and for formatting afterward.
private static final Instant LDAP_EPOCH = Instant.parse("1601-01-01T00:00:00Z");
// A unit in LDAP time is 100 nanoseconds
private static final int UNITS_PER_SECOND = 10_000_000;
private static final long NANOS_PER_UNIT = Duration.ofSeconds(1).toNanos() / UNITS_PER_SECOND;

private static final DateTimeFormatter FORMATTER
        = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss zzz", Locale.US);

Now the conversion can go like this:
    long units = 132_590_231_990_000_000L; // Targeted Time
    long seoncds = units / UNITS_PER_SECOND;
    long nanos = units % UNITS_PER_SECOND * NANOS_PER_UNIT;
    Duration sinceLdapEpoch = Duration.ofSeconds(seoncds, nanos);
    ZonedDateTime dateTime = LDAP_EPOCH.plus(sinceLdapEpoch).atZone(ZoneOffset.UTC);
    String formattedDate = dateTime.format(FORMATTER);
    System.out.println(formattedDate);

Output is:

2021-02-28 21:59:59 Z

It's the same point in time as I get from your code.
Explaining your code
Since LDAP time units are 100 nanoseconds, when your code uses the variable name nanoseconds, it's wrong. First you divide by 10 000 000 (10 million), which gets you seconds, so the variable name mills is wrong too. The formula you asked about in your title, (((1970-1601) * 365) - 3 + Math.round((1970-1601)/4) ) * 86400L calculates the number of seconds from the LDAP eopch in 1601 to the Unix and Java epoch in 1970. It does this by first calculating the number of days, taking into account that one fourth of the years are leap years, and then multiplying by the number of seconds in a day in UTC, 86 400. I agree with you that it's very hard to read and understand. Subtracting this number form the seconds you had in the ill-names mills variable gives you the number of seconds since the Java epoch of January 1, 1970 at 00:00 UTC. Finally you multiply by 1000 to convert from seconds to milliseconds since this is what the constructor of the outdated Date class requires.
Links

*

*Oracle tutorial: Date Time explaining how to use java.time.

*LDAP, Active Directory & Filetime Timestamp Converter


text:
Q: CORS Fix for BabylonLoader.js in three.js To amuse myself I have been working my way through the old NeHe demos and implementing them in three.js.  You can see the progress so far here.  I have gotten to 31 which uses models.  I thought it would be fun to test out the various model loaders.  So far, I got OBJ and Collada to work but Babylon kept giving me cross-origin errors.  Basically the same error as seen in this SO post.  So I tried the same fix suggested by AJ Campbell in that post, i.e. I changed the BabylonLoader load method by adding the line loader.crossOrigin = '';  Thus:
load: function ( url, onLoad, onProgress, onError ) {

    var scope = this;

    var loader = new THREE.FileLoader( scope.manager );
    loader.crossOrigin = '';        // added by rkwright
    loader.load( url, function ( text ) {

        onLoad( scope.parse( JSON.parse( text ) ) );

    }, onProgress, onError );

},

This works perfectly, but it may not be the right solution (seems hackish).  Seems like this is a bug (missing code) in three.js?


text:
Q: replace String to number in loop I want to create a fill in the blank quizz web site.
My problem is putting a different name="" value of all inputs.
So I create a function Who change a string giving into input.
But the problem is they have all the same name (inpName1).
What I want to do is giving them a diffrent names (inpName1,inpName2,inpName3...) so I can recuperate them later into DB
var i=0;
function MyFunction() {
  var str = document.getElementById("myTextArea").value;
  var res = str.replace(/#champ/g, "<input type='text' name='inpName"+ i++ +"'>");
  document.getElementById("finalText").innerHTML = res;

}

A: Instead of inpName1, inpName2 etc use [] notation in name attribute:
<input type='text' name='inpName[]'>
<input type='text' name='inpName[]'>
<input type='text' name='inpName[]'>
<input type='text' name='inpName[]'>

In this case your values will be available on server via $_POST['inpName'] array.


text:
Q: Three JS OBJloader - obj not importing properly i'm trying to import an obj with OBJLoader but it isn't importing properly
The obj is like this -
Obj img
And it's importing this -
Obj in three js
What happens is that the whole obj isn't importing well.
What can i do about it ?
The code that i'm doing is
var objLoader = new THREE.OBJLoader();
        var mtlLoader = new THREE.MTLLoader();
            mtlLoader.setTexturePath("obj2/");
            mtlLoader.setPath(  "obj2/"  );
            mtlLoader.load( "Mules/Base_10.mtl", function( materials ) {
                materials.preload();
                objLoader.setMaterials( materials );
                objLoader.load( 'obj2/Mules/Base_10.obj', function ( object ) {

                        object.traverse( function ( child )
                        {
                            if ( child instanceof THREE.Mesh )
                            {
                                meshes.push(child);
                            }
                        });
                        var object = meshes[meshes.length-1];
                        object.position.y = -0.05;
                        object.position.x = 0;
                        object.position.z = 0;

                        object.name = "salto";
                        scene.add(object);
                    }, onProgress, onError );
            });

Thank you.

A: The problem is:
                object.traverse(...);
                var object = meshes[meshes.length-1]; //<-- you overriding the object, with the last mesh.
                object.position.y = -0.05;
                object.position.x = 0;
                object.position.z = 0;

                object.name = "salto";
                scene.add(object); //<-- than you add the object to your scene.

do not override the object. Also you don't need to traverse through the objects, as you will add the whole thing to your scene. and you do nothing with your meshes anyway :)
so try this:
                object.position.y = -0.05;
                object.position.x = 0;
                object.position.z = 0;

                object.name = "salto";
                scene.add(object);


text:
Q: I want to change Raspberry Pi code about neopixel in Python import board
import neopixel

pixels = neopixel.NeoPixel(board.D18, 144)

for i in range(0, 144):
    pixels[i] = (255, 0, 0)

I'd like to change the code above to the following format.
import RPi.GPIO as GPIO
import neopixel

GPIO.setmode(GPIO.BOARD)

pixels = neopixel.NeoPixel(blanks, 144)

for i in range(0, 144):
    pixels[i] = (255, 0, 0)

How should I change the blanks? Or how should I change the code?


text:
Q: Maintaining data with factories in angular I'm new to angular and I have the next issue. I have two jsp, the first one sets a value in a variable that I want to use on mi second view, I want to do it using factories, mi's problem is that the first view set the value correctly, but when I want to recover it on the second, it's undefined. I have researched, but I cannot find the answer can anybody help me.
That is my first view.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"    "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

    AgregaNombre
    <input id="nombre" ng-model="nombre" type="text" />
    <button id="addBtn" class="btn" ng-click="add()">Añadir</button>

{{nombreFac}}

PresentaDatos

services.js
var app = angular.module('Modulo', []);

app.factory('Factoria',function(){

var regreso = {};

return{ getSaludo : function(nombre) {
        regreso = nombre;
        alert(regreso);
        return regreso;
    },getData : function(){
        return regreso;
    }
    }
return regreso;

});

app.controller("controladorForm", ['$scope','Factoria', function($scope,Factoria){

$scope.add = function(){
    $scope.nombreFac = Factoria.getSaludo($scope.nombre);
}

$scope.get = function(){
     $scope.nombreFac = Factoria.getData();
}

}
]);

 app.controller("controladorPresenta", ['$scope','$rootScope','Factoria',     function($scope,$rootScope,Factoria){
 $scope.nombreFac = Factoria.getData();
 alert(Factoria.getData());
}
]);

mi second view
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

{{nombreFac}}


text:
Q: Cassandra multi dc setup using two separate OSE clusters We have two separate ose clusters one in cmc and another in emc.
OSE cluster - AA in CMC
OSE cluster - BB in EMC
Installed one Cassandra cluster on AA in cmc - Nodes can talk among each other in CMC cluster.
Installed second Cassandra cluster on BB in emc - Nodes can talk among each other in EMC cluster. Both Cassandra nodes from AA in CMC cannot talk to BB in EMC.
Any help will be appreciated. Thanks

A: You need to specify addresses accessible from other DCs as broadcast_address (doc) and set listen_on_broadcast to true.  Then you need to add the nodes from other DC into list of seed nodes, so they will know each other.
Don't forget about networking - if you listen on public IP, then other could access your servers - use firewall, enable SSL, etc.
P.S. Search for instructions on setting up multi-region cluster in AWS or Azure, and follow instructions (except selecting the snitch)


text:
Q: What makes Phenom II series different from the Athlon II series? Ok thats my CPU "Athlon II X2 250"
But, What would the difference If I used an Phenom one ? Is there an difference between Athlon X2 II and Phenom X2 ? II (2 "i"'s just like F4 Phantom II)

A:
What would the difference If I used a Phenom II X2 processor

Wikipedia says it best:

The Athlon II series is based on the AMD K10 architecture and derived
  from the Phenom II series. However, unlike its Phenom siblings, it
  does not contain any L3 Cache.

Athlon II
Additionally,

The Phenom II triples the shared L3 cache size from 2MB (in the
  original Phenom line) to 6MB, leading to benchmark performance gains
  as high as 30%.

Phenom II
Worth pointing out there are specific Phenom II processors, which are based on a Athlon II core,  which also do not have L3 cache although still marketed as a Phenom II.


text:
Q: is there any way to create a hidden hotspot from ubuntu? I would like to create a hidden hotspot from my Ubuntu for my phone, is there any way to do this? I want that only people who know the SSID can connect to the WiFi.

A: Yes, you can do this with this script https://github.com/Daniyal-Javani/AP-Hotspot
You can run this with downloading ap-hotspot file and do chmod 777 ap-hotspot or install with sudo apt-get install ap-hotspot Then change codes in /usr/bin/ap-hotspot with my script!

A: I needed exactly this, and didn't find a solution else where. Posting for when my future self inevitably forgets it.
NetworkManager now allows hidden SSID in AP mode.
After creating the hotspot, edit the generated connection file /etc/NetworkManager/system-connections/Hotspot.nmconnection and add hidden=true under [wifi], it should look something like
[wifi]
hidden=true
mac-address-blacklist=
mode=ap

Then reload and restart the connection:
sudo nmcli connection reload Hotspot
nmcli connection up Hotspot

A: There is no way known to create the access Point hotspot with hidden SSID. However to do Wifi hotspot without hidden SSID:
http://www.howtogeek.com/116409/how-to-turn-your-ubuntu-laptop-into-a-wireless-access-point/
With screenshots.


text:
Q: tdd steps to write junit tests for decorator pattern
Is it possible to write unit tests for below piece of functionality ?

or,

Is it possible to develop below piece of functionality using TDD ?

public ZipInputStream getZipInputStream(File zipFile) throws FileNotFoundException {
        ZipInputStream zipInputStream = new ZipInputStream(
                new FileInputStream(zipFile));
        return zipInputStream;
}

I know that this question may sounds silly, but as a newbie to TTD, i am not able to find any solution for the above :) .

A: You've asked two questions in one.

Is it possible to write unit tests for below piece of functionality?

Most people wouldn't consider a test for this functionality to be a "unit test", because it has to interact with the file system.  It's therefore more of an integration test than a unit test.  However, whether it's possible or not, it's not really a good idea.  There's nothing here worth testing.  This method doesn't have any logic of its own, so there is no gain in testing it.  All you'd be testing is the Java API.

Is it possible to develop below piece of functionality using TDD?

When using TDD, you write code that meets a clear, testable requirement.  Something this small is unlikely to have its own requirement.  The requirement that leads to this code being written is going to be something to do with processing data that's found in a zip file.  So you'll write a method that does a whole lot more than this - preceded of course by writing the test for that method.
However, the third step in the TDD process is refactor.  (Remember "red" - "green" - "refactor" - "red" - "green" - "refactor").  You might very well end up writing the method that you've quoted; not by trying to make a test work, but rather by extracting it from a larger method during the refactor step.  So the answer is yes, it is possible to develop this functionality, but most likely it would be during the "refactor" step, not during the "green" step.

A: You're basically combining 2 platform calls (new ZipInputStream() and new FileInputStream()) with no particular logic or conditionals.
It's so simple that I wouldn't even bother testing that one.
In any case, you can't possibly test drive the decorator pattern because it isn't implemented by you. The Decorator is ZipInputStream itself.

A: You could try to write a test method that receives the input stream decorating a mocked ZipFile that you will provide. Create the mock so that it returns fake ZipEntry instances that you can later verify against the ZipInputStream's getNextEntry() method.
This way you can test that the returned ZipInputStream is really decorating the provided ZipFile (I would suggest a name such as testReturnedZipInputStreamDecoratesProvidedZipFile() or something along those lines...).


text:
Q: passing hash and array to function problem I am trying to pass ConnectODBC(%settings , @connectionString); hash abd then array
In the function I load then like my (%settings , @connectionString) = @_;
for hash i get the right values but for print $connectionString[0] . ".\n";
I get Use of uninitialized value $conection[0] in concatenation (.)
Any idea why ?

A: Since you are assigning to a list/hash, the first argument absorbs it all.
my %h1 = ( key => value );
my @a1 = (1, 2 );
my ( @a2, %h2 ) = ( @a1, %h1 );
# @a2 now contains (1,2,key,value) and %h2 is undefined.

To obtain what you want, you should pass references instead.
ConnectODBC( \%settings , \@connectionString);
sub ConnectODBC {
    my ( $setting_ref, $connection_ref ) = @_;
    my %settings = %$setting_ref;
    my @connectionString = @$connection_ref;
}

I should note that making hashes and arrays out of the references in the subroutine probably is unnecessary. You can access the settings directly from the reference. $setting_ref->{key} is the same as $settings{key}.


text:
Q: MongoDB ReplicaSet on windows azure - Sockect exception error I have 3 node replica set deployed in windows azure. While doing performance testing, the test code halts after sometime. In the server I can see the following error log -
Fri Aug 30 23:14:59.982 [conn2454] SocketException handling request, closing client connection: 9001 socket exception [SEND_ERROR] server [ip:port]
For the performance test I am using multithreaded code to only read data from the replicaset.
So far I have tried http://docs.mongodb.org/manual/faq/diagnostics/#does-tcp-keepalive-time-affect-sharded-clusters-and-replica-sets. But it did not help so far.
Any thoughts/suggestions will be welcomed.
Thanks

A: This is old, but just in case someone else stumbles across this.
You need to set the TCP/IP keep alive times different from the stock Linux configuration if you are running under Azure:
echo 45 > /proc/sys/net/ipv4/tcp_keepalive_time
echo 30 >  /proc/sys/net/ipv4/tcp_keepalive_intvl
echo 20 >  /proc/sys/net/ipv4/tcp_keepalive_probes


text:
Q: C++ errors when using ios_base and ofstream void DataSaver::save( const std::vector<long>& vec )
{
    using std::ios_base;
    std::ofstream file;
    file.open( "/home/david/Desktop/test", ios_base::out | ios_base::binary );
    for(int i = 0; i < vec.size(); i++)
        file << vec.at( i ) << "\00\01\10\00";
    file.close();
}

This causes a few errors :

g++ main.cpp datasaver.cpp
  datasaver.cpp: In member function 'void DataSaver::save(const std::vector&)':
  datasaver.cpp:11:16: error: aggregate 'std::ofstream file' has incomplete type and cannot be defined
  datasaver.cpp:12:41: error: incomplete type 'std::ios_base' used in nested name specifier
  datasaver.cpp:12:57: error: incomplete type 'std::ios_base' used in nested name specifier

I included iostream , ofstream and vector
Can someone explain whats wrong?

A: You probably need
#include <fstream>

as file streams are actually defined in it


text:
Q: how to ease in js popup modal trying to ease in a popup modal using js, i have my code below but unsure where to add the transition style, i've looked in the css and there's no luck so im assuming its to do with the js of it.
My code is below.
// Get the modal
var modal = document.getElementById('loginModal');

// Get the button that opens the modal
var btn = document.getElementById("login");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
    modal.style.fadeIn(3000);
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none".fadeIn(3000);
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

A: use jQuery:
window.onclick = function(event) {
 if (event.target == modal) {
  $("#loginModal").fadeOut(3000)
 }
}

3000 stands for the amount of miliseconds you want the transition to be.
Check this link for further infos about fade in and fade out:
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_fadeout_fadein


text:
Q: Context meaning of a passage
Whether the languages of the ancient American peoples were used for
  expressing abstract universal concepts can be clearly answered in the
  case of Nahuatl. Nahuatl, like Greek and German, is a language that
  allows the formation of extensive compounds. By the combination of
  radicals or semantic elements, single compound words can express
  complex conceptual relations, often of an abstract universal
  character.
       The tlamatinime ("those who know") were able to use this rich stock of abstract terms to express the nuances of their thought. They
  also availed themselves of other forms of expression with metaphorical
  meaning, some probably original, some derived from Toltec coinages. Of
  these forms the most characteristic in Nahuatl is the juxtaposition of
  two words that, because they are synonyms, associated terms, or even
  contraries, complement each other to evoke one single idea. Used as
  metaphor, the juxtaposed terms connote specific or essential traits of
  the being they refer to, introducing a mode of poetry as an almost
  habitual form of expression.

I have answer the question  from the passage:
A main purpose of the passage is to

*

*delineate the function of the tlamatinime in Nahuatl society

*explain the abstract philosophy of the Nahuatl thinkers

*describe some conceptual and aesthetic resources of the Nahuatl
language

*argue against a theory of poetic expression by citing evidence about
the Nahuatl

*explore the rich metaphorical heritage the Nahuatl received from the
Toltecs

I couldn't paraphrase the passage so Sound perplexing to get the answer.
Can someone explain please.
The answer is given (3) but my guess was (2). Is there any easy trick to get the answer easily?

A: The passage is primarily about language, which is why (3) is the correct answer.
The paragraph is talking about how the Nahuatl language forms compound words (like German does) and how it combines other words to form rich metaphors. More importantly, just about every sentence is talking about language in one way or another:

Whether the languages of the ancient American peoples were used for expressing abstract universal concepts can be clearly answered in the case of Nahuatl. Nahuatl is a language that, like Greek and German, allows the formation of extensive compounds. By the combination of radicals or semantic elements, single compound words can express complex conceptual relations, often of an abstract universal character. The tlamatinime ("those who know") were able to use this rich stock of abstract terms to express the nuances of their thought. They also availed themselves of other forms of expression with metaphorical meaning, some probably original, some derived from Toltec coinages. Of these forms the most characteristic in Nahuatl is the juxtaposition of two words that, because they are synonyms, associated terms, or even contraries, complement each other to evoke one single idea. Used as metaphor, the juxtaposed terms connote specific or essential traits of the being they refer to, introducing a mode of poetry as an almost habitual form of expression.

Test questions like this one ask about the main purpose of the passage. To prevent the test from being too easy, test questions will often include tangential purposes as well. For example, in this question, language is indeed used to express complex thoughts, which might lead some to choose (2). Also, Nahuatl did get some ideas about metaphors from the Toltecs, so (5) is true as well – but it's not the main point of the passage.


text:
Q: Laravel 5 determine if current user has permission to update a post I am following jeffreys laravel fundamental series and I'm stuck at some point.
How can I ensure that the current user can only edit/update his own article?
I have the feeling that I have to focus on my ArticleRequest class, but no idea what to tell laravel to do inside authorize().
My ArticlesController:
<?php
namespace App\Http\Controllers;

use App\Article;
use Carbon\Carbon;
use App\Http\Requests\ArticleRequest;
use App\Http\Requests;
use Illuminate\Http\Request;
use Auth;

class ArticlesController extends Controller
{

public function __construct() {
  $this->middleware('auth');
}

public function index() {

  $articles = Article::latest('published_at')->published()->get();
  return view('articles.index')->withArticles($articles);
}

public function show($id) {

  $article = Article::findOrFail($id);
  //dd($article->created_at->diffForHumans());
  return view('articles.show')->withArticle($article);
}

public function create() {

  return view('articles.create');
}

public function store(ArticleRequest $request) {

  //Create new article witj the attributes from the form
  $article = new Article($request->all());
  //Get the authenticated users articles and save a new one (with passed trough $article object)
  Auth::user()->articles()->save($article);

  return redirect('articles');
}

public function edit($id) {

  $article = Article::findOrFail($id);
  return view('articles.edit')->withArticle($article);
}

public function update($id, ArticleRequest $request) {

  $article = Article::findOrFail($id);
  $article->update($request->all());
  return redirect('articles');

 }
}

ArticleRequest:
<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class ArticleRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {

        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {

        return [
            'title' => 'required',
            'body' => 'required',
            'published_at' => 'required|date'
        ];
    }
}

My ArticlesTabel Schema:
Schema::create('articles', function (Blueprint $table) {
          $table->increments('id');
          $table->integer('user_id')->unsigned();
          $table->string('title');
          $table->text('body');
          $table->timestamp('created_at');
          $table->timestamp('published_at');

          $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');

      });

A: I can give you advice,
In my most projects i use Entrust Laravel.
Here is link : Entrust Laravel
You can install easily with composer :
composer require zizaco/entrust:5.2.x-dev

Version depend on laravel framework version you are using.
if you will go through documentation you can see this :
class Permission extends EntrustPermission
{
}

Create this class in App directory.
After this you will have blade code :
@permission('manage-admins')

This is visible to users with the given permissions. Gets translated to
    \Entrust::can('manage-admins'). The @can directive is already taken by core
    laravel authorization package, hence the @permission directive instead.

@endpermission

Easy but you have to go through documentation.
Let me know if anything else.

A: For adding roles and permissions you can use github package zizaco/entrust.
click here
check how to add roles and permissions.check all answers which was given by me in below link.
click on link for example


text:
Q: Python - Create a dict from a txt file We are given a file (.txt) in the form:
Johnson, Joana
Volleyball Club
Erickson, John
Mcdonald, Joe

Smith, Johnny
Debate Club
Chess Club
McIlroy, Molly
Dino, Dennis

Jackson, Jamie
Gibson, Ginny
Fried, John

I have to write a function which calls this file and returns a dictionary in the form: {'first person's name' : [list of friends within each stanza] so this should be returned:
{'Johnson, Joana': ['Erickson, John', 'Mcdonald, Joe'], 'Smith, Johnny': ['McIlroy, Molly', 'Dino, Dennis'], 'Jackson, Jamie': ['Gibson, Ginny', 'Fried, John']}
I wrote a function below but it only processes the first stanza of the file instead of all of it, so it returns:
{'Johnson, Joana': ['Erickson, John', 'Mcdonald, Joe']}
I am only a beginner in python so if someone can help me without complicating it I would really appreciate it, I cannot seem to process the whole file
def name_to_friends(file):

    '''(file open for reading) -> dict of {str: list of str}
    '''

    for line in file:
        dic = {}
        lst = []
        for line in file:
            if line == '\n':
                dic.update({lst[0]:lst[1:]})
                break
            else:
                name = line.strip()
                if ',' in line:
                    lst.append(line)
    return dic

A: You're almost there; remove the break; and clear the list object each time you add another name and friends to your dictionary:
def name_to_friends(file):
    for line in file:
        dic = {}
        lst = []
        for line in file:
            if line == '\n':
                dic.update({lst[0]:lst[1:]})
                lst = []
            else:
                name = line.strip()
                if ',' in line:
                    lst.append(line)

        if lst:
            dic.update({lst[0]:lst[1:]})

    return dic

The last if lst is needed for when there is no empty line at the end of the file.
Your break statement would stop reading the file altogether the first time you encountered an empty line; by removing it you get to continue to the next block.
A more idiomatic method would be:
def name_to_friends(file):
    dic = {}

    for line in file:
        line = line.strip()
        # skip empty lines until we find the start of a block
        if not line:
            continue

        friends = dic[line] = []
        for line in file:
            line = line.strip()
            if not line:
                break  # end of block, continue to the next list of friends
            if ',' in line:
                friends.append(line)

    return dic

This nests a second loop over the file lines inside the first; this advances the file line reading position too, so when the inner loop stops (because the file is done or we just read an empty line), the outer loop will continue reading where we left off.

A: if the file is not too large you could simply do something like
{k[0]: k[1:] for k in [l.split('\n') for l in file.read().split('\n\n')]}

Edit: to remove clubs (no comma) you could
{k[0]: [fr for fr in k[1:] if ',' in fr] for k in [ln.split('\n') for ln in file.read().split('\n\n')]}


text:
Q: Is there a possibility to delete a string that starts with a ">" and ends with a newline in postgresql via sql update statement? Lets say I have a database with about 50k entries in a column called content.
This column contains strings which causes problems to my further work.
Now here is the thing I need to do it for all the rows inside of that table.
Any Ideas?
Here an example:
'user wrote:
-----------------------------------------------------
> Some text
> that vary too much and I dont need it actually
> here is end of the text
The text I actually need.'

I would like to remove all of the unnecessary part so the only thing that is left is in this case :
'The text I actually need.'

A: This should delete all lines that start with a >:
regexp_replace(textcol, E'^>.*\n', '', 'gn');

The g flag is needed to delete all such lines, and the n flag makes the ^ match the position right after each line break.
I use an "extended" string literal (the leading E) so that I can write a newline as \n.


text:
Q: Qual melhor pratica para resolver o problema com o git? Seguinte, o cenário é: No meu trabalho tem um projeto com apenas uma branch a master. Tiveram commits que quebraram a versão que estava em produção. Então, quando eu peguei o projeto, precisei clonar o projeto em um commit especifico. Assim o fiz, clonei em um commit especifico, adicionei novas funcionalidades. Tenho algumas dúvidas, por exemplo:

*

*Como faço para subir a minha versão sem dar conflito? Eu pensei em criar uma nova branch mas perderia o historico, gostaria apenas de remover todos esses commits que quebraram a aplicação e voltar para a versão que eu baixei, para que eu consiga commitar.

*Tevo ter duas branches? Tipo uma master e uma para desenvolvimento?

*O que mais posso fazer?

A: Não existe uma melhor pratica que se aplique em todos os casos. O problema que você está enfrentando é a falta de branchs. Eu, por exemplo, trabalho da seguinte forma:

*

*Uma branch com o código que vai para produção, chamada master

*Uma para o homologação, chamada staging

*Uma nova branch a cada funcionalidade

Assim quando existe uma nova funcionalidade o processo fica assim:

*

*Criar uma branch à partir da master, exemplo cadastro-de-usuarios

*Depois de pronto para testes, fazer merge da cadastro-de-usuarios com a staging

*Depois de homologado, fazer merge da cadastro-de-usuarios com a master
Se esse histórico é importante para vocês é possivel criar uma nova branch que contenha ele e depois fazer um reset na master para o ultimo commit sem erros.
Exemplo de comandos para criar um backup da master e reseta-la:
git checkout master
git checkout -b backup-master
git checkout master
git reset --hard HASH_DO_COMMIT_CORRETO
git push origin --force

Existem formas mais sofisticadas de organizar suas branchs, recomendo seguir o  mais simples para você e sua equipe. Também recomendo esse artigo sobre o git flow: Git Flow
Há outra técnica chamada feature toggles, eu ainda não usei, mas é interessante: Feature Toggles vs Feature Branches


text: Q: real roots, no complex roots, Does anyone know a material or even proof of Does anyone know a material or even proof of the theorem that says every polynomial of degree n has no more than n REAL roots(real roots, no complex roots)?


text:
Q: Return timezone aware postgres fields as a string I'd like to use the create_engine parameters to get my timezone aware data out (in python), not as a datetime.datetime, but as a string representation of the UTC time it stores.
Specifically, I have:
engine = create_engine(DB_URI,
                       convert_unicode=True,
                       json_serializer=json.dumps)

conn = engine.connect()
res = find_all(conn, myquery)

But my dates come back like this:
datetime.datetime(2020, 4, 14, 7, 30, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)

While I expect it to look more like:
2020-04-14 07:30Z

What can I change so that sqlalchemy will retrieve these values as text timestamps?
I expected the following to work as well:
PGTZ = psycopg2.extensions.new_type(
    psycopg2.extensions.DATEARRAY.values,
    'PGTZ',
    lambda value, curs: value.isoformat() if value is not None else None)

psycopg2.extensions.register_type(PGTZ)

But this had no effect.
I've consulted other references:

*

*Timezone aware datetime to string? This doesn't help because it converts after query time, which is not what I'm looking for

*https://access.crunchydata.com/documentation/psycopg2/2.7.5/extras.html#psycopg2.extras.register_tstz_w_secs This is promising

*https://www.postgresql.org/message-id/20130801121119.GA10036%40llserver.lakeliving.com This is about storage, not about retrieval

*https://stackoverflow.com/a/43121970/1052117 This is close, but is about flask

*https://docs.sqlalchemy.org/en/13/dialects/postgresql.html#sqlalchemy.dialects.postgresql.JSON this is close but serializes json in particular.

A: Try the cast() or type_coerce() functions?
The cast() function will use an explicit type conversion in the database, while the type_coerce() will only treat it as that type on retrieval into Python.


text:
Q: Swift pod in objective-C project my pod looks like this
platform :ios, '8.1'

pod 'Masonry'
pod 'Parse'
pod 'SSKeychain'
pod 'Reachability'

When I add 'pod Charts', I get error like this
[!] Pods written in Swift can only be integrated as frameworks; this feature is still in beta. Add `use_frameworks!` to your Podfile or target to opt into using it. The Swift Pod being used is: Charts

If I update podfile to this:
platform :ios, '8.1'
use_frameworks!

pod 'Masonry'
pod 'Parse'
pod 'SSKeychain'
pod 'Reachability'
pod 'Charts'

It messes up project and SSKeychain shows nonsense errors like duplicate interface and enums definitions.
Should I do something more to support Swift pod framework? Or I have to update project to remove somehow those open source files (SSKeychain and so on)?

A: Maybe you should remove the cache for a given pod, or clear the cache completely. Please do it according to pod cache clean

pod cache clean [NAME]
Remove the cache for a given pod, or clear the
  cache completely.
If there is multiple cache for various versions of the requested pod,
  you will be asked which one to clean. Use --all to clean them all.
If you dont give a podNAME, you need to specify the --all flag (this
  is to avoid cleaning all the cache by mistake).
Options:
--all
Remove all the cached pods without asking.
Inherited options:
--silent
Show nothing.
--verbose
Show more debugging information.
--no-ansi
Show output without ANSI codes.
--help
Show help banner of specified command.

Hope it helps to you.


text:
Q: What is the difference between creating an image from a disk and creating an image from a snapshot in GCP? In Google Cloud Platform, what is the difference between creating an image from a disk and taking a snapshot of the disk and then creating the image from the snapshot?

A: It's the same thing, you create an image. The image from disk is the immediate copy of active data. Image from snapshot can refer older data, depending on the age of the snapshot.
So, if you create a snapshot and immediately create an image on the snapshot (and you don't care to keep a snapshot ), the snapshot step is useless. It's only a question of temporality.


text:
Q: Call same queuetrigger function for multiple queues in parallel I  am creating multiple queues dynamically like workbook1, workbook2...workbook100.
I have written one queuetrigger function which needs to be trigger for all the queues created dynamically once any message arrive
I want to trigger same trigger function in parallel whenever there is message in multiple queues.

A: There is not a method to implement your requirements directly. Because you can only bind one trigger to the same function:https://learn.microsoft.com/en-us/azure/azure-functions/functions-triggers-bindings#overview
However, you can copy the same function with different triggers even it's an unwise way. Or you could try the Precompiled functions referred to the answer.
If you still have questions , please let me know.


text:
Q: How to dynamically generate a Java Bean class using plain Java? I went through some of the samples that have used libraries to generate bean classes from JSON, XML etc. What I would like to know is, whether there's a way to dynamically generate a java bean class, with the parameters I give?
For example if I give an array of Strings as arguments which would represent the properties of the Pojo class for now, how can I generate the POJO?
Arguments: {"field1", "field2", "field3"}
Generate POJO would be:
public class TestBean {
    private String field1;

    TestBean() {
    }

    public String getField1() {
      return field1;
    }

    public void setField1(String field1) {
      this.field1 = field1;
    }
}

It should be the same for field2 and field3 as well.
Here I'm assuming that all the properties above are String and the class name is constant for now. Is there any way I can achieve this? Thanks in advance.

A: The problem with generating an actual Java class at runtime is that there is no way you can access it using standard Java syntax as the compiler doesn't know about it.
In practice therefore, most people just use a map in this circumstance. The only case I can think where you would need to generate a real class is where there is some other code you can't change that requires a Java object and inspects it dynamically using reflection or otherwise.
If you don't need this you are better off using a map, or possibly some utility class designed to emulate a Java Bean.
The Apache BeanUtils package provides the DynaBean interface to implement dynamic Java Beans. That said, the classes are only recognised as beans if accessed from the rest of the BeanUtils package.
There are several subclasses depending on what you want, for example, LazyDynaBean:
DynaBean myBean = new LazyDynaBean();
myBean.set("myProperty", "myValue");


text:
Q: HLS stream with jwplayer using requirejs I would like to use JWPlayer loading by RequireJS to play HLS streams. But I have a problem with it.
All the single files are working for me ( for example .mp4 files ) except the streams.
I've created a plunker example, in the playlist there is an .mp4 file and a test stream from the jwplayer's site and the stream doesn't work.
Please help me, because if the JWPlayer can not work with RequireJS we will not buy the official licence :(


text:
Q: Looking an efficient way to reuse a set of widgets or an alternative Here's what i have at the moment:

This is created with quite a bit of code for just 1 widget:
date_label = tk.Label(date_entry_frame, text="Enter creation timestamp: ")
date_label.pack(side=tk.TOP)
label_0 = tk.Label(date_entry_frame, text='DD/MM/YY:')
label_0.pack(side=tk.LEFT)
entry_1 = tk.Entry(date_entry_frame, width=2, borderwidth=1)
label_1 = tk.Label(date_entry_frame, text='/', borderwidth=0)
entry_2 = tk.Entry(date_entry_frame, width=2, borderwidth=1)
label_2 = tk.Label(date_entry_frame, text='/', borderwidth=0)
entry_3 = tk.Entry(date_entry_frame, width=4, borderwidth=1)
# time entries and labels
label_3 = tk.Label(date_entry_frame, text='HH:MM', borderwidth=0)
entry_4 = tk.Entry(date_entry_frame, width=2, borderwidth=1)
label_4 = tk.Label(date_entry_frame, text=':', borderwidth=0)
entry_5 = tk.Entry(date_entry_frame, width=2, borderwidth=1)

# space management
entry_1.pack(side=tk.LEFT)
label_1.pack(side=tk.LEFT)
entry_2.pack(side=tk.LEFT)
label_2.pack(side=tk.LEFT)
entry_3.pack(side=tk.LEFT)
label_3.pack(side=tk.LEFT)
entry_4.pack(side=tk.LEFT)
label_4.pack(side=tk.LEFT)
entry_5.pack(side=tk.LEFT)

Is there some alternatives to this? Or a way to reuse this without copy-pasting the large block of code?
I have tried using classes but i couldn't figure out how to use the manage space with classes.

A: The answer is no different with tkinter than with any large block of code in any language: move the code into a function or into a class.
Arguably the best solution is to move it to a class which inherits from the Frame widget. That allows you to treat instances of the class like first class widgets (eg: you can call pack, place, grid, and destroy on them).
For example, you want to be able to use the class like this:
start = DateTimeEntry(root, "Enter start time", 1, 1, 2019, 0, 0)
end = DateTimeEntry(root, "Enter end time", 31, 12, 2019, 0, 0)

start.pack(side="top", fill="x")
end.pack(side="top", fill="x")

The class might look something like this:
class DateTimeEntry(tk.Frame):
    def __init__(self, master, label, day=1, month=1, year=2000, hour=0, minute=0):
        super().__init__(master)

        date_label = tk.Label(self, text=label)
        label_0 = tk.Label(self, text='DD/MM/YY:')
        label_1 = tk.Label(self, text='/', borderwidth=0)
        label_2 = tk.Label(self, text='/', borderwidth=0)
        label_3 = tk.Label(self, text='HH:MM', borderwidth=0)
        label_4 = tk.Label(self, text=':', borderwidth=0)

        self.entry_day = tk.Entry(self, width=2, borderwidth=1)
        self.entry_month = tk.Entry(self, width=2, borderwidth=1)
        self.entry_year = tk.Entry(self, width=4, borderwidth=1)
        self.entry_hour = tk.Entry(self, width=2, borderwidth=1)
        self.entry_minute = tk.Entry(self, width=2, borderwidth=1)

        date_label.pack(side=tk.TOP, fill="x")
        label_0.pack(side=tk.LEFT)
        self.entry_day.pack(side=tk.LEFT)
        label_1.pack(side=tk.LEFT)
        self.entry_month.pack(side=tk.LEFT)
        label_2.pack(side=tk.LEFT)
        self.entry_year.pack(side=tk.LEFT)
        label_3.pack(side=tk.LEFT)
        self.entry_hour.pack(side=tk.LEFT)
        label_4.pack(side=tk.LEFT)
        self.entry_minute.pack(side=tk.LEFT)

        self.set(day, month, year, hour, minute)

    def get(self):
        return (
            (self.entry_day.get(), self.entry_month.get(), self.entry_year.get()),
            (self.entry_hour.get(), self.entry_minute.get())
        )

    def reset(self):
        self.entry_day.delete(0, "end")
        self.entry_month.delete(0, "end")
        self.entry_year.delete(0, "end")
        self.entry_hour.delete(0, "end")
        self.entry_minute.delete(0, "end")

    def set(self, day, month, year, hour, minute):
        self.reset()
        self.entry_day.insert(0, day)
        self.entry_month.insert(0, month)
        self.entry_year.insert(0, year)
        self.entry_hour.insert(0, hour)
        self.entry_minute.insert(0, minute)


text:
Q: Store MS Access Report into SQL Server I am using MS Access, Excel and Power BI to generate reports from different sources. The final report after ETL, Merging, Filtering, working on it is exported in .CSV and .XLSX format into a specific folder in the computer (we save all in windows 2016 server folder).
At the same time, I have created SQL Server tables to store those data (only table and columns, but not storing any data yet)
Is there any way to automatically upload and store data in the SQL Server table each time the new report is generated? I need to keep the daily/weekly report for historical purposes in a single table.
Probably I need to use some ETL automation tool? Python Scripts?

A: This process does not make sense?
You don't save the results of a report. A report is based on a query against the database. So, for the report, you simply execute a query with the date range or criteria.
That way, you might run the report today 1 time, or 10 time. Each time you run this report, it is hitting the database and pulling the data. The results will not change if you run the report for today's data 1 time, or 10 times. And if in 3 months from now you run the report with todays date range, then it should produce the same report.
This idea that in any "sensible" data system, that you attempt to save the results of the report makes no sense at all. You could I suppose generate the report and save it as a PDF, but for what possible reason would you not be able at any time you please to simply re-run the report with the SAME criteria you had before, and thus re-create the report any time you please?
You seem to be taking some kind of spreadsheet approach. You enter data into Excel, and then print it out. So, now you saving a whole copy of the spreadsheet everyday, and that data over time has nothing to do with the pervious data.
This Excel kind of approach is not how a database system works, nor is it how any system with reporting abilities is going to work with any success here.
You can save/put"summary" data into that final database from Access. At that point then you could/should be able to now generate your report as you please in Access (the data will come from that sql server final resting place.
So, the goal and idea here is to generate a report against that final data set.
So, perhaps your question is how can I send some summary data from Access into that final database? Of which then I am free to run reports over and over at will and anytime one pleases. The idea that a report can ONLY be run one time, and that is it? How is that going to work in any production system?
So, you need to send  the data FIRST to the final database. (and if this is summary data that you generate with a bunch of code and processing - then fine).
Once you  send that data (perhaps summary data) to the final database? Well then of course you should be able to run reports "on demand" at any time you please.
It should not matter if you run the report 1 time or 20 times, or in a month run that report 3 more times. That report will have some type of criteria to restrict the data that flows into that report. And it should not matter the number of times and when you re-run tat report in the future - the results should be the same.
If you are asking can you easy send data from Access to SQL server? Sure, but that sending of data certainly can't be attached to WHEN you run a report 1 time, or 10 times. How could people on a mutli-user system run reports at the same time, or even re-run reports?
So, the process of sending that summary data, or new data to sql server has to be separated from the process(s) that allow you to run reports against your final database system.
You can easily run reports in Access that pulls data from the final resting place (SQL server I assume?). But the process of sending that data to sql server needs to be separated from the "event" of running such reports, else you have a VERY difficult time making this system work. What would occur if you need or want or it just so happens that someone re-runs a report? You can't have the reports sending the data to the SQL database. The ETL process has to be separated out from that report generating event.
If your process creates the the summary data (say into some local Access tables), you can then simply use append query(s) from access to linked table(s) that you have in the sql database. So, after your ETL process, you run some append queries in Access that takes the local data and sends it to SQL server.


text:
Q: Concatenating columns' string values depending on the condition in Pandas I am concatenating three columns' values that are all formatted as str to be able to get the full address. The first one is the unit number, and some properties do not have a unit number, so I would like to not concatenate the unit number value for those where it's missing. How do I add the if statement?
df['address_original'] = df['unit_number'].str.cat(df[['street_number', 'street_name']],
                                                   sep=', ')
print df['address_original'][:5]

0                 , 184, VEALE ROAD
1                 , 124, VEALE ROAD
2    , 1068, CLEARWATER VALLEY ROAD
3               , 1605, PINE STREET
4         , 1425, LOPEZ CREEK DRIVE
Name: address_original, dtype: object

Here's the original dataframe:
import pandas as pd
df = pd.DataFrame(data=search_results1)
print df.info()
print type(df)

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2619 entries, 0 to 2618
Columns: 111 entries, access to zoning
dtypes: object(111)
memory usage: 2.2+ MB
None

Here's currently what's in address_original column
print df['address_original'][:3]
0                 , 184, VEALE ROAD
1                 , 124, VEALE ROAD
2    , 1068, CLEARWATER VALLEY ROAD
Name: address_original, dtype: object

A: Is it then?
df['address_original'] = np.where(df['unit_number'].isnull(), df['street_number'].astype(str)+','+df['street_name'].astype(str), df['unit_Number'].astype(str)+','+df['street_number'].astype(str)+','+df['street_name'].astype(str))

I am still not sure how your target column should look like

A: Try this, may this helps you
import numpy as np
import pandas as pd

data = pd.read_csv('c.csv')
print(data)

def GetFullAddress(unitno, add1, add2):
    print(unitno, add1, add2)
    sunitno = ''
    if(unitno>0):
        sunitno = str(unitno)+', '

    return sunitno + add1 + ', '+add2

data['address'] = data.apply(lambda row: GetFullAddress(row['unitno'],row['add1'],row['add2']))
print(data)

Used data is:
   unitno         add1         add2
0       0  'address11'  'address21'
1      12  'address12'  'address22'
2       0  'address13'  'address23'
3      14  'address14'  'address24'
4       0  'address15'  'address25'


text:
Q: Rationale for difference in "default" access-specifier for a base class I know that there're few differences between struct and class in C++. I also understand the reason(s) for few of the difference(s). Like this one,

*

*Members of struct are public by
default; members of class are
private by default. The reason why members of struct are public by default, is to make C++-struct compatible with C-struct.  And the reason why member of class are private by default, is to introduce the concept of data encapsulation (i.e enforcing object-oriented principles/techniques/etc).

What I don't understand is this, quoting the Standard $11.2/2 [class.access.base]

In absence of an access-specifier for
  a base class, public is assumed when
  the derived class is declared struct
  and private is assumed when the class
  is declared class.

What is the rationale for this twist and anti-uniformity? Why is this difference needed?
Example from the Standard,
class B {  };
class D1 : private B {  };
class D2 : public B { };
class D3 : B { };         //B private by default
struct D4 : public B { };
struct D5 : private B { };
struct D6 : B { };        //B public by default
class D7 : protected B { };
struct D8 : protected B { };

Here B is a public base of D2, D4, and
  D6, a private base of D1, D3, and D5,
  and a protected base of D7 and D8.

EDIT
Some of you might say, this difference makes sense given the default access for struct and class being different (the difference given in the bullet-point above). But I think, inherited-struct altogether is incompatible with C-struct (which doesn't support inheritance), no matter how you derive it. I may be wrong though. That is why I'm seeking good explanations, possibly with examples! :-)

A: I'm not sure why you think it's a twist, you have consistency with member sub-objects and base class sub-objects. They are both public for classes declared with struct and private for classes declared with class. Simple and easy to remember.

A: Doesn't this make sense given the default access for struct and class being different? (as in your first bullet point)
If you inherit from a struct (which by default is public) then without specifying an access modifier, you are implying public inheritenance whereas If you inherit from a class (which by default is private) then without specifying an access modifier, you are implying private inheritenance.
Did I miss something in your question?


text:
Q: Container where each item can have multiple non-unique keys (c++17) Image I have this enum class:
enum class MyEnum {
    enum1,
    enum2,
    enum3
}

And I have a struct/class called MyClass...
Each MyClass object is associated with one or more MyEnum value.
I am wanting a container that will hold MyClass objects, and be able to return a list of all MyClass objects that are associated with a specific MyEnum value when requested. Something a bit like:
class Container<std::vector<MyEnum> key, MyClass item> {
public:

    std::vector<MyClass> getMyClassItemListByMyEnumKey(MyEnum enum) {
        return /*code to gather all MyClass items that have the searched MyEnum enum*/;
    }
};

I can think of a few ways to do this with questionable efficiency and scalability... But does anyone know of a pre-existing solution to this problem? This problem will absolutely not grow outside of what I have posted, there will be no future expansions that I should consider.
I am using c++17 and have no problem with 3rd party libraries as long as they've not got restrictive licenses.

A: Simply transcribing your requirements into a container: you want to go from an Enum to a bunch of MyClass objects:
map<Enum, vector<MyClass>>

Though that's not quite right, since you really want to potentially share MyClass objects amongst multiple keys. So:
map<Enum, vector<shared_ptr<MyClass>>>

This'll get the job done, but you might have questions about performance. If your Enum values are all [0, n-1), and performance becomes an issue, it might be worth simply wrapping a vector:
class CustomMap {
    std::vector<shared_ptr<MyClass>> elems;

public:
    CustomMap() {
        elems.resize(n);
    }

    std::vector<shared_ptr<MyClass>>& operator[](Enum e) {
        return elems[static_cast<std::underlying_type_t<Enum>>(e)];
    }

    // etc.
};

And then of course, shared_ptr really isn't right for the job either - you probably want to have a vector<MyClass*> such that the CustomMap separately manages them, etc. There's a lot more rabbit holes you can go down, depending on where you want to go.