text:
Q: Sinon spy method that is called in backbone view initialize I execute a method in the Backbone's View initialize method.
initialize : function(options) {
      this.myMethod();
   }

I am trying to spy on this method using sinon like:
this.spyMyMethod = sinon.spy(this.view, "myMethod");

end then
it('should call my method', function(){
  expect(this.spyMyMethod).toHaveBeenCalledOnce();
});

but the test fails...
Any ideas?

A: You are spying on the method too late.
Wherever you are assigning this.view I assume it is from a call like new Views.SomeView(). It is that new call that will make the initialize function be executed.
Update
I don't really recommend doing this because it is pretty messy, but you can possibly do something like the following: (I don't know sinon but this is how you would do it with the base jasmine spy objects)
it('should call my method', function(){
  var dummyView = new Views.SomeView();
  spyOn(dummyView, "myMethod");
  spyOn(Views, "SomeView").andCallFake(function () {
    dummyView.initialize();
    return dummyView;
  });
  new Views.SomeView();
  expect(dummyView.myMethod).toHaveBeenCalled();
});

Another Possiblilty
Looks like it might be possible to override that method with a spy like below. If that works, it is probably the cleanest way to do this.
it('should call my method', function(){
  spyOn(Views.SomeView.prototype, "myMethod");
  new Views.SomeView();
  expect(Views.SomeView.prototype.myMethod).toHaveBeenCalled();
});

A: you need to return a new instance of your view for the initialize method to be called.
I'm not sure if this.view = new View(); already however


text:
Q: Can I indicate a regular expression requirement for a parameter value using Swagger? In my REST API, one of the submitted parameter values must be a code following the regex:
/[A-Z]{2}[0-9]{4}/
Is there any way, besides putting it in the description property of the parameter, for me to indicate that the value is not valid if it does not match my regular expression?
I was not able to find any mention of regex's in the Swagger doc, except as a way to identify Patterned Fields (which is not what I want to do).

A: You can use a field named pattern in your api's parameters if is not a body or in your scheme definitions for properties, it use standard ECMA 262 : (http://json-schema.org/latest/json-schema-validation.html#rfc.section.3.3)
[UPDATE Jul. 2019]
OpenAPI 3 spec -
https://swagger.io/docs/specification/data-models/data-types/#pattern

redpajama_set_name: RedPajamaStackExchange


text:
Q: (node:9374) Warning: To load an ES module, set "type": "module" I just started to learn React today.
How do I get rid of that error message on my Console in the Terminal in Visual Studio.
(node: 9374)Warning: To load an ES module,
 set "type": "module" in the package.json or use the .mjs extension.
/Users/nishihaider/workspace-ui/react-todo-app/src/App.js:1

import React from "react";
import "./App.css";

function App() {
  <>
  return (

ToDo

  );
  </>
}

export default App;

A: Here is my approach:
1 - Update package.json like:
  "main": "index.js",
  "type":"module",

2 - use.js when importing, like:
import {isPrime} from './isPrime.js';

3 - here is isPrime.js
export const isPrime ....

A: For those using TypeScript with node.js, and is trying to use the import statement. I have found that setting the module to value es2015 in the tsconfig.json gives this error, while setting it to commonjs works.
tsconfig.json
    {
     "module": "commonjs"
    }

A: Just Change this:
export default App;

To this:
module.exports = App;

A: You just need to update package.json like this,
{"type": "module"}

It's worked for me,
Thanks!

A: I have a parent file importing child components, so I get same problem about ES module.
in my case, I must define more details when i import the component. like this:

import db from "../config/Database"; false
import db from "../config/Database.js"; true

Another example :

import Users from "../models/UserModel"; incorrect
import Users from "../models/UserModel.js"; correct

I don't know why it has to be like this, but when I try the problem is resolved. I hope this helps

A: to add Type: module  in package.json - helps :)
package.json contain:
{
  "name": "react_template",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^5.30.0",
    "webpack-cli": "^4.6.0"
  }
}

A: First, install the latest version of Node.js. It has the latest and greatest features.
Second, add the "type": "module" line in your package.json file.
{

  "type": "module"

}

Third, use the --experimental-modules flag when invoking nodejs:
node --experimental-modules app.js
You should be good to go!
An alternative is to avoid adding the "type": "module" line in your package.json file and instead rename your app.js file to app.mjs.
Note that now the require() syntax will stop working.

A: you are also sorrounding the return statement with React Fragments which is not correct. Your return statement should look like the following:
 import React from "react";
 import "./App.css";

 function App() {
   return (
    <>

ToDo

    </>
   );
 }

export default App;

I'm quite sure this was the source of your issues all along and not the module import/export issue.

A: adding the "type": "module" line in your package.json file and instead rename your app.js file (or whatever) to app.mjs.

A: SIMPLE AND FAST SOLUTION FOR BEGINNERS
1  RENAME YOUR JS FILE MJS LIKE  (hello.js >  hello.mjs)
2  GIVE MJS FILE NAME IN YOUR  EXPORT  LIKE  ( import { first } from './pg.mjs')


text:
Q: What is the appropriate usage of 'that is' In this page:
https://arstechnica.com/gadgets/2020/11/google-photos-kills-off-unlimited-storage-policy-moving-forward/
the caption under Figure 1 is:

Google is no longer offering unlimited photo storage—except to Pixel
users, that is.

Why is it necessary to use "that is" at the end?
Does it add any extra information to the preceding sentence?

A:
Google is no longer offering unlimited photo storage—except to Pixel users, that is.

That is adds quite a lot of information. The writer is annoyed with Google and "that is" clarifies that the writer is being satirical and ironic.
Paraphrased, the sentence might read:
That Google is no longer offering unlimited photo storage—except to Pixel users, comes as no great surprise, does it? Google is attempting to control a market that it already dominates. Because Google owns the Pixel brand, it is favouring its own customers so as not to cause a lot of trouble and also to encourage people to buy Pixel phones. This practice is discriminatory as well as being massively inconvenient to the majority of people who do not have a Pixel phone and do not want one. In fact, it is a clear demonstration that Google is attempting, by its power and this imposition to create a monopoly in the marketplace.


text:
Q: why the kubernetes service ip could not expose backend port but the host ip when scanned kubernetes v1.16.0 service cluster ip, it is not shown the service backend service expose port but the host expose port:
bash-4.4# nmap -T4 10.108.94.72
Starting Nmap 7.70 ( https://nmap.org ) at 2020-06-06 18:54 CST
Nmap scan report for service-mysql-for-portal-server.sre.svc.cluster.local (10.108.94.72)
Host is up (0.000011s latency).
Not shown: 995 closed ports
PORT     STATE SERVICE
22/tcp   open  ssh
111/tcp  open  rpcbind
8000/tcp open  http-alt
8443/tcp open  https-alt
9000/tcp open  cslistener

this is my service define:
kind: Service
apiVersion: v1
metadata:
  name: service-mysql-for-portal-server
  namespace: sre
  selfLink: /api/v1/namespaces/sre/services/service-mysql-for-portal-server
  uid: a0f5e0e6-34ba-4e56-b147-bc48badcefc8
  resourceVersion: '113416'
  creationTimestamp: '2020-06-06T04:51:42Z'
  labels:
    app: service-mysql-for-portal-server
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: >
      {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{},"labels":{"app":"service-mysql-for-portal-server"},"name":"service-mysql-for-portal-server","namespace":"sre"},"spec":{"ports":[{"port":3306,"protocol":"TCP","targetPort":3306}],"sessionAffinity":"None","type":"ClusterIP"}}
spec:
  ports:
    - protocol: TCP
      port: 3306
      targetPort: 3306
  selector:
    app: apollo-mysql
  clusterIP: 10.108.94.72
  type: ClusterIP
  sessionAffinity: None
status:
  loadBalancer: {}

why would this happen? what should I do to fix this?


text:
Q: Type T does not satisfy the constraint C for type parameter P error in TypeScript I'm trying to implement this in TypeScript:

interface IViewModel { }
interface IScope<TViewModel extends IViewModel> {
    vm: TViewModel; // {1}
}
interface IController<TViewModel extends IViewModel, TScope extends IScope<TViewModel>> { }

class Controller<TViewModel extends IViewModel, TScope extends IScope<TViewModel>>
    implements IController<TViewModel, TScope> { } // {2}

but I'm getting an error on line {2}: "Type 'IScope<TViewModel extends IViewModel>' does not satisfy the constraint 'IScope<TViewModel extends IViewModel>' for type parameter 'TScope extends IScope<TViewModel>'."
If I go further and try to extend the Controller class:

interface IMainViewModel extends IViewModel { }

class MainController
    extends Controller<IMainViewModel, IScope<IMainViewModel>> { } // {3}

I get a similar error on line {3}: "Type 'IScope<IMainViewModel>' does not satisfy the constraint 'IScope<TViewModel extends IViewModel>' for type parameter 'TScope extends IScope<TViewModel>'."
Seems to me that this should work. What am I doing wrong?
I'm pretty new to TypeScript, I mainly write code in C#, and if I write this code in C# - by just rewriting TypeScript syntax to its C# equivalent, it works just fine.
The weirdest thing is that if I remove line {1}, both errors disappear.

A: Typescript interfaces are structural. That explains why when you removed the only item from {1} you don't get any errors anymore because any thing would be compatible with an empty interface.
That said the following should also work:
interface IScope<TViewModel> {
    vm: TViewModel; // {1}
}

interface IController<TViewModel, TScope extends IScope<TViewModel>> { }
class Controller<TViewModel, TScope extends IScope<TViewModel>>
    implements IController<TViewModel, TScope> { // Gets an error
}

Looks like a typescript compiler error (you might want to report it here). To be clear the following does work:
interface IScope {
    vm: number; // {1}
}

interface IController<TViewModel, TScope extends IScope> { }
class Controller<TViewModel, TScope extends IScope>
    implements IController<TViewModel, TScope> {
}


text:
Q: Can Interactivity reset popup view model every time triggered? Is Interactivity the best way to show new Window? If so how can I reset/re-init ViewModel of my UserControl? Because I see it reuses popup.

A: In the ViewModel for you Interaction Request, there should be a property named Notification. That gets set each time the request is called. Add some logic there to clear the list boxes.
See below:
public INotification Notification
{
    get
    {
        return notification;
    }
    set
    {
        if (value is ItemSelectionNotification)
        {
            notification = value as ItemSelectionNotification;
            OnPropertyChanged(() => Notification);
            //*** Add ListBox clearing code here!!
            // Maybe a call to a method -> ClearListBoxes();
        }
    }
}

This is what my ItemSelectionNotification class looks like in case you need it.
public class ItemSelectionNotification : Confirmation
{
    public ItemSelectionNotification() { }
    public ItemSelectionNotification(object payload)
    {
        Payload = payload;
    }
    public object SelectedItem { get; set; }
    public object Payload { get; } = null;
}


text:
Q: Is the preposition optional in "going down (to) the store"? Cambridge Dictionary says:
In informal situations, we can use down to talk about a quick trip to a destination which we consider to be less central than where we are. In this meaning, we can use it with or without to. Without to is less formal:

I'm just going down (to) the shop. Do you want anything?
Are you going down (to) the golf club tonight?

Is Cambridge wrong here?
I haven't ever heard "I am going down the shop" unless used to say "I'm perusing the aisles of a store", and not "I am going to the shop."
Maybe it's different in the UK? I can't even see how this would begin to be right.
I understand that

*

*I am going down the store

and

*

*I am going down to the store

are two different things. Is there a dialect / is it "informal" to mix those two phrases into the 2nd definition?

A: The Longman Dictionary Online confirms the informal use when omitting "to" in such expressions

go down the shops/club/park etc British English spoken informal to go to the shops, a club etc
Does anyone want to go down the pub tonight?

At risk of sounding classist, elitist or snobbish, I'd say that the expression is mainly used by the working class and younger people.
A British band called Sham 69 has a song named "Hurry Up Harry".
The lyrics include

We're going down the pub
Come on come on
Hurry up Harry come on
Come on come on
Hurry up Harry come on
We're going down the pub
We're going

It's better down the pub, a national campaign celebrating Britain's passion for pubs was launched in May 2013.

As far as I know, the word "shop" is also mainly used by British English speakers as opposed to saying "store".
This EL&U answer as well as this one cover the meanings and etymology of "shop" and its variations.


text:
Q: Which device amplifies the optical signal in fiber optics? My teacher ask me one question. How the optical signal or information was transfered in fiber optics communication?
Then i explained it and use the word optical amplifier then teacher ask me what is optical amplifier i said which amplifies optical signal then again which device amplifies the optical signal in fibre optics communication?
I was dump at that moment i dont have the answer for it and i google it then i read about Doped fiber amplifier(DFA) but i didn't get it so can you give me any suggestion to understand it like any website or explain it.

A: An optical amplifier works just like a laser, but with a few small differences. In a laser, light is created, usually due to spontaneous emission from the gain medium. Light then circulates in an optical cavity while being further amplified in the gain medium. A single photon can traverse the laser cavity many millions of times before being released.
In contrast, an amplifier does not (ideally) produce any laser output on it's own. An amplifier consists of a gain medium, just like a laser, but has no optical cavity in which light circulates. Instead, light enters one end of the cavity, traverses the gain medium only a few times (in the case of a fiber amplifier, only once) and then immediately exits.
In the case of telecommunication equipment, the input light is the data signal that needs to be amplified by the relay station. In many other applications, coupling a low power seed laser with an optical amplifier can be a convenient and efficient way to get a high power laser beam. A lot of laser cutting and machining is done this way, for example. In this case engineers may call the laser system a Master Oscillator/Power Amplifier or MOPA system.


text:
Q: qgis join attributes by location - options when joining attributes by location there are a multitude of options to tick:

*

*intersects

*overlaps

*contains

*within

*equals

*crosses

*touches

There is no documentation available.
Where could I find information, what each of these options means?

A: This links explains the spatial relationships defined by the Open Geospatial Consortium:
[https://docs.safe.com/fme/html/FME_Desktop_Documentation/FME_Transformers/Transformers/spatialrelations.htm][1]
This should help you.

A: The link in the accepted answer gives a 404, use the version in the comment.
Alternatively, this answer on GIS stack exchange also gives a great overview of the differences specific to QGIS.


text:
Q: includes function not working for plotly trace - js I have an array of Plotly traces.
console.log(traces):
traces:
[{…}]
0:
name: "temprature"
type: "scatter"
x: (7523) [1527581340000, …]
y: (7660) [15.68, …]
__proto__: Object
length: 1
__proto__: Array(0)

At an event, I want to check if a newly created trace is on the list or not. Firstly, I check it with the includes function but it didn't work, then I found this answer on how to check the availability of an object in an array in js.
function contains(a, obj) {
        for (var i = 0; i < a.length; i++) {
            if (a[i] === obj) {
                return true;
            }
        }
        return false;
}

but it seems not to work for me.
$("#temprature").change(function () {
        var trace_temprature  = {
                            x: index,
                            y: temprature,
                            name: document.getElementById('temprature').name,
                            type: 'scatter'
        };

        if (document.getElementById('temprature').checked) {
            if( !traces.includes(trace_temprature) ){
                traces.push(trace_temprature);
            }
            console.log('trace in the add ', traces);
            console.log('temperature trace: ', trace_temprature) // this line prints the same object on the previous list

        } else {
            console.log('if condiiton: ', contains(traces, trace_temprature)); // this line print False
            if( contains(traces, trace_temprature) ){
                var ind = traces.indexOf(trace_temprature);
                traces.splice(ind, 1);
            }

        }

    });

any ideas?


text:
Q: Javascript passed array has no length my javascript code stop executing when I try to access the length property from my passed array.
var arrParams = getParams(url);
var strRef = getRef(arrParams);

function getRef(pv_arrParams)
{
    portFromCS.postMessage({greeting: 'before .length'});
    portFromCS.postMessage({greeting: pv_arrParams.length}); <- no log
    .
    .
    .
}

the array is not null or empty. When I debug its works fine but not otherwise.
edit: here is an example. Its a Firefox addon
https://www.file-upload.net/download-12913625/example.rar.html
so when I debug its not empty or undefined:


text:
Q: Tortoise SVN in not working with Netbeans 11 I installed Netbeans 11 but when I committed a code there is an error. But TortoiseSVN works fine with netbeans 8.2.

A: You need re-run the TortoiseSVN installer (or during the TortoiseSVN installation) and select the option "command line client tools". I have made a screenshot of the option that appears during installation:

Enabling this option netbeans 11.1 starts detecting SVN.


text:
Q: Vertical align with bootstrap not working Maybe I don't have it setup right? I've been looking at code for the past 3 hours so it's possible I'm over looking something. Either way I have this h3 in a div and I want it to be centered both horizontally and vertically, however only horizontal is working.

{{ uni.u_name }

Update: Using Bootstrap V4

A: This answer is for bootstrap 4:
To vertically align the column content, you can use my-auto class in column itself:

           {{ uni.u_name }

Further, to align the items inside a column horizontally, you can use mx-auto and for both horizontal and vertical alignment, use m-auto. Horizontal align will work for single column.

To align all the columns, you need to supply the align-items-* classes inside the row element but not inside the col element:

      Top A

      Top B

      Top C

      Mid A

      Mid B

      Mid C

      Bottom A

      Bottom B

      Bottom C

Hope this helps!

A: try with flex and align-self-center:

      Center

      Taller

A:

.align-items-center {
  display: flex;
  align-items: center;  /*Aligns vertically center */
  justify-content: center; /*Aligns horizontally center */
}

Hello

A: check this css

{{ uni.u_name }

and this is the css (put it in the head tag)


text:
Q: Move specific item to last position Let there is a model Item with attributes id, name and specific record in DB with name 'other'.
How to get in single SQL query an ActiveRecord::Relation object with items sorted in way that other item is at last position?
As temporarily solution I used Item.where.not(name: 'other') + Item.where(name: 'other') but it results in 2 queries.
NB: it's not a real code but an extremely simplified example.

A: Perhaps something like below will help - we read all Items, and use slice to remove the Item with name equal to other, and append it back to array at the end.
a = Item.all.tap do |arr|
    arr << arr.slice!(arr.index { |t| t.name == "other"})
end

A: if i get you right then you're looking for a SQL query, right? Then you could try something like that:
select id, name
from (
  select id, name, decode(name, 'other', 999, 1) as sort
  from items
)
order by sort

I have no database right now to test the statement. But I think you get the idea.
Good luck

A: Resolved with adding class method to Item model:
def self.sorted
  find_by_sql("SELECT * FROM items ORDER BY (CASE name WHEN 'other' THEN 0 ELSE 1 END) DESC, id ASC")
end


text:
Q: Linux picking wrong source IP I have an EC2 instance running on a k8s cluster. The instance has three three interface cards.
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9001 qdisc mq state UP group default qlen 1000
    link/ether 02:9c:bb:70:ee:be brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.206/24 brd 10.0.2.255 scope global dynamic eth0
       valid_lft 2821sec preferred_lft 2821sec
---
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 02:7a:d4:ac:64:b4 brd ff:ff:ff:ff:ff:ff
    inet6 fe80::7a:d4ff:feac:64b4/64 scope link
       valid_lft forever preferred_lft forever
9: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 9001 qdisc mq state UP group default qlen 1000
    link/ether 02:54:4e:b4:b4:e8 brd ff:ff:ff:ff:ff:ff
    inet 10.0.6.4/24 brd 10.0.6.255 scope global dynamic eth2
       valid_lft 2863sec preferred_lft 2863sec
    inet6 fe80::54:4eff:feb4:b4e8/64 scope link
       valid_lft forever preferred_lft forever

Please ignore eth1 as not yet configured correctly.
When I ping (ping -I 10.0.6.4 www.google.com) from eth2 to internet, I notice that linux picks the primary interfaces's IP
[ec2-user@ip-10-0-2-206 ~]$ sudo tcpdump -i eth2 -n
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth2, link-type EN10MB (Ethernet), capture size 262144 bytes
14:19:08.968772 IP 10.0.2.206 > 142.251.42.36: ICMP echo request, id 17679, seq 9, length 64
14:19:09.992871 IP 10.0.2.206 > 142.251.42.36: ICMP echo request, id 17679, seq 10, length 64
14:19:11.016767 IP 10.0.2.206 > 142.251.42.36: ICMP echo request, id 17679, seq 11, length 64

As you can see the source IP is incorrectly selected as 10.0.2.206 instead of 10.0.6.4.
[ec2-user@ip-10-0-2-206 ~]$ ip rule
0:      from all lookup local
511:    from 10.0.6.4 lookup 10002
512:    from all to 10.0.2.4 lookup main
512:    from all to 10.0.2.185 lookup main
512:    from all to 10.0.2.233 lookup main
1024:   from all fwmark 0x80/0x80 lookup main
32766:  from all lookup main
32767:  from all lookup default

[ec2-user@ip-10-0-2-206 ~]$ sudo ip route show table 10002
default via 10.0.6.1 dev eth2 src 10.0.6.4
10.0.6.0/24 dev eth2 proto kernel scope link src 10.0.6.4

[ec2-user@ip-10-0-2-206 ~]$ sudo ip route show table main
default via 10.0.2.1 dev eth0
default via 10.0.6.1 dev eth2 metric 10002
10.0.2.0/24 dev eth0 proto kernel scope link src 10.0.2.206
10.0.2.4 dev eni379b345d249 scope link
10.0.2.185 dev eni0231b3becdb scope link
10.0.2.233 dev eni5be9f7773c7 scope link
10.0.6.0/24 dev eth2 proto kernel scope link src 10.0.6.4
169.254.169.254 dev eth0

[ec2-user@ip-10-0-2-206 ~]$ ip route get 172.217.174.68 from 10.0.6.4
172.217.174.68 from 10.0.6.4 via 10.0.6.1 dev eth2 table 10002 uid 1000
    cache

All config seems to be correct but source address is still picked up from primary interface. What am I missing?

A: The one place I did not look carefully is iptables. I found the following entries in it.
Chain AWS-SNAT-CHAIN-0 (1 references)
target     prot opt source               destination
AWS-SNAT-CHAIN-1  all  --  anywhere            !ip-10-0-0-0.xxxx.compute.internal/16  /* AWS SNAT CHAIN */

Chain AWS-SNAT-CHAIN-1 (1 references)
target     prot opt source               destination
SNAT       all  --  anywhere             anywhere             /* AWS, SNAT */ ADDRTYPE match dst-type !LOCAL to:10.0.2.206 random-fully

Searching further, I found AWS documentation on the subject: https://docs.aws.amazon.com/eks/latest/userguide/external-snat.html
As per documentation when I executed the command kubectl set env daemonset -n kube-system aws-node AWS_VPC_K8S_CNI_EXTERNALSNAT=true, the SNAT entries were removed from the VMs.
Once that was done, pings from eth2 showed correct source IP - 10.0.6.4.


text:
Q: Integrate Laravel with AWS cognito I configured a AWS Cognito user pool few months ago & connected it to node.js application, everything was perfect
Now, I want to connect laravel to AWS Cognito, I followed the instructions in this article
I get the following error
Error executing "AdminInitiateAuth" on "https://cognito-idp.eu-west-1.amazonaws.com"; AWS HTTP error: Client error: `POST https://cognito-idp.eu-west-1.amazonaws.com` resulted in a `400 Bad Request` response:
{"__type":"UnrecognizedClientException","message":"The security token included in the request is invalid."}
UnrecognizedClientException (client): The security token included in the request is invalid. - {"__type":"UnrecognizedClientException","message":"The security token included in the request is invalid."}

I'm every sure the credentials is correct, but I get this error.
Is there any missing configuration in the article?

A: I've had the same 'problem' following the same article. I've fixed it by verifying my credentials in the .env
AWS_COGNITO_KEY=
AWS_COGNITO_SECRET=

These are the Access Keys of the IAM user
https://github.com/black-bits/laravel-cognito-auth#cognito-user-pool


text:
Q: Can I use fd redirection in bash to input from and output to different files? My program read and write fd = 3 (for example), I want it read from file1 and write to file2 when running it in bash. Can I use fd redirection to make it?
Something like below, but it's wrong
./prog 3<file1 3>file2

A: If what you want is to copy file1 to file2 and file1 is a text file:
First open file1 to read from it
exec 3<file1
Then file2 to write to it. Use different fd than the one used for file1
exec 4>file2
Finally you'd like to iterate over file1 like this
while read -u 3 line;  do  echo $line >&4 ; done

In fact it can be executed in a single line
 exec 3<file1 ; exec 4>file2 ; while read -u 3 line;  do  echo $line >&4 ; done

Enjoy!


text:
Q: Is it possible to make passive voice of following sentences What will be the passive of these sentences? Are 'going' and 'go' intransitive verbs in these sentences?

I am going to school
I go to London

Any help would be appreciated.
Thank you

A: As pointed out in the comments, the intransitive verb "go" not having a direct object makes it difficult to construct a passive form. You would need to use a transitive verb in order to construct a passive form.

*

*I am going to school.

*

*--> I am approaching the school.

*--> The school is being approached by me.

*I go to London.

*

*--> I am approaching London.

*--> London is being approached by me.


text:
Q: Tick labels above axis Is there any way to place tick marks on the x-axis above the axis? Note that I am talking about marks on the axis, not on a frame (because my graph has no frame). To be more specific, here's the reason I need that: I have a graph of a lower semi-circle with some shading generated by the following code:
ClearAll[x, y, a];
gthick = Thickness[0.005];
g1 = RegionPlot[x^2 + y^2 < 1 , {x, -1, 1}, {y, -0.6, 0}, Frame -> False];
g2 = Plot[-Sqrt[1 - x^2], {x, -1, 1}, PlotStyle -> {Red, gthick}];
g3 = ListLinePlot[{{-0.8, -0.6}, {0.8, -0.6}}, PlotStyle -> {Blue, gthick}];
g4 = Graphics[{Dashing[Small], Line[{{-0.8, -0.6}, {-0.8, 0}}],
   Line[{{0.8, -0.6}, {0.8, 0}}]}];
Show[{g1, g2, g3, g4}, PlotRange -> {{-1.2, 1.2}, {-1.2, 0.2}},
   AspectRatio -> Automatic, Axes -> True, AxesOrigin -> {0, 0},
   Ticks -> {{{-1.05, -1, 0}, {-0.65, -Sqrt[1 - a^2], 0}, {0.65, Sqrt[1 - a^2], 0},
   {1.05, 1, 0}}, None}, TicksStyle -> Directive[FontSize -> 15]]

And the output (anybody can check that) is:

Anybody can see that on a picture like this, so that it looks nice, tick labels should be above the x-axis. But how?
P.S. (edited) I know that I can add text on the graph at desired positions. But can it be achieved with tick labels being tick labels, thru some options?


text:
Q: Soundmanager2 Soundcloud API crossdomain.xml I am using Soundmanager2 to stream files from soundcloud and display Eq visuals, but I'm having trouble with getting the eqdata when pausing or changing a track.
Shown here
I understand that Flash is unable to access the metadata due to the cross domain policy defined in the "crossdomain.xml" file on soundcloud as seen in this post: (and many others)
How to use SoundManager2 to stream from SoundCloud, and make visualizations?
I realize that I have to resolve the track's stream_url before loading it into sound manager. I'm doing this with an ajax call to a php script that resolves the url (shown below):
var client_id = '866143113772fec9556700f7f88f3abc',
url = 'http://api.soundcloud.com/resolve.json?url=http://soundcloud.com/aries-audio-music/tracks&client_id=';

$.getJSON(url+client_id+'&callback=?', function(playlist){

    $.each(playlist, function(index, track) {

        //append to playlist
        $('
' + track.title + '
').data('track', track).appendTo('.tracks');

        //get resolved stream url
        $.ajax({
            type: 'GET',
            url: 'get_sc_url.php?id='+track.id,
            success: function(data) {
                console.log(data);
                sm2_addtrack(track, data);      //create SM2 sound object with resolved url
            }
        });
    });
});

function sm2_addtrack(track, stream_url) {
    soundManager.createSound({
        id: 'track_' + track.id,
        url: stream_url,
        usePolicyFile : true,
        usePeakData: false,
        useWaveformData: false,
        useEQData: true,
.....

get_sc_url.php used to resolve stream_url
<?php

require 'include/referrer_check.php';
require 'include/SC_API_KEY.php';
require 'include/API_cache.php';

$track_id = intval($_GET['id']);
$key = get_soundcloud_api_key();
$api_call = 'http://api.soundcloud.com/tracks/'.$track_id.'/stream/?client_id='.$key;

function get_web_page($url) {

    /*
     * hat tip: http://forums.devshed.com/php-development-5/curl-get-final-url-after-inital-url-redirects-544144.html
    */

    $options = array(
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_RETURNTRANSFER => false,     // return web page
        CURLOPT_HEADER => true,
        CURLOPT_NOBODY => true,
        CURLOPT_CONNECTTIMEOUT => 5,        // timeout on connect
        CURLOPT_TIMEOUT        => 5,        // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
        CURLOPT_RETURNTRANSFER => true,     // return web page
    );

    $ch      = curl_init( $url );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    curl_close( $ch );

    return $header;
}

$myUrlInfo = get_web_page($api_call);

echo $myUrlInfo["url"];

?>

The result I am getting is something like this:
ec-media.soundcloud.com/Ez0B3lUZjjCR.128.mp3?f10880d39085a94a0418a7ef69b03d522cd6dfee9399eeb9a52200996dfabd3cefb29b7554ff4fd02baab5100d3a070e07d55f6e1eb41808c65398ce84cd496788c171f7e4&AWSAccessKeyId=AKIAJNIGGLK7XA7YZSNQ&Expires=1415223069&Signature=A0qaC1Nr3%2FXw4jwFYMjA%2F98arwI%3D
which plays but gives me no spectrum data at all and I still get the
computeSpectrum() (EQ data) SecurityError: Error #2123
from soundmanager2.
I know for sure that ec-media.soundcloud.com/crossdomain.xml is being downloaded, but I still can't solve this problem.

A: I think it may be because I'm trying to access the soundcloud crossdomain.xml policy file (which is HTTPS) from a HTTP document. secure="false" is not defined in Soundcloud's crossdomain.xml policy file so it defaults to secure="true", therefore the SWF can not access anything.
I doubt Soundcloud will ever set secure="false" in their crossdomain.xml for obvious reasons (it defeats the purpose of even having HTTPS).
I "think" this is why I get computeSpectrum() (EQ data) SecurityError: Error #2123, but I don't have access to a HTTPS enabled server to test this so I could be wrong.


text:
Q: Is there a way to effectively change the year dash(ex. 1976-1977) to a processable one? I was just practicing and got stuck here.
I was trying to convert my Date(dtype was object) to int data. But when I typed in
pd.to_numeric(df.date)

it gave me
ValueError: Unable to parse string "1976-77" at position 5

and it seems that although the df I have mostly is written in int format(ex. 1977) it does have quite a lot that is written like the above(1976-77)
I do understand that I can just ignore those and type in
pd.to_numeric(df.date, errors='coerce')

But, I was wondering if there is a way to handle those data with dashes too? Maybe by modifying all the data containing "-", leaving them with only the year in front of them? e.g. convert "1967-1968" to "1967"

A: If 'Dates' is your column then following might help:
df['NewDates']=df['Dates'].apply(lambda x: str(x).split("-")[0])

Just splitting on dash and retaining first element

A: Instead of apply you can perform str operations directly on Dataframe column using the str function
In [36]: df = pd.DataFrame({"date":["2020-2021","1964-1965","1999-2000"]})

In [37]: df
Out[37]:
        date
0  2020-2021
1  1964-1965
2  1999-2000

In [38]: df["NewDates"] = df.date.str.split("-",expand=True)[0]
Out[38]:
0    2020
1    1964
2    1999
Name: 0, dtype: object


text:
Q: How do I store order of a sortable multiselect with select2-rails? I have a ton of many-to-many relationships in a CMS I built for work.  I am currently using Select2 3.5.3 to assign these relationships.  This all works well.  My issue is attempting the make them drag and drop sortable and store the result of this in the database.
I got the  Select2 Drag and Drop Sorting section demo working in my forms, but I don't quite understand how I would make this dynamic like the rest of my select2 instances  -- in my simple implementation I initialize select2 on anything with the .select2 class.  I also don't understand how I would store order in the db.
I have an example below modified from an old Ryan Bates update function.  In this example I am attempting to update the Case Study model relationship with the Site model.  Case Study and Site have standard has-and-belongs-to-many relationships with each other.
Models
sites.rb
  has_many :case_studies_sites
  has_many :case_studies, :through => :case_studies_sites

case_study.rb
  has_many :case_studies_sites
  has_many :sites, :through => :case_studies_sites

Update Function
...how I think it would be accomplished.  One other important point to note: I have added a position:integer field to the case_studies_sites table.
def select2_sort
    self.case_studies.each_with_index do |id, index|
      CaseStudiesSite.where(case_study_id: id).update_all({position: index+1})
    end
  end

Forms and JS
sites/_form.html.erb
Here is an example of the sites form.
   <div class="form-group">
      <%= f.label :case_study, "Related Case Studies" %>
      <%= f.collection_select :case_study_ids, CaseStudy.all, :id, :title, {}, {class: 'select2 form-control', multiple: true} %>
   </div>

sites.js.coffee
And finally here is the coffee script I am currently using to run the basic select2.
$(document).on 'ready page:load', ->
  $('.select2').select2()

Both the form fields and JS are currently set for the standards select2 (aka not sortable) as I have not figured out how to translate the select2 demo to these fields.


text:
Q: Need carification on the JavaScript code behaviour in strict mode In this MDN document about the Strict Mode of JavaScript, under "Semantic differences -> this in function calls", it's mentioned that:

When a function was called with call or apply, if the value was a primitive value, this one was boxed into an object (or the global object for undefined and null). In strict mode, the value is passed directly without conversion or replacement.

I need clarification for this statement. When I test this, I don't see any difference based on the mode (strict or sloppy) of the code.
Please let me know if I have misunderstood the statement.
This is how I've tested:

(function() {
  function a() {
    console.log(this);
  }

  function b() {
    "use strict";
    a.call(2);
  }

  function c() {
    a.call(3);
  }

  b();
  c();
})();

Result :

A: The behavior being described depends on whether the function being called is in strict mode, not the caller.

(function() {
  function strict() {
    "use strict";
    console.log(this);
  }

  function sloppy() {
    console.log(this);
  }

  function b() {
    strict.call(2);
  }

  function c() {
    sloppy.call(3);
  }

  b();
  c();
})();

Normally you put an entire script into strict mode, so the distinction between caller and callee doesn't matter.


text:
Q: Width Of page Changing When Height Exceeds Viewable Area I made a website.  When the body get longer than the page so that a scroll bar will show up, the body is moved a few pixels to the left.  This confuses me.  Is there some automated setting that is doing this?
This is my css if u want to see it.
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font: inherit;
  vertical-align: center;
}

#cohenImage{
    float:right;
    margin-left:1em;
    border: .2em solid #D3D3D3
}

.block {
    display:block;
}

/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
  display: block;
}

/*******************************************************************************
Theme Styles
*******************************************************************************/

body {
    box-sizing: border-box;
    color:#373737;
    background: transparent;
    font-family: 'Myriad Pro', Calibri, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    width: 70%;
    margin-right:auto;
    margin-left:auto;
    padding: 3em;
    background-image:url('../Cohen-Background.jpg');
    background-color:#000000;
}

.inline{
    display:inline;
}

.title {
  margin: 0;
  color: #fff;
  font-size: 300%;
  font-weight: 700;
  text-shadow: #111 0px 0px 10px;
  padding-top:.8em;
  padding-bottom:.7em;
}

h1, h2, h3, h4, h5, h6 {
  margin: 10px 0;
  font-weight: 700;
  color:#222222;
  font-family:'Lucida Grande', 'Calibri', Helvetica, Arial, sans-serif;
  letter-spacing: -1px;
}

h1 {
  font-size: 250%;
  font-weight: 700;
}

h2 {
  padding-bottom: 10px;
  font-size: 250%;
}

h3 {
  font-size: 200%;
}

h4 {
  font-size: 170%;
}

h5 {
  font-size: 120%;
}

h6 {
  font-size: 110%;
}

p {
  font-size:105%;
}

b {
    font-weight:bold;
}

footer p {
  color: #f2f2f2;
}

ul.menu {
    margin: 0;
    padding: 0;
}

ul.menu {
    height: 80px;
    float:left;
}

ul.menu li {
    list-style: none;
    float:left;
    height: 2em;
    text-align: center;
    background : -webkit-gradient(linear, left top, left bottom, from(rgb(168,168,168)), to(rgb(69,69,69)));
    background : -moz-linear-gradient(top, rgb(168,168,168), rgb(69,69,69));
    background: -o-linear-gradient(top, rgb(100,170,255) 0%,rgb(69,69,69) 100%);
    background: -ms-linear-gradient(top, rgb(100,170,255) 0%,rgb(69,69,69) 100%)
}

ul.menu li a {
    display: block;
    padding: 0 20px;
    text-align: center;
    line-height: 2em;
    text-decoration:none;
    background : -webkit-gradient(linear, left top, left bottom, from(rgb(168,168,168)), to(rgb(69,69,69)));
    background : -moz-linear-gradient(top, rgb(168,168,168), rgb(69,69,69));
    background: -o-linear-gradient(top, rgb(168,168,168) 0%,rgb(69,69,69) 100%);
    background: -ms-linear-gradient(top, rgb(168,168,168) 0%,rgb(69,69,69) 100%);
    color:white;
    font-weight:bold;
}

ul.menu li a:hover {
    background: #919191;
}

ul li.active a{
    background : #9E9E9E;
}

.wrapper {
    width: 100%;
    height: 2.1em;
    background : #464646;
    background : -webkit-gradient(linear, left top, left bottom, from(rgb(168,168,168)), to(rgb(69,69,69)));
    background : -moz-linear-gradient(top, rgb(168,168,168), rgb(69,69,69));
    background: -o-linear-gradient(top, rgb(168,168,168) 0%,rgb(69,69,69) 100%);
    background: -ms-linear-gradient(top, rgb(168,168,168) 0%,rgb(69,69,69) 100%)
    position: relative;
}

.inner {
  position: relative;
  padding: 2em;
  margin: 0 auto;
  font-size:105%
}

.header{
  background:rgba(0, 0, 0, 0.9);
  border-top: .3em solid #2E2E2E;
  border-left: .3em solid #2E2E2E;
  border-right: .3em solid #2E2E2E;
  border-top-left-radius: 1em;
  border-top-right-radius: 1em;
  text-align:center;
  margin-right:auto;
  margin-left:auto;
  color:white;
}

#main_content_wrap {
  background: #FCFCFC;
  text-align:left;
  padding:0;
  margin:0;
}

#main_content {
  padding-top: 3em;
}

#footer_wrap {
  background:rgba(0, 0, 0, 0.9);
  border-top: .3em solid #2E2E2E;
  border-left: .3em solid #2E2E2E;
  border-right: .3em solid #2E2E2E;
  border-bottom-left-radius: 1em;
  border-bottom-right-radius: 1em;
  text-align:center;
  margin-right:auto;
  margin-left:auto;
  color:white;
}

table {
    background-color: #EEEEEE;
    border: 2px solid #D4D4D4;
    border-collapse: collapse;
    padding-left: 2px;
}
thead {
    color:black
}
th {
    background-color: #D4D4D4;
    padding-right: 4px;
}
tr, td, th {
    border: 2px solid #D4D4D4;
    padding-left: 4px;
}
dt {
    font-weight: bold;
}

/*******************************************************************************
Small Device Styles
*******************************************************************************/

/* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
        body{
        width: 100%;
    }
}

/* Smartphones (landscape) ----------- */
@media only screen
and (min-width : 321px) {
        body{
        width: 100%;
    }
}

/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {
    body{
        width: 100%;
    }
}

/* iPads (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
    body{
        width: 100%;
    }
}

/* iPads (landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) {
    body{
        width: 100%;
    }
}

/* iPads (portrait) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) {
    body{
        width: 100%;
    }
}

/* Desktops and laptops ----------- */
@media only screen
and (min-width : 1224px) {
    body{
        width: 70%;
    }
}

/* Large screens ----------- */
@media only screen
and (min-width : 1824px) {
    body{
        width: 70%;
    }
}

/* iPhone 4 ----------- */
@media

only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
    body{
        width: 100%;
    }
}

A: This is a feature of almost all browsers. If an element is too tall for the window, the vertical scroll bar appears. This scroll bar does occupy some of the width that was previously available to the window. So if you have css that depends on the width of the window, like width: 100%, then those items will change size. If you want the vertical scroll bar to not appear and not take up any of your screen width use something like: overflow: hidden or overflow-y: hidden

A: The browser has to make room for the vertical scrollbar (not all browsers, Safari and maybe Chrome on OS X may render the scrollbar on top of content, I didn't test for a long time so I'm not sure).
This is the expected behavior of an element part of the UI of the software that a browser is: please see a previous answer on the reasons this is expected from the user and not a problem to be solved by us webdesigners and webdevelopers.


text:
Q: Log android app events I want to find a good 3rd party tool to use for logging all my android app events and view on a remote server. I only have access to client side of the app with no control of the server side.
I want to track the following from my app:

*

*Which screen did users visit

*What actions he did on the screens(with
timestamps)

*Some app specific relation between these events. (the
app has a bunch of actions together which constitute a meaningful
event)

*User Information etc.

I am currently using ACRA + Google docs (old format) for tracking crashes-only. But cannot create any new project using this setup anymore (google doc support deprecated).
Also what would be a good architecture to submit the logs - at every event, group them together.

A: Try google analytics :
http://www.google.com/analytics/
or flurry:
http://www.flurry.com/


text:
Q: How to call C++ exe with multiple parameters from command line using C# .net i am performing offline operations on images taking image as a input  with parameters and processing it in VTK C++ exe i am unable to pass parameters to C++ exe through C#  program and retrive output .
please explain  me with  some example

A: If you just mean that you have a compiled C++ program (which we'll call "foo.exe", with path stored in string "exe_folder") and you want to call that with command line parameters (stored in string "exe_params") from C#, then the following should work:
string exe_params = "target_image.jpeg HOUGH_TRANSFORM"; // Or whatever params are appropriate.
string exe_full_path = Path.Combine(exe_folder, "foo.exe");
Process proc = System.Diagnostics.Process.Start(exe_full_path, exe_params);

https://msdn.microsoft.com/en-us/library/h6ak8zt5(v=vs.110).aspx

A: Let say that your executable is called test.exe and it is in the test dir. For me, the following would be working:
        Process process = new Process();
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.FileName = "cmd.exe";
        startInfo.Arguments = "/C cd C:\\..test\\ && test.exe target_image.jpg yourtransformation";
        process.StartInfo = startInfo;
        process.Start();

If you have further problems, try setting the working directory of processStartInfo.


text:
Q: Positioning an overlay produces a different outcome to drawtext with ffmpeg I have an image overlay I'm positioning using the equation: overlay=1015:(((H-h)/2) + 225 + 60) which works as expected.
However, when I try and apply this to drawtext x=1045:y=(((H-h)/2) + 225 + 60) it doesn't position at the same y coordinate?
Are there any nuances people know about?
Thanks.

A: The overlay and drawtext filters have different variable names.
Assuming you mean H to refer to the height of the frame and h and the height of the text, you would replace h with th. Both H and
h refer to the frame height in drawtext.
x=1045:y=(((H-th)/2) + 225 + 60)


text:
Q: How to read python data types from a file This seems like it should be the most basic thing to do in python that it should be almost a default option.  I have a text file that has lines such as
123, [12, 23, 45, 67]

The second array is variable in length.  How do I read this in?  For whatever reason I cannot find a single piece of documentation on how to deal with '[' or ']' which one might argue is the single most basic character in python.
np.loadtxt was a bust, apparently this is only for the most simple of file formats
np.genfromtxt was a bust, due to the missing columns.  BTW one would like to believe the missing_value functionality could be helpful here.  Would be useful to know what, if anything, the missing_value thing actually does (it is not explained clearly in the documentation at all).
I tried the np.fromstring route  which gives me
['123', '[12', '23', '45', '67]']

Presumably I could parse this item by item to deal with the '[' and ']' but at this stage I have just made my own python file reader to read in a fairly basic python construct!
As for the desired output, at this stage I would settle for almost anything.  The obvious construct would be line by line of the form
[123, [12, 23, 45, 67]]

A: loadtxt and genfromtxt parse a line, starting with a simple split.
In [360]: '123, [12, 23, 45, 67]'.split(',')
Out[360]: ['123', ' [12', ' 23', ' 45', ' 67]']

then they try to convert the individual strings.  Some convert easily to ints or floats.  The ones with [ and ] don't.  Handling those is not trivial.
The csv reader that comes with Python can handle quoted text, e.g.
 `one, "twenty, three", four'

I have not played with it enough to know whether it can treat [] as quotes or not.
Your bracketed text is easier to parse if you use different delimiters inside the brackets, eg
In [371]: l1='123; [12, 23, 45, 67]'.split(';')
In [372]: l1
Out[372]: ['123', ' [12, 23, 45, 67]']
In [373]: l2=l1[1].strip().strip(']').strip('[').split(',')
In [374]: l2
Out[374]: ['12', ' 23', ' 45', ' 67']

As Warren commented, plain CSV is something of an industry standard, and used in many languages.  The use of brackets and such has not been standardized.  But there are data exchange languages like XML, JSON and yaml, as well as non-text data files (e.g. HD5F).
JSON example:
In [377]: json.loads('[123, [12, 23, 45, 67]]')
Out[377]: [123, [12, 23, 45, 67]]

A: The default option is eval. It lets you evaluate Python expressions in strings. It's a security hazard though, see e.g. this question. But ast.literal_eval should be okay. For example:
from ast import literal_eval

with open("name of file") as fh:
    data = [literal_eval(line) for line in fh]


text:
Q: Graph-theory question regarding degrees and cliques Suppose we have a graph $G$, where each node in there has a degree of at most $d$. I need to show that it is possible to determine if $G$ has a clique of size $k$ in time of at most $n^c \cdot d^k$ steps where $c$ is some constant.
Any help will be great.

A: For each vertex $v$, denote by $\Gamma(v)$ the set of neighbors of $v$. For each vertex $v$, set $A_1:=\Gamma(v)$ and $C_1:=\{v\}$. In the following recursion, $A_i$ denotes the set of possible candidates to enter the clique and $C_i$ is the largest clique containing $v$ which we have already found:
For each $w\in A_i$, check whether $C_i\subseteq\Gamma(w)$. If so, then we have found a larger clique $C_{i+1}:=C_i\cup\{w\}$. Also, we can set $A_{i+1}:=\Gamma(w)\cap A_i$ since any vertex in an even larger clique will have to be a neighbor of all vertices in $C_{i+1}$. For performance reasons, we would stop as soon as $|A_i\cup C_i|<k$, of course.
If at some point you reach $i=k$, then $C_k$ is a clique of size $k$. On the other hand, if there is a clique of size $k$, then this procedure will find it by starting at any of its vertices. The running time is $nd^k$.


text:
Q: Would like to write bytes to multiple binary files I need to write the same bytes to all files with extension TIFF in a particular folder. I am completely new to PowerShell (or any other coding for that matter). I have worked out how to change the bytes in a single file like this (simplified for this post):
$bytes  = [System.IO.File]::ReadAllBytes("C:\test.tiff")
$bytes[5] = 0x51
$bytes[8] = 0x4A
[System.IO.File]::WriteAllBytes("C:\test.tiff", $bytes)

However, rather than specifying the file I need to loop through the files in a particular folder to check if they have the extension TIFF before writing the bytes and I am not sure how to do that. Any help would be appreciated.

A: use a ForEach loop with Get-ChildItem
foreach ($File in (Get-ChildItem 'C:\Folder' -Filter '*.tiff')){
    $bytes  = [System.IO.File]::ReadAllBytes($File.FullName)
    $bytes[5] = 0x51 ; $bytes[8] = 0x4A
    [System.IO.File]::WriteAllBytes($File.FullName, $bytes)
}

change C:\Folder to your folder, this will modify only .tiff files.


text:
Q: Limit which menu/nav items appear based on User Agent / Device in Wordpress.. possible? I'm in the process of turning a clients wordpress site into a responsive design, mostly just building a mobile version.
The client has expressed that they don't want all of their pages to appear on the mobile site, so instead of the full 7 primary menu items, I'd only be using 5.
I'm not sure what the best way to do this would be, I've only ever built Mobile sites separately before. Any input would be appreciated, or links to tutorials / information regarding what I'm trying to do. Thank you.

A: You could give those elements custom classes and then hide them based on device max-width. You can setup any number of rules like this and this is what is commonly known as a media query. It's the basis for changing styles based on size.
@media only screen and (max-width: 959px) {
    div.desktop-only {
    display:none;
    }
    }

You can also set a range.
@media only screen and (min-width: 768px) and (max-width: 959px) { /*code here*/ }


text:
Q: Combining the rows with overlapping data ranges in SAS Since I am new to SAS I need some help to understand how to combine the overlap date ranges into one row.I want to combine the overlap date ranges when they have matching Id. If the dates don't overlap then I want to keep them as it is. IF they over lap by Matching Id and drug code Then it should combine into one line. Please look at the same ple data set which I have below and the expected results:
            Current Data set:
            ID  Drug Code   BEG_Date    End_Date
            1   100 1/1/2018    1/1/2019
            1   100 1/1/2018    3/1/2018
            1   100 2/1/2018    04/30/2018
            1   90  4/1/2018    04/30/2018
            1   100 5/1/2018    6/1/2018
            1   98  6/1/2018    8/31/2018
            1   100 9/1/2018    5/4/2019

            Expected results:
            ID  Drug Code   BEG_Date    End_Date
            1   100 1/1/2018    3/31/2018
            1   90  4/1/2018    04/30/2018
            1   100 5/1/2018    6/1/2018
            1   98  6/2/2018    8/31/2018
            1   100 9/1/2018    5/4/2019

            I wrote some SAS code but I am combining the dates even when there is no overlap. I want to write some code which should work in SAS.

            PROC SORT DATA=Want OUT=ONE;
                BY PERSON_ID BEG_DATE DRUG_CODE END_DATE;
            RUN;
            data TWO (DROP=PERSON_ID2 DRUG_CODE2 BEG_DATE END_DATE
                RENAME=(BEG2=BEG_DOS
                END2=END_DOS));
                SET ONE;
                RETAIN BEG2 END2;
                PERSON_ID2=LAG1(PERSON_ID);
                DRUG_CODE2=LAG1(DRUG_CODE);

                IF PERSON_ID2=PERSON_ID AND DRUG_CODE2=DRUG_CODE AND BEG_DATE LE(END2+1) THEN
                    DO;
                        BEG2=MIN(BEG_DATE,BEG2);
                        END2=MAX(END_DATE,END2);
                    END;
                ELSE
                    DO;
                        SEG+1;
                        BEG2=BEG_DATE;
                        END2=END_DATE;
                    END;

                FORMAT BEG2 END2 MMDDYY10.;
            RUN;

            DATA THREE(DROP=BEG_DOS END_DOS SEG);
                RETAIN BEG_DATE END_DATE;
                SET TWO;
                BY PERSON_ID SEG;
                FORMAT BEG_DATE END_DATE MMDDYY10.;

                IF FIRST.SEG THEN
                    DO;
                        BEG_DATE=BEG_DOS;
                    END;

                IF LAST.SEG THEN
                    DO;
                        END_DATE = END_DOS;
                        OUTPUT;
                    END;
            RUN;

A: This is how I would do it. Create an obs for each ID DRUG and DATE.  Flag the gaps and summarize by RUN.
data have;
   input ID  Drug_Code   (BEG End)(:mmddyy.);
   format BEG End mmddyyd10.;
   cards;
1   100 1/1/2018    3/1/2018
1   100 2/1/2018    04/30/2018
1   90  4/1/2018    04/30/2018
1   90  6/1/2018    8/15/2018
1   100 5/1/2018    6/1/2018
1   98  6/1/2018    8/31/2018
1   100 9/1/2018    5/4/2019
;;;;
   run;
proc print;
   run;
/*1   100 1/1/2018    1/1/2019*/

data exv/ view=exv;
   set have;
   do date = beg to end;
      output;
      end;
   drop beg end;
   format date mmddyyd10.;
   run;
proc sort data=exv out=ex nodupkey;
   by id drug_code date;
   run;
data breaksV / view=BreaksV;
   set ex;
   by id drug_code;
   dif = dif(date);
   if first.drug_code then do;  dif=1; run=1; end;
   if dif ne 1 then run+1;
   run;
proc summary data=breaksV nway missing;
   class id drug_code run;
   var date;
   output out=want(drop=_type_) min=Begin max=End;
   run;
Proc print;
   run;

A: Computing the extent range composed of overlapping segment ranges requires a good understanding of the range conditions (cases).
Consider the scenarios when sorted by start date (within any larger grouping set, G, such as id and drug)

*

*Let [ and ] be endpoints of a range

*# be date values (integers) within

*Extent be the combined range that grows

*Segment be the range in the current row

Case 1 - Growth. Within G Segment start before Extent end
Segment will either not contribute to Extent or extend it.
   [####]       Extent
+    [#]        Segment range DOES NOT contribute
 --------
   [####]       Extent (do not output a row, still growing)

or
   [####]       Extent
+    [#####]    Segment range DOES contribute
 --------
   [#######]    Extent (do not output a row, still growing)

Case 2 - Terminus. 3 possibilities:

*

*Within G Segment start after Extent end,

*Next G reached (different id/drug combination),

*End of data reached.

#2 and #3 can be tested by checking the appropriate last. flag.
   [####]       Extent
+        ..[#]  Segment beyond Extent (gap is 2)
 --------
   [####]       output Extent
           [#]  reset Extent to Segment

You can adjust your rules for Segment being adjacent (gap=0) or close enough (gap < threshold) to mean an Extent is either expanded, or, output and reset to Segment.
Note: The situation is a little more (not shown) complicated for the real world cases of:

*

*missing start means the Segment has an unknown start date (presume it to be epoch (0=01JAN1960, or some date that pre-dates all dates in the data or study)

*missing end means the Segment is active today (end date is date when processing data)

Sample code:
data have;
  call streaminit(42);
  do id = 1 to 10;
    do _n_ = 1 to 50;
      drug = ceil(rand('UNIFORM', 10));
      beg_date = intnx ('MONTH', '01JAN2008'D, rand('UNIFORM',20));
      end_date = intnx ('DAY', beg_date, rand('UNIFORM',75));
      OUTPUT;

    end;
  end;
  format beg_date end_date yymmdd10.;
run;

proc sort data=have out=segments;
  by id drug beg_date end_date;
run;

data want;
  set segments;
  by id drug beg_date end_date;  * will error if incoming data is NOT sorted;

  retain ext_beg ext_end;
  retain gap_allowed 0; * set to 1 for contiguously adjacent segment ;

  if first.drug then do;
    ext_beg = beg_date;
    ext_end = end_date;
    segment_count = 0;
  end;

  if beg_date <= ext_end + gap_allowed then do;
    ext_end = max (ext_end, end_date);
    segment_count + 1;
  end;
  else do;
    extent_id + 1;
    OUTPUT;
    ext_beg = beg_date;
    ext_end = end_date;
    segment_count = 1;
  end;

  if last.drug then do;
    extent_id + 1;
    OUTPUT;
    * reset occurs implicitly;
    * it will happen at first. logic when control returns to top of step;
  end;

  format ext_: yymmdd10.;
  keep id drug ext_beg ext_end segment_count extent_id;
run;


text:
Q: Why does this change the order of evaluation in F# I am working through the Project Euler puzzles (https://projecteuler.net/) using F#. It turns out that a lot of the puzzles require the generation of prime numbers, which is an expensive computation.
To make my life easier, I want to create a module that will generate prime numbers, but also write them to a text file so I just look them up the next time I need them.
Here is my prime generator module:
module Utilities

open System
open System.IO
open System.Reflection

module Primes =

    //This is where the cache file is
    let private cachePath =
        Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
        + "\PrimeCache.txt"

    //Parses the file to an int list
    let private readCache : int list =
        let text = File.ReadAllText(cachePath).Trim()
        text.Split([|','|])
        |> Seq.filter(fun w -> w |> String.length > 0)
        |> Seq.map(fun w -> Int32.Parse(w))
        |> Seq.toList

    //Writes an int list to the file
    let writeCache cache =
        let text = String.Join(",", cache |> Seq.map(fun n -> n.ToString()))
        File.WriteAllText(cachePath, text)

    //In-memory cache
    let mutable cache = []
    cache <- readCache

    let private appendElement element list =
        element::(list |> List.rev) |> List.rev

    let private isPrimeInner (n : int) =
        if n < 2 then false
        else
            let len = cache.Length
            //Factor can't be greater than the square root
            let factorLimit = Convert.ToInt32(Math.Ceiling(Math.Sqrt(Convert.ToDouble(n))))

            let mutable i = 0
            let mutable stop = false
            let mutable isPrime = true

            while stop = false do
                //Get the next element from cache
                let p = cache.[i]

                i <- i+1

                //Don't go past last index of cache
                if i >= len
                then stop <- true
                else ()

                //Don't check primes > sqrt(n)
                if p > factorLimit
                then stop <- true
                else ()

                //If its divisible by any prime, its not a prime
                if n % p = 0
                then
                    stop <- true
                    isPrime <- false
                else ()

            //Add primes to cache
            if isPrime
            then cache <- appendElement n cache
            else ()

            isPrime

    let isPrime (n : int) : bool =
        let result = isPrimeInner n
        result

    let getPrimes : int seq =
        seq {
            for p in cache do
                yield p

            let next = if cache.Length > 0
                       then cache.[cache.Length-1]+1
                       else 2

            for n = next to Int32.MaxValue do
                if isPrimeInner n
                then yield n
                else ()
        }

    let saveCache : unit =
        writeCache cache

Here is the code for the problem I am currently working on that consumes this.  (The actual problem is to sum all primes under 2,000,000, but I am testing on 1000 for now):
module Problem10

let getAnswer =

    let limit = 1000

    let primes = Utilities.Primes.getPrimes
                |> Seq.takeWhile(fun p -> p < limit)

    let result = primes |> Seq.sum

    Utilities.Primes.saveCache

    result

This will give the right answer, but will save an empty cache file back to the disk.  If I step through it in the debugger, the call to saveCache is one of the first things that is hit, before any breakpoints I set inside isPrimeInner.  If I switch the calling code to this:
module Problem10

let getAnswer =

    let limit = 1000

    let primes = Utilities.Primes.getPrimes
                |> Seq.takeWhile(fun p -> p < limit)

    let result = primes |> Seq.sum

    let x = Utilities.Primes.cache
    Utilities.Primes.writeCache x

    result

the cache will be properly saved with new primes.
I've seen this kind of behavior before in C# when misusing iterator blocks.  I don't understand how these two versions of the calling code are any different at runtime.  What am I doing wrong here?


text:
Q: Ansible playbook working only in region eu-east-1 i'm trying to manage some changes through ansible but my playbooks works only if I set region: us-east-1.
My aws cli work perfectly in every region.
This is an example playbook:
- name: Test aws
  hosts: local
  connection: local
  gather_facts: no

  tasks:
    - name: Gather information about all instances
      community.aws.ec2_instance_info:
         region: eu-west-1

and this is the error i get:
"error": {
        "code": "AuthFailure",
        "message": "AWS was not able to validate the provided access credentials"
    },

I already have enable STS global endpoint for all regions.
Does anybody has any clue?
Many thanks!


text:
Q: How can i remove "index.php" and redirect to home url For example if my home page url is  "mywebsite.com/index.php", I want to access index.php on "mywebsite.com"
what is the standard procedure that every website uses ?

A: You must create an .htaccess file and write the following:
DirectoryIndex index.php

The file must be inside your folder with index.php


text:
Q: Specific Routing For Different Controllers Can I have different routes which will be activated upon different controllers ? For example If I have controller "Age" this controller to accept this kind of routing.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

If I have another controller for example "Name" to accept this kind of routing.
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

A: routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Name",                                              // Route name
            "Name/{action}/{id}",                           // URL with parameters
            new { controller = "Name", action = "Index" }  // Parameter defaults
        );

A custom route for your NameController.
There are different samples at asp.net


text:
Q: Inline SVG css animation not working on Safari I'm using the latest version of these:

This is the CSS I am using to achieve the desired CSS animation effects across literally all browsers except Safari.
.tt-divider {
      border-style: outset;
      border-color: LawnGreen;
      border-radius: 3px;
      margin-bottom: 2.5vh;
      margin-top: 2.5vh;
      background: gold;
      border-width: 2px;
      animation: grow-divider 2s forwards linear;
      margin: auto;
  }
  @-webkit-keyframes grow-divider{
      from {width:0%; }
      to {width:100%; }
  }
  @keyframes grow-divider{
      from {width:0%; }
      to {width:100%; }
  }

  #landing-logo {
      display: inline-block;
      max-width: 350px;
      min-width: 150px;
      width: 50vw;
      margin-top: 5vh;
      margin-bottom: 1vh;
  }
 #navigation{
      padding-left: 7.5vh;
      padding-right: 7.5vh;
      text-align:center;
 }
 #btm-right-nav{
     max-width: 55px;
     position: fixed;
     right: 25px;
     bottom: 10px;
 }
 .btm-right-ico {
     display: block;
     color: lawngreen;
     margin:auto;
     margin-bottom: 5vh;
     font-size: 16px;
     text-rendering: optimizeLegibility;
 }
 .fontawesome-i2svg-active .btm-right-ico {
     animation-name: grow-buttons;
     animation-duration: 2s;
     animation-timing-function: linear;
     animation-play-state: running;
     animation-fill-mode: forwards;
     animation-iteration-count: 1;
     animation-direction: normal;
 }
 @-webkit-keyframes grow-buttons{
      from {font-size:16px; }
      to {font-size: 45px; }
  }
 @keyframes grow-buttons{
      from {font-size:16px}
      to {font-size:45px;}
  }

The grow-divider animation works perfectly, and another irrelevant one works perfectly as well on a different page. The only one I cannot get to work only on Safari is the grow-buttons animation. Yes Safari in general I've back-tested every version made in the past 5 years it does exactly the same thing..
Initially I thought it was a CSS naming problem... no I've tried multiple implementations of CSS for compatibility to no avail. I then thought it was just Safari, it could be, but why are my other CSS animations working then? I even put my CSS on the newly generated  element via JS and it doesn't work. I even used async programming in JQuery to make sure the CSS wasn't applied before the  was changed to <svg>
It's worth mentioning that the CSS classes on the original  element are injected into the new <svg> from font-awesome... so the CSS animation is inherited.. this logic works on all browsers except Safari...
I have absolutely no idea what is causing it, anyway here's the html for the entire page:

I think I could get it to work if I just yanked my own svg and put it neatly in an  and didn't do some masking magic on my buttons.. I don't want to do that because that'll cut off a ton of features of fontawesome and take more time... so in the meantime I have the animation turned off for Safari users and it's sad because I want this animation it's incredibly satisfying and I really don't want to have to bake my own masked SVGs and put them in a  just so I can run CSS animations over SVGs... I mean.. is that what I have to do?
Can I inject inline SVG into a  src?
Here's the baked SVG data from fontawesome after the page loads (I took out the data:)

        <svg class="svg-inline--fa fa-bars fa-w-16 btm-right-ico" data-
   fa-mask="fas fa-circle" data-fa-transform="shrink-7" aria-
   hidden="true" focusable="false" data-prefix="fas" data-icon="bars"
  role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"
    data-fa-i2svg=""><defs><clipPath id="clip-hzzHNtGIZRrn"><path
   fill="currentColor" d=""></path></clipPath><mask x="0" y="0"
 width="100%" height="100%" id="mask-jyjnVEKbKq5c"
 maskUnits="userSpaceOnUse" maskContentUnits="userSpaceOnUse"><rect
  x="0"
 y="0" width="100%" height="100%" fill="white"></rect><g
transform="translate(256 256)"><g transform="translate(0, 0)
scale(0.5625, 0.5625)  rotate(0 0 0)"><path fill="black" d=""
  transform="translate(-224 -256)"></path></g></g></mask></defs><rect
   fill="currentColor" clip-path="url(#clip-hzzHNtGIZRrn)"
    mask="url(#mask-
    jyjnVEKbKq5c)" x="0" y="0" width="100%" height="100%"></rect></svg>

        <svg class="svg-inline--fa fa-phone fa-w-16 btm-right-ico" data-
 fa-mask="fas fa-circle" data-fa-transform="shrink-7" aria-hidden="true"
focusable="false" data-prefix="fas" data-icon="phone" role="img"
xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" data-fa-
 i2svg=""><defs><clipPath id="clip-YDDPIJZX3DpE"><path
  fill="currentColor" d=""></path></clipPath><mask x="0" y="0"
    width="100%" height="100%" id="mask-eJs29EAdXlZv"
 maskUnits="userSpaceOnUse" maskContentUnits="userSpaceOnUse"><rect
 x="0" y="0" width="100%" height="100%" fill="white"></rect><g
 transform="translate(256 256)"><g transform="translate(0, 0)
 scale(0.5625, 0.5625)  rotate(0 0 0)"><path fill="black" d=""
transform="translate(-256 -256)"></path></g></g></mask></defs><rect
  fill="currentColor" clip-path="url(#clip-YDDPIJZX3DpE)"
  mask="url(#mask-
 eJs29EAdXlZv)" x="0" y="0" width="100%" height="100%">
     </rect></svg>

A: Wow..... really hope this helps someone...
To fix the problem you use regular old css to transform scale it in the animation.
Font-size can be used to scale up inline SVGs on all browsers except Safari
@-webkit-keyframes grow-buttons{
      from { -webkit-transform: scale(1); transform: scale(1);}
      to { -webkit-transform: scale(3); transform: scale(3);}
  }
@keyframes grow-buttons{
      from { -webkit-transform: scale(1); transform: scale(1);}
      to { -webkit-transform: scale(3); transform: scale(3);}
  }

Bottom line:
Use transform: scale() instead of font-size: ()px on SVG CSS animations to maximize compatibility.


text:
Q: How to Set Limit for options.FindOne() in go mongo-driver I see there is a way to SetLimit() for Find() func,  But I don't see any options to set limit for FindOne() , Since we are searching single result out of FindOne() we don't even have to limit it ? Automatically it handles limit ?
Tried setting limit using 1options.FindOne()` , But I do not see a way to do that .

A: It's not documented, but it's common sense that Collection.FindOne() implies a behavior of that of Limit=1. The return value of Collection.FindOne() doesn't give access to multiple result documents, that's why options.FindOne doesn't even have a SetLimit() method.
If you check the source code, it's in there:
// Unconditionally send a limit to make sure only one document is returned and the cursor is not kept open
// by the server.
findOpts = append(findOpts, options.Find().SetLimit(-1))

Note that FindOptions.Limit documents that:
// Limit is the maximum number of documents to return. The default value is 0, which means that all documents matching the
// filter will be returned. A negative limit specifies that the resulting documents should be returned in a single
// batch. The default value is 0.
Limit *int64


text:
Q: ElementRef has no instance of style I was writing up some code which was going to update the position of a div with dart.
So, what i was coming up with something like, on mouse down on a div, start updating the position of the element.
The html will be as follows:

with the dart looking like:
@ViewChild("selection")
DivElement selectionDiv;

mouseDownFunction(mouse){
  selectionDiv.style.left = "${mouse.position.left}px";
}

and when this happens, it tries to call style on selectionDiv, but says that ElementRef has no instance of style.

A: This is expected functionality. selectionDiv isn't a DivElement, but an ElementRef. To get the dart:html element, use the getter selectionDiv.nativeElement.
Hope this helps.

A: As Tobe O suggested in his answer the problem is that selectionDiv is a ElementRef and not a DivElement.
But I would like to add that enabling checked mode could help you catch this kind of error early in the future. By default Dartium performs no type checking. If you want to benefit from your type annotations, you need to specify the --checked VM flag when launching Dartium.
On Linux, you can do something like this to enable checked mode:
DART_FLAGS='--checked' path/to/dartium

Your code should now produce the following error message:
ORIGINAL EXCEPTION: type 'ElementRef' is not a subtype of type
'DivElement' of 'value' where
  ElementRef is from package:angular2/src/core/linker/element_ref.dart
  DivElement is from dart:html

The stack trace that is provided with the error message above can tell you which variable caused the error.
ORIGINAL STACKTRACE:
#0      MyComponent.selectionDiv= (package:my_package/my_component.dart:15:14)


text:
Q: Problems with MPAndroidChart configuration. Xaxis, bar background my dear StackOverflow community! I would really appreciate help from a person who has used MPAndroidChart for a while or just knows the things about this library.
This post can be a bit long, but please if you know some tips or tricks, or you have used this library - please read a bit, maybe you can save me a lot of time and help solve at least one problem.
So, making the long story short.
What I am trying to achieve

And what I have right now.

Don't laugh just yet.
So I have three problems:

*

*Set the background of the bars as a Drawable item. I have three drawable gradient backgrounds, no shapes or strokes, just plain gradient, which I want to set as background for my bars.

*The distance between bars. I haven't succeeded in setting the distance between bars like in the first picture. I don't know how to properly make bars in one DataSet near each other and set this space between DataSets.

*The X-axis. I know that it has been a pain in the ass for a lot of people to set x-axis labels. I am using IndexAxisValueFormatter and passing it a List of Strings, which I want to set them as my labels.

For example, I have 5 data sets with 3 bars in each. How should I properly configure my BarChart?
Thank you in advance, lovely StackOverflow community!

A: 2) To set space between datasets, use groupBars method. It allows setting:

*

*space between bars in same data set

*space between datasets
mChart = (BarChart) findViewById(R.id.chart);

final ArrayList<BarEntry> bar1List = new ArrayList<>();
final ArrayList<BarEntry> bar2List = new ArrayList<>();
final ArrayList<BarEntry> bar3List = new ArrayList<>();
final ArrayList<String> xLabels = new ArrayList<>();

for (int i = 0; i < 3; i++) {
    bar1List.add(new BarEntry(i, (float) randInt()));
    bar2List.add(new BarEntry(i, (float) randInt()));
    bar3List.add(new BarEntry(i, (float) randInt()));

    xLabels.add("entry " + i);
}

// set color for bars
BarDataSet bar1Set = new BarDataSet(bar1List, "Bar 1");
bar1Set1.setColor(Color.rgb(255, 0, 0));

BarDataSet bar2Set = new BarDataSet(bar2List, "Bar 2");
bar2Set.setColor(Color.rgb(0, 255, 0));

BarDataSet bar3Set = new BarDataSet(bar3List, "Bar 3");
bar3Set.setColor(Color.rgb(0, 0, 255));

// for 3 bars in a dataset, this must equals "1" :
//     (barWidth + barSpace) * 3 + groupSpace = 1

// space between data sets
final float groupSpace = 0.25f;
// space between bars in same data set
final float barSpace = 0.05f;
// width of bar
final float barWidth = 0.2f;

BarData barData = new BarData(bar1Set, bar2Set, bar3Set);
barData.setBarWidth(barWidth);

// make this BarData object grouped
barData.groupBars(0, groupSpace, barSpace); // start at x = 0

mChart.setData(barData);

3) To show list of strings as x-axis label, create IAxisValueFormatter & set it as ValueFormatter of x-axis.
    XAxis xAxis = mChart.getXAxis();
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
    xAxis.setDrawGridLines(false);
    xAxis.setDrawAxisLine(false);
    xAxis.setCenterAxisLabels(true);
    xAxis.setGranularity(1f);
    xAxis.setTextSize(12);
    xAxis.setAxisMinimum(0);
    xAxis.setAxisMaximum(barData.getXMax() + 1);

    // xLabels is populated in code above in (2)

    // show user-defined string
    IAxisValueFormatter xAxisFormatter = new IAxisValueFormatter() {
        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            if (value >= 0 && value <= xLabels.size() - 1) {
                return xLabels.get((int) value);
            }

            // to avoid IndexOutOfBoundsException on xLabels, if (value < 0 || value > xLabels.size() - 1)
            return "";
        }
    };

    xAxis.setValueFormatter(xAxisFormatter);

A: What you are trying to do you can achieve this by following below example:
    float barWidth;
    float barSpace;
    float groupSpace;

    // (barWidth * 2) + (barSpace * 2) + groupSpace should be equal to one
    barWidth = 0.25f;
    barSpace = 0.05f;
    groupSpace = 0.4f;

    int groupCount = 7;

    ArrayList<String> xVals = new ArrayList<String>();

    xVals.add("Jan");
    xVals.add("Feb");
    xVals.add("Mar");
    xVals.add("Apr");
    xVals.add("May");
    xVals.add("Jun");
    xVals.add("Jul");

    ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
    ArrayList<BarEntry> yVals2 = new ArrayList<BarEntry>();

    yVals1.add(new BarEntry(0, (float) 2));
    yVals2.add(new BarEntry(0, (float) 3));
    yVals1.add(new BarEntry(1, (float) 1));
    yVals2.add(new BarEntry(1, (float) 2));
    yVals1.add(new BarEntry(2, (float) 3));
    yVals2.add(new BarEntry(2, (float) 4));
    yVals1.add(new BarEntry(3, (float) 6));
    yVals2.add(new BarEntry(3, (float) 5));
    yVals1.add(new BarEntry(4, (float) 4));
    yVals2.add(new BarEntry(4, (float) 3));
    yVals1.add(new BarEntry(5, (float) 2));
    yVals2.add(new BarEntry(5, (float) 6));
    yVals1.add(new BarEntry(6, (float) 5));
    yVals2.add(new BarEntry(6, (float) 7));

    BarDataSet set1, set2;
    set1 = new BarDataSet(yVals1, "A");
    set1.setColor(getColor("defaultGreen"));
    set1.setValueTextColor(getColor("primaryDark"));
    set1.setValueTextSize(defaultValueTextSize);

    set2 = new BarDataSet(yVals2, "B");
    set2.setColor(getColor("defaultOrange"));
    set2.setValueTextColor(getColor("primaryDark"));
    set2.setValueTextSize(defaultValueTextSize);

    BarData data = new BarData(set1, set2);
    barChart.setData(data);
    barChart.getDescription().setText("No. of Contracts signed in 6 months");
    barChart.getDescription().setTextSize(12);
    barChart.setDrawMarkers(true);
    barChart.setMarker(markerView(context));
    barChart.getAxisLeft().addLimitLine(lowerLimitLine(2,"Minimum",2,12,getColor("defaultOrange"),getColor("defaultOrange")));
    barChart.getAxisLeft().addLimitLine(upperLimitLine(6,"Target",2,12,getColor("defaultGreen"),getColor("defaultGreen")));

    barChart.getBarData().setBarWidth(barWidth);
    barChart.getXAxis().setAxisMinimum( 0 );
    barChart.getXAxis().setAxisMaximum(0 +
    barChart.getBarData().getGroupWidth(groupSpace, barSpace) * groupCount);
    barChart.groupBars(0, groupSpace, barSpace);
    barChart.animateY(1000);
    barChart.getData().setHighlightEnabled(true);
    barChart.invalidate();

    //X-axis
    XAxis xAxis = barChart.getXAxis();
    xAxis.setGranularity(1f);
    xAxis.setGranularityEnabled(true);
    xAxis.setCenterAxisLabels(true);
    xAxis.setDrawGridLines(false);
    xAxis.setAxisMaximum(groupCount);
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
    xAxis.setValueFormatter(new IndexAxisValueFormatter(xVals));
    //Y-axis
    barChart.getAxisRight().setEnabled(false);
    YAxis leftAxis = barChart.getAxisLeft();
    leftAxis.setDrawGridLines(true);
    //        leftAxis.setSpaceTop(35f);
    leftAxis.setAxisMinimum(0f);

    barChart.getXAxis().setGranularityEnabled(true);
    barChart.getXAxis().setGranularity(1.0f);
    barChart.getXAxis().setLabelCount(set1.getEntryCount());


text:
Q: Regular Expression to match from specified character to second line end i have text like this
aaa111
bbb222
ccc333
ddd444

and i need to match with Regular Expression from specified character to second new line
for example from bbb return like this :
ccc333

i used this code but not work fine
            string[] lines = input.Split('\n');
            string nums = "";
            for (int i = 1; i < 10; i++)
            {
                nums = lines.Length >= i ? lines[i - 1] : null;
                Match match = Regex.Match(nums, @"\bbbb\w*\b");
                if (match.Success)
                {
                    break;
                }
            }

A: Submitting my comment to answer so that solution is easy to find for future visitors.
You may use this regex:
\bbbb.*\r?\n(.*)

RegEx Demo
RegEx Breakup:

*

*\b: Word boundary

*bbb: Match bbb

*.*\r?\n(.*): Match any text followed by a line break followed by any text with 0 or more length. We capture last (.*) in group #1

Code:
string pattern = @"\bbbb.*\r?\n(.*)";
string input = @"aaa111
bbb222
ccc333
ddd444";

foreach (Match m in Regex.Matches(input, pattern)) {
   Console.WriteLine(m.Groups[1]); // ccc333
}

Online Code Demo

A: If your data is well constrained, you can use
^bbb\d{3}\s\w{3}\d{3}$

An explanation


text:
Q: MySQL Join Scenario I know there are many "similar" questions, but I cannot figure out how to make this work. I am hoping it is quite simple for someone else!
I have a query that looks like the following:
SELECT
    d.name DishName,
    alt.name AllergyName
FROM meals_dish d
JOIN meals_dishingredient di ON di.dish_id = d.id
LEFT JOIN meals_food_allergytypes fat ON fat.food_id = di.food_id
LEFT JOIN meals_allergytypes alt ON alt.id = fat.allergytypes_id
GROUP BY d.id, alt.id
ORDER BY d.name

that is giving me table similar to the following:
Dish Name               |    AllergyName
-----------------------------------------
Almond Pudding          |     NULL
Almond Pudding          |     Egg
Apple Cake              |     Milk
Apple Cake              |     Lactose
Apple Cake              |     Egg
Apple Cake              |     NULL
Avocado Chocolate Cream |     Milk
Avocado Chocolate Cream |     Lactose
Avocado Chocolate Cream |     NULL
Avocado Chocolate Cream |     Peanuts
Avocado Chocolate Cream |     Tree Nuts
Avocado Chocolate Cream |     Soy
Avocado Egg             |     NULL
Avocado Egg             |     Egg
Bacon Wrapped Asparagus |     NULL
Baked Cauliflower       |     NULL
Baked Cauliflower       |     Milk
Baked Cauliflower       |     Lactose
Baked Salmon            |     NULL
Baked Salmon            |     Milk
Baked Salmon            |     Lactose

Now, what I would like to do, is to make a list of all dishes where any of the allergy names for a specific dish is not 'Egg', or etc.
For example, if I wanted to only get dishes that someone who could not eat Egg was, then I would run this query and should get back the dishes of Avocado Chocolate Cream, Bacon Wrapped Asparagus, Baked Cauliflower and Baked Salmon.
I have tried to set up some WHERE NOT IN, and other similar ones, but I continue to only remove a certain ingredient from the dish instead of just not selecting the dish. For example, in my attempted queries, with the 'Egg' example, Apple Cake would simply still return, but the specific row of 'Egg' would now not show.

A: First, think about how to determine which dishes have "Egg" in them.
SELECT
   FoodAllergyTbl.dish_id
FROM
    `meals_food_allergytypes` AS FoodAllergyTbl
INNER JOIN
    `meals_allergytypes` AS AllergyTbl
     ON FoodAllergyTbl.allergy_types_id = AllergyTbl.id
WHERE
    AllergyTbl.name = 'Egg';

Then you can select the list of dishes where the id isn't in the above listing.
SELECT
    name
FROM
    `meal_dish`
WHERE
    `id` NOT IN (
    SELECT
       FoodAllergyTbl.dish_id
    FROM
        `meals_food_allergytypes` AS FoodAllergyTbl
    INNER JOIN
        `meals_allergytypes` AS AllergyTbl
         ON FoodAllergyTbl.allergy_types_id = AllergyTbl.id
    WHERE
        AllergyTbl.name = 'Egg'
);

A: you could use NOT  IN this way  for Dish Name  eg  for Egg:
  select name
  from meals_dish
  where  name not in (
  SELECT distinct d.name
  FROM meals_dish d
  JOIN meals_dishingredient di ON di.dish_id = d.id
  LEFT JOIN meals_food_allergytypes fat ON fat.food_id = di.food_id
  LEFT JOIN meals_allergytypes alt ON alt.id = fat.allergytypes_id
             AND alt .AllergyName = 'Egg'
  )


text:
Q: How to perform link rewriting with a .NET Regex? I need to use C# Regex to do a link rewrite for html pages and I need to replace the links enclosed with quotes (") with my own ones. Say for example, I need to replace the following
"slashdot.org/index.rss"

into
"MY_OWN_LINK"

However, the actual link can be of the form
"//slashdot.org/index.rss" or
"/slashdot.org/index.rss"

where there can be other values that comes before "slashdot.org/index.rss" but after the quote (") which I don't care about.
To summarize, as long as the link ends with "slashdot.org/index.rss", I would want to replace the entire link with "MY_OWN_LINK".
How can I use Regex.Replace for the above?

A: Try this. Will work with no slash, single and two slashes.
    string pattern =  @"[/]{0,2}slashdot\.org[/]{0,2}index\.rss";
    test1 = Regex.Replace(test1, pattern, "MY_OWN_LINK");

A: edit: updated answer according to comment.
First, you don't have to use a regular expression for this job. Just check whether or not the string ends with `"slashdot.org/index.rss"', and if it is, replace the entire string.
If you're using regular expression, you'd better just test whether or not the string ends with
"slashdot.org/index.rss" and act accordingly, like so:
if (Regex.IsMatch(str,"slashdot.org/index\.rss$")) {str = new_str;}

If you insist of using Regex.Replace, go for
Regex.Replace(str,"^.*slashdot.org/index\.rss$","MY_OWN_LINK");

where the ^ and the $ stands for line/string begin/end respectively. The first .* means "capture the start of the URL, whatever it is". The last dot is perpended with slash, as it usually means "any character".
For additional info, see this cheat sheet of regular expression in C#.


text:
Q: Length of arbitrary $2$D curve when transformed by simple skew This is a real-world problem that I can tackle by brute force but I'd like to know if there is a faster way to do it. I suspect there is.....
I have a dataset $d$ where $d(0)$ $d(1)$ $d(2)$ are an ordered set of data. Each of them contains an $x$ and $y$ coordinate, and the distance precalculated from the previous point. So typical data might be:
$$\begin{align}
&d(0): x=0,\ y=0,\ d=0\\
&d(1): x=3,\ y=0,\ d=3\\
&d(2): x=2,\ y=1,\ d=1.414\\
&\quad\vdots
\end{align}$$
The real-world data has tens or hundreds of thousands of points, and the distance between points is small $O(10^{-5})$, but the principle is the same. The important figure is the total length of the path.
We then apply a simple linear skew +stretch to the plane, and to all the points: $x\rightarrow x - Ay$, $y \rightarrow By$, and need to calculate the new total length.
I need to create a lookup table of this for about $100,000$ combinations of $A$ and $B$, so that for any given $(A, B)$ in the set, I can find the length of the curve when transformed.
Clearly it's not that demanding computationally; also clearly the scale factor isn't constant for all curves and skews, it depends on the exact curve shape.  I could iterate through each $(A, B)$, and for each, skew the $10$-$100$k points and recalculate the total new distance, but that seems inefficient. Its also about $10^{12}$ point recalculations and Pythagorases (is that a valid plural?).
So I wonder, is there any generalised faster way?

A: $T\mathbf x$ is a transformation that skews $\mathbf x$
You want to know $\|T\mathbf x\|$
and $\|T\mathbf x\|^2= \langle T\mathbf x, T\mathbf x \rangle = \mathbf x^TT^TT\mathbf x$
$T = \begin{bmatrix} 1&B\\A&1\end{bmatrix}$ would be the matrix that provides the skew described above.
$T^TT = \begin{bmatrix} 1+A^2&(A+B)\\(A+B)&1+B^2\end{bmatrix}$
$\|T(x,y)\| = \sqrt {(1+A^2)x^2 + 2(A+B) xy + (1+B^2)y^2}$

A: The solution of @Doug M is excellent.
I would like to attract your attention on a different feature.

*

*First of all, one can get rid of the enlargment (homothety) operation because this operation can be done at the end by multiplying the results by the enlargment ratio.

*Then, the stretch is either $S = \begin{bmatrix} 1&A\\0&1\end{bmatrix}$ (with your notations) or, in the general case of an affine transform with determinant 1, under the form of a "LU" product (https://en.wikipedia.org/wiki/LU_decomposition) of a lower and a upper triangular matrix:
$$S = \underbrace{\begin{bmatrix} 1&0\\B&1\end{bmatrix}}_{\text{skew in the Oy direction}} \ \ \times \ \ \underbrace{\begin{bmatrix} 1&A\\0&1\end{bmatrix}}_{\text{skew in the Ox direction}}$$
which means having simpler tables to manage.


text:
Q: I am unable to use "GoogleSignIn.getLastSignedInAccount(this);" in a class This is my code inside a java class.
 "GoogleSignIn.getLastSignedInAccount(this)" was workin fine when I was using it in a Activity But it's showing errors on java class files.
The error is "incompatible types: MessageAdapter cannot be converted to Context"
How can I get the Context value in this java class
 @Override
        public void onBindViewHolder(final MessageViewHolder viewHolder, int i) {

            Messages c = mMessageList.get(i);

            final String from_user = c.getFrom();
            String message_type = c.getType();

            mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(from_user);
            mUserDatabase.keepSynced(true);
            mUserDatabase.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    //   String name = dataSnapshot.child("name").getValue().toString();
                    String image = dataSnapshot.child("thumb_image").getValue().toString();

**GoogleSignInAccount current_user = GoogleSignIn.getLastSignedInAccount(this);**

                    fuser = FirebaseAuth.getInstance().getCurrentUser();
                    if (!from_user.equals(fuser.getUid())) {

//                      viewHolder.displayName.setText(name);

                        Picasso.with(viewHolder.profileImage.getContext()).load(image)
                                .placeholder(R.drawable.default_avatar).into(viewHolder.profileImage);

                    }
                }

and this is another override method inside this class
 @Override
        public int getItemViewType(int position) {

            **GoogleSignInAccount fuser = GoogleSignIn.getLastSignedInAccount(context);**
            String fuser_id = fuser.getId();
            if (mMessageList.get(position).getFrom().equals(fuser_id)){
                return 1;
            } else {
                return 0;

            }
        }

A: The error is pretty straight forward, it states "incompatible types: MessageAdapter cannot be converted to Context".
You pass this as param, which at the current scope refers to the adapter. The method requires a context to work.
There are multiple solutions for this, the the most lazy one I think is to get the context from viewholder class, like
holder.itemView.getContext(), this solves the syntax error, but does not solve the structural problem.
There are other appraches like not handling such logic inside adapter, delegating the action would be a more elegant approach.
Also, learn about scopes in java, to understand the this reference.


text:
Q: text file reading in c# I have a text file, its the content from a mail body.it includes html codes.
I want to take only href tags from that text file.I want to do this with asp.net c# web application.
Does any one have a code to help me ...
Thanks

A: Try using the Html Agility Pack to parse the HTML from your email and extract the href attributes from <a> tags.
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(emailBody);
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
{
   HtmlAttribute att = link.Attributes["href"];
   string href = att.Value;
}

A: You could use regular expression even though it is not a perfect solution:
class Program
{
    static void Main(string[] args)
    {
        var text = File.ReadAllText(@"d:\test.htm");

        Regex regex = new Regex("href\\s*=\\s*\"([^\"]*)\"", RegexOptions.IgnoreCase);
        MatchCollection matches = regex.Matches(text);
        foreach(Match match in matches)
        {
            Console.WriteLine(match.Groups[1]);
        }
    }
}


text:
Q: Use spark in a sbt project in intellij Here is the build.sbt file:
name := "scalaChartTest"

version := "1.0"

scalaVersion := "2.11.7"

//libraryDependencies += "org.jfree" % "jfreechart" % "1.0.19"
//
//libraryDependencies += "org.scalafx" %% "scalafx" % "8.0.0-R4"
//
//libraryDependencies += "com.github.wookietreiber" %% "scala-chart" % "latest.integration"

libraryDependencies += "org.apache.spark" % "spark-core_2.11" % "1.4.1"

And I got an error after refreshing:
15:56:30 SBT project import
         [warn] Multiple dependencies with the same organization/name but different versions. To avoid conflict, pick one version:
         [warn]  * org.scala-lang:scala-compiler:(2.11.0, 2.11.7)
         [warn]  * org.scala-lang:scala-reflect:(2.11.2, 2.11.7)
         [warn]  * jline:jline:(0.9.94, 2.12.1)
         [warn]  * org.scala-lang.modules:scala-parser-combinators_2.11:(1.0.1, 1.0.4)
         [warn]  * org.scala-lang.modules:scala-xml_2.11:(1.0.1, 1.0.4)
         [warn]  * org.slf4j:slf4j-api:(1.6.4, 1.7.10)

What went wrong here?

A: You have indirect dependencies to the libraries that are mentioned in the warning. There is a conflict, since the version in the indirect dependency is different from what is specified in your sbt-file (in this case probably by the scala version). The conflict is automatically resolved by sbt (chosing either of the versions depending on your configuration). However, the version that is chosen automatically may not be the version you intend to use, hence the warning.
In your case, this probably isn't an issue. Though, if you want to, you can explicitly exclude the indirect dependencies:
libraryDependencies += "org.apache.spark" % "spark-core_2.11" % "1.4.1" excludeAll (
  ExclusionRule(organization = "org.scala-lang"),
  ExclusionRule("jline", "jline"),
  ExclusionRule("org.slf4j", "slf4j-api")
  )

A: I learned from the spark programming guide that spark 1.4.1 depends on scala 2.10.x, so I change the build.sbt to:
name := "scalaChartTest"

version := "1.0"

scalaVersion := "2.10.5"

libraryDependencies += "org.apache.spark" % "spark-core_2.10" % "1.4.1"

And the warning disappeared.