Q: Use SnapHelper to Scroll to a Child view in a recyclerview item In my recyclerview onCreateViewholder method I create a dynamic which would have unspecified number of text views inside a linear layout
 if (sessionManager.getBookScrolOrientation() == AppConstents.HORIZONTAL) {
        LinearLayout linearLayout = new LinearLayout(context);
        ViewGroup.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT , ViewGroup.LayoutParams.MATCH_PARENT);
        linearLayout.setLayoutParams(layoutParams);
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);

        Spannable spannable = getVerseSpanableHorizontal(pidreference.get(position) , cidreference.get(position));

        Pagination pagination =  new Pagination(spannable,
                pageWidth,
                pageHight,
                textPaint,
               lineSpacingMultiplier,
               lineSpacingExtra,
                isTextPaddingIncluded);

        List<CharSequence> list = pagination.getPages();

        for (CharSequence charSequence : list){
            TextView tv = new TextView(linearLayout.getContext());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Tools.getScreenWidth() , ViewGroup.LayoutParams.MATCH_PARENT);
            tv.setLayoutParams(params);
            tv.setText(charSequence);

            linearLayout.addView(tv);
        }

        MainViewHolder viewHolder = new MainViewHolder(linearLayout);

        return viewHolder;

    }

When i use SnapHelper with this recyclerview it scrolls to the center of linear layout not the next textview. How can i make it scroll to the next textview inside the linearlayout?

A: If I understand correctly, the problem is that SnapHelper snaps the center of the current view to the center of the recycler. As the docs say:

The implementation will snap the center of the target child view to the center of the attached RecyclerView.

If you want the the current view to snap to the start of the recycler use a libraray such as this one. Import it with gradle and activate it like this:
GravitySnapHelper(Gravity.START).attachToRecyclerView(recyclerview);


Q: How to specify which app to make changes with heroku? Hello I have multiple heroku apps. Whenever I I run this command heroku buildpacks:set heroku/nodejs  it applies it to the wrong heroku app. How can I specify which app to make this change to. It seems like whenever I run any command with heroku it does it to a different app.

A: Most Heroku CLI commands support the -a parameter to specify the application, in this case:
heroku buildpacks:set heroku/nodejs -a <app name>


Q: Functional Swift returns error Why does r1 work but r2 throw a compilation error (Cannot invoke '+' with an argument list of type '(NSArray, [Int])')?
func reduce<T1, T2>(input:[T1], initialResult: T2, f:(T2, T1) -> T2) -> T2 {
    var result = initialResult
    for x in input {
        result = f(result, x)
    }
    return result
}

let array2D = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

let r1 = reduce(array2D, []){result, x in
    result + x}

let r2 = reduce(array2D, []){result, x in
    return result + x}

A: If you specify the return type, it silences this error, e.g.:
let r3 = reduce(array2D, []){result, x -> [Int] in
    return result + x}

If you specify that that initial empty array is an Int array, the error is silenced:
let r4 = reduce(array2D, [Int]()){result, x in
    return result + x}


Q: webkitfullscreenchange event not firing, when the element contains Flash I have an element that contains a video player: that video player can either be Flash or HTML5 based. I want to be able to make that element fullscreen (I know, only works in webkit at the moment) and run some resizing scripts when it happens.
Here is how I do it:
this.getEl('.fullscreen').bind('click', $.proxy(function() {
    this.getEl('#tpPlayer')[0].webkitRequestFullScreen();
}, this));

And the event listener:
this.getEl('#tpPlayer').bind('webkitfullscreenchange', function() {
    console.log('fullscreen change');
    $(this).toggleClass('tpPlayer tpPlayerFullScreen');
});

When #tpPlayer contains a <video> element, everything works fine: the element goes fullscreen, the event fires, the message is logged and the classes are toggled. However, when #tpPlayer contains a Flash <object>, the element goes fullscreen fine, but no event is fired (so the callback does not run either).
Why is this happening and how to avoid this?


Q: Removing Uploaded Files from Google when item Expires We're using the Google CSE (Custom Search Engine) paid service to index content on our website. The site is built of mostly PHP pages that are assembled with include files, but there are some dynamic pages that pull info from a database into a single page template (new releases for example). The issue we have is I can set an expire date on the content in the database so say "id=2" will bring up a "This content is expired" notice. However, if ID 2 had an uploaded PDF attached to it, the PDF file remains in the search index.
I know I could write a cleanup script and have cron run it that looks at the db, finds expired content, checks to see if any uploaded files were attached and either renames or removes them, but there has to be a better solution (I hope).
Please let me know if you have encountered this in the past, and what you suggest.
Thanks,
D.

A: There's unfortunately no way to give you a straight answer at this time: we have no knowledge of how your PDFs are "attached" to your pages or how your DB is structured.
The best solution would be to create a robots.txt file that blocks the URLs for the particular PDF files that you want to remove. Google will drop them from the index on its next pass (usually in about an hour).
http://www.robotstxt.org/

A: What we ended up doing was tying a check script to the upload script that once it completed the current upload, old files were "unlinked" and the DB records were deleted.
For us, this works because it's kind of an "add one/remove one" situation where we want a set number of of items to appear in a rolling order.


Q: bxslider bx-viewport height is 0 if shown later I have an angular application in which i am using bxslider plugin.
I have created bxslider directive to call the plugin and everything was working fine till i extended the functionality.
This is the code for creating directive
angular.module('sbAdminApp')
.directive('bxSlider', function(){
    return{
        restrict: "A",
        require: "ngModel",
        link: function(scope, element, attrs, ctrl){
            element.ready(function(){
                $($(element[0])).bxSlider({
                    controls:false,
                    pager:true,
                    maxSlides: 1,
                    minSlides:1
                });
            })
        }
    }
})

This is the html

Controller with values in array
angular.module('sbAdminApp')
.controller('mobileViewCtrl', function($scope){
    $scope.mobileBanner = ['banner_small.png', 'banner_small.png', 'banner_small.png'];
})

But actually that slider div is hidden and i am showing it with ng-show on click of anchor because of which the height of bxslider is 0 i need to do slight resize of window to let bxslider get the required height.
I want bxslider should come correct initially when i am showing div.

A: Thanks for all you support mates. I found the answer.
I was using ng-show to manage when i need to show the slider because of which initially the slider was hidden and giving problem.
But now i switched to ng-if which is not just hiding the slider or completely removing it from DOM and insert it when i need so that bxslider is initialised only when shown and working completely fine.
Found the difference here : what is the difference between ng-if and ng-show/ng-hide

A: The problem is that - Slides/images must be visible before slider gets initiate.
In your case possible solutions are -
Either:

*

*You can reload slider after ng-show animation complete

*Slider can be initiate after ng-show animation complete

To reload bx slider doc -
http://bxslider.com/examples/reload-slider
http://bxslider.com/examples/reload-slider-settings
Sample code:
var slider = $('.bxslider').bxSlider({
  mode: 'horizontal'
});
//Inside ng-show callback
slider.reloadSlider();

Trigger event when ng-show is complete
Call a function when ng-show is triggered?


Q: ignore "channel_layout" when working with multichannel audio in ffmpeg I'm working with multichannel audio files (higher-order ambisonics), that typically have at least 16 channels.
Sometimes I'm only interested in a subset of the audiochannels (e.g. the first 25 channels of a file that contains even more channels).
For this I have a script like the following, that takes a multichannel input file, an output file and the number of channels I want to extract:
#!/bin/sh
infile=$1
outfile=$2
channels=$3

channelmap=$(seq -s"|" 0 $((channels-1)))

ffmpeg -y -hide_banner \
  -i "${infile}" \
  -filter_complex "[0:a]channelmap=${channelmap}" \
  -c:a  libopus -mapping_family 255 -b:a 160k -sample_fmt s16 -vn -f webm -dash 1 \
  "${outfile}"

The actual channel extraction is done via the channelmap filter, that is invoked with something like -filter:complex "[0:a]channelmap=0|1|2|3"
This works great with 1,2,4 or 16 channels.
However, it fails with 9 channels, and 25 and 17 (and generally anything with >>16 channels).
The error I get is:
$ ffmpeg -y -hide_banner -i input.wav  -filter_complex "[0:a]channelmap=0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16" -c:a libopus -mapping_family 255 -b:a 160k  -sample_fmt s16 -vn -f webm -dash 1 output.webm
Input #0, wav, from 'input.wav':
  Duration: 00:00:09.99, bitrate: 17649 kb/s
    Stream #0:0: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 44100 Hz, 25 channels, s16, 17640 kb/s
[Parsed_channelmap_0 @ 0x5568874ffbc0] Output channel layout is not set and cannot be guessed from the maps.
[AVFilterGraph @ 0x5568874fff40] Error initializing filter 'channelmap' with args '0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16'
Error initializing complex filters.
Invalid argument

So ffmpeg cannot guess the channel layout for a 17 channel file.
ffmpeg -layouts only lists channel layouts with 1,2,3,4,5,6,7,8 & 16.
However, I really don't care about the channel layout. The entire concept of "channel layout" is centered around the idea, that each audio channel should go to a different speaker.
But my audio channels are not speaker feeds at all.
So I tried providing explicit channel layouts, with something like -filter_complex "[0:a]channelmap=map=0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16:channel_layout=unknown", but this results in an error when parsing the channel layout:
$ ffmpeg -y -hide_banner -i input.wav  -filter_complex "[0:a]channelmap=map=0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16:channel_layout=unknown" -c:a  libopus -mapping_family 255 -b:a 160k  -sample_fmt s16 -vn -f webm -dash 1 output.webm
Input #0, wav, from 'input.wav':
  Duration: 00:00:09.99, bitrate: 17649 kb/s
    Stream #0:0: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 44100 Hz, 25 channels, s16, 17640 kb/s
[Parsed_channelmap_0 @ 0x55b60492bf80] Error parsing channel layout: 'unknown'.
[AVFilterGraph @ 0x55b604916d00] Error initializing filter 'channelmap' with args 'map=0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16:channel_layout=unknown'
Error initializing complex filters.
Invalid argument

I also tried values like any, all, none, 0x0 and 0xFF with the same result.
I tried using mono (as the channels are kind-of independent), but ffmpeg is trying to be clever and tells me that a mono layout must not have 17 channels.
I know that ffmpeg can handle multi-channel files without a layout.
E.g. converting a 25-channel file without the -filter_complex "..." works without problems, and ffprobe gives me an unknown channel layout.
So: how do I tell ffmpeg to just not care about the channel_layout when creating an output file that only contains a subset of the input channels?

A: Based on Audio Channel Manipulation you could try splitting into n separate streams the amerge them back together:
-filter_complex "\
[0:a]pan=mono|c0=c0[a0];\
[0:a]pan=mono|c0=c1[a1];\
[0:a]pan=mono|c0=c2[a2];\
[0:a]pan=mono|c0=c3[a3];\
[0:a]pan=mono|c0=c4[a4];\
[0:a]pan=mono|c0=c5[a5];\
[0:a]pan=mono|c0=c6[a6];\
[0:a]pan=mono|c0=c7[a7];\
[0:a]pan=mono|c0=c8[a8];\
[0:a]pan=mono|c0=c9[a9];\
[0:a]pan=mono|c0=c10[a10];\
[0:a]pan=mono|c0=c11[a11];\
[0:a]pan=mono|c0=c12[a12];\
[0:a]pan=mono|c0=c13[a13];\
[0:a]pan=mono|c0=c14[a14];\
[0:a]pan=mono|c0=c15[a15];\
[0:a]pan=mono|c0=c16[a16];\
[a0][a1][a2][a3][a4][a5][a6][a7][a8][a9][a10][a11][a12][a13][a14][a15][a16]amerge=inputs=17"

A: Building on the answer from @aergistal, and working with an mxf file with 10 audio streams, I had to modify the filter in order to specify the input to every pan filter. Working with "pan=mono" it only uses one channel identified as c0
-filter_complex "\
[0:a:0]pan=mono|c0=c0[a0];\
[0:a:1]pan=mono|c0=c0[a1];\
[0:a:2]pan=mono|c0=c0[a2];\
[0:a:3]pan=mono|c0=c0[a3];\
[0:a:4]pan=mono|c0=c0[a4];\
[0:a:5]pan=mono|c0=c0[a5];\
[0:a:6]pan=mono|c0=c0[a6];\
[0:a:7]pan=mono|c0=c0[a7];\
[0:a:8]pan=mono|c0=c0[a8];\
[0:a:9]pan=mono|c0=c0[a9];\
[a0][a1][a2][a3][a4][a5][a6][a7][a8][a9]amerge=inputs=10"


Q: RecyclerView RecyclerViewDataObserver was not registered Im working with RecyclerView, SyncAdapter and greenrobot eventbus
When my SyncAdapter finished syincing i post a message into the message bus:
EventBus.getDefault().post(new EventMessagesRefreshed());

In my target class i do the following:
@Subscribe
public void onEvent(EventMessagesRefreshed event) {
    this.init();
}

And in my init() i create the adapter for the recyclerview and set it:
public void init() {
    if(this.listRowParent != null) {
        this.adapter = new FragmentMessagesListAdapter(this.getActivity(), SingletonMessages.getInstance().getMessages());
        this.listRowParent.setAdapter(this.adapter);
    }
}

// listRowParent is my RecyclerView!

The fragment which receives the event is inside a of a  tab view. So there are multiple tabs and sometimes ofcourse the SyncAdapter posts the EventMessagesRefreshed into the message bus when im not in the correct target tab but since it is registered it tries to call init() and to create the adapter and set it to the RecyclerView. If that happens i get the following error:
Could not dispatch event: class EventMessagesRefreshed to subscribing class class FragmentMessagesList
java.lang.IllegalStateException: Observer android.support.v7.widget.RecyclerView$RecyclerViewDataObserver@2c3421a7 was not registered.
    at android.database.Observable.unregisterObserver(Observable.java:69)
    at android.support.v7.widget.RecyclerView$Adapter.unregisterAdapterDataObserver(RecyclerView.java:5688)
    at android.support.v7.widget.RecyclerView.setAdapterInternal(RecyclerView.java:873)
    at android.support.v7.widget.RecyclerView.setAdapter(RecyclerView.java:857)

So i need to init() my adapter and RecyclerView only when the RecyclerViewDataObserver is registered.
How can i do that?

A: You need to register Data observer to listen to data changes from sync adapter.
mRecyclerViewAdapter.registerAdapterDataObserver(myObserver);
RecyclerView.AdapterDataObserver are a result of which notify methods you call. So for instance if you call notifyItemInserted() after you add an item to your adapter then onItemRangeInserted() will get called
A more detailed example
protected void setupRecyclerView() {
    mAdapter = new MyAdapter(mItemList);
    mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            checkAdapterIsEmpty();
        }
    });

    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mRecyclerView.setHasFixedSize(true);

    mRecyclerView.setAdapter(mAdapter);
    checkAdapterIsEmpty();
}`

The adapter may publish a variety of events describing specific
  changes. Not all adapters may support all change types and some may
  fall back to a generic "something changed" event if more specific data
  is not available.


Q: Send photo/image to application Does anyone know if it's possible to get your application on this screen?
Or is this ability only able for Apple?
I did some searching but couldn't find anything relevant, I wasn't exactly sure what to even call this screen.
I'm new so I can't post images...but basically on an iPhone 5, open up a picture. Click the icon that has a rectangle with an arrow jumping out of it. The menu that pop's up is the one I'm talking about.

A: Unfortunately, for no good reason, Apple doesn't list any 3rd party apps in the Photos app even for apps that register the fact that they can open such files.
If you want this feature, file an enhancement request using Apple's bug reporting tool.

A: To directly answer your question, no there is no way to get your application on that list.
For some reason Apple handles images with their own activity sheet.
To get images off the camera roll, look into UIImagePickerController


Q: Relative or dynamic site url possible? I have a local Xampp wordpress installation that I am using as sort of an intranet with some people I work with.
I require them to be able to access it on our LAN router -- I found that I needed to change the site url and links from http://localhost:8080 to my IP http://192.168.x.xx:8080 for images and css to show.
However, I have found that when we are connected to a different router, or my travel router, this IP changes and obviously makes it not work on the LAN.
I'm not really wanting to search/replace and change the site name every time a new computer and/or server is hosting the local site.
Question: So I'm really interested to see if there is a way to make the site/home URL dynamic to the hosting computer's current IP or computername. Or if I'm looking for the wrong type of solution.
I have searched extensively for a solution to this, but I feel my problem is I'm not sure what terms to search for -- or if there is a better solution. I hope someone smart could point me in the right direction.
-Based on my internet searches, I have tried a couple plugins - Relative URLs and "Root relative URLS" in hopes it would fix but it has not made a difference.
-I have also set a static IP address in my travel router - however, the problem persists that I would need to change the ip address in the site if the computer changes.
-I've also tried this in my wp-config:
<?php
define('WP_HOME', 'http://' . $_SERVER['HTTP_HOST']);
//add the next line if you have a subdirectory install
define('WP_SITEURL', WP_HOME . '/wordpress');

A: If anyone out there has a similar situation as me, I found a solution by adding:
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/* THIS IS CUSTOM CODE CREATED AT ZEROFRACTAL TO MAKE SITE ACCESS DYNAMIC */
$currenthost = "http://".$_SERVER['HTTP_HOST'];
$currentpath = preg_replace('@/+$@','',dirname($_SERVER['SCRIPT_NAME']));
$currentpath = preg_replace('/\/wp.+/','',$currentpath);
define('WP_HOME',$currenthost.$currentpath);
define('WP_SITEURL',$currenthost.$currentpath);
define('WP_CONTENT_URL', $currenthost.$currentpath.'/wp-content');
define('WP_PLUGIN_URL', $currenthost.$currentpath.'/wp-content/plugins');
define('DOMAIN_CURRENT_SITE', $currenthost.$currentpath );
@define('ADMIN_COOKIE_PATH', './');

In the wp-config.php
I found this solution on the site: http://davidmregister.com/dynamic-wp-siteurl/
Thanks everyone!

A: I usually just avoid the issue entirely every time I create a new wordpress site:
define('WP_HOME', '/');
define('WP_SITEURL', '/');

will cause wordpress to use root-relative urls for everything. Makes site migrations to other domains far easier. Ofc, if you access your site using a folder (eg. "http://<domain>/blog") you could change them to:
define('WP_HOME', '/blog/');
define('WP_SITEURL', '/blog/');

For existing sites, make sure the database and any theme/plugin files are free from absolute urls generate by wordpress using the old WP_HOME and WP_SITEURL values.
EDIT: just to clarify, you add these defines to your wp-config.php.


Q: is there exist some alternative of Enum.GetName(Type, Object) method in Swift? in c# is possible to get enum name of any type with method
Enum.GetName (Type, Object)

is there possible to do the same in Swift?
As example I have some enum that must have Int raw value, but also I need it's own name.
how to do this in Swift 3?

A: To get an enumeration case's name as a String, you can use init(describing:) on String:
enum Foo: Int {
    case A
    case B
    case C
}

let s = String(describing: Foo.A)
print(s) // "A"

You can bake this into the enum:
enum Foo: Int {
    case A
    case B
    case C
    var asString: String { return String(describing: self) }
}

let s = Foo.A.asString
print(s) // "A"

A: Pre-requisite: you have an enumeration type with an underlying RawValue; i.e., an enumeration conforming to RawRepresentable.

The C# method Enum.GetName Method (Type, Object) is described as follows:

Enum.GetName Method (Type, Object)
public static string GetName(
  Type enumType,
  object value
)

Parameters
enumType

*

*Type: System.Type

*An enumeration type.

  value

*

*Type: System.Object

*The value of a particular enumerated constant in terms of its underlying type.

  Return Value
  - Type: System.String
  - A string containing the name of the enumerated constant in enumType whose value is value; or null if no such constant is
  found.

"Translated" into Swift, this method takes an enum type as first argument, and a value of the underlying type of the enum as its second one; where the latter would (for the pre-requisites of RawRepresentable conformance) translate into a value of the RawValue type of the enum in Swift.
Finally, the return type System.String (with possible null return) would translate to an optional String return type in Swift (String?).
Knitting these observations together, you could implement your similar getName method (for finding String representation of your cases represented as YourEnum.RawValue instances at runtime) by combining the init?(rawValue:) blueprinted in RawRepresentable with the init(describing:) initializer of String:
func getName<T: RawRepresentable>(_ _: T.Type, rawValue: T.RawValue) -> String? {
    if let enumCase = T(rawValue: rawValue) {
        return String(describing: enumCase)
    }
    return nil
}

/* example setup */
enum Rank: Int {
    case n2 = 2,n3,n4,n5,n6,n7,n8,n9,n10,J,Q,K,A
}

/* example usage */
let someRawValue = 7
if let caseName = getName(Rank.self, rawValue: someRawValue) {
    print(caseName) // n7
}

This is contrived and coerced "translation" however, as Swift enum:s are quite different (and more powerful) than those of C#. You would generally have an actual instance instance of the enum (e.g. Rank.n7) rather than one of its RawValue (e.g. 7), in which case you could simply use the init(describing:) initializer of String directly as described in the answer of @AlexanderMomchliov.


Q: Is there a way to upload a folder from the Files app into a computer on the local network? Is there a way to upload a folder from the Files app into a computer on the local network? The only solution I have found is to start an SFTP server on the computer, and use the app Secure Shellfish to expose that SFTP directory in the Files app. This solution is, unfortunately, very slow (maxes out at 9 MB/s in a network that can handle 70 MB/s).
PS: SMB barely even works, and is the slowest option ever.

A: FE File Explorer can do this:

FE File Explorer is a powerful file manager app on your iPhone and iPad. It can access not only local files, but also files on your computer and NAS. Stream movies and music to your iPhone/iPad. Directly view and manage documents, photos, files on your computers and cloud without downloading to your iPhone/iPad.

*

*Add the remote computer's server (I recommend a WebDAV server)

*Now add the directories from the Files app you need

*You can copy stuff between these "remotes" now. Take care not to background the app while the file transfers are ongoing, as iOS sucks and closes all background apps.

I achieved ~63 MB/s using this method.


Q: Integrating existing crystal report C# I externally created a Crystal Report that I now want to integrate into my C# application using Visual Studio. I added a new item(Crystal Report template) to my project and chose the "From an Existing Report" radio button. I then entered the path of where my report exists. The report then shows up, and the data appears when I click on the Main Report Preview button.
The report has a static parameter that I need to populate before displaying the report.
Being new to C# I am unsure how to

*

*Populate the parameter

*Cause the Report to appear

I did search for how to populate the parameter and this is the code I'm using.
CrystalReport1 g3 = new CrystalReport1();
g3.SetParameterValue("SupplierName", SupplierID);
g3.Refresh();

I don't get an error, but my report isn't showing up, so I must be doing something wrong.


Q: C++ Remove Evenly numbered words from a string having some issues with implementing the logic for one homework problem. The platform I am using currently is Visual Studio 2013 and am a beginner. We are using the terminal (command prompt) built in with the application to get the input and output. We are currently using "CIN" and "COUT". The problem is as follows:
"Write a program that asks the user for a sentence and then strips out every even-numbered word. For example: "All The Presidents Men" would become "All Presidents". Return the modified sentence to main() function using an output parameter and then display both the original and modified sentences".
I've been trying to apply this with logic that puts each word into an array/vector, and removes each word with an index of an even number. I have yet to successfully accomplish this and am seeking some assistance from you experts!
Thank you much.

A: Live Demo
std::string line;

// get input from cin stream
if (std::getline(cin, line)) // check for success
{
    std::vector<std::string> words;
    std::string word;

    // The simplest way to split our line with a ' ' delimiter is using istreamstring + getline
    std::istringstream stream;
    stream.str(line);

    // Split line into words and insert them into our vector "words"
    while (std::getline(stream, word, ' '))
        words.push_back(word);

    if (words.size() % 2 != 0) // if word count is not even, print error.
        std::cout << "Word count not even " << words.size() << " for string: " << line;
    else
    {
        //Remove the last word from the vector to make it odd
        words.pop_back();

        std::cout << "Original: " << line << endl;
        std::cout << "New:";

        for (std::string& w : words)
            cout << " " << w;
    }
}

A: You could write something like this
int count = -1;
for (auto it =input.begin();it!=input.end();){
if(*it==' '){
    count++;it++;
    if (count%2==0){
       while (it != input.end()){
            if (*it==' ')break;
            it=input.erase (it);
       }
   }else it++;
 }else it++;
}`


Q: Generic Repository should use Unit of Work or DbContext directly
*

*When I use Generic Repository with Entity Framework, do I need to use Unit of Work because to my knowledge UOW coordinate between multiple repositories. Or let Generic Repository work directly on the DbContext because UOW is not needed.

*Which is best practice : use generic repository or implement repository class for each entity type.

A: I don't know which generic repository you are refering to, but here is my experience with A generic repository.
In general, a unit of work or repository is not needed with EntityFramework. EntityFramework does it all.
However, in my first EF project I found myself creating a factory class that handed out and saved all entities. The class was doing that without doing the complete work of a unit of work, nor providing a standardized interface like a repository does. The huge class was in need of some structure. So, my personal advice is against one big repository for all entities, this repository will grow and will be increasingly difficult to maintain. If you think of such a class you better use EF as it is.
In the second project I use a UnitOfWork and generic repository. This suits my purposes much better. One unit of work to do the save operation, saving all changes in one save operation and the same interface for all repositories. Two classes of which I only have to change the unit of work to accommodate a new entity. The unit of work also hides the use of the dbContext which to my opinion causes ugly code.
I do not use a fancy unitofwork or generic repository (I found mine at: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application), just enough to have some guidance in implementation.
I agree with Gert in his immediate reply: it is all about personal preference.


Q: Wait function return value I have the following program in my book which I tried to run:
int i;
void *xpto(void *ptr) {
    printf ("xpto: beggining\n");
    for (; i<5; i++)
        sleep(1);
    printf ("xpto: end i=%d\n", i);
    exit(i);
}

int main(int argc, const char * argv[]){
    int a, b, c;
    i = 0;
    printf ("before fork\n");
    a = fork();
    if (a == 0) {
        printf ("before calling xpto\n");
        xpto(NULL);
        exit (EXIT_SUCCESS);
    }
    else if (a > 0) {
        b = wait(&c);
        printf ("after wait (%d, %d)\n",
                b, WEXITSTATUS(c));
        exit (EXIT_SUCCESS);
    }}

This is the output:
before fork
before calling xpto
xpto: beggining
xpto: end i=5
after wait (-1, 0)
Program ended with exit code: 0

In the parent process, shouldn't wait(&c) return the child process id, instead of returning -1?


Q: Oauth2 and YouTube - what am I doing wrong? I've been working on this unsuccessfully for a long time now.  The YouTube developer examples seem straightforward enough, but I always meet the same two errors:
Access is Denied (when running on IIS)
Or
redirect_uri_mismatch (When running in Visual Studio)
This is the code that always fails for me:
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
  {
    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets,
        // This OAuth 2.0 access scope allows an application to upload files to the
        // authenticated user's YouTube channel, but doesn't allow other types of access.
        new[] { YouTubeService.Scope.YoutubeUpload },
        "user",
        CancellationToken.None
    );
  }

I have:
- Updated the clients_secret and used it with the Javascript version, so I'm fairly sure that isn't the issue
- Tried to create a custom FileDataStore to add as another parameter
Here is more detail to the Access Denied error I get when debugging.  It appears as soon as I get to the "credential" line.

at Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task task)
     at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.d__1.MoveNext() in c:\ApiaryDotnet\default\Src\GoogleApis.Auth.DotNet4\OAuth2\GoogleWebAuthorizationBroker.cs:line 59
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
     at _Default.d__1.MoveNext() in c:\Users\Michael\documents\visual studio 2015\websites\website1\Default.aspx.cs:line 46

And this is what shows up in the properties for the credential right before it errors out:

ReadTimeout = 'stream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'
  WriteTimeout = 'stream.WriteTimeout' threw an exception of type 'System.InvalidOperationException'  int {System.InvalidOperationException}


Q: How to put constraints on HTML form inputs?
I have a form that looks like this.
What I want to do is, I want to make sure that Minimum Age < Maximum Age
and Minimum Skill Level < Maximum Skill Level
What is a way to put constraints on the inputs?
HTML
{% extends "template.html" %}
{% set active_page = "events" %}
{% block content %}

EVENTS PAGE

Click here to go to the welcome page

    <form action = "/events_success" method=post>
      Event Name:

      <input type="text" name="eventname" required="">

      Sports:

      <select name="sports">
       {% for item in sports_data %}
         <option value="{{ item[0] }}">{{ item[0] }}</option>
       {% endfor %}
     </select>

     Location:

      <select name="location">
       {% for item in loc_data %}
         <option value="{{ item[0] }}">{{ item[0] }}</option>
       {% endfor %}
     </select>

      Time:

        <input type="datetime-local" name="time" required>

      Number of Players:

      <input type="text" name="numplayers" required>

      Minimum Age:

      <input type="text" name="minage" required>

      Maximum Age:

      <input type="text" name="maxage" required>

      Minimum Skill Level:

      <input type = "radio" name = "minskill" value = "1" required> 1
      <input type = "radio" name = "minskill" value = "2"> 2
      <input type = "radio" name = "minskill" value = "3"> 3
      <input type = "radio" name = "minskill" value = "4"> 4
      <input type = "radio" name = "minskill" value = "5"> 5

      Maximum Skill Level:

      <input type = "radio" name = "maxskill" value = "1" required> 1
      <input type = "radio" name = "maxskill" value = "2"> 2
      <input type = "radio" name = "maxskill" value = "3"> 3
      <input type = "radio" name = "maxskill" value = "4"> 4
      <input type = "radio" name = "maxskill" value = "5"> 5

      Creator: {{ session['username'] }}

      <input type="submit" value="Send">
    </form>

{% endblock %}

A: You can just try some javaScript to prevent the form submission if those fields fails to fulfill that condition. Please check my demo.
**Note: It's just a demo. That's why didn't put any authentication.

window.onload = function() {
    let submit = document.querySelector("#submit");

    function validateAge(minAge, maxAge) {
        let min = parseInt(minAge, 10);
        let max = parseInt(maxAge, 10);
        return min >= max ?  false :  true;
    }
    function validateSkill(minSkill, maxSkill) {
        let min = parseInt(minSkill, 10);
        let max = parseInt(maxSkill, 10);
        return min >= max ?  false :  true;
    }

    submit.onclick = function() {
        let minAge = document.querySelector("#minage").value;
        let maxAge = document.querySelector("#maxage").value;
        let radios = document.querySelectorAll('input[type="radio"]:checked');
        let minSkill = radios[0].value;
        let maxSkill = radios[1].value;

        if(validateAge(minAge, maxAge) && validateSkill(minSkill, maxSkill))
            return  true;
        else {
            alert("Invalid data");
            return false;
        }
    }

}
    <form id="myForm" action = "/events_success" method=post >

      Minimum Age:

      <input type="text" name="minage" id="minage" required>

      Maximum Age:

      <input type="text" name="maxage" id="maxage"  required>

       Minimum Skill Level:

      <input type = "radio" name = "minskill" value = "1" required> 1
      <input type = "radio" name = "minskill" value = "2"> 2
      <input type = "radio" name = "minskill" value = "3"> 3
      <input type = "radio" name = "minskill" value = "4"> 4
      <input type = "radio" name = "minskill" value = "5"> 5

      Maximum Skill Level:

      <input type = "radio" name = "maxskill" value = "1" required> 1
      <input type = "radio" name = "maxskill" value = "2"> 2
      <input type = "radio" name = "maxskill" value = "3"> 3
      <input type = "radio" name = "maxskill" value = "4"> 4
      <input type = "radio" name = "maxskill" value = "5"> 5

      <input type="submit" value="Send" id="submit">
    </form>

A: You can use some common PHP validation techniques. These are more beneficial as less risky to injection and other exploits.
PHP:
  if (empty($_POST["code"])) {
    $errcode = "Verify that you're human";
  } else {
    $code = test_input($_POST["code"]);
    if (!$_POST['code'] < $string) {
      $errcode = "Make code greater than string";
    }
  }

HTML:

Scrambled code:  <input type="text" name="code" id="code" />  * <?php echo $errcode;?>


Q: commands to make ethernet interfaces up down using ip command I was using following commands to up the devices
# ifconfig p1p1:1 10.250.0.0 netmask 255.255.0.0 up
# ifconfig p1p1:2 10.251.0.0 netmask 255.255.0.0 up
# ifconfig p1p1:3 10.252.0.0 netmask 255.255.0.0 up

I don't have ifconfig installed currently on a new device, but have ip command
I can use ip addr command to see the ip addresses of my system
what are the equivalent commands  of ifconfig ... up using command ip
ip link show output is:
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: p1p1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT qlen 1000
    link/ether 00:ba:e7:ae:ed:3e brd ff:ff:ff:ff:ff:ff
3: p1p2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT qlen 1000
    link/ether 00:ba:e7:ae:ed:3f brd ff:ff:ff:ff:ff:ff
4: em1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT qlen 1000
    link/ether 60:aa:3e:25:47:1f brd ff:ff:ff:ff:ff:ff
5: em2: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc mq state DOWN mode DEFAULT qlen 1000
    link/ether 60:aa:3e:25:47:2f brd ff:ff:ff:ff:ff:ff

A: The following example will assume that your network card's name is eth0.
To bring up interface: ip link set eth0 up
To bring down interface: ip link set eth0 down


Q: CouchDB backup into S3 in json format I am checking ways to back up CouchDB records for all databases. The docs suggest to either use replication to a new CouchDB instance or simply copy the .couch files. But .couch files cannot be read by a text editor and we want to export records to json format and put it to S3.
I found curl can be used to retrieve data in json
curl -X GET http://127.0.0.1:5984/[mydatabase]/_all_docs?include_docs=true > /Users/[username]/Desktop/db.json

Is there a way to

*

*Split it into json files of say 10,000 records each so that if the DB is huge and there's a failure at Y record I can resume it from the batch that includes Y

*Run the _all_docs on all databases that exist instead of running it individually for each database?

If there's an alternative to curl I'd be happy to try use that as well


Q: No se guardan los datos en el SQL y Java Buenas estoy tratando de guardar datos en una base de datos, me sale se guardaron correctamente los datos sin embargo no aparecen en el SQL, estoy trabajando con MVC y CRUD no se que puede estar mal espero que puedan ayudarme
public void Create(Personal per) {
    try{
        st = conexion.createStatement();
        rs = st.executeQuery("insert into DPersonal ("+per.getCodigo()+",'"+per.getDNI()+",'"+per.getNombre()+",'"
                +per.getApellido()+",'"+per.getEdad()+per.getSexo()+",'"+per.getDireccion()+",'"
                +per.getCelular()+",'"+per.getCorreo()+per.getFoto()+",') values (?,?,?,?,?,?,?,?,?,?");
    } catch (Exception ex){
        Mensajes.MD("Datos registrados correctamente");
    }
}

   @Override
public void actionPerformed(ActionEvent ae) {
    if (ae.getSource() == vista.btnGuardar) {
        //lectura de datos
        int cod = Integer.parseInt(vista.txtCodigoP.getText());
        String dni = vista.txtDNIP.getText();
        String nom = vista.txtNombreP.getText();
        String ape = vista.txtApellidosP.getText();
        int ed = Integer.parseInt(vista.txtEdadP.getText());
        String s = vista.cboSexoP.getSelectedItem().toString();
        String direc = vista.txtDireccionP.getText();
        int cl = Integer.parseInt(vista.txtCelularP.getText());
        String cor = vista.txtCorreoP.getText();
        Icon f = vista.jlblFoto.getIcon();
        //creamos el objeto
        Personal per = new Personal(cod, dni, nom, ape, ed, s, direc, cl, cor, f);
        //lo insertamos en la BD
        CRUDpersonal cp = new CRUDpersonal();
        cp.Create(per);
    }


Q: Connect to WiFi with "networksetup -setairportnetwork en0 ssid password" without entering the password in plaintext? How to connect to a WiFi network using networksetup -setairportnetwork en0 ssid password without using the password in plaintext?


Q: How to Correctly Cancel a TPL Task with Continuation I have a long running operation which I am putting on a background thread using TPL. What I have currently works but I am confused over where I should be handling my AggregateException during a cancellation request.
In a button click event I start my process:
private void button1_Click(object sender, EventArgs e)
{
    Utils.ShowWaitCursor();
    buttonCancel.Enabled = buttonCancel.Visible = true;
    try
    {
        // Thread cancellation.
        cancelSource = new CancellationTokenSource();
        token = cancelSource.Token;

        // Get the database names.
        string strDbA = textBox1.Text;
        string strDbB = textBox2.Text;

        // Start duplication on seperate thread.
        asyncDupSqlProcs =
            new Task<bool>(state =>
                UtilsDB.DuplicateSqlProcsFrom(token, mainForm.mainConnection, strDbA, strDbB),
                "Duplicating SQL Proceedures");
        asyncDupSqlProcs.Start();

        //TaskScheduler uiThread = TaskScheduler.FromCurrentSynchronizationContext();
        asyncDupSqlProcs.ContinueWith(task =>
            {
                switch (task.Status)
                {
                    // Handle any exceptions to prevent UnobservedTaskException.
                    case TaskStatus.Faulted:
                        Utils.ShowDefaultCursor();
                        break;
                    case TaskStatus.RanToCompletion:
                        if (asyncDupSqlProcs.Result)
                        {
                            Utils.ShowDefaultCursor();
                            Utils.InfoMsg(String.Format(
                                "SQL stored procedures and functions successfully copied from '{0}' to '{1}'.",
                                strDbA, strDbB));
                        }
                        break;
                    case TaskStatus.Canceled:
                        Utils.ShowDefaultCursor();
                        Utils.InfoMsg("Copy cancelled at users request.");
                        break;
                    default:
                        Utils.ShowDefaultCursor();
                        break;
                }
            }, TaskScheduler.FromCurrentSynchronizationContext()); // Or uiThread.

        return;
    }
    catch (Exception)
    {
        // Do stuff...
    }
}

In the method DuplicateSqlProcsFrom(CancellationToken _token, SqlConnection masterConn, string _strDatabaseA, string _strDatabaseB, bool _bCopyStoredProcs = true, bool _bCopyFuncs = true) I have
DuplicateSqlProcsFrom(CancellationToken _token, SqlConnection masterConn, string _strDatabaseA, string _strDatabaseB, bool _bCopyStoredProcs = true, bool _bCopyFuncs = true)
{
    try
    {
        for (int i = 0; i < someSmallInt; i++)
        {
            for (int j = 0; j < someBigInt; j++)
            {
                // Some cool stuff...
            }

            if (_token.IsCancellationRequested)
                _token.ThrowIfCancellationRequested();
        }
    }
    catch (AggregateException aggEx)
    {
        if (aggEx.InnerException is OperationCanceledException)
            Utils.InfoMsg("Copy operation cancelled at users request.");
        return false;
    }
    catch (OperationCanceledException)
    {
        Utils.InfoMsg("Copy operation cancelled at users request.");
        return false;
    }
}

In a button Click event (or using a delegate (buttonCancel.Click += delegate { /Cancel the Task/ }) I cancel theTask` as follows:
private void buttonCancel_Click(object sender, EventArgs e)
{
    try
    {
        cancelSource.Cancel();
        asyncDupSqlProcs.Wait();
    }
    catch (AggregateException aggEx)
    {
        if (aggEx.InnerException is OperationCanceledException)
            Utils.InfoMsg("Copy cancelled at users request.");
    }
}

This catches the OperationCanceledException fine in method DuplicateSqlProcsFrom and prints my message, but in the call-back provided by the asyncDupSqlProcs.ContinueWith(task => { ... }); above the task.Status is always RanToCompletion; it should be cancelled!
What is the right way to capture and deal with the Cancel() task in this case. I know how this is done in the simple cases shown in this example from the CodeProject and from the examples on MSDN but I am confused in this case when running a continuation.
How do I capture the cancel task in this case and how to ensure the task.Status is dealt with properly?

A: You're catching the OperationCanceledException in your DuplicateSqlProcsFrom method, which prevents its Task from ever seeing it and accordingly setting its status to Canceled. Because the exception is handled, DuplicateSqlProcsFrom finishes without throwing any exceptions and its corresponding task finishes in the RanToCompletion state.
DuplicateSqlProcsFrom shouldn't be catching either OperationCanceledException or AggregateException, unless it's waiting on subtasks of its own. Any exceptions thrown (including OperationCanceledException) should be left uncaught to propagate to the continuation task. In your continuation's switch statement, you should be checking task.Exception in the Faulted case and handling Canceled in the appropriate case as well.
In your continuation lambda, task.Exception will be an AggregateException, which has some handy methods for determining what the root cause of an error was, and handling it. Check the MSDN docs particularly for the InnerExceptions (note the "S"), GetBaseException, Flatten and Handle members.

EDIT: on getting a TaskStatus of Faulted instead of Canceled.
On the line where you construct your asyncDupSqlProcs task, use a Task constructor which accepts both your DuplicateSqlProcsFrom delegate and the CancellationToken. That associates your token with the task.
When you call ThrowIfCancellationRequested on the token in DuplicateSqlProcsFrom, the OperationCanceledException that is thrown contains a reference to the token that was cancelled. When the Task catches the exception, it compares that reference to the CancellationToken associated with it. If they match, then the task transitions to Canceled. If they don't, the Task infrastructure has been written to assume that this is an unforeseen bug, and the task transitions to Faulted instead.
Task Cancellation in MSDN

A: Sacha Barber has great series of articles about TPL. Try this one, he describe simple task with continuation and canceling


Q: Precision of $\sinh x$ at $x \approx 0$ What can we do to increase the precision of $\sinh x$ at $x \approx 0$?
I tried to use conjugation , but it gives me $e^{2x} - e^{-2x}$ which is again the subtraction of "similar" numbers at $x \approx 0$
Thank you

A: It is unlikely that $\sinh x$ is computed using the definition when $x\approx 0$, exactly to avoid subtraction cancellation.
Indeed, when $x\approx 0$ one uses the Taylor expansion
$
\sinh x \approx x+x^3/6+x^5/120+O(x^7)
$
or a better polynomial or rational function (Padé approximant), as for instance in http://www.doc.ic.ac.uk/~svb/CS/Lab/Minix%203/lib/math/sinh.c.


Q: mysql query slow with joins upon enabling the slow_query_log in mysql. I found that the query below was one of slowest query with 15 secs or more. How can I optimize this query. All tables are Innodb and
server: Server version: 5.6 Thank you
    EXPLAIN EXTENDED SELECT
    ntv_staffs.fname,
    ntv_staffs.id,
    ntv_staffs.mname,
    ntv_staffs.profile_pic,
    ntv_staffs.lname,
    ntv_staff_office.cug,
    ntv_staff_office.extension,
    ntv_staff_office.off_email,
    ntv_staff_office.job_title,
    ntv_designations.`name` as designation_name,
    ntv_branches.`name` as branch_name,
    ntv_departments.`name` as department_name,
    ntv_departments.id as department_id
    FROM
    ntv_staffs
    INNER JOIN ntv_staff_office ON ntv_staffs.id = ntv_staff_office.pid
    INNER JOIN ntv_departments ON ntv_staff_office.department_id = ntv_departments.id
    INNER JOIN ntv_branches ON ntv_staff_office.branch_id = ntv_branches.id
    INNER JOIN ntv_designations ON ntv_staff_office.designation = ntv_designations.id
    where ntv_staffs.id='662';

+----+-------------+------------------+--------+---------------+---------+---------+----------------------------------------------+------+----------+-------------+
| id | select_type | table            | type   | possible_keys | key     | key_len | ref                                          | rows | filtered | Extra       |
+----+-------------+------------------+--------+---------------+---------+---------+----------------------------------------------+------+----------+-------------+
|  1 | SIMPLE      | ntv_staffs       | const  | PRIMARY       | PRIMARY | 4       | const                                        |    1 |   100.00 |             |
|  1 | SIMPLE      | ntv_staff_office | ALL    | NULL          | NULL    | NULL    | NULL                                         |  247 |   100.00 | Using where |
|  1 | SIMPLE      | ntv_branches     | eq_ref | PRIMARY       | PRIMARY | 4       | abc_portal_new.sks_staff_office.branch_id     |    1 |   100.00 |             |
|  1 | SIMPLE      | ntv_designations | eq_ref | PRIMARY       | PRIMARY | 4       | abc_portal_new.sks_staff_office.designation   |    1 |   100.00 | Using where |
|  1 | SIMPLE      | ntv_departments  | eq_ref | PRIMARY       | PRIMARY | 4       | abc_portal_new.sks_staff_office.department_id |    1 |   100.00 |             |
+----+-------------+------------------+--------+---------------+---------+---------+----------------------------------------------+------+----------+-------------+

A: Try setting a btree-index for ntv_staff_office.pid.


Q: Is there a way to copy a Windows program from an external HDD into WINE? I am running Windows 10 on an external HDD.  I only use Windows for one program for work, otherwise, I use Ubuntu 19.04 (Dingo).  Is there a way to move or copy this program from my Windows HDD into WINE?
This program was installed by the IT dept at my client's office, so I don't have access to the installation media.  None of them know Ubuntu (or any other Linux distro), so it'll be easier if I don't have to involve them.
I want to be able to format the external HDD to use as just a drive instead of reserving it for just one program.

A:
Is there a way to move or copy this program from my Windows HDD into WINE?

Sure, you can copy the files to your WINE. WINE is a directory in your /home/$USER so you can copy files to that and see them in an explorer in WINE.
Mind though: copying it into WINE does NOT mean you can use that software. That depends on what the software is. Even if you did have the installation media it does not guarantee to work in WINE either.
Would it be an option to create an ISO from the external HDD and create a virtualbox VDI so you can use it virtually? Like https://www.intowindows.com/how-to-boot-and-install-from-iso-in-virtualbox/ That would also enable your software inside the container.


Q: How can I get the output of a Timed Out command by subprocess.check_output()? I'm trying to run some commands using the python library subprocess. Some of my commands might get stuck in loops and block the python script. Therefore I'm using check_output() with a timeout argument to limit the commands in time. When the command takes too much time, the function raise a TimeoutExpired error. What I want to do is get what the command has been able to run before being killed by the timeout.
I've except the error and tried "except sp.TimeoutExpired as e:". I read on the doc that if I do e.output it should give me what I want. "Output of the child process if this exception is raised by check_output(). Otherwise, None.". However I don't get anything in the output.
Here is what I did:
import subprocess as sp
try:
        out = sp.check_output('ls', stderr=sp.STDOUT, universal_newlines=True, timeout=1)
except sp.TimeoutExpired as e:
        print ('output: '+ e.output)
else:
        return out

Let say the folder I'm working with is huge and so 1 second isn't enough to ls all its files. Therefore the TimeoutExpired error will be raised. However, I'd like to store what the script was able to get at least. Does someone have an idea?

A: Found a solution, posting it here in case someone is interested.
In Python 3, the run method allows to get the output.
Using the parameters as shown in the example, TimeoutExpired returns the output before the timeout in stdout:
import subprocess as sp

for cmd in [['ls'], ['ls', '/does/not/exist'], ['sleep', '5']]:
    print('Running', cmd)
    try:
        out = sp.run(cmd, timeout=3, check=True, stdout=sp.PIPE, stderr=sp.STDOUT)
    except sp.CalledProcessError as e:
        print(e.stdout.decode() + 'Returned error code ' + str(e.returncode))
    except sp.TimeoutExpired as e:
        print(e.stdout.decode() + 'Timed out')
    else:
        print(out.stdout.decode())

Possible output:
Running ['ls']
test.py

Running ['ls', '/does/not/exist']
ls: cannot access '/does/not/exist': No such file or directory
Returned error code 2
Running ['sleep', '5']
Timed out

I hope it helps someone.


Q: Forced convection: temperature gradient in conical pipe My situation involves a conical pipe of known dimensions and material composition. Warmer-than-ambient air is added to the small end at a steady, known flow rate.  I'm hoping for a way to estimate interior air temperature at a given time (after warm air begins to be added) and at a given distance (measured from the small end of the pipe).


Q: matching Charaters in soql query I have written the below to match postcodes with a custom obect for account allocation as is suggested best practice
    trigger PostcodeBulk on Account (before insert) {

    Set<String>Postcode = new set<String>();

    For(Account acc : trigger.new) {
        if (acc.billingpostalcode != null){
            postcode.add(acc.BillingPostalCode);
        }
    }
Map<String,String> postcodeowner = new map<string,string>();
    For (postcodes__c P : [select postcode__c, user__c from postcodes__c where postcode__C in :postcode]);
        postcodeowner.put(p.postcode__c,p.user__c);

    For(account acc : trigger.new){
        if(postcodeowner.containsKey(acc.BillingPostalCode)){
            acc.OwnerId = postcodeowner.get(acc.BillingPostalCode);
        }
    }
           }

my problem is that I only need to make the match on upto the first 4 characters, but sometimes less..
I thought of
if (acc.billingpostalcode != null){
            postcode.add(acc.BillingPostalCode.substring(0,4));

But this only matches exact I need to add a wildcard somewhere for example
[select postcode__c, user__c from postcodes__c where postcode__C in ::postcode.substring(0,2) + '%']

But I cannot make this work
Any help is appreciated
thanks

A: You cannot use wildcard expressions with a SOQL IN operator.  You should use the LIKE operator
  string postCodeSearch = postCode.substring(0,2) + '%';

  list<postcodes__c> codes = [select postcode__c, user__c from postcodes__c where postcode__C LIKE :postCodeSearch];

A: Instead of using the :: variable in the SOQL statement, set a string variable above it that takes the postcode substring, and add the '%' to it, then use that variable in the SOQL statement


Q: How to set text dynamically to texbox in vba? Dear Fellow StackOverFlow-members,
I try to dynamically create texboxes in a userform and set default text depending on value from a tab.
First the user fill in textboxes like in the photo
When he clicks the button above, it calls the function that create textboxes in the same userform. Exactly as much as the total of values of the textboxes, futhermore for value "0" it counts as 1 textbox to add.
What I want is when it encounters 0 value I want the new texbox created to set defaut text as "null". Like so :
My code :
For i = 0 To UBound(tabValTextBox)
            valTemp = tabValTextBox(i)
            If valTemp = 0 Then
                iTextBoxMasqueA = iTextBoxMasqueA + 1
                Set textBoxCableA = UserForm1.Controls.Add("Forms.TextBox.1")
                colTextBoxCableA.Add textBoxCableA
                With textBoxCableA
                    .Name = "cable" & iTextBoxCableA
                    .Top = iTextBoxCableA * textBoxCableA.Height + 50
                    .Left = 150
                    .Text = "Nul"
                End With
            Else
                For j = 0 To valTemp - 1
                    iTextBoxCableA = iTextBoxCableA + 1
                    Set textBoxCableA = UserForm1.Controls.Add("Forms.TextBox.1")
                    colTextBoxCableA.Add textBoxCableA
                    With textBoxCableA
                        .Name = "cable" & iTextBoxCableA
                        .Top = iTextBoxCableA * textBoxCableA.Height + 50
                        .Left = 150
                    End With
                Next j

            End If
        Next i

 tabValTextbox() is a tab containing the values of the left textboxes.
However the result I get looks like this  :    I don't get as much textboxes as expected.
I don't understand where I'm missing something. I want to learn from this, so if possible, explain me what I'm doing wrong here, or if my approach is lacking insight.

A: Try this:
For i = 0 To UBound(tabValTextBox)
    valTemp = tabValTextBox(i)
    iTextBoxCableA = iTextBoxCableA + 1
    If valTemp = 0 Then
        Set textBoxCableA = UserForm1.Controls.Add("Forms.TextBox.1")
        colTextBoxCableA.Add textBoxCableA
        With textBoxCableA
            .Name = "cable" & iTextBoxCableA
            .Top = iTextBoxCableA * textBoxCableA.Height + 50
            .Left = 150
            .Text = "Nul"
        End With
    Else
        For j = 0 To valTemp - 1
            Set textBoxCableA = UserForm1.Controls.Add("Forms.TextBox.1")
            colTextBoxCableA.Add textBoxCableA
            With textBoxCableA
                .Name = "cable" & iTextBoxCableA
                .Top = iTextBoxCableA * textBoxCableA.Height + 50
                .Left = 150
            End With
        Next j
    End If
Next i

I've moved the iTextBoxCableA increment outside of the zero condition, and removed the iTextBoxMasqueA increment entirely as you weren't using it.
I can't test this myself but I think it'll sort the problem of overlapping out.


Q: Azure AD B2C Application won't show up as an option to add role assignment. (Graph API) I'm following this documentation:
https://learn.microsoft.com/en-us/azure/active-directory-b2c/microsoft-graph-get-started?tabs=app-reg-ga
And I found another question answered that I thought fit my case:
https://learn.microsoft.com/en-us/answers/questions/199433/can39t-add-role-assignments-to-azure-b2c-applicati.html
My problem is that the app that I registered will not appear as an option when I try to follow the "Enable user delete and password update" portion of the documentation.
I am also mindful of the notice "Please allow a few minutes to for the permissions to fully propagate." But I've at it for 2 hours now, so I don't think that is the problem.
Here is my App and its API permissions:

And my B2C Tenant:

A: Microsoft has answered this question on this thread as follows:
Hi All · Thank you for reaching out.
There seems to be an issue with the UI. I will report the issue to the product team and get it addressed.
However, as of now, you can follow below steps and use PowerShell to add application to the User Administrator role:

*

*Install latest Azure AD PowerShell Module.

*Run Connect-AzureAD -TenantId Your_B2CTenant.onmicrosoft.com and sign in with Global Administrator account in that tenant.

*Run Get-AzureADDirectoryRole cmd and copy the object id of the User Administrator role.

*Navigate to Azure AD > Enterprise Applications > Search the app and copy the object id of the app.

*Run Add-AzureADDirectoryRoleMember -ObjectId object_ID_copied_in_Step3 -RefObjectId object_ID_copied_in_Step4 cmdlet.
To verify, navigate to Azure AD B2C > Roles and Administrators > User Administrator. You should see the application present under this role


Q: Is such an iOS model possible to implement? I would like to do the following:

*

*Sell a game for $0.99 at launch with no feature restrictions.

*If it's less than successful, make it free, but limit some features to in-app purchase (I would do this via an update to the existing app).

*BUT, I would like users who originally purchased the app (before it was free) to still have all of the features.  In other words, I want to find a way to credit the new in-app purchases to those users, so that they don't have to pay twice.

I would like to do this all with the existing app, instead of making two separate versions of the app (paid and free).
EDIT: it is essential that not a single user ever have to pay twice (i.e. that users who previously paid for the app, do not have to purchase the in-app upgrades in the future).
EDIT 2: It seems like this question has already been answered here: From Paid to FREE w/IAP: Preventing double-charging

A: Certainly.
The company I work for has done this in the past.
If you know you might want to do this in the future, in your first version store a flag to NSUserDefaults indicating that the user has had the paid version. Then, on your In-App version check this flag and provide the content immediately.
If you already have a version released, you may have to look for something that you are already storing, e.g. the user has a highscore greater than zero to indicate that the user has already purchased the app. (There will be a small number of users that may have downloaded the app but not opened it and these users may be charged twice).

A: Yeah, it is. Before you Update your app with FREE version, you add all users that have paid for it serial number "PAID"(or something), and everything else is just conditional statements(if-else). Congrats!


Q: Add unique ID to containing div of file input thumbnail image I have thumbnail previews of a users selected images prior to upload. It will also allow a user to re-arrange the order of the images using jQuery UI. I want to track the order of the images by adding a unique ID to each thumbnails containing div, but I am not able to generate a unique ID. See Code below. Ideally I would like the div ID to match the image name, so then after the form post I use it to match to the filename in the IEnumerable<HttpPostedFileBase>. For example, if the uploaded image is called pic1.jpg, the div containing the thumbnail would be
. The line in question would seem to be div.id = File.name, but I am unable to generate a unique ID of any kind?
CODE
//jQuery UI sort
$(function () {
  $("#upload-thumbnails").sortable();
  $("#upload-thumbnails").disableSelection();
});
//Thumbnail preview
jQuery(function ($) {
  var filesInput = document.getElementById("ImageUploads");

  filesInput.addEventListener("change", function (event) {

var files = event.target.files; //FileList object
var output = document.getElementById("upload-thumbnails");

for (var i = 0; i < files.length; i++) {
  var file = files[i];

  var picReader = new FileReader();

  picReader.addEventListener("load", function (event) {

    var picFile = event.target;

    var div = document.createElement("div");
    div.id = File.name;
    div.innerHTML = "Remove";

    output.insertBefore(div, null);
    div.children[1].addEventListener("click", function (event) {
      div.parentNode.removeChild(div);
    });

  });

  //Read the image
  picReader.readAsDataURL(file);
}

});
});

A: In most cases while we uploading images we rename them as the time stamp because of the uniqueness. But for searching, dealing with time stamp is much harder, then add a class name of the div as the file name.
...
var div = document.createElement("div");
div.id = Date.now();
div.className += ' ' + File.name;
...

I am sure this will be help full.
Thanks

A: Not sure I get the question :)
Try instead:
$(div).attr('id', 'yourIDHere')

Or you never use your defined var file , could it not be?
div.id = file.name;

You can generate UUIDs via JS see here


Q: If $v\otimes w=0$ then $v=0$ or $w=0$.
Let $v \otimes w \in V \otimes W$. If $v \otimes w = 0$ then $v=0$ or $w=0$.

I am having a difficult time proving "basic" things like this involving tensor products. I know that $v\otimes w$ is the decomposable bilinear form $V^*\times W^*\to \mathbb F$ given by $(\alpha,\beta)\mapsto\langle\alpha,v\rangle \langle\beta,w\rangle$. However, the notions of tensors still confuse me, any help would be much appreciated.

A: Assume $v \neq 0$ and $w \neq 0$. Then we have $f,g \in V^*$ such that $f(v) \neq 0$ and $g(w) \neq 0$ (why?). This implies that $(v\otimes w)(f,g) = f(v)g(w) \neq 0$, and hence $v \otimes w \neq 0$.

A: I assume you mean vector spaces over a field, otherwise it won't be true (e.g. for $\mathbb Z$-modules $\mathbb Z/5 \otimes \mathbb Z/3 = 0$). Use the definition of the tensor product: a linear map $V\otimes W \to U$ for any vector space $U$ is the same as a bilinear map from  the pair $V,W$ to $U$. Now a tensor $\sum_i v_i \otimes w_i$ is nonzero if and only if there exists a bilinear map $f$ such that $\sum_i f(v_i, w_i) \ne 0$. I will leave to you to find such a map in your case.


Q: Improving JavaScript path finding algorithm I'm working on an HTML/JavaScript flowchart designer similar to Visual Studio flowchart designer. One of the most fascinating features of VS flowchart designer, is its intelligent path creation algorithm, I think there should be a powerful path finding algorithm behind the scenes (something like A* for example).
I've implemented a path finding algorithm (a simple version of A*) in my application which tries to find a path between my source and destination nodes. Although it is generating the expected results, but it is really poor in terms of performance and speed, as it takes a long calculation time (in fact the calculation time increases as the path gets longer).
What are your suggestions for improving the performance? Do you know how Visual Studio is finding the path so quickly?


Q: Javascript Design Pattern Prototype error for web3.js Don't know what I am doing wrong, created a javascript prototype for a web3js application I am working on. When I try calling the function in the prototype it is not seeing the function in it. Throwing "persona.testing() is not a function" when I check the console.log.
Web3 = require('web3');

if(typeof web3 != "undefined")
    web3 = new Web3(web3.currentProvider);
     else {
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
     }

var initweb3 = function(address,abi) {
        this.address = address,
        this.abi = abi;
        this.contract;
        web3.eth.defaultAccount = web3.eth.accounts[0];
        this.contract = web3.eth.contract(this.abi);
        this.contract = this.contract.at(this.address);
 }

var paddress = "0x0",
    pabi = "",

    maddress = "",
    mabi = "";
    persona = new initweb3(paddress,pabi);
    //minion = new initweb3(maddress,mabi);

persona.prototype = {

testing: function(){
  console.log('Yes, I know');
},

testing1: function(){
  console.log('No, I don't');
}
};

persona.testing();

A: You could use Object.assign
persona = Object.assign({}, persona, {
  testing: function(){
    console.log('Yes, I know');
  }
});

or
persona.prototype.testing = function(){};

A: You should use prototype when you want to create one or more instances of a function.
in your case initweb3 is a constructor function.
make sure your constructor function starts with uppercase letter.
For example:
  function Person(){ /*...*/ }
  Person.prototype.sayHi = function() { };

  const p = new Person();
  p.sayHi();

in your use case persona is already an instance object, if you want to add a new function to it you simply do persona.testing = function() {}
OR
You can also try extending the initweb3 function.
initweb3.prototype.testing = function(){ /* code goes here */}
.
.
.
persona.testing();

Watch this video to learn more about prototypes in JavaScript.
https://www.youtube.com/watch?v=riDVvXZ_Kb4


Q: Page breaks on php tag The following code is written in php file and breaks page
<?php

$myrows1=cpabc_player_plan();

foreach ($myrows1 as $index=>$item1) //start foreach party plan
{
    if ($item1 === reset($myrows1))
    {}
?>

<?php }?>

while if I use it as
<?php
$myrows1=cpabc_player_plan();

foreach ($myrows1 as $index=>$item1) //start foreach party plan
{
  if ($item1 === reset($myrows1))
    {}
}?>

then it works fine.

A: You can use foreach():  endforeach Block like this:
<?php foreach ($myrows1 as $index=>$item1): ?>

 some html tags

   <?php
     if ($item1 === reset($myrows1))
       {}
   ?>

 some html tags

<?php endforeach; ?>

for other php statements you can read this page.


Q: Make Syntastic close just the error window I've got the (Mac)Vim Syntastic plugin installed via Janus. When I open the :Errors window to view the reason for syntax errors, it shrinks the file with the errors to one line and uses the rest of the real estate for the Errors window.
Is there a way to make it hog less room for errors and more importantly, how do I close just the Errors window?  The usual :q closes both the Errors window AND the original file, even if the cursor is in the Errors window.  (That's not 100% correct -- it gratefully does not close the file if the file hasn't yet been saved).

A: Syntastic uses the location list (a window-local variant of the quickfix list), so a :lclose will close it, but keep the other buffers.
As per syntastic's help pages, the initial height can be configured:
:let g:syntastic_loc_list_height=5

But I suspect that your intrusive Janus distribution has a hand in that. Vim "distributions" like spf-13 and Janus lure you with a quick install and out of the box settings, but you pay the price with increased complexity (you need to understand both Vim's runtime loading scheme and the arbitrary conventions of the distribution) and inflexibility (the distribution may make some things easier, but other things very difficult). Vim is incredibly customizable, using someone else's customization makes no sense.

A: Syntastic gets confused when you're juggling multiple buffers on one screen so here's a script that will collect information about the situation, then do the right thing:
function JustCloseSyntasticWindow()
    "Check which buffer we are in, and if not, return to the main one:
    if &ft == "qf"
        normal ZZ
    endif
    "Since different buffers have different command spaces, check if we've
    "escaped the other buffer and then tell syntastic to stop.
    if &ft != "qf"
       SyntasticReset
       " --- or ----
       SyntasticToggleMode
    endif
endfunction

au FileType buffer1_ft nnoremap :yourcmd<CR>:call JustCloseSyntasticWindow()<cr>

au FileType main_win_ft nnoremap :yourcmd<CR>:call JustCloseSyntasticWindow()<cr>

Don't be shy on the duct tape for this job, it's the only thing holding the unit together.

A: The command to close the Syntastic error window is:
:SyntasticReset

A: You can use :lclose to close it.


Q: VSCode, typescript, eslint and prettier -> null check does not work I've tried to setup typescript linting to use prettier and while prettier works, i seem to have lost the basic typescript error checking. How can i get this back?

^ should complain about accessing .value on foo?
My tsconfig.json
{
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": true,
    "module": "es6",
    "target": "es5",
    "jsx": "react",
    "allowJs": true,
    "sourceMap": true,
    "moduleResolution": "node",
    "baseUrl": "./src",
    "allowSyntheticDefaultImports": true,
    "paths": {
      "~/*": ["./*"]
    }
  },
}

.eslintrc.json
{
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "prettier/@typescript-eslint",
    "plugin:prettier/recommended"
  ],
  "plugins": ["@typescript-eslint", "prettier"],
  "env": {
    "browser": true,
    "jasmine": true,
    "jest": true,
    "es6": true
  },
  "rules": {
    "prettier/prettier": [
      "error",
      { "singleQuote": true, "semi": false }
    ],
    "@typescript-eslint/no-use-before-define": "off",
    "@typescript-eslint/no-explicit-any": "off",
    "@typescript-eslint/class-name-casing":  ["error", { "allowUnderscorePrefix": true }],
    "@typescript-eslint/interface-name-prefix": ["error", { "prefixWithI": "always", "allowUnderscorePrefix": true}],
    "@typescript-eslint/no-unused-vars": ["error", { "args": "none"}],
    "@typescript-eslint/no-non-null-assertion": "off",
    "semi":"off"
  },
  "parser": "@typescript-eslint/parser"
}


Q: Magento2: How can remove comma from price? I know my question may be duplicate of this question but I have tried this and didn't get solution. I have edited core files of price with str replace but after page load it is again showing price with comma.
I have tired with Locale/xml file but price coming from js may be. Anyone have an idea for that please?

A: Create custom module and override default file Format.php
Step1 : app/code/Adamsmage/Custprice/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Framework\Locale\Format" type="Vendor\Currency\Model\Format" />
</config>

Step2 : app/code/Adamsmage/Custprice/Model/Format.php
<?php
namespace Adamsmage\Custprice\Model;

use Magento\Framework\Locale\Bundle\DataBundle;

class Format extends \Magento\Framework\Locale\Format
{
    private static $defaultNumberSet = 'latn';

    public function getPriceFormat($localeCode = null, $currencyCode = null)
    {
        $localeCode = $localeCode ?: $this->_localeResolver->getLocale();
        if ($currencyCode) {
            $currency = $this->currencyFactory->create()->load($currencyCode);
        } else {
            $currency = $this->_scopeResolver->getScope()->getCurrentCurrency();
        }

        $localeData = (new DataBundle())->get($localeCode);
        $defaultSet = $localeData['NumberElements']['default'] ?: self::$defaultNumberSet;

        $format = $localeData['NumberElements'][$defaultSet]['patterns']['currencyFormat']
            ?: ($localeData['NumberElements'][self::$defaultNumberSet]['patterns']['currencyFormat']
                ?: explode(';', $localeData['NumberPatterns'][1])[0]);

        //your main changes are gone here.....
        $decimalSymbol = '.';
        $groupSymbol = ',';

        $pos = strpos($format, ';');
        if ($pos !== false) {
            $format = substr($format, 0, $pos);
        }
        $format = preg_replace("/[^0\#\.,]/", "", $format);
        $totalPrecision = 0;
        $decimalPoint = strpos($format, '.');
        if ($decimalPoint !== false) {
            $totalPrecision = strlen($format) - (strrpos($format, '.') + 1);
        } else {
            $decimalPoint = strlen($format);
        }
        $requiredPrecision = $totalPrecision;
        $t = substr($format, $decimalPoint);
        $pos = strpos($t, '#');
        if ($pos !== false) {
            $requiredPrecision = strlen($t) - $pos - $totalPrecision;
        }

        if (strrpos($format, ',') !== false) {
            $group = $decimalPoint - strrpos($format, ',') - 1;
        } else {
            $group = strrpos($format, '.');
        }
        $integerRequired = strpos($format, '.') - strpos($format, '0');

        $result = [
            //TODO: change interface
            'pattern' => $currency->getOutputFormat(),
            'precision' => $totalPrecision,
            'requiredPrecision' => $requiredPrecision,
            'decimalSymbol' => $decimalSymbol,
            'groupSymbol' => $groupSymbol,
            'groupLength' => $group,
            'integerRequired' => $integerRequired,
        ];
        return $result;
    }
}

I hope its work for you.

A: to remove decimals , you just need to install the free module Currency Formatter Extension from Mageplaza here the link : https://www.mageplaza.com/magento-2-currency-formatter/  .
Than you can disable the decimal from magento admin panel ->stores->configuration-> Mageplaza Extensions.
This worked for me in magento 2.3.3 installation .
Best regards


Q: Music and Sound Effects How to separate on and off(i mean how to mute separate ) function of Music Background and Sound Effect
AudioManager
public Sound[] sounds;

public static AudioManager instance;

void Awake()
{
    if (instance == null)
        instance = this;
    else
    {
        Destroy(gameObject);
        return;
    }

    DontDestroyOnLoad(gameObject);

    foreach (Sound s in sounds)
    {
        s.source = gameObject.AddComponent<AudioSource>();
        s.source.clip = s.clip;

        s.source.volume = s.volume;
        s.source.loop = s.loop;
        s.source.mute = s.mute;
    }
}

Sound.cs
public string name;
public AudioClip clip;

[Range(0f, 1f)]
public float volume;

public bool loop;
public bool mute;

[HideInInspector]
public AudioSource source;

This is my Music and Sound Effects


Q: Set variable while foreach loop is working I have foreach loop that copies files.
I want to set label to "Working.." while the foreach loop is copying the files.
I have tried:
label.text = "Ready";
foreach (file in files)
{
    File.Copy(firstDest, secondDest);
    label.text = "Working..";
}
label.text = "Ready";

But the label never changes even when it's copying the files for a while 2-3 seconds.
Do you know how to solve this? Thanks!

A: You should do your copy operation in another thread.
 label.text = "Ready";
var tasks = Task[files.length];

for (var i=0 ; i<files.length; i++) {
    tasks[i] = Task.Run(()=>{
        File.Copy(firstDest, secondDest);
    });
}

label.text = "Working..";
await Task.WhenAll(tasks);
label.text = "Ready";

In case you want to run it all in one task and not each copy in parallel
label.text = "Ready";

var task =Task.Run(()=>{
foreach (file in files){
      File.Copy(firstDest, secondDest);

}
});

label.text = "Working..";
await task;
label.text = "Ready";


Q: Setting up groups and roles correctly on Google Cloud Platform IAM I have recently been reviewing our roles and IAM on our very small (but set up a long time ago) organization on GCP and realized that we don't have any Essential Contacts defined (https://console.cloud.google.com/iam-admin/essential-contacts). I didn't have access to view this.
I went back and completed the foundational set up (https://console.cloud.google.com/cloud-setup - I don't think this existed when I originally signed up) to make sure I had the right groups set up with the right roles/permissions (and that I was a member of them).
But when I go to Essential Contacts and try to click "add Contact", I get a message that I don't have the permissions required.

So I can go and add this permission to myself individually or some group (that's not my question).
My question is:

*

*Have I actually set up the fundamental groups correctly? (if not, how)

*(Assuming I have set them up correctly) why is this permission left out of the roles assigned to the organization admins group ("gcp-organization-admins@DOMAIN" given that "Organisation administrators have access to administer all resources belonging to the organisation"). In other words, shouldn't an organizational admin already have this permission?

PS I am the owner of this (small) GCP organization.

A: Seems you're using the default role with your created project, It's not recommended to use it. Even if you're the owner of the project and you're unable to create Essential Contacts, it means you are not setting up the fundamental groups correctly.
If you're unable to create Essential Contacts, that means you require Essential Contacts Admin role, recommend you to have at least one additional user with the Security admin role, with permissions to get and set any IAM policy. This role helps the user to grant any one owner or with any other role in the project. The owner role is a legacy role and has a wide range of permissions.
Please refer to the official GCP doc for more information.
Edit :

*

*First please check whether you are using the correct Organization & Project.

*Check If you have set up your foundation & admin role properly, you can get the result as shown in below image

If not set properly you will get the result as shown in the below image.

*You can check your roles :
Login to the console >>Click on IAM & Admin>>Select IAM >>click on permissions
then you can view VIEW BY ROLES & VIEW BY PRINCIPALS

Check whether you have Essential contacts admin roles in VIEW BY PRINCIPALS, if not available, you are unable to add/view contacts. By default the owner also doesn’t have that permission so add it as below.
You can grant access to the Essential contacts admin role as shown in the below image, so that you can get permission to add contacts.


Q: Is there a way in Javascript/Angular to subscribe to a 'request sent' event hook? I'm wondering if there's a way in a Javascript/Angular application to hook into a 'request-sent' event emitted by the browser immediately after it sends off a request. The purpose is that we want to ensure/control the order of the requests that go out, and we were thinking of sending each one out in response to the previous one emitting a 'request sent' event (this way we ensure the most important requests get out first). We want to allow the requests to run asynchronously/simultaneously so we don't have the option of waiting for one request to return before sending the next one. We want to send each request as soon as we know the previous one was successfully sent.
The challenge with this is that the order in which the requests are sent in the code does not match the order we see in the Chrome network tab, so we can't rely on the sequences of events that run in the code to guarantee that the same sequence will be followed when the browser sends the requests.
This is why it would be really convenient if we could hook into a 'request sent' event fired from the browser or something of that sort. That would ensure that all requests can still go out asynchronously while also controlling the order in which they go out.
Thanks for any forthcoming help.

A: If you want to maintain the order of api calls, you can user switchMap operator.
let's say that you have two api calls:
const apiCall1$ = this.http.get("/endpoint1");
const apiCall2$ = this.http.get("/endpoint2");

and you want to wait for apiCall1 to finish before sending apiCall2, you can do it like this:
apiCall1$.pipe(switchMap(() => apiCall2$)).subscribe({
    next: (response) => {
        //do something...
    }
});


Q: Getting checkbox values in angularjs and passing them into another controller I am transitioning from jquery to angularjs. I am trying to develop a small app in SPA style. Left side is the menu that controls the content on the right side. Left side menu has its own controller. When the user selects a checkbox and clicks on 'Go', the checkbox value should be passed to the controller that controls the right side content. Here is the link to the app. Below are the issues I have.
1)I am stumped on a simple problem of accessing checked values of a checkbox. How do I access values of checked checkboxes. The checboxes are on left side menu, and I am using ng-model to currently access the values as below
index.html

          <input type="checkbox" name="firstSearch" id="firstSearch_{{searchOneCB.code}}" ng-model="main.selected[searchOneCB.code]" />
{{searchOneCB.description}}

      <button class="btn btn-primary" style="width:80px;margin-right: 10px" ng-click="main.submit()">
          Go
      </button>

MainCtrl.js to access the checkbox value.
main.submit = function() {
  console.log(main.selected);
}

The values are now in the form of an array as below
[BBBB: true, AAAA: true].

Is this the right way to access the values? What is the best way to retrieve only the checked checbox values?
2) Another question is, once I get the list of checked checkboxes values, how can I pass them to the contentCtrl.js that controls the content on right side?

A: You should inject the controller into the controller you want to use. The answer has already been answered here is the link.
How do I inject a controller into another controller in AngularJS


Q: ASP.Net MVC in shared hosting environment It's a very simple question, but I wasn't able to find exact answer.
Do you need to install anything extra besides .Net Framework 3.5 and IIS7 to run ASP.Net MVC applications?
Hope it will be useful to other people too.

A: If you don't use any third party libraries, then no.
The host has to have the .NET 3.5 SP1 installed.
However you need to be aware of the trust level issues. Most shared hosts run in medium trust mode. Although this will suffice for the MVC itself, it may not for your other code. If you use reflection for example, you will need the full trust enabled.
Basically this simple code may get you into trouble:
object something = 5;

if (something is int)
{
    // Do something
}

Check your code and choose the host wisely.


Q: When using oracle-jdk17 and gson 2.10, there is an issue that private time cannot be converted The following error occurred when using gson for conversion；
 Unable to make field private final java.time.LocalDate java.time.LocalDateTime.date accessible: module java.base does not "opens java.time" to unnamed module @7006c658
My JDK version is java 17.0.5 2022-10-18 LTS, the os is ubuntu 22.04, and the gson version is 2.10;
Here is my code
        Gson gson = new GsonBuilder().registerTypeAdapter(LocalDate.class, new LocalDateAdapter().nullSafe()).create();
        Type mapType = new TypeToken<Map<String, Object>>() {}.getType();
        Type listType = new TypeToken<List<Object>>() {}.getType();
        Map<String,Object> map = gson.fromJson(geoCode, mapType);
        String adCode = null;
        if (Objects.nonNull(map) && map.get("infocode").equals("10000")){
            List<Object> list = gson.fromJson(gson.toJson(map.get("geocodes")), listType);
            Map<String,Object> temp = gson.fromJson(gson.toJson(list.get(0)),mapType);
            adCode = String.valueOf(temp.getOrDefault("adcode","110000"));
        }
        String weatherInfo = getWeatherInfo(adCode);
        return gson.fromJson(weatherInfo, Weather.class);

public class LocalDateAdapter  extends TypeAdapter<LocalDate>   implements JsonSerializer<LocalDate>, JsonDeserializer<LocalDate> {
    @Override
    public LocalDate deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        String asString = jsonElement.getAsJsonPrimitive().getAsString();
        return LocalDate.parse(asString,DateTimeFormatter.ISO_LOCAL_DATE);
    }

    @Override
    public JsonElement serialize(LocalDate localDate, Type type, JsonSerializationContext jsonSerializationContext) {
        return new JsonPrimitive(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
    }

    @Override
    public void write(JsonWriter jsonWriter, LocalDate localDate) throws IOException {
        jsonWriter.value(localDate.toString());
    }

    @Override
    public LocalDate read(JsonReader jsonReader) throws IOException {
        return LocalDate.parse(jsonReader.nextString());
    }
}

The data structure looks like this
{"date":"2022-11-28","week":"1","dayweather":"多云","nightweather":"晴","daytemp":"14",
   "nighttemp":"-5","daywind":"西北","nightwind":"西北","daypower":"4","nightpower":"4"}


Q: Trouble with writing text to a .ini file I am working on a small game project in the Unity 3D engine. I am trying to write a class that will allow a settings menu to write the recorded settings to an .ini file. However, I can't seem to get myto write to the file. I think I wrote the class correctly to do it based upon the MSDN article on the subject. Here is my class
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine;

//Used to allow other files to access the script by name
namespace INI

{
public class iniFile {
    public string path;

    string winDir=System.Environment.GetEnvironmentVariable("windir");

    [DllImport("KERNEL32.DLL")]
    private static extern long WritePrivateProfileString(string section, string key, string value, string filePath);
    [DllImport("KERNEL32.DLL")]
    private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

    /// INIFile Constructor.
    public iniFile(string INIPath) {
        path = INIPath;
    }
    /// Write Data to the INI File
    public void IniWriteValue(string Section, string Key, string Value) {
        long success = WritePrivateProfileString(Section, Key, Value, this.path);
        Debug.Log (Section);
        Debug.Log (Key);
        Debug.Log (Value);
        Debug.Log (path);
        Debug.Log (success);
        return;
    }

    /// Read Data Value From the Ini File
    public string IniReadValue(string Section, string Key) {
        StringBuilder temp = new StringBuilder(255);
        int i = GetPrivateProfileString(Section,  Key, "", temp, 255, this.path);
        return temp.ToString();
    }
}
}

Here is my call for this class:
if (GUI.Button (new Rect (Screen.width * guiGameplayApplyButtonPlaceX, Screen.height *    guiGameplayApplyButtonPlaceY, Screen.width * guiGameplayApplyButtonSizeX, Screen.height *     guiGameplayApplyButtonSizeY), "Apply")) {
        ini.IniWriteValue("Gameplay","Difficulty","Test");
        print ("Apply");
    }

I created the instance of the class like this:
iniFile ini = new iniFile(@"..\settings\settingsTest.ini");

A: Maybe that's not the exact answer to your question, but what for you want to create file with settings? Wouldn't be much easier, to use Unity3d built-in feature for saving game preferences, which also works cross-platform?
If you want to give it a try, read about PlayerPrefs.


Q: How to structure/implement multidimensional data / data cube I've been reading into what a data cube is and there are lots of resources saying what it is and why (OLAP/ business intelligence / aggregations on specific columns) you would use one but never how.
Most of the resources seem to be referencing relational data stores but it doesn't seem like you have to use an RDBMS.
But nothing seems to show how you structure the schema and how to query efficiently to avoid the slow run time of aggregating on all of this data.  The best I could find was this edx class that is "not currently available": Developing a Multidimensional Data Model.

A: You probably already know that there are 2 different OLAP approaches:

*

*MOLAP that requires data load step to process possible aggregations (previously defined as 'cubes'). Internally MOLAP-based solution pre-calculates measures for possible aggregations, and as result it is able to execute OLAP queries very fast. Most important drawbacks of this approach come from the fact that MOLAP acts as a cache: you need to re-load input data to refresh a cube (this can take a lot of time - say, hours), and full reprocessing is needed if you decide to add new dimensions/measures to your cubes. Also, there is a natural limit of the dataset size + cube configuration.

*ROLAP doesn't try to pre-process input data; instead of that it translates OLAP query to database aggregate query to calculate values on-the-fly. "R" means relational, but approach can be used even with NoSQL databases that support aggregate queries (say, MongoDb). Since there is no any data cache users always get actual data (on contrast with MOLAP), but DB should able to execute aggregate queries rather fast. For relatively small datasets usual OLTP databases could work fine (SQL Server, PostgreSql, MySql etc), but in case of large datasets specialized DB engines (like Amazon Redshift) are used; they support efficient distributed usage scenario and able to processes many TB in seconds.

Nowadays it is a little sense to develop MOLAP solution; this approach was actual >10 years ago when servers were limited by small amount of RAM and SQL database on HDD wasn't able to process GROUP BY queries fast enough - and MOLAP was only way to get really 'online analytical processing'. Currently we have very fast NVMe SSD, and servers could have hundreds gigabytes of RAM and tens of CPU cores, so for relatively small database (up to TB or a bit more) usual OLTP databases could work as ROLAP backend fast enough (execute queries in seconds); in case of really big data MOLAP is almost unusable in any way, and specialized distributed database should be used in any way.

A: The general wisdom is that cubes work best when they are based on a 'dimensional model' AKA a star schema that is often (but not always) implemented in an RDBMS. This would make sense as these models are designed to be fast for querying and aggregating.
Most cubes do the aggregations themselves in advance of the user interacting with them, so from the user perspective the aggregation/query time of the cube itself is more interesting than the structure of the source tables. However, some cube technologies are nothing more than a 'semantic layer' that passes through queries to the underlying database, and these are known as ROLAP. In those cases, the underlying data structure becomes more important.
The data interface presented to the user of the cube should be simple from their perspective, which would often rule out non-dimensional models such as basing a cube directly on an OLTP system's database structure.


Q: I have hbase metadata in gcs from another environment. I want to create table from this but not sure how? I have a Hbase table extract in google cloud bucket from SIT environment. I want to create a hbase table using that but I am not sure how to do it. I tried creating dummy table and pushing the data inside of it but it didn't worked out. Any help is appreciated. Thank You !
I tried creating hbase table from metadata stored in gcs but somehow the data is not visible in the new table created. I want to use the data to create hbase table so I can continue my development.


Q: How to navigate to a route without routerLink in angular2 I am working with nebular framework, from the amazing guys at akveo.
One of the components is a context menu that creates a popup menu with it's options read from an array
items = [{ title: 'Profile' }, { title: 'Log out' }];

I want to navigate to a different screen but tutorials talk mostly about routerLink

This is my link out

But in this case, I can't add a  tag because they abstracted the click event and allow you to subscribe like
this.menuService.onItemClick()
  .pipe(
    filter(({ tag }) => tag === 'my-context-menu'),
    map(({ item: { title } }) => title),
  )
  .subscribe(title => {
    console.error(`${title} was clicked!`)
  });

And that prints when each button was clicked, but I have to trigger the navigation inside the .subscribe() function.
How to do so?

A: First of all, the outer route has got to exist, in some routing.module
// app-routing.module.ts
const routes: Routes = [
  { path: 'getMeOut', component: OutComponent },
  ..
]

Four things are needed then

*

*Import Router from @angular/router.

*Create a private router in your constructor private router: Router.

*Call navigateByUrl() with the desired route.

*Identify your context menu with the nbContextMenuTag property.

Then, in the module that holds the context menu, we create the router to handle the navigation like
// awesome.component.ts
import { Router } from '@angular/router'
import { NbMenuService } from '@nebular/theme';

@Component({
  selector: 'awesome',
  styleUrls: ['./awesome.component.scss'],
  templateUrl: './awesome.component.html',
})

ngOnInit() {
  this.menuService.onItemClick()
  .pipe(
    filter(({ tag }) => tag === 'my-context-menu'),
    map(({ item: { title } }) => title),
  )
  .subscribe(title => {
    if (title === 'Log out') this.router.navigateByUrl('/getMeOut');
    console.error(`${title} was clicked!`)
  });
}

constructor(
  private menuService: NbMenuService,
  private router: Router) {
}

See the simple use of navigateByUrl from @angular/router.
Just add nbContextMenuTag="my-context-menu" to the html template
<nb-action *nbIsGranted="['view', 'user']" >
 <nb-user nbContextMenuTag="my-context-menu"></nb-user>
</nb-action>

I hope it's not a dupe. I found this answer but it meant more about nested routers.