text:
Q: I am not able to fetch items from the NgRx store and the observable remains undefined import { Post } from './models/post.model';
import { AppActions, SET_POSTS } from './app.actions';

export interface State {
    posts: Post[]
}

const initialState: State = {
    posts: []
}

export function appReducer(state = initialState, action: AppActions) {
    switch(action.type) {
        case SET_POSTS:
            return {
                ...state,
                posts: action.payload
            }
        default:
            return state;
    }
}

export const getPosts = (state: State) => state.posts;

So this is what I have on the reducer end, I don't think there's anything wrong with it I wrote it from the examples provided on the official documentation.
  ngOnInit() {
    this.posts$ = this.store.select(fromPost.getPosts);
    this.postService.getPosts();
  }

Now, the postService is working and I have been able to confirm this by logging it, but for some reason it never gets populated.
 .subscribe((posts: Post[]) => {
    this.store.dispatch(new AppAction.SetPosts(posts));
 }

When I log posts, I get the expected output, so I am wondering if it's the dispatch that's being improperly called or handled.
import { Action } from '@ngrx/store';
import { Posts } from './models/post.model';

export const SET_POSTS = 'Set Posts';

export class SetPosts implements Action {
    readonly type = SET_POSTS;

    constructor(public payload: Post[]) {}
}

export type AppActions = SetPosts;

This is the post actions, so I don't see anything wrong with it or is there?
Update:
   this.posts$ = this.store.select(fromPost.selectPosts);
   this.postService.getPosts();
   console.log(this.posts$);
   this.posts$.subscribe( value => console.log(value));
   //Object { _isScalar: false, actionsObserver: {…}, reducerManager: {…}, source: {…}, operator: {…} }

   //undefined

I also made some changes in the reducer:
const getPosts = (state: State) => state.posts;

export const selectState = (state: State) => state;
export const selectPosts = createSelector(
  selectState,
  getPosts
);

I am still getting nothing when I do this in my html file:
<div *ngIf="(posts$ | async) as posts">
  <div *ngFor="let post of posts">
    {{ post.title}}
  </div>
</div>

A: Short answer, you have write a selector to bind the post to the UI.
Create Selector.ts file
import { createSelector } from '@ngrx/store';
import * as fromPost from 'post.reducer'

export const selectState = (state: State) => state;
export const selectPost = createSelector(
  selectState,
  fromPost.getPosts
);

In your component
constructor() {
  this.store.dispatch(new LoadPost())
}

ngOnInit() {
    this.posts$ = this.store.select(selectPost);
  }

Create an effect that calls postService, async services are side effects to the store and should be handled through Effects.
Documentation for Setting up effects
create posts action.ts
import { Action } from '@ngrx/store'

export enum PostActionTypes {
  LoadPost = '[Post] Load Post',
  SetPosts = '[Post] Load Post Success',
  LoadPostFailure = '[Post] Load Post Failure',
}

export class LoadPost implements Action {
  readonly type = PostActionTypes.LoadPost
}

export class SetPosts implements Action {
  readonly type = PostActionTypes.SetPosts
  constructor(public payload: Post[]) {}
}

export class LoadPostFailure implements Action {
  readonly type = PostActionTypes.LoadPostFailure
  constructor(public payload: any) {}
}

export type PostActions =
| LoadPost
| SetPosts
| LoadPostFailure

create Post effect.ts
import { Injectable } from '@angular/core'
import { Actions, ofType } from '@ngrx/effects'
import { of } from 'rxjs'
import { catchError, map, switchMap } from 'rxjs/operators'

@Injectable()
export class PostEffects {
  constructor(private postService: PostService, private actions$: Actions) {}

  @Effect()
  loadPosts$ = this.actions$.pipe(
    ofType(PostActions.LoadPost),
    switchMap(() => {
      return this.postService.getPosts().pipe(
        map(posts => new SetPosts(posts)),
        catchError(error => of(new LoadPostFailure(error)))
      )
    })
  )
}

NOTE: Effects are Injectable classes, make sure you add them to
NgModule({
  declarations: [],
  imports: [
    ...
    EffectsModule.forRoot([ ... effects ]), // Effect classes as CSV
    ...
  ]
})


text:
Q: Actions to create secret on K8S I'm trying to create a secret in k8s using github actions like following (I've pre step which install lightweight k8s - k3s)
  - name: example tests
    shell: bash
    env:
      SUPER_SECRET: ${{ secrets.KUBECONFIG }}
   run: |
       kubectl create secret generic mysec --from-literal="$SUPER_SECRET" -n default

But I got error, any idea how to do it using github actions?
I use the settings->secrets and create a KUBECONFIG value and put the file content
in my local env I created a secret successfully  with a kubeconfig file like:
 kubectl create secret generic mysec --from-file=./kubeconfig -n default

But in the CI I want to use it from the secret env in github ...
The error is: Error: Error: The process '/usr/local/bin/kubectl' failed with exit code 1
Error: ENAMETOOLONG: name too long, open '/home/runner/work/_temp/*** *** *** *** *** ***
What am I missing here?
I tried also with
kubectl create secret generic mysec --from-literal kubeconfig=$SUPER_SECRET -n default
If there is other way to make it work please let me know.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to prevent to use specified class/method in code with static analysis tools? We have many teams with a lot of java code.
For avoiding performance issue, we want to prevent to use some specified classes/methods on many code repositories.
How to prevent to use specified class/method in code with static analysis tools, like CheckStyle, Sonarqube?

A: This sounds like a good candidate for Checkstyle's
IllegalType and IllegalImport checks. Also, for finer granularity, you can use ImportControl.
Additionally, in your configuration, you can forbid certain methods as follows, using MatchXPath:

<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
        "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
        "http://www.puppycrawl.com/dtds/configuration_1_3.dtd">

<module name="Checker">
    <property name="charset" value="UTF-8"/>

    <module name="TreeWalker">
        <module name="MatchXpath">
            <property name="query" value="//METHOD_CALL//DOT[.//IDENT[@text = 'yourForbiddenMethod']]"/>
            <message key="matchxpath.match"
                     value="Avoid using deprecated method 'yourForbiddenMethod()'."/>
        </module>

    </module>
</module>

Code example:

public class Test {
    static int method(Object args) {
        return AllowedClass.yourForbiddenMethod(args);
    }
}

Result:
➜  src java -jar checkstyle-8.42-all.jar -c config.xml Test.java
Starting audit...
[ERROR] /src/Test.java:3:29: Avoid using deprecated method yourForbiddenMethod(). [MatchXpath]
Audit done.
Checkstyle ends with 1 errors.

A: You can also try JArchitect, with cqlinq you can create your custom rules to detect all the uses of specific classes/methods.

A: You might take a look at ArchUnit. I suspect you could use it to write some unit tests to look for the classes/packages you want to forbid and to throw errors if it encounters them.
You can also write custom checks for Checkstyle


text:
Q: Client side validation for image width/height before upload, ASP.NET MVC5 I am trying to validate width and height of image before upload.
I created a validation attribute and server side works as expected, but i can not manage to fix the client side validation.
This is the custom validation attribute
public class ImageDimensionsAttribute : ValidationAttribute, IClientValidatable
    {
        private readonly int _width;
        private readonly int _height;
        private readonly string _dims;

        public ImageDimensionsAttribute(int width, int height)
        {
            _width = width;
            _height = height;
            _dims = String.Format("{0},{1}", _width, _height);
        }

        public override bool IsValid(object value)
        {
            if (value == null) return true;
            var file = value as HttpPostedFileBase;

            using (var img = Image.FromStream(file.InputStream))
            {
                return img.Width <= _width && img.Height <= _height;
            }
        }

        public override string FormatErrorMessage(string name)
        {
            return string.Format(Messages.InvalidImageDimensions, _width, _height);
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                ValidationType = "imagedimensions"
            };
            rule.ValidationParameters.Add("dims", _dims);
            yield return rule;
        }
    }

and my javascript
$(function () {
        $.validator.addMethod("imagedimensions", function (value, element, params) {
            if (value == null)
                return true;

            var file = element.files[0];
            var reader = new FileReader();
            var image = new Image();
            var sizes = params.split(",");
            var maxWidth = parseInt(sizes[0]);
            var maxHeight = parseInt(sizes[1]);

            var result = false;
            reader.readAsDataURL(file);
            reader.onload = function (_file) {
                image.src = _file.target.result;
                image.onload = function () {
                    var w = this.width,
                        h = this.height
                    console.log(w, h);
                    if (w > maxWidth || h > maxHeight) {
                        return false;
                    } else {
                        console.log("i am valid size but validator can not await");
                        return true;
                    }
                };
            };
        });

        $.validator.unobtrusive.adapters.addSingleVal("imagedimensions", "dims");
    }(jQuery));

Seems like javascript function does not await till reader.onload executes so it ALWAYS returns false - everything invalid. I am looking for a way to make javascript "await".


text:
Q: How to sendkeys element using R programming? I have tried to sendkeysElement using R programming. Here is my code
require(RSelenium)
remdir<-remoteDriver()
remdir$open()

remdir$navigate("http://www.flipkart.com")
sbox<-remdr$findElement(using = 'name',"q")

sbox$sendkeysToElement(list("laptops",key="enter"))

But I got the error like this
Error in checkError(res) :
Undefined error in httr call. httr output: length(url) == 1 is not TRUE

A: You have a number of typo's which maybe an issue. The code works with chrome:
require(RSelenium)
rD <- rsDriver()
remdir<- rD$client
remdir$open()

remdir$navigate("http://www.flipkart.com")
sbox <- remdir$findElement(using = 'name',"q")

sbox$sendKeysToElement(list("laptops",key="enter"))
rm(rD)
gc()


text:
Q: Speed of photons in Cosmic Microwave Background Radiation relative to the earth (or solar system) At https://living-universe.com/questions-and-answers/absolute-motion-of-photons-in-the-2-7cbr/, we are told that the Cosmic Microwave Background Radiation (CMBR) is propagating relative to the earth (or solar system) at the speed of 375 km/sec. If we treat the frame that the earth (or solar system) is moving in as an inertial frame, then the speed of the photons in the CMBR relative to this inertial frame is only 375 km/sec. But 375 km/sec is far slower than the speed of light, 3 x 10^8 m/sec, or 3x10^5 km/sec. Therefore, the speed of the photons in the CMBR relative to the chosen inertial frame (earth or solar system) is about 1000 times slower than the expected speed of light. How does this difference in speed square with special relativity which says the speed of light (or photons) relative to any inertial frame is the constant, c, which is 3 x 10^8 m/sec? Or can we avoid this discrepancy with special relativity by saying that the frame in which the earth (or solar system) is moving is not an inertial frame? Even if we say that, will that be enough to account for the great difference between the speed of the photons in the CMBR relative to the chosen inertial frame (earth or solar system) and c?

A: You are confusing the principle of the constancy of the speed of light with the phenomenon of relativistic Doppler shift. Although the speed of light is always the same, the frequency of light can be increased or reduced as a consequence of relative motion between the observer and the source of the light. When we examine the CMB, we find it is redshifted in one direction and blue-shifted in another, suggesting that we are moving relative to it. That motion is motion relative to a the frame in which the CMB originated, not relative to the individual photons in the CMB, as they all move at a constant speed of c.


text:
Q: How to maintain the order of the parameters on the return I have a query that searches for a table with various ids, I would like the return of the data to be in the same order as the parameters
Query:
SELECT * FROM products WHERE products.idProduct IN (332,2,3)
This query returns the data in order
2...\
3...\
332...

Expected result:
332...\
2...\
3...

Is there any way I can run this?


text:
Q: Fourier Series of Triangular waveform Fourier Series of Triangular waveform

this is the solution of Fourier series of a triangular waveform from the book Circuits and Networks: Analysis and Synthesis by Shyammohan S. Palli.
In this problem they have take the time period of the triangular waveform from  -π to +π instead of 0 to 2π.
Now, from -π to 0 the equation of the waveform is as shown below

and from 0 to +π the equation of the waveform is

Which gives

My question is,
If i take the interval from 0 to 2π.then from 0 to +π the equation of the waveform will be

and from +π to +2π the equation of the waveform will be

But this gives

which did not match with previous.My question is why they took the interval from -π to +π instead of 0 to 2π.
I will post my calculation here


text:
Q: Increasing video height and width in Blackberry player screen I am playing video in Blackberry,it plays well but i need to show the video in full screen mode.Now it plays video with spaces at top and bottom i have to play in full screen
For this i used methods
videoControl.setDisplayFullScreen(true);
_videoControl.setDisplaySize(Display.getWidth(),Display.getHeight());

But those are not working how can i solve this.

A: The video player can be incredibly fickle when it comes to what sizes it will display. From my testing, it seems that you have to hit one of the magic ratios (half size seemed to work pretty reliably) or it just won't show anything.
Rather than setting the size that would equal fullscreen as well as telling it to be fullscreen, you should probably use VideoControl.setDisplayFullScreen() without the setDisplaySize()
I have an answer about camera programming that might help Black berry camera programming


text:
Q: Optimize development Virtual Machine As a best practice I use a virtual machine for my development - I would like to try and optimize my VM as much as possible. All I have installed is server 2003, IIS and Visual Studio 2008.
What do you do to optimize your development VM i.e what service do you switch off etc...

A: I switch off the file system indexer, saving disk space and CPU time.

A: I always disable "System Restore" on my Windows XP virtual PCs.

A: Ixclude my build folder from my virus guard for on access scans
These are the services that I turn off in my VM

*

*Turned off Shutdown event tracker

*Switched off indexing on c:\

*Error Reporting Service switched off

*Smart Card Access switched off

*TCP/IP NetBIOS Helper

*Remote Desktop Help Session Manager

*Remote Registry

*Uninterruptible Power Supply

*Windows Audio

*Wireless Zero Configuration

A: Putting the disk images on external HDD  (even usb) can improve performance (with a laptop specifically)

A: There is a great article about Virtual Machine performance here
It's written specifically about Sharepoint virtual machines, but there are plenty of tips that apply in general.

A: As always, there is no single set of recommendations that are universally "correct" or "best". However, these are some of the items that have worked well for my development virtual environments.
Hardware Tips

Plenty of memory!
Determine how much memory each one of your virtual machines require and how much memory your host requires (if you are running things in the host at the same time). Add up the total of memory requirements for all VMs that will be running simultaneously and determine the maximum VM RAM load and add in the host load. I suggest having at least 512MB of "padding"
For example, I need about 768MB for the host OS (WinXP Pro SP3) and about 1GB in my guest OS (WinXP Pro SP3 w/ Visual Studio 2005/2008 and SQL Server Developers Edition).
1024MB + 768MB + 512MB = 2.3GB
Personally, since RAM is incredibly cheap currently, I just maxed out my 32-bit system with 4GB (3.5 addressable).
Separate Spindle for your OS and VMs
Have a disk separate from your OS disk to run your virtual machine images. This greatly reduces the disk I/O contention between the Host  and the Guests.
NOTE: Using an external HDD to get the spindle separate can help, but beware - Firewire and USB have higher latency than IDE, SATA, or SCSI! While the USB 2.0 and Firewire interfaces have more than sufficient bandwidth for maximum disk throughput they do add a significant amount of latency to each operation. This becomes very significant in high disk transaction, small file accesses situations like C++ compilation. I haven't had a chance to run some tests on eSATA yet to see how well it performs in comparision to internal SATA access times.
Use Disks with Low Access Times
During development there is quite a bit of random disk access occuring, especially during compilation in languages like C++. Using a 7200 RPM over a 5400RPM drive for your VMs reduces access times and thus, reduces compile times. Going to a 10,000RPM or high-end SSD reduces these times further. The point of diminishing returns depends on the particular disk access load/patterns of your environment.
Host Tips

Disable Virtual Machine File Virus Scanning
Tell your virus scanner to ignore your Virtual Machine directory OR the .vmdk file extension so that it won't be constantly scanning your virtual machine disks.
Avoid CPU contention
If you are running more than one virtual machine at a time OR you are doing work both in the host and the guest OS, then save at least 1 CPU for the host OS on a multi-core/proc machine.
For example, if you are running two virtual machines and doing no work in the host OS then a dual core processor on the host with single core virtual machines will probably serve you best.
If you are running a single virtual machine and no work on the host OS, then running a dual processor VM may be helpful if the virtual machine applications can make use of the second processor.
If you are running two virtual machines, 1 which is single proc and 1 which is dual proc, you probably need to be running a quad-core system.
VMware Note (not confirmed for other virtualization applications): If you give a virtual machine multiple processors, it will wait for both processors to become available and will reserve them even if it isn't using them. This can cause significant contention between virtual machines or between the virtual machine and the host.
Guest Tips

Allocate sufficient memory
Make sure you allocate enough RAM to cover the virtual machine's demand
Avoid using snapshots
Don't use snapshots unless you really need to. There is a significant disk I/O penalty associated with maintaining a snapshot based virtual machine file system.
Don't run unnecessary services
Such as:

*

*Indexing

*System Restore

*Error Reporting

*Wireless Zero Configuration

Don't run security software
Consider not running anti-virus, anti-spyware, or firewall software within your VM. You'll have to weigh the pros/cons of security vs speed here. For many, if they get a virus it's not a problem, they just restore a previous copy or snapshot. For others, the potential exposure of sensitive information requires strict security policies even within the VM.
I will say that not running anti-virus or firewall software within the VM is probably the number one reason that VMs of Windows often feel "snappier" than their physical host OS counterparts.
Defragment!
Unfortunately, there are three places file fragmentation can occur in a VM configuration: Within the Guest OS's filesystem, within the virtual machine file's (e.g. vmdk) representation of the VM, and the virtual machine file on the physical disk itself. The order in which you defragment each matters.

*

*First, defragment the filesystem within the guest OS (e.g. run disk defragmenter in the guest OS or use a tool like JkDefrag or Defraggler, etc within the guest OS)

*Second, defragment the virtual machine file (e.g. VMDK) using tools such as vmware-diskmanager

*Third, defragment the file system on the host which holds the virtual machine file (i.e. run disk defragmentation on the host OS)

A: I disable the Windows page file when using VMware Server.  Disk IO is the weakest link with VMWare Server, and nothing is worse than paging virtualized RAM to a virtualized disk file.  Give your VM enough RAM and this works pretty well.
Also, not all virtualization solutions perform the same in different areas.  VMware is great for stability and mobility of VM images, but you might want to try some other solutions if you have the time.  I've found that better disk IO performance gives me a better overall experience, so I traded the better CPU performance (and overall stability, unfortunately) of VMware server for the better IO performance of VirtualBox.  The non-free VMware versions may be much better, but I have no idea.
I've found that putting the disk images on a separate drive doesn't buy you that much.  Plenty of people will argue this, and it can give you a little bit more performance depending on how much else is going on with the host, but for me it was marginal.  I tried using a raw disk also, which didn't do as much as I'd hoped.
One thing that does really kill IO performance is running with a snapshot active.  This uses a copy-on-write strategy on most implementations, and you can expect 20% drop in disk performance.

A: I recently built a VM and I started to optimize it before I even did the install by using Nlite and Windows Update Downloader.  NLite allows you to strip out all the components you don't need (mspaint,pinball,french, etc.), apply all your windows updates, and tweak out registry and service settings.  So you can have the System Indexer disabled on first boot for example.  If your using Vista or 2008 Vlite is available as well.

A: Two SSDs, one for the host's OS and one for the VMs.

A: You can use this free tool by Quest to optimize a virtual desktop. It turns off a bunch of stuff.
http://communities.quest.com/community/vworkspace/blog/2011/09/08/introducing-the-free-quest-vworkspace-desktop-optimizer
Full disclosure: I work for Quest but did not work on this tool.


text:
Q: Chrome Web Push Notification with Encrypted Payload in Python Can someone please explain how to send Web Push Notification with Payload for Chrome using Curl/Python ?
This is the code I am trying:
Code:
fcm_url = "https://fcm.googleapis.com/fcm/send"
headers = {'Content-Type': 'application/json'}
headers.update({'Authorization': 'key=' + fcm_key})

encoded = {'body': "i\x87\xb7W\xee\xd6QzL\xb6Q\xfe\xf5=t\xc4D[\xfe\xe3+g\xb7\x86\xdd\x81\xb9I\xffX\x99\x9b\x85$x\x80\xc6\x88\xe3\xbcm\x91\xff\x17a\x87C\x81\xf0\xbd\xb3}Y\xc8\xdb:\x14\x02\xf2R\xe7\x12\xcb\x1c\x0f\x13\xca'\xec7B\xc3\x9e\xb2\x17\xa0\xf0\xcd\xed3\xff\x1e\xc9k'A\xfb\x84\xf0\x17\xd4+I\xe0\xe0\x92i%\x00\xf0\xe0\xdb[\xa5\xc9/'\xc3L\xf6a\x183\xc1x7\xa6\x04!\xcctH\xf3\xf3\xcf\xf5\x12r\xd3\xf4\xd4\x8b\x10pc\x84Dd\xee\xe5'\x82\xa8\x81\x9a\xf4\x94\xd3\x12\x166\x91G3t\x08\xf9\xbe\x1b\x90\x02\xc6\x17\x17\xc3\xe9\x08qQK\xd4\xce\xc2\x88\x8f\xcbA\xc9\xfd]\x99\x13\xfd\xa6v2\xd65\x1b\xd5\x82)FUX\x92c\xed\xecF\x91rk\xba\x04\xd2\x90\x93a\n\x96|M}\x10\xc4\xb0\xe4\xdd\x1dd4\xf1\xcb\x06<\xf7\x06\xf9\xfe\xce\x19W\xaa\xc4", 'crypto_key': 'BJUZv_0v3lqIkptS5R4r-DKbVXl4Cpd4YN4ASO4dcNzEGPgtNW7EDF2HBSNGy0fI8kBJj3bnSuCh0bmR46ICKpc', 'salt': 'bjNe7m6zIQeDcsh4TF_wqg'}

crypto_key = "dh=" + encoded["crypto_key"]
salt = "salt=" + encoded['salt']
headers.update({'crypto-key': crypto_key, 'content-encoding': 'aesgcm', 'encryption': salt})
fcm_data = {"data": {"message": base64.urlsafe_b64encode(encoded['body'])}, "registration_ids": google_ids_array}
resp = requests.post(fcm_url, data=json.dumps(fcm_data), headers=headers)

Response:
(200, 'OK')
{"multicast_id":66796434737498,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:14768189819%063a1cbcf9fd7ecd"}]}

but the notification doesn't contain the above specified Data.
Cases Tried, But None Useful:
1) fcm_data = {"data": {"message": "Hello"}, "to": google_ids_array[0]} # Wrong Notification
2) fcm_data = {"data": {"message": "Hello"}, "registration_ids": google_ids_array} # Wrong Notification
3) fcm_data = {"data": {"message": base64.urlsafe_b64encode(encoded['body'])}, "to": google_ids_array[0]} # Wrong Notification
4) fcm_data = {"data": {"message": base64.urlsafe_b64encode(encoded['body'])}, "registrations_ids": google_ids_array} # Bad Request, to

5) fcm_data = {"raw_data": "He", "registration_ids": google_ids_array} # success, No Notification
6) fcm_data = {"raw_data": str({"message": "Hello"}), "registration_ids": google_ids_array} # Failure, MessageTooBig
7) fcm_data = {"raw_data": base64.urlsafe_b64encode(encoded['body']), "registration_ids": google_ids_array} # Failure, MessageTooBig

Can someone please suggest how to send correct Web Notification with Payload on Chrome Browser ?
Any Suggestion/Hint would be helpful...
Thanks,

A: Working Code
fcm_url = "https://fcm.googleapis.com/fcm/send"
encoded = {'body': "i\x87\xb7W\xee\xd6QzL\xb6Q\xfe\xf5=t\xc4D[\xfe\xe3+g\xb7\x86\xdd\x81\xb9I\xffX\x99\x9b\x85$x\x80\xc6\x88\xe3\xbcm\x91\xff\x17a\x87C\x81\xf0\xbd\xb3}Y\xc8\xdb:\x14\x02\xf2R\xe7\x12\xcb\x1c\x0f\x13\xca'\xec7B\xc3\x9e\xb2\x17\xa0\xf0\xcd\xed3\xff\x1e\xc9k'A\xfb\x84\xf0\x17\xd4+I\xe0\xe0\x92i%\x00\xf0\xe0\xdb[\xa5\xc9/'\xc3L\xf6a\x183\xc1x7\xa6\x04!\xcctH\xf3\xf3\xcf\xf5\x12r\xd3\xf4\xd4\x8b\x10pc\x84Dd\xee\xe5'\x82\xa8\x81\x9a\xf4\x94\xd3\x12\x166\x91G3t\x08\xf9\xbe\x1b\x90\x02\xc6\x17\x17\xc3\xe9\x08qQK\xd4\xce\xc2\x88\x8f\xcbA\xc9\xfd]\x99\x13\xfd\xa6v2\xd65\x1b\xd5\x82)FUX\x92c\xed\xecF\x91rk\xba\x04\xd2\x90\x93a\n\x96|M}\x10\xc4\xb0\xe4\xdd\x1dd4\xf1\xcb\x06<\xf7\x06\xf9\xfe\xce\x19W\xaa\xc4", 'crypto_key': 'BJUZv_0v3lqIkptS5R4r-DKbVXl4Cpd4YN4ASO4dcNzEGPgtNW7EDF2HBSNGy0fI8kBJj3bnSuCh0bmR46ICKpc', 'salt': 'bjNe7m6zIQeDcsh4TF_wqg'}

crypto_key = "dh=" + encoded["crypto_key"]
salt = "salt=" + encoded['salt']
headers = {'Authorization': 'key=' + fcm_key, 'Content-Type': 'application/json', }
headers.update({'crypto-key': crypto_key, 'content-encoding': 'aesgcm', 'encryption': salt})
fcm_data = {"raw_data": base64.b64encode(encoded.get('body')), "registration_ids": google_ids_array}
resp = requests.post(fcm_url, data=json.dumps(fcm_data), headers=headers)

For Encoding The Payload, you can refer to this Python Library: https://github.com/web-push-libs/pywebpush
Thanks


text:
Q: CMS projects to learn from? There have been quite a few questions about CMS systems but I wonder if there are any good open-source versions available that support ASP.NET MVC (preferably 2.0) and work well with SQL Server?
I'm not looking for a CMS system to use, although that will probably happen too. I'm looking for a CMS system to learn from! So basically, it should follow the KISS principle.
Yeah, I know about DotNetNuke. It looks okay but it feels like overkill to me. There should be alternatives, right?

And no, I'm not a beginner! My web development skills go back to the time when Internet Explorer was still displaying static pages on a Windows 3.11 system when RAM was still measured in kilobytes and with CompuServe as provider over a 33k6 model phone line. But it never hurts to learn from existing code.

A: as far as whats readily available DNN is the best to go with and although it may seem overkill after a few hours of stepping through code you will see the patterns used and understand the DNN system is not so large as it first seems. Also the core DNN team has their code reviewed and gets much input from Microsoft corp when they want to showcase new features of the .net framework.
other than DNN there is a commercial CMS built in .net called Ektron (AKA CMS400). what a terrible system. i had the misfortune of having to use this at one job and on top of being slow it is terribly buggy as well. it has some good features but i wouldn't recommend learning from it cause the results are lack-luster at best.
good luck

A: There are very few CMS systems based on MVC, as the technology is so new.  The only open source one I am aware of is MyTrip.MVC.  It's pretty basic, so doesn't have all the bells and whistles, but seems well put together.


text:
Q: Python Assign Value to New Column If Contains() Is True How can I use the str.contains() method to check a column if it contains specific strings and assign a value if true in a different column?  Essentially, I'm trying to mimic a CASE WHEN LIKE THEN syntax in SQL but in pandas.  Really new to python and pandas and would appreciate any help!  Essentially, I want to search 'Source' for either video, audio, default, and if found, then Type would be video, audio, default accordingly.  I hope this makes sense!
Source                 Type
video1393x2352_high    video
audiowefxwrwf_low      audio
default2325_none       default
23234_audio            audio

A: Use the str.extract method ... takes a regular expression as an argument ... returns matched group as a string ...
df['Type'] = df.Source.str.extract('(video|audio|default)')

For some case sensitivity you could add ...
df['Type'] = df.Source.str.lower().str.extract('(video|audio|default)')

Example, including a non match follows ...
In [24]: %paste
import pandas as pd

data = """
Source
video1393x2352_high
audiowefxwrwf_low
default2325_none
23234_audio
complete_crap
AUDIO_upper_case_test"""

from StringIO import StringIO # import from io for python 3
df = pd.read_csv(StringIO(data), header=0, index_col=None)

df['Type'] = df.Source.str.lower().str.extract('(video|audio|default)')
## -- End pasted text --

In [25]: df
Out[25]:
                  Source     Type
0    video1393x2352_high    video
1      audiowefxwrwf_low    audio
2       default2325_none  default
3            23234_audio    audio
4          complete_crap      NaN
5  AUDIO_upper_case_test    audio

A: Try using numpy.where or pandas.DataFrame.where. Both take a boolean array and conditionally assign based on that.
In [4]: np.where([True, False, True], 3, 4)
Out[4]: array([3, 4, 3])

http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html
You would construct the boolean array using str.contains, and then pass it to the where method.

A: Try something like:-
import re
input_values = ['video1393x2352_high', 'audiowefxwrwf_low', 'default2325_none', '23234_audio']
pattern = re.compile('audio|video|default')
res_dict = {}
for input_val in input_values:
    type = pattern.findall(input_val)
    if type:
        res_dict[input_val] = type[0]

print res_dict #{'23234_audio': 'audio', 'audiowefxwrwf_low': 'audio', 'video1393x2352_high': 'video', 'default2325_none': 'default'}


text:
Q: For matrix $A$, find all real numbers $k$ for which there exists a nonzero vector $v$ s.t. $Av = kv$. Find all real numbers $k$ for which there exists a nonzero, 2-dimensional vector $v$ such that
$$\begin{pmatrix} 2 & 12 \\ 2 & -3 \end{pmatrix} {v} = k {v}.$$

I tried expanding but I could not collect anything from the equations I got. I have not learned eigenvalues and eigenvectors yet.

A: Find the eigenvectors $\nu = (-3,2)$ and $(4,1)$ and corresponding eigenvalues $-6$ and $5$.

A: HINT
If your matrix on the LHS is $A$, you are solving $A \vec{v} = k \vec{v}$ which is equivalent to $(A - kI) \vec{v} = \vec{0}$. Could you solve the resulting 2 equations?

A: You haven't learned about eigenvalues yet, but this question is identical to asking for eigenvalues for the matrix $A = \begin{bmatrix} 2& 12 \\ 2 & -3 \end{bmatrix}$. There is a standard procedure for finding eigenvalues. For our particular matrix $A$, this goes as follows:
First we deform the problem into something that we can calculate. We see that for $k \in \mathbb{R}$, $\exists v \neq 0$ such that $Av = kv$ if and only if $\exists v \neq 0$ such that $(A - kI)v = 0$. But $\exists v \neq 0$ such that $(A - kI)v = 0$ if and only if $A - kI$ is not invertible (this is a fact about square matrices). $A - kI$ is invertible if and only if $det(A - kI) \neq 0$. And the great thing about this last point is that we can calculate whether $det(A - kI) \neq 0$ for any $k$, using the formula for determinant:
\begin{align*}
det(A - kI) = & \
det \left( \begin{bmatrix} 2 - k & 12 \\ 2 & -3 -k \end{bmatrix} \right) \\
= &  (-3-k)(2-k) - 12*2 \\
= &  k^2 + k - 30 \\
= & (k+6)(k-5)
\end{align*}
Therefore $det(A - k I ) = 0$ whenever $k = -6$ or $5$. We conclude that the values of $k$ such that there exists a nonzero $v \in \mathbb{R}^2$ such that $A v = kv$ are $-6$ and $5$.


text:
Q: Keep changing active bootstrap on every button click I am using bootstrap tabs. There are 6 tabs and the 1st tab is active on page load.

People

Current Performance

Tools

Collaboration Enablers

Infrastructure

Practices

Now i have a grid-view for with some labels, radio buttons and Next and previous buttons.
So i want the active tab to change every time i click next button. How to do that?
Initially PEOPLE tab is active. On next click CURRENT PERFORMANCE should be active.


text:
Q: Change logo on scroll Shopify dawn theme I would like to know how to use javascript to change the source of the logo image after scrolling a certain amount in shopify dawn theme.

A: This isn't tested but you can do it like this
const heightToAdjustElement = 350;
const newLogoSrc = "cdn.shopify.com/s/files/1/0551/9242/0441/files/Dawn_logo_90x.png"

window.addEventListener('scroll', (event) => {
  if (document.body.scrollTop > heightToAdjustElement || document.documentElement.scrollTop > heightToAdjustElement) {
  document.querySelector('.header__heading-logo').src = newLogoSrc;
}
});

You should create a new section setting for the alternative logo too and link the js variable newLogoSrc with what ever that is something like {{ section.settings.alternative_logo }}
https://developer.mozilla.org/en-US/docs/Web/API/Element/scroll_event
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop

A: Try these CSS code
  .shopify-section-header-sticky .header__heading-link{
    background-image: url("https://cdn.shopify.com/s/files/1/0678/1567/0065/files/GrowGen-web-logo-2021_new_1_2.png?v=1668927470&width=250");
    background-size: cover;
    background-repeat: no-repeat;
    width: 250px;
    height: 90px;

    }

  .shopify-section-header-sticky img{
    display:none;
  }


text:
Q: how to set values of textboxes inside a wpf listview? in a WPF application I have a listview with multiple selection allowed with custom numeric up down controls inside a column.
XAML:
                    <GridViewColumn Header="Level" Width="80">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal" Height="50" >
                                <TextBox x:Name="txtGroupLevel" Width="30" Text="1" VerticalAlignment="Center" HorizontalAlignment="Center" FontFamily="Century Gothic" />
                                <StackPanel Orientation="Vertical"  Width="20" Height="50" Margin="5,2.5,0,0">
                                    <Button x:Name="cmdUp" Content="˄" FontWeight="Bold" Height="20" Click="cmdUp_Click" />
                                    <Button x:Name="cmdDown"  Content="˅" FontWeight="Bold" Height="20" Margin="0,5,0,0" Click="cmdDown_Click" />
                                </StackPanel>
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>

Obviously I need the TextBox txtGroupLevel to be incremented/decremented when I click the up/down buttons.
What code do I need in the click events of my buttons in order to do that?
thanks for help


text:
Q: How do I this in MySQL? I have three columns (id, version, platform) in a table.
I want that when I go to insert a new record in the table, don't let me insert the same version for the same platform. I mean, if I have a row with (1, 10, android) and another with (2,11, iphone), when I go to insert the new version 10 for android don't be allowed, but if I'm going to add the new version 10 for iphone allow me to do it.
I hope you are understood, thanks. (sorry for my bad english)

A: Create a composite unique index on (platform, version):
CREATE UNIQUE INDEX ux_platform_version ON tbl (platform, version)


text:
Q: Phpseclib SSH2 not executing Shell Scripts Currently trying to create a PHP web application to run a variety of Shell Scripts to handle website generation and cleanup on delete.
Here's a snippet from my deletePropertyProcess.php:
$ssh = new Net_SSH2($server);

if(!$ssh->login("username", "password")) {
  $result['result'] = 'ERROR';
  $result['message'] = 'Login failed to server ' . $server;
} else {
  $result = $ssh->exec("cd /var/www/sites ; sudo /usr/local/bin/delete_property_folder.sh -c $comp -p $prop");
  echo $result;
}

Where delete_property_folder.sh is a bash script on my remote server and -c $comp -p $prop are my script options/parameters.
The fun part is, all of this works flawlessly via Putty. Running this functionality from PHP via Ajax returns the exit status of the Shell Script and the anticipated output from Ajax, but none of the changes handled by my Shell Script are actually applied.
Like I said, this runs perfectly from Putty so I doubt the issue is the Shell Script but here it is anyways:
#!/bin/bash

function fix_file_permissions() {
    chown -Rf username:username $1/$2

    echo $?;
}

function delete_specified_folder() {
    rm -rf $1/$2

    echo $?;
}

##Main Script Body
POSITIONAL=()
while [[ $# -gt 0 ]]
do
    key="$1"

    case $key in
        -c|--company)
            COMPANY="$2"
            shift
            shift
        ;;
        -p|--property)
            PROPERTY="$2"
            shift
            shift
        ;;
        *) #unknown option
            POSITIONAL+=("$1") #save it in an array for later
            shift
        ;;
    esac
done
set -- "${POSITIONAL[@]}" #restore positional parameters

PERMISSIONS_FIXED=$(fix_file_permissions $COMPANY $PROPERTY)
if [ $PERMISSIONS_FIXED -eq 0 ]; then
    FOLDER_DELETED=$(delete_specified_folder $COMPANY $PROPERTY)
    echo $FOLDER_DELETED
    exit
fi
echo 1

At this point, any recommendations would be useful. Let me know if you need any more information.

A: I've managed to get it working by feeding the sudo password via --STDIN to the Shell Script's full path using the following:
$result = $ssh->exec("cd /var/www/sites; echo 'password' | sudo -S /usr/local/bin/delete_property_folder.sh -c $comp -p $prop");

echo-ing your password with sudo -S allows you to pass your password via the pipe into the sudo shell script execution.


text:
Q: Excel VBA macro is giving me an overflow error 6 I have a macro that combines cells in a range based on their borders.  It was working fine until I realized it didn't account for the properties of the text (specifically the bold font).  I added the second part to the macro, and for some reason I'm getting an overflow.  Here is the macro:
    Sub TestMacro()
    Dim c As Range
    Dim outputText As String
    Dim strDelim As String
    strDelim = "XXXX"

    Selection.EntireColumn.Offset(0, 1).Clear
    Selection.EntireColumn.Offset(0, 1).Insert
    Selection.EntireColumn.Offset(0, 1).Font.Bold = False

    For Each c In Selection
        If c.Borders(xlEdgeTop).LineStyle <> xlNone Then
            If outputText <> "" Then
                c.Offset(-1, 1).Value = outputText
                FixBold c.Offset(-1, 1), strDelim
            End If
            outputText = IIf(c.Font.Bold, strDelim, "") & c.Value & IIf(c.Font.Bold, strDelim, "")
        Else
            outputText = outputText & " " & IIf(c.Font.Bold, strDelim, "") & c.Value & IIf(c.Font.Bold, strDelim, "")
        End If
    Next c

    If outputText <> "" Then
        With Selection.Cells(Selection.Cells.Count).Offset(0, 1)
            .Value = outputText
            FixBold .Cells(1), strDelim
        End With
    End If

End Sub

Sub FixBold(r As Range, strD As String)
    Dim i As Integer
    Dim j As Integer
    Dim k As Integer
    Dim sVal As String
    Dim s As Variant
    Dim boolBold As Boolean

    sVal = Replace(r.Value, strD & " " & strD, " ")
    r.Value = Replace(r.Value, strD, "")
    i = InStr(1, sVal, strD)
    While i > 0
        j = InStr(i + 1, sVal, strD)
        r.Characters(Start:=i - 2 * k * Len(strD), Length:=j - i - Len(strD)).Font.Bold = True
        i = InStr(j + 1, sVal, strD)
        k = k + 1
    Wend
End Sub

I believe the overflow error is coming from "r.Characters(Start:=i - 2 * k * Len(strD), Length:=j - i - Len(strD)).Font.Bold = True" towards the bottom.

A: I had experimented with the following input and received an overflow after too long:

To cut a long story short, your While condition checks to ensure that i is greater than zero, but i will switch between the occurrences of "XXXX" rather than reach zero.
If i is currently at the last match of "XXXX" within sVal, j will be assigned to the position of the next match. However, j will be assigned to the next match. Since there isn't one, it is assigned 0, from which i can be assigned to the first match all over again. This continues until k exceeds 32767, the upper limit for a signed 16-bit integer.
This aside, all that your code is presently doing is making each section bold, regardless of whether the corresponding cell is bold or not. I will post improved code in an update in a separate answer if I get the chance, but I trust that this at least explains the overflow error.
We will iterate through this to find out exactly what is going on.
Initialisation
sVal = "The quick brown XXXXFOXXXXX jumps over the lazy dog"
boolBold = undefined
i = 17
j = undefined (0)
k = undefined (0)
s = undefined (Empty)

First pass
sVal = "The quick brown XXXXFOXXXXX jumps over the lazy dog"
boolBold = False
i = 24
j = 23
k = 1
s = Empty

Second pass
sVal = "The quick brown XXXXFOXXXXX jumps over the lazy dog"
boolBold = False
i = 17
j = 0
k = 2
s = Empty

Third pass
sVal = "The quick brown XXXXFOXXXXX jumps over the lazy dog"
boolBold = False
i = 24
j = 23
k = 3
s = Empty

Fourth pass
sVal = "The quick brown XXXXFOXXXXX jumps over the lazy dog"
boolBold = False
i = 17
j = 0
k = 4
s = Empty

A: The following code should be more suitable — take particular note of FixBold(r,rs):
Option Explicit

Sub TestMacro()
    ' Assumes that:
    '   - Selection is contiguous

    Dim c As Range
    Dim outputText As String
    Dim groupedRange As Range
    Dim lastRow As Long

    Set groupedRange = Nothing                      ' The range which feeds outputText
    lastRow = Selection.Row + Selection.Rows.Count  ' The final row in Selection (relative to start)

    Selection.EntireColumn.Offset(0, 1).Clear
    Selection.EntireColumn.Offset(0, 1).Insert
    Selection.EntireColumn.Offset(0, 1).Font.Bold = False

    For Each c In Intersect(Selection.Rows.Cells, Selection.Columns(1).EntireColumn)
        If c.Borders(xlEdgeTop).LineStyle <> xlNone Then
            If outputText <> "" Then
                c.Offset(-1, 1).Value = outputText
                FixBold c.Offset(-1, 1), groupedRange
            End If
            outputText = c.Value
            Set groupedRange = c
        Else
            outputText = outputText & " " & c.Value
            ' Assign to the group
            If Not groupedRange Is Nothing Then
                ' Set -- combine with c
                Set groupedRange = Union(groupedRange, c)
            Else
                ' Unset -- Union(a,b) with null parameters throws an error
                Set groupedRange = c
            End If
        End If
    Next c

    If outputText <> "" Then
        With Selection.Cells(Selection.Cells.Count).Offset(0, 1)
            .Value = outputText
            FixBold .Cells(1), groupedRange
        End With
    End If

End Sub

Sub FixBold(r As Range, rs As Range)
    ' Iterate through the cells in supporting range rs
    ' For each cell in rs which is formatted bold,
    '   update the corresponding formatting in r
    ' We won't need a string delimiter here

    If rs Is Nothing Then Exit Sub  ' Ignore this if rs wasn't given

    Dim c As Range  ' Cell iterator variable
    Dim l As Long   ' Cell length
    Dim lt As Long  ' Elapsed length (remember to include space between cells)

    lt = 1

    For Each c In rs.Cells

        l = Len(c.Text)
        If c.Font.Bold And l > 0 Then
            r.Characters(lt, l).Font.Bold = True
        End If
        lt = lt + l + 1

    Next c

End Sub


text:
Q: Facebook pixel test_event_code Ive been looking across the documentation for meta's pixel and I can't seem to find much on where to place the test_event_code https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/main-body#test_event_code in conjunction with fbq()
Is it in the fourth parameter? because theres very little I've found on it.
Javascript:
fbq('track', 'lead', data, {eventID: 'EVENT_ID', test_event_code: 'CODE'})

A: In the "Test events" tab of your Pixel on the Business Account Manager you would find the following instructions

Test server events
Follow these steps on your terminal or Graph API Explorer to start seeing activity.

*

*Within your server payload, add the "test_event_code" parameter to the event you wish to test.
TEST93608

*Copy the test code and paste it below as the value of your test_event_code parameter. For example: {test_event_code: TEST93608}

*Send the payload. If the payload is received successfully, it will be shown on this screen.

In Java, using the FB sdk that would mean
import com.facebook.ads.sdk.serverside.EventRequest;
...
EventRequest myEventRequest = new EventRequest(this.pixelId, this.context);
myEventRequest.addDataItem(myEvent).setTestEventCode("TEST93608");


text:
Q: Calculate volume of area enclosed by the surface $\sqrt[3]{x^2}+\sqrt[3]{y^2}+\sqrt[3]{z^2}=\sqrt[3]{a^2}$.
Calculate the volume of the area enclosed by the surface
  \begin{equation}
x^{(2/3)}+y^{(2/3)}+z^{(2/3)} = a^{(2/3)}
\end{equation}
  where $a > 0$ is a constant.

However I'm not sure where to begin.

A: $$
V: (\frac{x_1}{a})^{2/3}+(\frac{x_2}{a})^{2/3}+(\frac{x_3}{a})^{2/3}\le1$$
$$y_i=(\frac{x_i}{a})^{1/3}$$
$$\frac{D(x_1,x_2,x_3)}{D(y_1,y_2,y_3)}=27a^3y_1^2y_2^2y_3^2$$
$$V=\int_V\mathrm{d}x_1\mathrm{d}x_2\mathrm{d}x_3=\int27a^3y_1^2y_2^2y_3^2\mathrm{d}y_1\mathrm{d}y_2\mathrm{d}y_3$$
$$\left\{
\begin{array}{ccc}
y_1&=&r\cos(\theta_1)\\
y_2&=&r\sin(\theta_1)\cos(\theta_2)\\
y_3&=&r\sin(\theta_1)\sin(\theta_2)
\end{array}
\right .$$
$$\frac{D(y_1,y_2,y_3)}{D(r,\theta_1,\theta_2)}=r^2\sin(\theta_1)$$
So
$$V=\int^{\pi/2}_0\mathrm{d}\theta_1\int^{\pi/2}_0\mathrm{d}\theta_2\int_0^1 27a^3(r\cos(\theta_1))^2(r\sin(\theta_1)\cos(\theta_2))^2(r\sin(\theta_1)\sin(\theta_2))^2r^2\sin(\theta_1)\mathrm{d}r\\
=\int^{\pi/2}_0\mathrm{d}\theta_1\int^{\pi/2}_0\mathrm{d}\theta_2\int_0^1 27a^3r^8\cos^2(\theta_1)\sin^5(\theta_1)\cos^2(\theta_2)\sin^2(\theta_2)\mathrm{d}r$$
$$V=3a^3\frac{\Gamma(3/2)\Gamma(6/2)}{2\Gamma(9/2)}\frac{\Gamma(3/2)\Gamma(3/2)}{2\Gamma(6/2)}=3/4a^3\frac{(\Gamma(3/2))^3}{\Gamma(9/2)}=\frac{a^3}{70}\pi$$

A: I want to remind you the answer above is incorrect, altough almost correct.
The volume calcuted there is 1/8'th of the actual volume, because 'xyz' lets both angles only range from $0$ to $\pi/2$, which means he only accounts for the 1 first octant.
Because the volume is symmetrical in all three axis, you can just multiply the outcome by 8, or calculate the integral
\begin{align*}
&3a^3\int_0^{\pi}\int_0^{2\pi}\cos^2\theta\sin^2\theta\cos^2\varphi\sin^5\varphi \text{ d}\theta\text{ d}\varphi\\
={}& \dfrac{4a^3}{35}\pi
\end{align*}
(PS See you in college tonight ;))


text:
Q: Controlar estoque da loja virtual Estou em um projeto de loja virtual e tenho uma dúvida quanto a processo de controle de estoque.
Inicialmente estou fazendo tudo na tabela product onde tenho dois campos: manage_stock e stock. Manage Stock irá controlar se o produto terá ou não controle de estoque na hora das vendas e Stock é o estoque em questão.
Quando um pedido tiver seu status marcado como pago eu decremento direto no produto na coluna stock.
Segue estrutura da tabela:
Tabela product
id    name      manage_stock    stock
1     Mouse     0               NULL
2     Teclado   1               50
3     Monitor   1               10
4     Gabinete  0               5

Tabela product
Essa lógica está correta? ou devo criar uma tabela só pra o estoque vinculando o produto. A baixa no estoque é um simples decremento direto na tabela produtc?

A: Minha visão do contexto:
Uma tabela para produtos;
Uma tabela para movimentação do estoque.
Na tabela de movimentação você controlaria as entradas e saidas dos produtos. Colocar tudo numa tabela só vai gerar dificuldades de escalabilidade da tua aplicação.


text:
Q: Terraform & AWS: ACM Certificate Never Validated I am trying to create an ACM certificate to apply to my Amazon ALB using Terraform 0.12.0.  I'm able to create my ALB without a certificate with no problem.  The entire infrastructure stack is built and deployed as expected.  Now, I've added the following code to create the Route 53 validation record, request the certificate, and assign it to a new ALB listener:
resource "aws_route53_zone" "main" {
  name = "${var.zone_name}"
}

resource "aws_route53_record" "validation" {
  name    = "${aws_acm_certificate.main.domain_validation_options.0.resource_record_name}"
  type    = "${aws_acm_certificate.main.domain_validation_options.0.resource_record_type}"
  zone_id = "${aws_route53_zone.main.zone_id}"
  records = ["${aws_acm_certificate.main.domain_validation_options.0.resource_record_value}"]
  ttl     = "60"
}

resource "aws_acm_certificate_validation" "main" {
  certificate_arn = "${aws_acm_certificate.main.arn}"
  validation_record_fqdns = "${aws_route53_record.validation.*.fqdn}"
}

resource "aws_alb_listener" "front_end_tls" {
  load_balancer_arn = "${aws_alb.main.id}"
  port              = "443"
  protocol          = "HTTPS"

  ssl_policy = "ELBSecurityPolicy-2016–08"
  certificate_arn = "${var.certificate_arn}"

  default_action {
    target_group_arn = "${aws_alb_target_group.main.id}"
    type             = "forward"
  }
}

When I run terraform apply, however, it seems to get stuck on the certificate validation.  I see messages like this:
module.dns.aws_acm_certificate_validation.main: Still creating... [38m21s elapsed]

I've let the code run for over 45 minutes, until I eventually see an error saying:
Error: Error creating LB Listener: SSLPolicyNotFound: SSL policy 'ELBSecurityPolicy-2016–08' not found
    status code: 400, request id: a5f052c1-86df-11e9-993c-f99526fa9bba

  on alb/main.tf line 25, in resource "aws_alb_listener" "front_end_tls":
  25: resource "aws_alb_listener" "front_end_tls" {

Error: Expected certificate to be issued but was in state PENDING_VALIDATION

  on dns/main.tf line 38, in resource "aws_acm_certificate_validation" "main":
  38: resource "aws_acm_certificate_validation" "main" {

If I login to the console, I see the certificate request still in the Pending Validation state.  I also see the Route 53 validation record created as expected.
Why is it that this certificate request is never processed and applied?  Am I missing something in my Terraform code?
UPDATE:  When I use an existing Route 53 zone (with a different domain name from the one I'm trying above) and reference it as a data resource in my aws_route53_record, it works with no problem.  The domain name I'm trying in this test was just purchased via Route 53 today, so I'm wondering if that has something to do with my issue.  I'm unable to do an nslookup on any of the records, even though I see them listed in the Route 53 console.  Maybe?  I'll let it sit for a couple days and see if it's just a timing issue.

A: I don't have reputation to comment, so writing an answer
OP mentioned in a comment that domain was purchased from route53, in that case a hosted zone should have been created for the domain. OP also mentions that they can see the records from AWS console but can't do nslookup for any of these records.
I think in this case OP might not have purchased a domain and might have created a private hosted zone and is working with that. And off course public ACM certs can't be validated with private hosted zone
AWS Forum: https://forums.aws.amazon.com/thread.jspa?threadID=238468

A: Before to apply the following code, make sure you've purchased one domain and then, fill domain_name variable, if it should be a wildcard, you can use wildcard_enable = true this way, you can create a wildcard certificate, really useful to reuse the same ACM in different subdomains.
My directory structure
.
|____main.tf
|____variables.tf

main.tf
locals {
  final_domain = "${var.wildcard_enable == true ? "*.${var.domain_name}" : var.domain_name}"
}

resource "aws_acm_certificate" "this" {
  domain_name       = local.final_domain
  validation_method = "DNS"

  tags = {
    "Name"       = "acm-cert-name"
    "costCenter" = "xxxxxxxxx"
    "owner"      = "xxxxxxxxx"
  }

  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_route53_record" "this" {
  depends_on = ["aws_acm_certificate.this"]
  zone_id    = "xxxxxxxxxx"
  name       = aws_acm_certificate.this.domain_validation_options.0.resource_record_name
  type       = "CNAME"
  ttl        = "300"
  records    = [aws_acm_certificate.this.domain_validation_options.0.resource_record_value]
}

variables.tf
variable "wildcard_enable" {
  description = "Variable that allow us to choose the possibility of not use wildcard certificate"
  default     = false
}

variable "domain_name" {
  description = "The name of the domain to which apply the cert"
}

First: apply this code as a module or just apply it and wait until AWS validate it.
Finally: use aws_acm_certificate.this.arn to get the ACM arn and it could be used on ALB.
If the ACM certificate wasn't validated yet, you can't use it with ALB because the AWS api doesn't retrieve the ACM ARN.
I hope will be useful to you and other users.

A: Be sure you put the right name servers in the domain configuration if you purchased outside Route53


text:
Q: Getting error while creating Job from Jobs API I am passing job configuration from database as string and storing as string in .Net Web API as
var result =  _context.Output.FromSqlRaw(StoredJson).ToList().FirstOrDefault().Details;

Now I Used RestSharp library to create request in .Net as
var client = new RestClient(".....");
var request = new RestRequest("/api/2.0/jobs/create", Method.Post);
string Auth = "......";

request.AddParameter("application/json", result, ParameterType.RequestBody);
request.AddParameter("Authorization", "Bearer " + Auth, ParameterType.HttpHeader);
var response = await client.ExecuteAsync(request);
return(response.content)

And My Json looks like this
{
    "name": "LoadData_test",
    "new_cluster": {
        "spark_version": "7.6.x-scala2.12",
        "init_scripts": [
            {
                "dbfs": {
                    "destination": "....."
                }
            }
        ],
        "instance_pool_id": ".......",
        "azure_attributes": {
            "spot_bid_max_price": -1
        },
        "autoscale": {
            "min_workers": 2,
            "max_workers": 5
        }
    },
    "libraries": [
        {
            "maven": {
                "coordinates": "......"
            }
        }
    ],
    "timeout_seconds": 0,
    "notebook_task": {
        "notebook_path": "......",
        "revision_timestamp": 0
    },
    "max_concurrent_runs": 1
}

And I think when I am passing this JSON into request.AddParameters, It is taking as text/plain. but I want it to be JSON.
I think, I have done everything right, but still getting error while send the request as
{"error_code":"INVALID_PARAMETER_VALUE","message":"Job settings must be specified."}

Can somebody please help me out ?
And I have use "..." as there is valid content.

A: I guess that you got the code generated by some codeegen, like Postman. It doesn't work with the latest RestSharp, as the way to build requests was broken.
The documentation has a complete overview of the RestSharp API for building proper requests, I strongly suggest looking at it.
Specifically, you need to replace this line:
request.AddParameter("application/json", result, ParameterType.RequestBody);

with
request.AddStringBody(result, DataFormat.Json);


text:
Q: How can I compile and run this 1989 written C program? I found this amazing piece of work by Arthur Whitney - http://www.jsoftware.com/jwiki/Essays/Incunabulum
It compiled with a few warnings
$ gcc-4.7 incuna.c -o incuna.o
incuna.c: In function 'ma':
incuna.c:8:15: warning: incompatible implicit declaration of built-in function 'malloc' [enabled by default]
incuna.c: In function 'pi':
incuna.c:26:7: warning: incompatible implicit declaration of built-in function 'printf' [enabled by default]
incuna.c: In function 'nl':
incuna.c:26:24: warning: incompatible implicit declaration of built-in function 'printf' [enabled by default]
incuna.c: In function 'pr':
incuna.c:28:10: warning: incompatible implicit declaration of built-in function 'printf' [enabled by default]
incuna.c: In function 'ex':
incuna.c:35:36: warning: assignment makes integer from pointer without a cast [enabled by default]
incuna.c:35:25: warning: return makes pointer from integer without a cast [enabled by default]
incuna.c: In function 'noun':
incuna.c:37:57: warning: return makes integer from pointer without a cast [enabled by default]
incuna.c: In function 'wd':
incuna.c:39:21: warning: incompatible implicit declaration of built-in function 'strlen' [enabled by default]

But it segfaulted on entering a basic input 1 + 1.
./incuna.o
warning: this program uses gets(), which is unsafe.
1 + 1
[1]    11525 segmentation fault  ./incuna.o

I'm guessing this has something to do with the difference in C compiler since 1989.
How would I be able to run this? Can I get this working on recent Linux/Mac? or on a VirtualBox VM? or anything else?
My Google searches turned up nothing related.

A: It converts pointers to int and long and vice-versa. This breaks with 64-bit architectures in which they have different sizes.
Compile it for a 32-bit target. E.g., with "-arch i386" using clang/LLVM on Mac OS X.

A: I would wager a guess that it segfaulted because of this:

incuna.c:8:15: warning: incompatible implicit declaration of built-in function 'malloc' [enabled by default]

If malloc is not declared, then it's not going to allocate you memory and you'll end up dereferencing a null and that could lead to a seg fault.
After including:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

The warnings for printf(), malloc(), and strlen() are gone. The code runs and works if you input:
1+1

Note the spacing is important here:
1 + 1

will segfault.

A: Run it through the preprocessor only:
gcc -E interp.c > interp-pp.c
Then prettify it in an editor, then use a debugger to watch what it does.

A: On my system (AMD64 Win 8), it appears that pointer values often have the top bit set, so treating a pointer as an integer (which this program does) will misbehave and crash.
Changing the qv(a) function ("query verb") allows the program to run:
qv(a){R a<'a';}

should be
qv(a){R a<'a'&&a>0;}

or
qv(a)unsigned a;{R a<'a';}

Here's a link to a minimally-modified version that should compile without warnings (with gcc, default options) and execute (with correct input).


text:
Q: How to read the particular XML tag from DOM parser in java  The xml is -
<?xml version="1.0" encoding="UTF-8"?>
<app_content>
            <app_type value="Browser">
                  <item>
                        <item_name>sdk_version</item_name>
                        <item_value>01.00.001</item_value>
                        <item_save>01.00.001</item_save>
                        <item_desc>LG SDK Version</item_desc>
                        <item_type>edit</item_type>
                  </item>
                  <item>
                        <item_name>use_internet</item_name>
                        <item_value>Yes/No</item_value>
                        <item_save>Y/N</item_save>
                        <item_desc>Internet Use</item_desc>
                        <item_type>combo</item_type>
                  </item>
 </app_type>
</app_content>

I want to read the contents of each item tag, so I have 2 items tag inside app_type.
I made the code like this -
Element mainElement = (Element) document.getElementsByTagName("app_type").item(0);
NodeList browserCategories =  mainElement.getElementsByTagName("item"); //item
        for(int i=0;i<browserCategories.getLength();i++){
        Element browserCategoryElement = (Element) browserCategories.item(i);
}

But after that I am not getting the attributes of each item and the value associated to each tags under item.
Like I want to read all the values like sdk_version , 01.00.001 ......

A: Got the Solution-
NodeList list = browserCategoryElement.getElementsByTagName("item_name");
NamedNodeMap map = browserCategories.item(i).getAttributes();


text:
Q: Can't include EOT font encoded by base64 to inline CSS I need to include the Roboto Condensed font in .EOT format for IE 7 within my inline CSS in one HTML file after encoding of the font by base64.
So first I've encoded the font by PHP code
<?php
$base64 = base64_encode(file_get_contents('roboto-condensed.eot'));
file_put_contents('base64_version.txt', $base64);
?>

And I got
DGMAA...........mAskA

Then I try to include the font as following:
<style>
@font-face{
font-family:'Roboto Condensed';
src:url('data:application/x-font-eot;base64,DGMAA...........mAskA') format('embedded-opentype');
}
body{
font-family:'Roboto Condensed';
}
</style>

Some text

But the font is not being loaded. However if I include it with
src:url('roboto-condensed.eot');

it's loaded successfully
I've tried also
src:url('data:application/vnd.ms-fontobject;charset=utf-8;base64,DGMAA...........mAskA') format('embedded-opentype'));

as mentioned by the link Font-face as base64 with fallbacks but without success


text:
Q: Constructing homeomorphism between (0,1] and $[1,\infty)$ I am trying to construct a homeomorphism between (0,1] and $[1,\infty)$ in the real line. But I am not sure how to construct a bijective continuous(also inverse is continuous) function for it. Can somebody help? Thank you...

A: $f(x)=\frac{1}{x}$ is a self-inverse, continuous bijection from $(0,1]$ to $[1,\infty)$.


text:
Q: Checkbox status in winform while code is in DLL I have been given a task to export code into a DLL to hide sensitive code from other developers on the project. This is a winform VB.net project and uses checkboxes extensively. Much of this sensitive code contains references like this.
If Form1.CheckBox102.Checked = False then
The problem is that placing this code into the DLL breaks those references. I'm under the impression that this is because you cant reference the form of the main exe from the DLL.
So this brings me to the question, what is one to do? Is there a way to 'establish' some kind of link between the two? Or is it just a matter of having those references passed in the code when accessing the classes of the DLL?


text:
Q: Coloring text with css using jQuery I have a little problem adding a class to a span element and so coloring it in order to perform simple validation.
Here is my js:
     function validateKey(){
        var length = $('#appkey').val().length;
        if(length != 8){
            $('#appkey').addClass('error');
            $('#appKeyInfo').addClass('error');
            return false;
        }else{
            $('#appkey').removeClass('error');
            $('#appKeyInfo').removeClass('error');
            return true;
        }
      }

And html:
KEY

<input type="text" id="appkey" value=""/>

Dein App-Key aus 8 Ziffern

And the jsfiddle: example
Any ideas?
UPDATE: coloring of appKeyInfo fails, coloring appkey works. When I remove color:red and type font-weight:bold instead the text is bold on error. when I remove color definition of appKeyInfo the text can be colored red on error, strange thing, but I need a font color for the appKeyInfo

A: The declaration for span#appKeyInfo takes precedence since it is an id you are styling.
 Try using color:red !important to force the override
Edit
Just a note, you can use multiple selectors in your jQuery. Like this:
$('#appkey', '#appKeyInfo').removeClass('error');

A: your comparison operator is wrong, use less than operator :
  function validateKey(){
    var length = $('#appkey').val().length;
    if(length < 8){
        $('#appkey').addClass('error');
        $('#appKeyInfo').addClass('error');
        return false;
    }else{
        $('#appkey').removeClass('error');
        $('#appKeyInfo').removeClass('error');
        return true;
    }
  }


text:
Q: jQuery Queue: Does it matter where you bind it to? I read this great thread: What are queues in jQuery?
Now it makes me wonder:
Does it matter which DOM object you bind queue to?
i.e. $('div').queue(); vs. $('body').queue({}) or even $('.foo').queue();

A: Each element has its own queue.
Calling $('.foo').queue(); will queue the function on every .foo element.


text: Q: 70s/80s children's book about space colonist boy who realises by telepathy that the aliens are sentient I must have read this in the early 1980s in the UK; possibly a 1970s publication. It was a children's novella about a boy who's part of a human space colonist family on a planet inhabited by aliens that aren't thought to be sentient. I think the planet was kind of desert-y or cowboy movie-ish, and the aliens roamed about it like horses or tumbleweeds. The aliens might have been wheel-shaped? The boy learned to communicate with them by telepathy and then had to persuade adult society to be nicer to the aliens.


text:
Q: UART communication protocol Arduino I want to simulate Serial communication on Arduino.
Serial communication data is like LOW | bits 0-7 | HIGH. So I did the code below:
uint8_t read8() {
      while(digitalRead(6));
      delayMicroseconds(52);
      uint8_t response = 0;
      for (uint8_t i = 0; i < 8; i++) {
        delayMicroseconds(104);
        response |= digitalRead(6) << i;
      }
      delayMicroseconds(156);
      return response;
    }

I am sending data via hardware serial TX to my custom RX pin. The first letter is correct, but another ones not. What is a mistake here? #9600


text:
Q: Estimating number of types of things, from many observations I go on a safari.  Each day, I see various animals, and a keep track of all of my observations.  Assume that each time I make an observation I see a single animal.  At one point, I've made a total of 153 observations and I've seen 127 rabbits, 22 gazelle, 3 lions, and 1 tiger (4 different species).  This makes me curious: what is the probability that the next animal I observe will be from a new species, i.e., not one of the 4 I've already seen?
Is there a way to get an estimate or bound on this probability?  If not, is there a pragmatic way to get an estimate, perhaps making some additional assumptions that might potentially be reasonable in practice?

I'm not trying to estimate the total number of species, but just that the next observation is from a species I haven't seen yet.  I feel like I might have read about this problem somewhere in a paper long ago, but I can't remember the details -- and now I've run across a practical situation where I need to solve it.  It feels like it ought to be possible to make some deduction by applying exchangeability, but I can't manage to make the details work out.

A: I am not an expert in this area, but I understand that both
The Indian Buffet Process and The Chinese Restaurant Process specifically address this question.

A: Assuming that each observation is independent, then maybe we can model this using Bernoulli. The Bayesian approach would be that,
Let $X$ be number of observation that doesn't belong to the 4 species you mentioned. Assume that, $$X \sim Bin(n,p)$$
$$p_{prior} \sim Beta(1, 1)$$
prior distribution of p is uniform here, i.e. any probability is equally possible. Then posterior probability of $p$ would be
$$p_{posterior} \sim Beta(1+n_{success}\ , 1+n_{failure})$$
In your case posterior p has distribution of $Beta(1, 154)$. Expectation of probability of seeing a "new species" in the next observation should be $1/155$. And if you failed to observe a new species in your next observation, you can update this distribution to $Beta(1, 155)$ and the expectation of this distribution becomes $1/156$.


text:
Q: Problems about Install apk from invite email of crashlytics I use Crashlytics to publish test version apk , when my members got the invite email, they open it and click "Check It Out" on Android device, but stock by this warning > "Safari is required"

So, does the link of Crashlytics only work on Safari? How Android device install Crashlytics?

A: Alex from Fabric here. For iOS apps, the email invitation needs to be opened in Safari on their iPhone or iPad. For Android apps, this restriction doesn't exist. From your screenshot, it seems like the user is opening an invitation to test an iOS app on their Android device, which won't work. But you did mention you're testing an APK, so I'd definitely like to look into this more. If you let me know the package name and your Fabric org, I can dig into it on our backend.


text:
Q: Display none only the table that i am clicking , not all tables Basically i am doing a document.querySelectorAll() which returns an array of div elements . I have a function which has a handleclick() function and each time i click in this button i want the hide the table of the button that i am click on not.
This is what i have right now

This is what happens when i click one of the dropdrown buttons

CURRENT BEHAVIOUR: All of the tables hide
EXCEPTED BEHAVIOUR: Onlt the table which is related to the button that i am clicking should hide
Here is the code snippet of the file

const handleTitleClick = (e) => {
    const row = document.querySelectorAll(
      "div[class*='MuiDataGrid-root']"
    ) as NodeList;

    const rowArr = Array.from(row);

    rowArr.map((r, i) => {
      const somerow = r;
      somerow.style.display = 'none';
      return row;
    });

    console.log(e);
    console.log(rowArr);
    console.log(row);
  };

A: You don't have to add display: none for all tables, but only for the tables associated with a particular hide button. You can wrap tables with additional blocks to reach your goal.
For example:
return (

  <button
    onClick={() => {
      const table = document.querySelector("#table-wrapper-1");
      table.style.display = "none";
    }}
  >
    >Hide table1
  </button>

    <MyTable1 />

  <button
    onClick={() => {
      const table = document.querySelector("#table-wrapper-2");
      table.style.display = "none";
    }}
  >
    >Hide table2
  </button>

    <MyTable2 />

;

)

By the way, I recommend that you use refs instead of querySelector.

A: // 1) select all btn element
const allbtn = document.querySelector(".allBtn")

// 2) add each btn click event
allBtn.map((btn, i)=> {
   btn.addEventListener("click", ()=> {
     // add btn data-attr in html and add table same id as own ...
     // ... buttons data-attr
     let currentId = btn.getAttribute('data-attr')
     //thats current btns table
     let currentTable = document.getElementById(`${currentId}`)
     currentTable.style.display = 'none'
   })
}


text:
Q: What permission is required to reorder SQL Server table columns Using SQL Server 2016 Management Studio, I can create or delete column but I can not reorder column order.
I get the error that this change requires the table to be dropped and re-created and I have not permission to do that. What permission should I have and how should I grant it using a query or using SMSS?

A: You don't really need any permission here as I say before, all what you need is:
Go to Options -> Designer -> uncheck prevent saving changes that require a table creation


text:
Q: How to redirect traffic to a specific IP through a proxy? I have an Ubuntu 18.04 machine that for accessing a specific IP (for example n.n.n.n) I need to use a proxy (p.p.p.p:p1) but at the same time, I cannot use the proxy for the rest of the traffic on that machine.
How can I send the traffic to that specific IP through proxy and don't touch the rest?


text:
Q: Windows PostgreSQL logs indicate many short time sessions I'm using windows XP with PostgreSQL 9.2.3, ODBC driver 9.01.0100, during some stress testing recently with log_connections and log_disconnections on, I noticed there're too many this kind of logs in log file:
2014-02-26 10:37:14.359 ,"connection received: host=127.0.0.1 port=11978",,,,,,,,,""
2014-02-26 10:37:14.359 ,"myUser","mydatabase",7996,"127.0.0.1:11978","authentication","connection authorized: user=myUser database=mydatabase",,,,,,,,,""

2014-02-26 10:37:14.390 ,"myUser","mydatabase","127.0.0.1:11978","disconnection: session time: 0:00:00.031 user=myUser database=mydatabase host=127.0.0.1 port=11978",,,,,,,,,""

Noticed the session time is very small which far from 1 seconds: 'session time: 0:00:00.031', and obviously it did nothing in this session but Open and close.
As I know, our business is based on .NET which of course use the ADO.NET, there's a connection pool facility default enabled, this is for saving the physical link to database every time we open a connection in code, so I really confuse what this log mean? does this hurt the performance lot?


text:
Q: Magento 2 : Create comma seperated sku filter for custom product grid I am using Magento ver. 2.4.4.
I have a custom grid, displaying the below fields data.
item_id,
rma_id  ,product_sku    ,order_item_id  ,reason_id  resolution_id   ,condition_id.
I want to create a filter for SKU, where we can put comma-separated or space-separated SKU & it will show results based on it.
Is there any way it can be done?
Kindly let me know your thoughts on this.

A: As i correct understand, you are using UI Component. Following example how to add multiply SKU filter on product grid. I hope you can properly add to your custom grid
Acme/StackExchange/view/adminhtml/ui_component/product_listing.xml
<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <listingToolbar name="listing_top">
        <filters name="listing_filters">
            <filterInput name="sku" template="ui/grid/filters/field" class="Acme\StackExchange\Ui\Component\Listing\Filter\Sku" provider="${ $.parentName }">
                <settings>
                    <dataScope>sku</dataScope>
                    SKU
                </settings>
            </filterInput>
        </filters>
    </listingToolbar>

    <columns name="product_columns">
        <column name="sku">
            <settings>
                <filter>false</filter>
            </settings>
        </column>
    </columns>
</listing>

Acme/StackExchange/Ui/Component/Listing/Filter/Sku.php
<?php
declare(strict_types=1);

namespace Acme\StackExchange\Ui\Component\Listing\Filter;

use Magento\Ui\Component\Filters\Type\Input;

class Sku extends Input
{
    /**
     * @inheridoc
     */
    protected function applyFilter(): void
    {
        if (isset($this->filterData[$this->getName()])) {
            $value = explode(',', $this->filterData[$this->getName()]);
            $value = array_map('trim', $value);

            $filter = $this->filterBuilder->setConditionType('in')
                ->setField('sku')
                ->setValue($value)
                ->create();

            $this->getContext()->getDataProvider()->addFilter($filter);
        }
    }
}

[Update]
In example with use logic with reset filter your module should depends on original logic. In this example:
Acme/StackExchange/etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Acme_StackExchange">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>

Example with the same logic, but with custom filter name
Acme/StackExchange/view/adminhtml/ui_component/product_listing.xml
<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <listingToolbar name="listing_top">
        <filters name="listing_filters">
            <filterInput name="sku_list" template="ui/grid/filters/field" class="Acme\StackExchange\Ui\Component\Listing\Filter\Sku" provider="${ $.parentName }">
                <settings>
                    <dataScope>sku_list</dataScope>
                    SKU (comma)
                </settings>
            </filterInput>
        </filters>
    </listingToolbar>
</listing>

Result


text:
Q: Reset slow_log tables in RDS of AWS I enabled the slow_log_query in RDS in AWS. I want to reset the table but i am getting Access denied in PhpMyadmin while truncating . Any Idea to make it possible .

A: I got a solution
Amazon RDS will not give you SSH access to its database server. That means you don't have the opportunity to view any of the log files, even the slow query log, for the database. But RDS provides a way to play with the slow queries.
If your slow queries are many then this table will hold too many queries to handle. You cannot truncate the table or delete any row from there. There is only a way to move all the data from this table to another table named 'slow_log_backup', making the slow_log table empty.
To do so you have to run a stored procedure already available in RDS.
Select the 'mysql' database and you can see some stored procedure listed. Run the procedure named 'rds_rotate_slow_log' by running CALL mysql.rds_rotate_slow_log command.
In the back-end RDS just renames those two tables, it does not actually move the data. Running the command twice will delete the slow log completely from the database server.


text:
Q: How do You Search for Variable Names I'm making a program that find sums multiple values that are in a single string. For example you put H2O in and it will return the molar mass value for that chemical (2*H + O). So I copied the periodic table and listed the values e.g "private double H = 1.008;". So the problem is I need to get that value based on the name of the variable. Here is an example.
private double H = 1.008;

System.out.println(multMass(2, H));
// should print 2.016

public static double multMass(int multiplier, String chem){
    return double(chem) * multiplier;
}              /\
               ||
  where the double would go(in this case 'double H')

A: Don't use raw variables for this. Use a Map instead:
Map<String, Double> elemWeights = new HashMap<>();

// Associate an element symbol and a weight
// This would be your "double H = 1.008"
elemWeights.put("H", 1.008);
elemWeights.put("Li", 6.94);
...

public static double multMass(int multiplier, String chem) {
    double weight = elemWeights.get(chem); // And do a lookup
    return weight * multiplier;
}

Or, a little neater:
Map<String, Double> elemWeights = Map.ofEntries(
    entry("H", 1.008),
    entry("Li", 6.94)
    ...
);

Or see here for other ways this can be written based on the version of Java that you're using.


text:
Q: Recovery and Norecovery in SQL Server Database Backup I am using SQL server 2012,I have sequence of backup file.Now i am restoring.
by mistake, Suppose i restore file with Recovery rather than Norecovery then how to restore further files?


text:
Q: Как реализовать проверку строки sql на наличие входных данных? Хочу реализовать систему регистрации и входа в аккаунт, но возникла проблема в  проверке таблицы на наличие записей. нужно шаблонно подставить в условия определенные значения, но не могу разобраться как правильно.
try:
    check = cur.execute('''SELECT name, password FROM user WHERE name=? password=?''', self.login, self.password)
    if check:
        pass
except IOError:
    pass

A: Для функции execute на месте аргумента необходимо указывать %s, а не ?.
Аргументы необходимо передавать кортежем или списком.
Но execute не возвращает данные, поэтому после запроса нужно получить их с помощью cur.fetchone() или cur.fetchall().
Таким образом правильный запрос будет выглядеть как:
cur.execute('''SELECT name, password FROM user WHERE name=%s password=%s''', [self.login, self.password])
user = cur.fetchone() # None или кортеж с данными


text:
Q: Writing test cases for a WordPress Plugin that has translations What is my aim?
I'm looking forward to write test cases for the available translations of a WordPress plugin.
My approach:
I have setup WordPress using VVV and my testing suite includes PHPUnit and WP-CLI.
In order to test (assert) the translations, I'm checking if the language's .mo file exists or not.
/**
 * Test the translations.
 */
public function test_translations() {
    $this->assertFileExists( $this->object->path . 'lang/domain-name-de_DE.mo' );
    $this->assertFileExists( $this->object->path . 'lang/domain-name-lt_LT.mo' );
    $this->assertFileExists( $this->object->path . 'lang/domain-name-nl_NL.mo' );
}

Where I'm stuck?
Is this the right approach to test translations for a WordPress plugin? If not, please suggest alternatives.

A: If all that you want to test is that the translation files exist, then this is probably the simplest approach, since you'll probably already be using PHPUnit to run unit/integration tests on the plugin code.
However, just checking whether the files exist doesn't tell you much. It doesn't tell you whether those languages are actually fully translated, or even if those files will be loaded properly by WordPress.
So the question you need to ask yourself is, "Why am I testing this?" If you just want to make sure that you don't accidentally leave out a translation file, then your tests should do what you need. If you want to actually ensure that you have complete translations for each language, and that these actually work, that's an entirely different story.
Testing translation loading
To check whether each translation file can be properly loaded by WordPress, you could probably create a PHPUnit test that loaded the files using load_plugin_textdomain(), and checking that it returns true, which would indicate that the textdomain could be properly loaded. You'll probably need to hook into the plugin_locale filter to check each locale that ships with your plugin.
Testing completeness
However, that still wouldn't tell you how many of the strings were actually translated into that language, how many are fuzzy, etc. If you want to check that each translation is at least xx% complete, you'll probably want to use a tool other than PHPUnit for that.
Testing appearance
You could also go further and check that the strings in each translation actually appear correctly in the plugin UI. Sometimes a string might be much longer in a translation than it is in the original language, and this can cause it to overflow the area allotted for it. To check this you'd need to use something like Codeception acceptance tests.
Conclusion
So, in conclusion, whether the tests you have are the right approach for you depends on what you want to test. Personally, I don't have any tests for my plugins' translations, although that last part about checking the UI has intrigued me. Just checking that the translations exist, as you are doing now, doesn't appear to me to provide much benefit. It is a check that is only as good as your list of translation files that you are checking for. And in one sense it doesn't actually test anything, just makes sure that it is there. That could be performed in a build script rather than PHPUnit. Checking that the translations can actually be loaded by WordPress does provide benefit IMO, because it actually tests that they aren't corrupted. And of course, it tests that they exist at the same time. So I'd probably expand your tests to check that too.
Edit
On a related note, you might also consider testing for any spelling errors in your main POT (and in translations too, I guess). It's easy for these to slip in under the radar. Probably there are shell scripts available that could do this.


text:
Q: Changing elements of a constant char* literal in VS This is the code:
int main()
{
    char* a = "abc";    // Should be 'const char*', but no warnings whatsoever on VS
    a[1] = 'e';         // No warnings on VS either

    std::cout<< a << " " << a[1];

    return 0;
}

Compiled using gcc version 6.2.0:
>g++ -O2 -o Test Test.cpp
Test.cpp: In function 'int main()':
Test.cpp:5:15: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
 char* a = "abc";
           ^~~~~

>./Test
Segmentation fault (core dumped)

Compiled using VS 2015.3:
>cl /EHsc /W4 /WX /O2 Main.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 19.00.24215.1 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

Main.cpp
Microsoft (R) Incremental Linker Version 14.00.24215.1
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:Main.exe
Main.obj

>Main.exe
abc e

HUH?^

Compiling without /O2 yields no warnings either, but crashes on runtime.

Is this a VS compiler bug or I'm missing something?

A: I do not think this can be called a bug. With a[1] = 'e'; You are changing the read only memory. String literals are not expected to be modified. This is effectively an undefined behavior. Why VS compiler is not giving a warning, like gcc? Well, every program (compiler is a program either) can be better. In this particular case very old piece of compiler code works because this is not a recent C++ feature (like T&& references). Old code may not give out the best error.
There are tons of other ways to write bad code. Unfortunately in C/C++ this is relatively easy. Here we are.
There are numerous static code checkers and sanitizers (ex: CodeSonar). Typically they are not free. They catch a lot of problems but not all of them.


text:
Q: margin-left code only for internet explorer I am attempting to code something specifically for IE since it works perfectly well on other browsers.  I want to add
margin-left: -1px;

to all IE variations by adding that line of code to the div.  I looked it up and tried this for my Internet Explorer 11 browser on the HTML page.

Any suggestions to what I am doing wrong?
UPDATE: I have been notified that conditional comments do not work for IE10 + IE11.  Being capable of adding margin-left: -1px to the code below for only IE is the issue.
here is the css
.mini-cart-items .mini-products-list-title {
    background-color : #233a77;
    border           : 2px solid #010d35;
    color            : #fff;
    font-size        : 16px;
    font-weight      : bold;
    height           : 20px;
    padding          : 2px;
    width            : 300px;
}


text:
Q: Can't login to OpenShift Origin with administrator (system:admin) I installed OpenShift origin (openshift-origin-client-tools-v3.11.0-0cbc58b-linux-64bit) and when I tried to login with oc login it asks for username and password.
If I type any username like bob and then any password like 123 it login successfully but without permissions.
[root@ip-10-0-0-12 centos]# oc get pods
No resources found.
Error from server (Forbidden): pods is forbidden: User "bob" cannot list pods in the namespace "default": no RBAC policy matched

So I tried to login as the admin system:admin but it asks for password and I don't have the password, I have two certificates of two system:admin users in the /root/.kube/config file:
-name: system:admin/10-0-0-12:8443
 ...
-name: system:admin/127-0-0-1:8443

How can I login as the admin of the cluster ?

A: I solved it.
tl;dr I copied the original config file to the /root/.kube/config, add it to the environment variables and upload the cluster:
cp /home/centos/openshift.local.clusterup/openshift-apiserver/admin.kubeconfig /root/.kube/config
export KUBECONFIG=/root/.kube/config
oc cluster up

Everything works fine now.
Details

system:admin credentials live in a client certificate. If you get
  prompted for a password, that means your $KUBECONFIG file does not
  contain those credentials.   Try to login with "system:admin" user
  using both, the default kube config and the config from
  /etc/origin/master.
/# oc login -u system:admin  --config=/etc/origin/master/admin.kubeconfig
  /# oc login -u system:admin  --config=/root/.kube/config   If login using  /etc/origin/master/admin.kubeconfig is done successfully just
  simply copy this file to /home/user/.kube/config (kube-config file
  inside the linux users home directory)
The system admin ~/.kube/config file that is originally generated
  after installing OpenShift 3.x+ is directly copied from the
  admin.kubeconfig.
To restore the ~/.kube/config file so that a administrator can log in
  as system:admin just copy the admin.kubeconfig file.
cp /etc/origin/master/admin.kubeconfig  ~/.kube/config.
After that try login again without providing any config file in oc
  login command.


text:
Q: Ocaml error with if statement I have a list of lists, eg [[1;2;3];[2];[3;4;5;6]; [7;8;9;10]
I want to place these in a Hashtbl where the key is the length of the list and the value is list of lists, which contains all sublists of the given length.
So for the example above the hash will look like as follows
Key            Value
 1              [[2]]
 3              [[1;2;3]]
 4              [[3;4;5;6];[7;8;9;10]]

In addition I am also trying to keep track of the length of the longest list and that number is what is returned by the function
The code that does this is as follows.
let hashify lst =
    let hash = Hashtbl.create 123456 in
        let rec collector curmax lst =
            match lst with
                    [] -> curmax
                | h::t -> let len = (List.length h) in
                                (if ((Hashtbl.mem hash len)=true)
                                then ( let v = (Hashtbl.find hash len) in Hashtbl.add hash len v@[h] ) (* Line 660 *)
                                else ( Hashtbl.add hash len [h]));

                                (collector (max len curmax) t)
        in
        collector 0 lst
    ;;

Now when I do this I get the following error for the code above
File "all_code.ml", line 600, characters 50-72:
Error: This expression has type unit but an expression was expected of type
     'a list

Why does Ocaml require a return type of 'a list and how do I fix this.
Thanks in advance
Puneet

A: You probably should add parenthesis in (v@[h]) to avoid have it parsed as (Hashtbl.add hash len v)@[h]
And you probably should not pass 123456 to Hashtbl.create but a reasonable prime number like  307 or 2017

A: You are almost there: @ has a lower priority than apply, and thus, as Basil said, Hashtbl.add hash len v@[h] is parsed as (Hashtbl.add hash len v)@[h]. Moreover, you are using way too much parenthesis and if ((Hashtbl.mem hash len)=true) is unnecessary verbose. So a possible good way to write your function is:
let hashify lst =
  let hash = Hashtbl.create 307 in
  let rec collector curmax = function
    | [] -> curmax
    | h::t ->
      let len = List.length h in
      if Hashtbl.mem hash len then
        let v = Hashtbl.find hash len in
        Hashtbl.add hash len (v@[h])
      else
        Hashtbl.add hash len [h];
      collector (max len curmax) t in
  collector 0 lst

A: Most heavy work on hash tables in OCaml hugely benefits from an update primitive. There are actually two versions, which do different things depending on whether the value exists in the table. This is the one you wish to use:
(* Binds a value to the key if none is already present, and then updates
   it by applying the provided map function and returns the new value. *)
let update hashtbl key default func =
  let value = try Hashtbl.find hashtbl key with Not_found -> default in
  let value' = func value in
  Hashtbl.remove hashtbl key ; Hashtbl.add hashtbl key value' ; value'

With these primitives, it becomes simple to manage a hashtable-of-lists:
let prepend hashtbl key item =
  update hashtbl key [] (fun list -> item :: list)

From there, traversing a list and appending everything to a hashtable is quite simple:
let hashify lst =
  let hash = Hashtbl.create 607 in
  List.fold_left (fun acc list ->
    let l = List.length list in
    let _ = prepend hash l list in
    max acc l
  ) 0 lst


text:
Q: Excel VBA - How to convert an Object into a String I like to convert an Object into a string. I found this topic but I can not get it to work in Excel 2010 ("Cast.xxx", "CArray()" and "Array()" seems to be unknown to Excel?)
I know how to convert a variant e.g. "toString = CStr(x)"  but not how to do it the best way for an object
Function toString(ByVal x As Variant) As String
  If TypeOf x Is Object  Then
      toString = ???
  Else
      toString = CStr(x)
  End If
End Function

any suggestions?

A: Are you referring to the IFormattable interface. For example in VB.NET?
Excel VBA isn't a language that will provide you with a ToString method since it doesn't support inheritance.
In your example, you are simply converting whatever the variant is to a string, but an object in VBA wont support this directly.
If you have an external COM object, this would need to be exposed in the interface to access this method to call it from VBA.
For your own classes, you could implement your own IFormattable interface for your objects, but you would have assign to that interface before being able to call the objects ToString method - possible with a helper method. You could of course just supply a ToString method for every class which will through the class interface, but if you want to include this functionality for all objects, then an interface is probably the way to go.
Hope that helps.


text:
Q: Lost cert for published app I have a free app published in Android market.  I have lost the certificate used to sign the current version but I want to publish an updated version. Android market refuses to accept my upgrade because it is signed by a new certificate. I realize the users will have to uninstall the current version to get the upgrade but it's not clear how to get the updated version into the market so that the current users will find it.
What are my options?
Thanks,
John

A: The only option is to change the description for your old app that would point to your new app and hope that existing users will notice it.


text:
Q: How correlated are the statistical significances of the same signal/non-signal for CMS and ATLAS? Consider a diphoton excess for both ATLAS and CMS at the same energy for two cases:

*

*false signal: I'd expect the two statistical significances to be
uncorrelated

*true signal: I'd expect the two statistical significances to be
strongly correlated

In general, can the statistical significance of the same signal for ATLAS and CMS be compared with one another in determining the significance of the signal?


text:
Q: performance impact of long list of catch c++ I want to create a method that can tell me if an exception is retry-able or not. Exceptions are from 3rd party library. So i have something like this :
bool isRetryable ( std::exception_ptr ex) {
    try {
        if(ex) {
            std::rethrow_exception (ex);
        }
        return true;
    } catch (const ExceptionA& ex) {
        return true;
    } catch (const ExceptionB& ex) {
        return true;
    } catch (const ExceptionC& ex) {
        return true;
    } catch (const ExceptionD& ex) {
        return false;
    } catch (const ExceptionE& ex) {
        return false;
    } catch (const ExceptionF& ex) {
        return false;
    }
}

The list of Exceptions can go as long as 100, So my question is - what is the impact of a long list of exception and is there any other way to accomplish the same goal ?

A: It depends on the C++ runtime library, but in general having a long list of catch blocks will result in O(n) performance as the implementation performs a linear scan, matching the thrown exception type against each of the types in the list of catch blocks in turn; this is e.g. how libstdc++ (the default C++ runtime on Linux) works.
I don't know whether any other runtime libraries optimize this, but I'd suspect they wouldn't, as a long list of exception blocks would usually be considered a "code smell" and also since the implementation is required to ensure that the first matching catch block receives the exception, which makes a linear scan the natural implementation.
However, if all your exceptions derive from a polymorphic base (e.g. std::exception) there is a much more elegant solution: you can take the typeid of the exception, construct a std::type_index and look it up in a container:
struct ExceptionA : std::exception {};
// etc.

static std::unordered_set<std::type_index> const retryables{
  typeid(ExceptionA),
  typeid(ExceptionB),
  typeid(ExceptionC)
};

bool isRetryable ( std::exception_ptr ex) {
    try {
        if(ex) {
            std::rethrow_exception (ex);
        }
        return true;
    } catch (const std::exception& ex) {
        return retryables.count(typeid(ex));
    }
}

Example.