text:
Q: How to route PUT and DELETE requests for the same url to different controller methods I was searching for an answer to this question, and found this question, which is indeed very similar. However the solutions(s) posted there don't seem to be working for me... I wonder if it has to do with the question's age.
Given the following URL:
/my/items/6

I want HTTP PUT requests for this URL to be handled by one action method, and HTTP DELETE requests to be handled by another action method. Below are the routes I defined (note these are based in an area, so context is an AreaRegistrationContext instance, if that matters):
context.MapRoute(null,
    "my/items/{id}",
    new { area = "AreaName", controller = "ControllerName", action = "Replace" },
    new
    {
        httpMethod = new HttpMethodConstraint("POST", "PUT"),
    }
);

context.MapRoute(null,
    "my/items/{id}",
    new { area = "AreaName", controller = "ControllerName", action = "Destroy" },
    new
    {
        httpMethod = new HttpMethodConstraint("POST", "DELETE"),
    }
);

URL generation works fine with both of these routes, however there are problems when routing incoming requests. Only the first-declared route correctly maps to its respective action.
I dug into the HttpMethodConstraint source code and discovered that it does not care about the "X-HTTP-Method-Override" parameter, only HttpContext.Request.HttpMethod.
I was able to solve this problem with the following custom route constraint class:
public class HttpMethodOverrideConstraint : HttpMethodConstraint
{
    public HttpMethodOverrideConstraint(params string[] allowedMethods)
        : base(allowedMethods) { }

    protected override bool Match(HttpContextBase httpContext, Route route,
        string parameterName, RouteValueDictionary values,
        RouteDirection routeDirection)
    {
        var methodOverride = httpContext.Request
            .Unvalidated().Form["X-HTTP-Method-Override"];

        if (methodOverride == null)
            return base.Match(httpContext, route, parameterName,
                values, routeDirection);

        return
            AllowedMethods.Any(m =>
                string.Equals(m, httpContext.Request.HttpMethod,
                    StringComparison.OrdinalIgnoreCase))
            &&
            AllowedMethods.Any(m =>
                string.Equals(m, methodOverride,
                    StringComparison.OrdinalIgnoreCase))
        ;
    }
}

...and these route definitions:
context.MapRoute(null,
    "my/items/{id}",
    new { area = "AreaName", controller = "ControllerName", action = "Replace" },
    new
    {
        httpMethod = new HttpMethodOverrideConstraint("POST", "PUT"),
    }
);

context.MapRoute(null,
    "my/items/{id}",
    new { area = "AreaName", controller = "ControllerName", action = "Destroy" },
    new
    {
        httpMethod = new HttpMethodOverrideConstraint("POST", "DELETE"),
    }
);

My question: is it really necessary to have a custom route constraint to accomplish this? Or is there any way to make it work out-of-the-box with standard MVC & routing classes?

A: Action filters are your friend...
HttpDeleteAttribute, HttpPutAttribute, HttpPostAttribute, HttpGetAttribute


text:
Q: Does SCO Unix 7.1.4 come with Python installed? Does SCO Unix 7.1.4 come with Python installed? I searched on Google but couldn't find any clue.

A: It is probably included in UnixWare 7.1.4. but if not, it is available from SCO Skunkware but is unlikely to be the latest version.

A: Unlikely.  It may be available as contributed software, though.  If it isn't in the contributed software you will have to install it from the source tree.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bottom navigation view icons colors does not appear correctly I am having a problem with this BottomNavigationView library    https://github.com/ittianyu/BottomNavigationViewEx
The colours I stated in this xml file don't appear correctly

color_state.xml

<?xml version="1.0" encoding="utf-8"?>

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:color="@android:color/black" android:state_checked="true" android:alpha="1"/>
        <item android:color="#bdbdbd" android:state_checked="false" />
    </selector>

As you can see, I have set the state_checked = true color to black but instead it appears like this.
The same happens to state_checked = false,
Any body know how can I solve this
Here is the BottomNavigation code:
<com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx
        android:layout_width="match_parent"
        android:layout_height="60dp"
        app:menu="@menu/navigation_view_menu"
        app:itemIconTint="@drawable/color_state"
        android:id="@+id/bottomnav"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:itemBackground="@android:color/transparent"
        app:itemTextColor="@drawable/state"
        android:background="@android:color/white"

        >

    </com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx>

A: itemIconTint should be color resource not drawable, app:itemIconTint="@drawable/color_state" should change to  app:itemIconTint="@color/color_state"

A: For me it was a really dumb thing - after hours of debugging, learning about differences between supplying @color and @drawable and differences between various states of the Views, it turned out that I had both layout and layout-v21 folders in my res directory and I was only editing the former.


text:
Q: Golang library (or code) needed for client JSON-RPC2.0 over websocket I have to add

*

*JSON-RPC2.0

*over websockets, to my

*Golang

*Client process

to communicate with another server. Unfortunately, none of the requirements can be changed.
I have libs and example code that offer parts of the solution but I have been unable to put it all together.
I have looked at Ethereum (I cannot find a client example) Ethereum rpc
A stackoverflow question that dials tcp.
This dials TCP
net.rpc not 2.0, dials tcp
over http net/rpc and http
This one looked promising but I cannot make my client work.
type Params struct {
    Name string `json:"name"`
}

func main() {
    h := NewRPCHandler()
    h.Register("some_handler", dummySuccessHandler)
    ts := http.Server{Handler: h}
    defer ts.Close()
    conn, _, err := websocket.DefaultDialer.Dial("ws://127.0.0.1:8080/ws_rpc", nil)
    if err != nil {
        log.Printf("Error dialing %v", err)
    }

    client := jsonrpc.NewClient(conn.UnderlyingConn())

    par := &Params{"newuser"}
    req, err := json.Marshal(&par)
    if err != nil {
        log.Printf("Bad marshal %#v", err)
    }
    var resp Result
    err = client.Call("some_handler", &req, &resp)

I tried with/without marshaling but I'm clutching at straws here.


text:
Q: Internet Explorer 11 Click problem on Xunit I am using Windows 10 with IE11 on selenium XUNIT test. Selenium doesn't click at a desired IE element. Can someone suggest a solution please?

A: We had similar problem back in the day when the change the webdriver for IE, whit this code I can run it only in some computers, because in another's we have a lost of comunication between IE and the driver/code due another problem.
public static IWebDriver ExplorerDriverSetUp()
    {
        var options = new InternetExplorerOptions();

        options.RequireWindowFocus = false;
        options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
        options.IgnoreZoomLevel = true;
        options.EnsureCleanSession = true;
        options.InitialBrowserUrl = URL;

        IWebDriver driver = new InternetExplorerDriver(options);
        driver.Manage().Window.Maximize();
        return driver;
    }


text:
Q: Forms and Objects I need help on how to properly construct this. My goal is that I can type a person's name and subject on the form and have it show the student's grade for that subject.  I don't know how to approach this.  As you can see, I don't know how to set this up.  Any suggestions on how to attack this?
HTML Code

    <form name="reportcard">

Enter Student's name here:

                Student Name:
                <input type="text" name="student1">

                Subject
                <input type="text" name="subject1">

                <input type="button" value="Compute" onclick="callParents()">

    </form>

Javascript
function Student (name, art, science, english, spanish, shop, socialScience, gym) {
  this.aname = name;
  this.math = art;
  this.science = science;
  this.english = english;
  this.spanish = spanish;
  this.shop = shop;
  this.socialScience = socialScience;
  this.gym = gym;
  }

var johnSmith = new Student ("John Smith", "B", "A", "A", "F", "A", "B", "A");

var janeSmith = new Student ("Jane Smith", "A", "B", "C", "A", "F" , "C", "A");

var jackSmith = new Student;
  jackSmith.aname = "Jack Smith";
  jackSmith.math = "A";
  jackSmith.shop = "A";

function callParents () {
  if (jackSmith.shop === "F") {
  console.log("Call Parents!!!");
     } else {
    console.log("Student is doing fine in school");
  }

A: Ok...I have made a few changes to both your html as well as JavaScript code
In html, you don't need the td to have an id, instead I have put the Id for the input elements.
Here is modified html code:

    <form name="reportcard">

                Enter Student's name here:

                Student Name:

                    <input id="student" type="text" name="student1">

                    Subject

                        <input id="subject" type="text" name="subject1">

                        <input type="button" value="Compute" onclick="callParents();">

    </form>

In the JavaScript code, instead of keeping all student objects separate, I have made them into a single collection of student list. So it would be easier to loop. And also added the extra code to check for the Student name and to check grade.
Here is the modified JavaScript code:
    function Student(name, art, science, english, spanish, shop, socialScience, gym) {
    this.aname = name;
    this.math = art;
    this.science = science;
    this.english = english;
    this.spanish = spanish;
    this.shop = shop;
    this.socialScience = socialScience;
    this.gym = gym;
}

var johnSmith = new Student("John Smith", "B", "A", "A", "F", "A", "B", "A");

var janeSmith = new Student("Jane Smith", "A", "B", "C", "A", "F", "C", "A");

var jackSmith = new Student();
jackSmith.aname = "Jack Smith";
jackSmith.math = "A";
jackSmith.shop = "A";

var studentList = [];
studentList.push(johnSmith);
studentList.push(janeSmith);
studentList.push(jackSmith);

function callParents() {

    var name = document.getElementById('student').value;

    var sub = document.getElementById('subject').value;

    for (var i = 0; i < studentList.length; i++) {
        if (studentList[i].aname == name) {
            if (studentList[i][sub] == 'F') {
                console.log("Call Parents!!!");
            } else {
                console.log("Student is doing fine in school");
            }
            break;
        }
    }
}

And here is the DEMO

A: You should have an object with student entries, acting as a map between student name and grades. Then you add an event listener to the button and call the function which edits the output.
This is how it could look like:
var students = {};
students["John Smith"] = new Student ("John Smith", "B", "A", "A", "F", "A", "B", "A");
students["Jane Smith"] = new Student ("Jane Smith", "A", "B", "C", "A", "F" , "C", "A");
students[jackSmith.aname] = jackSmith;

document.getElementById('submit').addEventListener('click', callParents);

var student = document.getElementById('student1');
var subject = document.getElementById('subject1');
var output = document.getElementById('output');

function callParents() {
    if (subject.value && student.value) {
        var grade = students[student.value][subject.value];
        output.innerHTML = grade === 'F' ? 'Call parents!' : grade;
    }
}

FIDDLE


text:
Q: Por que no funciona la validacion? Cual seria la Expresion regular? <input id="iniciarsesionnombre" placeholder="Usuario" pattern="/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/" required type="text" class="validate white-text">
           <script>
              $('#iniciarsesionnombre').keypress(function(e){
                   var regex = new RegExp("/^[a-z0-9_.+-]+\@(?:[a-z0-9-]+\.)+[a-z0-9]{2,63}$/i");
                   var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
                     if (regex.test(str)) {
                          return true;
                         }
                      e.preventDefault();
                    return false;
              });
              $(document).ready(function(){
                $("#iniciarsesionnombre").on('paste', function(e){
                  e.preventDefault();
                });
            });
          </script>


text:
Q: Solr Sunspot non-indexed field Solr (via Lucene) supports different ways to indicate the way a field is indexed in a document: indexed, tokenized, stored,...
I'm looking for a way to have fields that are stored in Solr but are not indexed. Is there a way to achieve that in Sunspot?

A: Sunspot's configuration DSL supports an option of :stored => true for many of its default types. For the example of the stored string, it would be much simpler than my first example:
searchable do
  string :name, :stored => true
end

This generates a field name of name_ss corresponding to the following dynamicField already present in Sunspot's standard schema:
<dynamicField name="*_ss" stored="true" type="string" multiValued="false" indexed="true"/>

You can also create your own custom field or dynamicField in your schema.xml to be stored but not indexed, and then use the Sunspot 1.2 :as option to specify a corresponding field name.
For example, a more verbose version of the above. In your schema:
<dynamicField name="*_stored_string" type="string" indexed="false" stored="true" />

And in your model:
searchable do
  string :name, :as => 'name_stored_string'
end

A: You can try :
http://localhost:8983/solr/admin/luke?numTerms=0
And read with xpath or regex those fields with schema attribute value:
<str name="I">Indexed</str>
<str name="T">Tokenized</str>
<str name="S">Stored</str>

You will get something like:
<lst name="field">
<str name="type">stringGeneralType</str>
<str name="schema">--SM---------</str>
</lst>


text:
Q: HttpsURLConnection getHeaderFields not returning set-cookie I'm sending a get request to one HTTPS URL and somehow I'm getting null value for "Set-Cookie". When iterating I can see header-key is having "set-cookie" but header-value is coming as null.
Here is my code:
URL obj = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
HttpsURLConnection.setFollowRedirects(false);

conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
            "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.connect();

Map em = conn.getHeaderFields();
System.out.println("header Values......" + em.toString());

String headerName = null;

for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++)
{
     System.out.println("Header Nme : " + headerName);
     System.out.println(conn.getHeaderField(i));

}

Output:

header Values......{null=[HTTP/1.1 200 OK], x-wily-info=[Clear guid=0BE0EC9D0A7E67816C471FA946FD2EBB], Date=[Sat, 29 Mar 2014 03:27:41 GMT], Content-Length=[8106], x-wily-servlet=[*******************], X-FRAME-OPTIONS=[SAMEORIGIN], Connection=[close], Content-Type=[text/html;charset=UTF-8]}

Header Nme : Date
Sat, 29 Mar 2014 03:27:41 GMT
Header Nme : X-FRAME-OPTIONS
SAMEORIGIN
Header Nme : x-wily-info
Clear guid=0BE0EC9D0A7E67816C471FA946FD2EBB
Header Nme : x-wily-servlet
*****************************
Header Nme : Content-Type
text/html;charset=UTF-8
Header Nme : Content-Length
8106
**Header Nme : Set-Cookie
null
Header Nme : Set-Cookie
null**
Header Nme : Connection
close
Response Code : 200

From browser I can see below:

Connection  close
Content-Length  8106
Content-Type    text/html;charset=UTF-8
Date            Sat, 29 Mar 2014 02:20:31 GMT
Set-Cookie  JSESSIONID=*********************; Path=/****; Secure; **HttpOnly**
Set-Cookie      loginToken=*************;Path=/****/login/LoginProcess.do; **HttpOnly**;                                                                                Secure
X-FRAME-OPTIONS SAMEORIGIN
x-wily-info Clear guid=0BA36F4A0A7E67816C471FA938E304CA
x-wily-servlet  *****************************************

I tried same on many HTTPS URLs, all of them working fine, this one is only creating issue; the major difference I noticed is that this server is actually sending cookie as 'HttpOnly'. Is it causing issue?

A: It seems this is a feature, due to XSS issues.
https://bugs.openjdk.java.net/browse/JDK-6890023

A: May be, There was a redirect on this url, you can try this before getting inputstream:
httpURLConnection.setInstanceFollowRedirects(false);

A: There was one more bug report which dicated that the problem of "HttpUrlConnection Set-Cookie Header lost with WebStart " also affects version 7u67, 8, 9 .
https://bugs.openjdk.java.net/browse/JDK-8055829

A: create your cookie and try setting the property like this. Also before setting see the syntax of how a proper cookie looks from the net
 connection.setRequestProperty("Cookie", myCookie);


text:
Q: Querying for software using SQL query in SCCM I am looking for specific pieces of software across our network by querying the SCCM Database. My problem is that, for various reasons, sometimes I can search by the program's name and other times I need to search for a specific EXE.
When I run the query below, does it take 13 seconds to run if the where clause contains an AND, but it will run for days with no results if the AND is replaced with OR. I'm assuming it is doing this because I am not properly joining the tables. How can I fix this?
select vrs.Name0
FROM v_r_system as vrs
join v_GS_INSTALLED_SOFTWARE as VIS on VIS.resourceid = vrs.resourceid
join v_GS_SoftwareFile as sf on SF.resourceid = vrs.resourceid

where
VIS.productname0 LIKE '%office%' AND SF.Filename LIKE 'Office2007%'

GROUP BY vrs.Name0

Thanks!

A: Your LIKE clause contains a wildcard match at the start of a string:
LIKE '%office%'

This prevents SQL Server from using an index on this column, hence the slow running query.  Ideally you should change your query so your LIKE clause doesn't use a wildcard at the start.
In the case where the WHERE clause contains an AND its querying based on the Filename clause first (it is able to use an index here and so this is relatively quick) and then filtering this reduced rowset based on your productname0 clause.  When you use an OR however it isn't restricted to just returning rows that match your Filename clause, and so it must search through the entire table checking to see if each productname0 field matches.

A: Here's a good Microsoft article http://msdn.microsoft.com/en-us/library/ms172984.aspx on improving indexes. See the section on Indexes with filter clauses (reiterates the previous answer.)
Have you tried something along these lines instead of a like query?
... where product name in ('Microsoft Office 2000','Microsoft Office xyz','Whateverelse')


text:
Q: Calculate what the new number should be If I know that the price for a particular product is $1750 WITH a 35% discount
How can I found out what was the original price? This is probably a simple answer but I i have tried getting 35% and adding it to 1750, then 35% off that is a smaller number than 1750.
This isn't for study, purely just exporting a list of products, and I don't know there price before the sale price, and my client wants to know what the original prices were!

A: Let $1750=n-0.35n$ then $1750=0.65n$ then $n= 1750/0.65$ where n is the original price.
Note: the answer might depend on how the "discount" is calculated.


text: Q: Highcharts 3.0 & Quirks Mode & IE9 We are trying to integrate Highcharts into our BI portal. The portal is out of the box product certified for IE 8 and earlier. Designed a page that renders the graph using HighCharts. This page is called within an iFrame on the portal. The graph page reneders fine when it is called by itself, however when it is called within the iFrame, the graph has some issues. Unfortunately we cannot control how the portal is designed. Any ideas or suggestions please? Thanks in advance.


text:
Q: How to show SnackBar in ValueNotifier state manager I'm working on a PageView with States managed by ValueNotifier. I choose ValuNotifier because it is fast and native. The ValueListenableBuilder works great for a regular page with states like loading, success and error where the body is rebuilt with the content state.
In the code above, ValueListenableBuilder rebuild the body page when state changes, but some states should only push SnackBar and should keep the current value.
What is the best way to handler error (or warning) in SnackBar or Dialog, keeping the body page with the current state (with data, for example)?

*

*All states (even error) carry all data to rebuild the body, than I show SnackBar and rebuild the body;

*Show SnackBar by one callback, viewpage will register one controller callback and do all the process to get the context and show SnackBar;
In my point of view, the 2nd distort the ideia of state manager but avoid to rebuild body; but the 1st looks over by the fact I have to carry all information all the time and 'rebuild' everything. I think, the 1st could be a big problem if body has animated transitions.
Do you recomend a 3rd alternative?
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

// ======= Controller =======

class CounterState {}

class SuccessCounterState extends CounterState {
  final int currentValue;

  SuccessCounterState(this.currentValue);
}

class MaxCounterState extends CounterState {}

class MinCounterState extends CounterState {}

class Counter extends ValueNotifier<CounterState> {
  Counter() : super(SuccessCounterState(0));
  var _localValue = 0;

  void increment() {
    if (_localValue + 1 > 9) {
      value = MaxCounterState();
    } else {
      _localValue++;
      value = SuccessCounterState(_localValue);
    }
  }

  void decrement() {
    if (_localValue - 1 < 0) {
      value = MinCounterState();
    } else {
      _localValue--;
      value = SuccessCounterState(_localValue);
    }
  }
}

// ==== Page ====

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final counter = Counter();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            ValueListenableBuilder<CounterState>(
              valueListenable: counter,
              builder: (BuildContext context, state, _) {
                if (state is SuccessCounterState) {
                  return Text(
                    '${state.currentValue}',
                    style: Theme.of(context).textTheme.headline4,
                  );
                }

                if (state is MaxCounterState) {
                  Future.delayed(const Duration(milliseconds: 1), () {
                    const snackBar =
                        SnackBar(content: Text('Reached the max value'));
                    ScaffoldMessenger.of(context).showSnackBar(snackBar);
                  });
                }

                if (state is MinCounterState) {
                  Future.delayed(const Duration(milliseconds: 1), () {
                    const snackBar =
                        SnackBar(content: Text('Reached the min value'));
                    ScaffoldMessenger.of(context).showSnackBar(snackBar);
                  });
                }

                return const SizedBox();
              },
            ),
          ],
        ),
      ),
      floatingActionButton: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FloatingActionButton(
            onPressed: counter.decrement,
            tooltip: 'Decrement',
            child: const Icon(Icons.remove),
          ),
          const SizedBox(width: 20.0),
          FloatingActionButton(
            onPressed: counter.increment,
            tooltip: 'Increment',
            child: const Icon(Icons.add),
          ),
        ],
      ),
    );
  }
}


text:
Q: How to define an activity for the Search Button? I am not using a SearchManager, but I have built my own custom search activity. I want this to be shown when the user clicks on the Search button. How can I do this?

A: If I understand you correctly, you are asking how to launch your search activity. Create an onClickListener for your button and an EditText field for the user to input text.  Query the intent in your search activity to get whatever the user was searching for when the user clicks on the "search" button.
 EditText et = new EditText(this);

 public void onClick(View v){
     String searchText = et.getText();
     Intent intent = new Intent(this, com.example.app.SearchActivity.class);
     intent.putExtra("searchQuery", searchText);
     startActivity(intent);
 }

http://developer.android.com/guide/appendix/faq/commontasks.html#opennewscreen

A: Inside of your own application, you can do this via monitoring onKeyDown(), AFAIK.
Inside other applications, this is not possible except via custom firmware.

A: Not sure if this will work or not, but have you tried extending a BroadcastReceiver that can catch the search's intent? Checking the developer reference the intent seems to be "android.search.action.GLOBAL_SEARCH". So, you'll have a Receiver class like:
public class MyIntentReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals("android.search.action.GLOBAL_SEARCH")) {
      Intent sendIntent = new Intent(context, MySearchActivity.class)
      context.startActivity(intent);
    }
  }
}

In your manifest, between the application tags, you should have
<receiver android:name="MyIntentReceiver">
    <intent-filter>
        <action android:name="android.search.action.GLOBAL_SEARCH" />
    </intent-filter>
</receiver>


text:
Q: find range of value in matlab from two columns which are dependent I have an excel file which contains 4 columns. First column is time based on seconds and the other three are my function. How is it possible to find a time for specific value in the time column? let me give an example:
let say I want to find where is this value in the second column: 0.7636 located in time column? I found it manually which is located between 6960-7020enter link description here.
So, if I have for example a couple of values, and also considering different functions then it is difficult to do it manually.
I hope to hear your support.
Thanks Sepideh

A: You have to think about what a good solution is first. Let's call your three functions f1(t), f2(t) and f3(t). Now you have values v=[v1,v2,v3] and you want to know the best matching time value.
What is the best matching time value? You have to find some kind of distance metric, which tells you how close the data matches. As a default, I would use the 2-norm unless you have a reason to use something else. This would be:
%no running code, just a formula
d(t)=sqrt((f1(t)-v1)^2+(f2(t)-v2)^2+(f3(t)-v3)^2)

Now having d defined, you want to minimize it. There are basically two approaches. If you are looking for the closest row in your data, calculate d(t) for each row and take the minimum. Another approach would be to interpolate f1 to f3 so you could fill the gaps between your rows, then again search for the minimum d(t)

A: You can try something like this, to find position of data in column#2:
data            = xlsread('Q1.xlsx');
ref             = 0.7636;               % your reference value
lb              = data(:,2) <  ref;     % find lower value
ub              = data(:,2) >  ref;     % find greater value
lower_bound     = find(data(:,2)==max(data(lb,2))); % find lower value position
upper_bound     = find(data(:,2)==min(data(ub,2))); % find greater value position
row             = data(sort([lower_bound upper_bound]),1);  % find position in column#1

and result will be row = [6960;7020].


text:
Q: Hand Keypoint Detection Model Not Converging I'm currently trying to train a custom model with tensorflow to detect 17 landmarks/keypoints on each of 2 hands shown in an image (fingertips, first knuckles, bottom knuckles, wrist, and palm), for 34 points (and therefore 68 total values to predict for x & y). However, I cannot get the model to converge, with the output instead being an array of points that are pretty much the same for every prediction.
I started off with a dataset that has images like this:

each annotated to have the red dots correlate to each keypoint. To expand the dataset to try to get a more robust model, I took photos of the hands with various backgrounds, angles, positions, poses, lighting conditions, reflectivity, etc, as exemplified by these further images:

I have about 3000 images created now, with the landmarks stored inside a csv as such:

I have a train-test split of .67 train .33 test, with the images randomly selected to each. I load the images with all 3 color channels, and scale the both the color values & keypoint coordinates between 0 & 1.
I've tried a couple different approaches, each involving a CNN. The first keeps the images as they are, and uses a neural network model built as such:
model = Sequential()

model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = 'same', activation = 'relu', input_shape = (225,400,3)))
model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = 'same', activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2,2), strides = 2))

filters_convs = [(128, 2), (256, 3), (512, 3), (512,3)]

for n_filters, n_convs in filters_convs:
  for _ in np.arange(n_convs):
    model.add(Conv2D(filters = n_filters, kernel_size = (3,3), padding = 'same', activation = 'relu'))
  model.add(MaxPooling2D(pool_size = (2,2), strides = 2))

model.add(Flatten())
model.add(Dense(128, activation="relu"))
model.add(Dense(96, activation="relu"))
model.add(Dense(72, activation="relu"))
model.add(Dense(68, activation="sigmoid"))

opt = Adam(learning_rate=.0001)
model.compile(loss="mse", optimizer=opt, metrics=['mae'])
print(model.summary())

I've modified the various hyperparameters, yet nothing seems to make any noticeable difference.
The other thing I've tried is resizing the images to fit within a 224x224x3 array to use with a VGG-16 network, as such:
vgg = VGG16(weights="imagenet", include_top=False,
    input_tensor=Input(shape=(224, 224, 3)))
vgg.trainable = False

flatten = vgg.output
flatten = Flatten()(flatten)

points = Dense(256, activation="relu")(flatten)
points = Dense(128, activation="relu")(points)
points = Dense(96, activation="relu")(points)
points = Dense(68, activation="sigmoid")(points)

model = Model(inputs=vgg.input, outputs=points)

opt = Adam(learning_rate=.0001)
model.compile(loss="mse", optimizer=opt, metrics=['mae'])
print(model.summary())

This model has similar results to the first. No matter what I seem to do, I seem to get the same results, in that my mse loss minimizes around .009, with an mae around .07, no matter how many epochs I run:

Furthermore, when I run predictions based off the model it seems that the predicted output is basically the same for every image, with only slight variation between each. It seems the model predicts an array of coordinates that looks somewhat like what a splayed hand might, in the general areas hands might be most likely to be found. A catch-all solution to minimize deviation as opposed to a custom solution for each image. These images illustrate this, with the green being predicted points, and the red being the actual points for the left hand:

So, I was wondering what might be causing this, be it the model, the data, or both, because nothing I've tried with either modifying the model or augmenting the data seems to have done any good. I've even tried reducing the complexity to predict for one hand only, to predict a bounding box for each hand, and to predict a single keypoint, but no matter what I try, the results are pretty inaccurate.
Thus, any suggestions for what I could do to help the model converge to create more accurate & custom predictions for each image of hands it sees would be very greatly appreciated.
Thanks,
Sam

A: It would be useful to provide the loss over time for both training and testing data set.
From your description, it seems like you can minimize the training loss, but the testing performance is not going well.
If that is the case, try to regularize the model more. One useful approach is doing data argumentation more.
From the comments, it seems we have problems even with training data, then it is not overfitting but under-fitting issue.
Try to increase the network complexity. Also you can read this post
What should I do when my neural network doesn't learn?


text:
Q: How to perform n number of operations parallely in rxjava I have a scenario. I am getting data from different sources in different time. I need to perform some intensive work on those data parallely on a background thread and get the result on the main thread. I thought of using BehaviorSubject. But I am not able to figure out how will I do the operation parallely and return the result back to main thread. Since subscribeOn doesn't have any effect in Subjects so I wont be able to perform the operation in background thread. Am I missing something to connect?

A: Can you try something like this pls:
Observable.merge(
                Observable.just(1, 2, 3).subscribeOn(Schedulers.io()),
                Observable.just("4", "5", "6").subscribeOn(Schedulers.io())
        )
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();

A: I recommend to take a look to ParallelFlowable and to try the example below
someFlowable
    .parallel(NUMBER_OF_THREADS)
    .runOn(scheduler)
    .doOnNext(this::doSomeWork)
    .sequential()
    .subscribe{ result -> ... }


text:
Q: what's the meaning of "it prevents any guarantees from being made about the interface of exceptions"? from PEP 352:

In Python 2.4 and before, any (classic) class can be raised as an
exception. The plan for 2.5 was to allow new-style classes, but this
makes the problem worse -- it would mean any class (or instance) can
be raised! This is a problem as it prevents any guarantees from being
made about the interface of exceptions.

so, I don't understand the meaning of "as it prevents any guarantees from being made about the interface of exceptions", can anyone help explain this?


text:
Q: How does BLAS sgemm/dgemm work? I am trying to make use of the function sgemm in BLAS using ctypes in python. Trying to solve C = A x B the following code works just fine:
no_trans = c_char("n")
m = c_int(number_of_rows_of_A)
n = c_int(number_of_columns_of_B)
k = c_int(number_of_columns_of_A)
one = c_float(1.0)
zero = c_float(0.0)

blaslib.sgemm_(byref(no_trans), byref(no_trans), byref(m), byref(n), byref(k),
               byref(one), A, byref(m), B, byref(k), byref(zero), C, byref(m))

Now I would like to solve this equation: C = A' x A where A' is the transpose of A and the following code runs without an exception but the result returned is wrong:
trans = c_char("t")
no_trans = c_char("n")
m = c_int(number_of_rows_of_A)
n = c_int(number_of_columns_of_A)
one = c_float(1.0)
zero = c_float(0.0)

blaslib.sgemm_(byref(trans), byref(no_trans), byref(n), byref(n), byref(m),
               byref(one), A, byref(m), A, byref(m), byref(zero), C, byref(n))

For a test I inserted a matrix A = [1 2; 3 4]. The correct result is C = [10 14; 14 20] but the sgemm routine spits out C = [5 11; 11 25].
As far as I understand it, the matrix A does not have to be transposed by me since the algorithm takes care of it. What is wrong with my parameter passing in the second case?
Any help, link, article, advice is appreciated!

A: Blas typically uses column-major matrices (like Fortran), hence A = [1 2; 3 4] means
    |1 3|
A = |   |
    |2 4|

and the result is correct (assuming that your Python library does the same). See this read-me

A: The result you have indicates sgemm had computed A*A' rather than A'*A as you wanted. The simple solution is to switch the two inputs to the function.


text:
Q: Domain-Driven-Design - How a UnitOfWork should be notified about entities that were updated? There is something not clear to me about domain-driven-design and unit of work pattern.
Let's say I have an entity that was retrieved from a repository. Once I updated this entity, how UnitOfWork should know that it was updated, so the updated entity can be persisted to the DB?
Currently, I see two options:
1) Manually call uow.Update(entity) in the service layer. E.g.:
Employee emp = EmployeeRepository.GetByID(1);
emp.Name = "NewName";
uow.Update(emp);
uow.Commit();

2) Rely on some ORM magic to track changes, and persist updated entities to the DB. E.g.:
Employee emp = EmployeeRepository.GetByID(1);
emp.Name = "NewName";
uow.Commit();

Both these options seems hairy to me:
First - if changes were made inside some aggregate, the aggregate should let the service layer know that it updated some entities.
Second - isn't relying on ORM implementation is violation of Persistence Ignorance principle?
What do you do in your projects? Or maybe I miss something / messed up something and there is better solution?
Thanks

A: First: Why does the aggregate have to let anyone know that it updated some entities?  If you're using 'Repository per Aggregate Root' and a proper ORM that will persist your entire graph you can do something like this..

Employee emp = employeeRepository.GetById(1);

emp.RewardWith(new GoldStar());

employeeRepository.Save(emp);

Any half decent ORM will be tracking the entire employee graph so it will know that the employees star chart has been modified and persist changes accordingly.
Second: your domain needs to be persistence ignorant.. it is very important that developers working with the system not be :)


text:
Q: Where do I override the create_export_query for a custom module? I am working with SugarCRM.
I have a custom module, I am trying to override the export method to not include all of the columns. I actually need to make the columns dependent on the visible columns in the list view (that I can figure out).
I have been going through all the files in SugarCRM, I notice that the built in modules have a Module.php file, where there is a 'SELECT Module.*' for the export method. I cannot find a file like that for my custom module. I am asking for help on where do I create (if needed) or where can I find the file to customize the create_export_query.

A: create_export_query is a method in SugarBean (/data/SugarBean.php is the base class for nearly all SugarCRM objects) and can be overriden in the bean's core class file. So if you have custom module MyModule you can find the core class in /modules/MyModule/MyModule.php
There is likely not a create_export_query() method there currently, so you can write one in. It'll look something like this:
<?php
require_once("include/SugarObjects/templates/basic/Basic.php");
class MyModule extends Basic{

  public function MyModule(){
    parent::Basic();
  }

  public function create_export_query(&$order_by, &$where, $relate_link_join=''){
    $query = " select * from {$this->table_name} "; // build your query string however you like
    return $query;
  }
}


text:
Q: D3 chart: How to align zero points of dual y axes I´m trying to create a D3 line chart with two vertical y axes, one on the left and one on the right side. The domain of the left axis may have negative values, which means the zeropoint will be shifted upwards. I want to align the zeropoint of the right axis to the one of the left axix.  Similar as you can see here, but without the x axis moving upwards too:

So far, i tried to search for the html g element which represents the tick of the zero point:
<g id="tmp" class="y axis" transform="translate(30,0)" fill="red">
    <g class="tick" style="opacity: 1;" transform="translate(0,330)">
    <g class="tick" style="opacity: 1;" transform="translate(0,257.5)">
    <g class="tick" style="opacity: 1;" transform="translate(0,185)">
        <line x2="-5" y2="0">
        <text dy=".32em" style="text-anchor: end;" x="-8" y="0">0</text>
    </g>

What i need here is to extract the "185" height value in the transform attribute, so that i can use it for the range in the second axis.
That was just my basic idea how it could have been done. Does anyone know how do it technically with D3/Javascript? Or maybe even has a more elegant solution?

A: no need to split the axis - just make sure min/max of both axis' are proportional. You just need to identify the axis that must be extended.
In your example simply use a factor of 10 to have both axis perfectly aligned. Your left axis is extended to go up to 12 instead of the initial 10.

A: In your case distance from -4 (min value) to 0 on the left scale must match the distance from -40 (min value) to 0 on the right scale  and distance from 0 to 10 (max value) on the left scale  must match to the distance from 0 to 120 (max value) on the right scale.
To build the right axis you can use two axes ( one that goes from -40 to 0 and the other one that goes from 0 to 120 ). You can get the base line of the left axis by doing: var base = leftAxis(0); The range of the first scale that you'll use to build the first axis will be  [leftAxis(minVal), base], the range of the second scale will be  [base, leftAxis(maxVal)].
Hope that helps! Good luck!


text:
Q: Using new codeigniter class instance but without database connection I'm using a comet like polling system for user notification. The client side uses Ajax to send a 30 seconds long query through a method in a controller class in Codeigniter. On the server side the polling method sleeps 5 seconds after every check for new changes. The whole application uses a database but sice the Ajax call creates a new apache process, calling the method in this controller initialize an unwanted new database connection every 5 seconds. I know I could close the connection with $this->db->close() inside the polling method but I suspect that opening an closing the database connection every 5 seconds for a lot of users could result in a big CPU usage.
Is there a way to create an extended instance of the base Codeigniter class BUT without a database connection, doing it runtime, without changing the config/database.php?
Something like this:
class Controller_without_database extends MY_Controller_with_database {

 function __construct() {
   parent::__construct();

   parent::__killdatabase();
 }

 public function poll(){
    while check_for_changes(); //it uses shared memory not database
    sleep(5);
 }
}


text:
Q: Evaluate $\lim_{t \rightarrow \frac{\pi}{4}}(\frac{|\sin^{\alpha}(t)-\cos^{\alpha}(t)|}{|\sin(t)-\cos(t)|^{\alpha}}), \alpha \in [0,1]$. I came across the following limit in an exercise and was wondering how to solve it:
$\lim_{t \rightarrow \frac{\pi}{4}}(\frac{|\sin^{\alpha}(t)-\cos^{\alpha}(t)|}{|\sin(t)-\cos(t)|^{\alpha}}), \alpha \in (0,1]$
Could it have something to do with the modulus of inequality?
I tried all the usual methods (l'hopital and some trig identities) but can't seem to get the desired result (=0). Would be nice if someone could give me some tips :)
PS: For anyone wondering what the original question was, it was to show that: for the function $f(x) = |x|^\alpha$ on the interval $[0,1]$, with $\alpha \in (0,1]$. Show that $\exists C > 0$ s.t. the modulus of continuity of $f(x)$ satisfies:
$\omega(f,h)\leq Ch^\alpha$, $h > 0$.
Determine the minimal possible value of $C$. (The limit came from my attempt to show $C \geq 1 \Rightarrow \min\{C\} = 1$)

A: You can try to compute the limit
$$
\lim_{t \rightarrow \frac{\pi}{4}^+}(\frac{|\sin^{\alpha}(t)-\cos^{\alpha}(t)|}{(\sin(t)-\cos(t))^{\alpha}}), \alpha \in (0,1].
$$
In this way you can get rid of the absolute value and just compute
$$
\lim_{t \rightarrow \frac{\pi}{4}^+}\frac{\sin^{\alpha}(t)-\cos^{\alpha}(t)}{(\sin(t)-\cos(t))^{\alpha}}, \alpha \in (0,1].
$$
I will compute this limit, and the same will apply if you compute the left limit. Applying L'Hopital rule:
$$
\lim_{t \rightarrow \frac{\pi}{4}^+}\frac{\sin^{\alpha}(t)-\cos^{\alpha}(t)}{\sin(t)-\cos(t)^{\alpha}}=
\lim_{t \rightarrow \frac{\pi}{4}^+}\frac{\alpha \sin^{\alpha-1}(t)\cos (t)+\alpha\cos^{\alpha-1}(t)\sin(t)}{\alpha(\sin(t)-\cos(t))^{\alpha-1} (\cos(t)+\sin(t))}.
$$
Note that since $\alpha \in (0,1]$, $\alpha -1<0$, and therefore
$$
\lim_{t \rightarrow \frac{\pi}{4}^+}\frac{\alpha \sin^{\alpha-1}(t)\cos (t)+\alpha\cos^{\alpha-1}(t)\sin(t)}{\alpha(\sin(t)-\cos(t))^{\alpha-1} (\cos(t)+\sin(t))}=\lim_{t \rightarrow \frac{\pi}{4}^+}(\sin(t)-\cos(t))^{1-\alpha}\frac{\alpha \sin^{\alpha-1}(t)\cos (t)+\alpha\cos^{\alpha-1}(t)\sin(t)}{\alpha (\cos(t)+\sin(t))}=0.
$$

A: Note that $|x|^\alpha$ is differentiable at $x=\frac1{\sqrt 2}$, so in particular Lipschitz. Thus,
$$ |x|^\alpha = \frac1{2^{\alpha/2}} + O\Big(x-\frac1{\sqrt 2}\Big), \quad \text{as }x\to \frac1{\sqrt 2}.$$
Since
\begin{align}\cos t &= \frac1{\sqrt 2} - \frac{t-\frac\pi4}{\sqrt 2} + O\Big(\left|t-\frac\pi4\right|^2\Big), \quad \text{and} \\ \sin t &= \frac1{\sqrt 2} + \frac{t-\frac\pi4}{\sqrt 2} + O\Big(\left|t-\frac\pi4\right|^2\Big), \quad \text{as }t\to \frac\pi{ 4}, \end{align}
the numerator is $O(t-\frac\pi4)$, while the denominator is eventually (as $t\to \frac\pi4$) bounded from below by $\frac12|t-\frac\pi4|^\alpha$. So the limit  is zero.
For the original problem: let $C_*$ be the infimum of all possible $C$s. If $\omega(f,h)\le C|h|^\alpha$, then since $|h|^\alpha = f(h)-f(0) \le \omega(f,h),$ we must have $C\ge 1$. On the other hand,  a standard argument shows $|f(x)-f(y)| \le |x-y|^\alpha$, so $C_*\le 1$. Hence, $C_*=1$.


text:
Q: error in converting RAW yuv into mp4 video with ffmpeg I am trying to convert raw yuv video into mp4 using ffmpeg.
ffmpeg -f rawvideo -vcodec rawvideo -s 1920x1080 -r 25 -pix_fmt yuv420p -i Beauty_3840x2160_120fps_420_10bit_YUV.yuv -c:v libx264 -preset slow -qp 0 bb/output.mp4

I got an error in video.
ffmpeg -f rawvideo -vcodec rawvideo -s 1920x1080 -r 25 -pix_fmt yuv420p -i Beauty_3840x2160_120fps_420_10bit_YUV.yuv -c:v libx264 -preset slow -qp 0 bb/output.mp4
ffmpeg version 4.2.4-1ubuntu0.1 Copyright (c) 2000-2020 the FFmpeg developers
  built with gcc 9 (Ubuntu 9.3.0-10ubuntu2)
  configuration: --prefix=/usr --extra-version=1ubuntu0.1 --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --arch=amd64 --enable-gpl --disable-stripping --enable-avresample --disable-filter=resample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libcodec2 --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libjack --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librsvg --enable-librubberband --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-lv2 --enable-omx --enable-openal --enable-opencl --enable-opengl --enable-sdl2 --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-nvenc --enable-chromaprint --enable-frei0r --enable-libx264 --enable-shared
  libavutil      56. 31.100 / 56. 31.100
  libavcodec     58. 54.100 / 58. 54.100
  libavformat    58. 29.100 / 58. 29.100
  libavdevice    58.  8.100 / 58.  8.100
  libavfilter     7. 57.100 /  7. 57.100
  libavresample   4.  0.  0 /  4.  0.  0
  libswscale      5.  5.100 /  5.  5.100
  libswresample   3.  5.100 /  3.  5.100
  libpostproc    55.  5.100 / 55.  5.100
[rawvideo @ 0x7fffe7e28440] Estimating duration from bitrate, this may be inaccurate
Input #0, rawvideo, from 'Beauty_3840x2160_120fps_420_10bit_YUV.yuv':
  Duration: 00:03:12.00, start: 0.000000, bitrate: 622080 kb/s
    Stream #0:0: Video: rawvideo (I420 / 0x30323449), yuv420p, 1920x1080, 622080 kb/s, 25 tbr, 25 tbn, 25 tbc
File 'bb/output.mp4' already exists. Overwrite ? [y/N] y
Stream mapping:
  Stream #0:0 -> #0:0 (rawvideo (native) -> h264 (libx264))
Press [q] to stop, [?] for help
[libx264 @ 0x7fffe7e35c00] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 BMI2 AVX2
[libx264 @ 0x7fffe7e35c00] profile High 4:4:4 Predictive, level 5.0, 4:2:0 8-bit
[libx264 @ 0x7fffe7e35c00] 264 - core 155 r2917 0a84d98 - H.264/MPEG-4 AVC codec - Copyleft 2003-2018 - http://www.videolan.org/x264.html - options: cabac=1 ref=5 deblock=1:0:0 analyse=0x1:0x111 me=hex subme=8 psy=0 mixed_ref=1 me_range=16 chroma_me=1 trellis=0 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=0 chroma_qp_offset=0 threads=9 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc=cqp mbtree=0 qp=0
Output #0, mp4, to 'bb/output.mp4':
  Metadata:
    encoder         : Lavf58.29.100
    Stream #0:0: Video: h264 (libx264) (avc1 / 0x31637661), yuv420p, 1920x1080, q=-1--1, 25 fps, 12800 tbn, 25 tbc
    Metadata:
      encoder         : Lavc58.54.100 libx264
    Side data:
      cpb: bitrate max/min/avg: 0/0/0 buffer size: 0 vbv_delay: -1
frame= 4800 fps= 16 q=-1.0 Lsize=11907234kB time=00:03:11.96 bitrate=508147.7kbits/s speed=0.646x
video:11907177kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.000485%
[libx264 @ 0x7fffe7e35c00] frame I:2789  Avg QP: 0.00  size:2638070
[libx264 @ 0x7fffe7e35c00] frame P:2011  Avg QP: 0.00  size:2404461
[libx264 @ 0x7fffe7e35c00] mb I  I16..4..PCM: 28.0%  0.0% 67.1%  4.9%
[libx264 @ 0x7fffe7e35c00] mb P  I16..4..PCM:  5.6%  0.0%  6.2%  0.6%  P16..4: 52.9% 23.9% 10.8%  0.0%  0.0%    skip: 0.0%
[libx264 @ 0x7fffe7e35c00] 8x8 transform intra:0.0% inter:9.6%
[libx264 @ 0x7fffe7e35c00] coded y,uvDC,uvAC intra: 99.4% 100.0% 100.0% inter: 100.0% 100.0% 100.0%
[libx264 @ 0x7fffe7e35c00] i16 v,h,dc,p: 89%  0%  1% 10%
[libx264 @ 0x7fffe7e35c00] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 65%  0%  0%  0%  0%  0%  0%  0% 35%
[libx264 @ 0x7fffe7e35c00] i8c dc,h,v,p:  1%  0% 94%  4%
[libx264 @ 0x7fffe7e35c00] Weighted P-Frames: Y:31.1% UV:29.3%
[libx264 @ 0x7fffe7e35c00] ref P L0: 21.3% 16.1% 27.4% 14.4% 11.7%  5.5%  3.6%

I got the green video.

A: Provide the proper -pixel_format and -video_size:
ffmpeg -framerate 120 -video_size 3840x2160 -pixel_format yuv420p10le -i input.yuv -vf scale=1920:1080 -r 25 -c:v libx264 -preset slow -qp 0 output.mp4

See:

*

*rawvideo demuxer documentation

*List of pixel formats (ffmpeg -pix_fmts)


text:
Q: how to create a new user jazn-data.xml programmatically? I'm using JDeveloper 11g.
I want to create a new user programmatically in 'jazn-data.xml'. Is this possible and how can I do it?

A: Yes, is possible.
Technically speaking, you do not create users in jazn-data.xml, this is just a file used at development time. At runtime, you create users in weblogic.
Please find below a link:
Creating WebLogic users programmatically from a standalone Java client

A: public void createWeblogicUser() {
try {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
    env.put(Context.SECURITY_PRINCIPAL, "weblogic");
    env.put(Context.SECURITY_CREDENTIALS, "welcome1");
    env.put(Context.PROVIDER_URL, "t3://127.0.0.1:7101");
    InitialContext ctx = new InitialContext(env);
    MBeanServer wls = (MBeanServer) ctx.lookup("java:comp/env/jmx/runtime");
    wls.invoke(new ObjectName(" Security:Name=myrealmDefaultAuthenticator")
         , "createUser"
         , new Object[] {"wls_user5555", "password123","User created programmatically."}
         , new String[] {"java.lang.String", "java.lang.String","java.lang.String"}
      );
    ctx.close();

}
catch(Exception ex) {
    ex.printStackTrace();
}

}


text:
Q: Ruby Timestamp Reliably Convert To UTC I am writing a Ruby script. It needs to accept time stamp from the user and then do some database queries using it.
As far as I know the database is storing timestamps in UTC.
I want to let the users specify the time in following format: 2015-01-01 05:00 AM CST
From what Google tells me CST is 6 hours behind UTC, so after conversion to UTC I would expect the time to be 2014-12-31 11:00 PM UTC.
But that is not what I am seeing.
Time.strptime('2015-01-01 05:00 AM CST', '%Y-%m-%d %I:%M %P %Z').utc
prints
2015-01-01 11:00:00 UTC
Shouldn't it have printed 2014-12-31 11:00 PM UTC?
Time.strptime('2015-01-01 05:00 PM CST', '%Y-%m-%d %I:%M %Z').utc
prints
2015-01-01 11:00:00 UTC
The change from AM to PM doesn't seem to make any difference, how can that be?

A: I had it backwards! UTC is AHEAD of CST, so when CST is converted to UTC 6 hours will be ADDED to the CST time!!
Ruby is doing it right.
So 5 AM CST = 11 AM UTC.
And 5 PM CST = 11 PM UTC.
The difference in day happens if I test 11 PM CST:
Time.strptime('2015-01-01 11:00 PM CST', '%Y-%m-%d %I:%M %P %Z').utc
prints
2015-01-02 05:00:00 UTC
That is it correctly incremented the day.


text:
Q: Android MediaStore won't bring last photo taken I'm having a serious problem with one specific android device(cat phone) that won't bring the last photo taken with this code:
 Cursor cursor = getContentResolver().query(
                    Media.EXTERNAL_CONTENT_URI, new
                            String[]{Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION},
                    Media.DATE_ADDED, null, "date_added ASC");
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    Uri uri = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
                    photoPath = uri.toString();
                } while (cursor.moveToNext());
                cursor.close();
            }

This works in several phones, several android versions, but It won't work in that phone(moveToFirst returns false).
The worst part is, that some apps WILL update this DB(for example, the take screen capture app). But If after taking a screenshot I take a photo, the last record of that cursor will be the screenshot.
I've found this workaround:
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, _uri));
    } else {
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, _uri));
    }

I put that code just before the cursor, but still won't work.
Any idea?
Edit:
I solved the problem, the issue was this:
Camera activity returning null android
But everyone always give half and answer. What I did was this:
... Creating the intent:
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
outputFileUri = getImageUri();            takePictureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);

...
/**
 * @return
 */
private Uri getImageUri() {
    Uri m_imgUri = null;
    File m_file;
    try {
        SimpleDateFormat m_sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String m_curentDateandTime = m_sdf.format(new Date());
        String m_imagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + m_curentDateandTime + ".jpg";
        m_file = new File(m_imagePath);
        m_imgUri = Uri.fromFile(m_file);
    } catch (Exception p_e) {
    }
    return m_imgUri;
}

Handling the response:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

                String photoPath = outputFileUri.getPath();

}

A: The answer is in my EDIT of the original post.


text:
Q: How to securely publish same npm package by several different people? There is an open source project. Multiple people are working on it. Multiple people need to publish it to the NPM registry.
How to securely publish a single project by multiple people?
Obviously, the owner of the package do not want to give his login/password to other people.

A: From the npm docs:

npm owner add <user> [<@scope>/]<pkg>
npm owner rm <user> [<@scope>/]<pkg>
npm owner ls [<@scope>/]<pkg>

https://docs.npmjs.com/cli/owner


text:
Q: Auto updating data coping Excel-VBA script I have an Excel file, having a sheet(SheetA) which is linked with a software to imports live market data, so it auto updates(every second) according to the  software it is linked to. I am taking some data from specific cells(which are not fixed and very large in number... other i could have just linked them) of SheetA to another sheet(SheetB) using VBA script to do some calculations, I want to know a way to keep my SheetB calculations automatically synchronized as SheetA updates its cell values.
TIA

A: Since updating can raise multiple Worksheet_Change events, it's not practical to write copying routine in that method. More practical would be on workbook opening:
Private Sub Workbook_Open() method is responsible for this event. So, now data in Sheet B will be updated, when workbook will be opened (so before any work). Even if updating code is opening workbook, then event is raised only once, therefore, the code will execute only once.


text:
Q: JS - http request file contains js variable I have a http request in a nodejs project to get a file which is a javascript file.
e.g. a.js:
var a = 'i am a.js';
var b = 'please convert me to js';

axios get function:
axios.get('a.js').then((response) => {
    let data = response.data
    // data should have var a and b as a STRING type
})

As I'm using javascript to get this file, how can I convert this file to simple javascript variable? Thankyou!

A: You could use require('a.js') instead, if it's on the same server.
There you should use exports.a = "i am a.js"
If not, you could use the eval function to run the javascrip code. eval(data)


text:
Q: Excel - Return Max/Min Value Since I am trying to find a way to return the previous largest/smallest value in a time series since the most recent data point. Please see the attached image
Input   Input   Output
Date    Value   Largest Since
10/31/2016  7   …
11/1/2016   10  …
11/2/2016   8   …
11/3/2016   5   …
11/4/2016   6   11/2/2016
11/5/2016   9   11/1/2016

Example
So for row 6, I want a formula (no VBA please) that would return the date 11/1/16, as the value 10 in column two with the corresponding date of 11/1/16 was the largest value prior to 11/5/16 (with the associated value 9).
Applying the same formula to 5 should return 11/2/16, given that the value 8 was the last largest value prior to 11/4/16.
I know some combination of rank, index/match, and large/small should get me there, but I can't quite figure it out at the moment.
Thanks!

A: With input dates assumed E1:E8 and Input values F1:F8, I used the following array formula for "Output Largest Since" starting in row H4 : =IFERROR(INDEX(E$1:E$8,MAX(IF($F$1:$F3>F4,ROW(F$1:F3),"")),1),""). I hope this helps.


text:
Q: Plotting Intersecting Circles On A 2-D Plane I am new to Mathematica and I would like to plot a number of circles all onto the same graph. I would like to visually observe which circles intersect each other. One constraint on all the circles is that the x-coordinate is always zero.
I have a list of 3-tuples (x-coordinate, y-coordinate, radius) which represent each circle. For example, (0,0,1), (0,1,5)... I am not sure how construct the circle intersections using the Plot command.

A: triples = Table[{0, RandomInteger[5], RandomReal[]}, {5}];
(* {{0,4,0.676806},{0,5,0.377882},{0,2,0.421773},{0,4,0.631164},{0,3, 0.820832}} *)

opts = {Axes -> True, PlotRange -> {{-1, 1}, {0, 6}}, Frame -> False,
      ImageSize -> 150, AspectRatio -> Automatic, BaseStyle -> Thick};

Graphics
g1 = Graphics[{Hue[RandomReal[]], Circle[{#, #2}, #3]} & @@@ triples, opts];

Graphics / Translate / Scale
g2 = Graphics[{Hue[RandomReal[]], Translate[Scale[Circle[], #3], {#, #2}]}&@@@ triples,
  opts]

ContourPlot
g3 = ContourPlot[Evaluate[(x - #)^2 + (y - #2)^2 == #3^2 & @@@ triples],
   {x, -1, 1}, {y, 0, 6}, Evaluate[opts], ContourStyle->Table[Hue[RandomReal[]], {5}]];

ParametricPlot
g4 = ParametricPlot[Evaluate[(#3 { Cos[t], Sin[t]} + {#, #2}) & @@@ triples],
 {t, 0, 2 Pi}, Evaluate[opts], PlotStyle->Table[Hue[RandomReal[]], {5}]];

Row[Labeled[##, Top] & @@@ {{g1, "Graphics"}, {g2, "Graphics/ Translate/ Scale"},
   {g3, "ContourPlot"}, {g4, "ParametricPlot"}}, Spacer[5]]

A: Graphics[
   Circle @@@ ({{#[[1]], #[[2]]}, #[[3]]} & /@
   {{0, 2, 3}, {0, 4, 6}, {0, 12, 9}})
         ]

A: Show[Graphics[{Circle[{0, 0}, 2], Circle[{1, 1}, 2]}], Axes -> True]


text:
Q: Signal travels with speed greater than light breaks causality Signal can't travel at speed greater than light speed in vacuum which is a assumption of special relativity. But if a signal travels at speed greater than $c$ then it will violate causality. I tried to prove this statement using Lorentz transformation equations. But in the denominator and imaginary number will arise. I need a mathematical proof.

A: Suppose I have a gun that fires bullets with a superluminal velocity V, and I'm going to use it to shoot you. In our rest frame I'm standing at the origin, $x=0$ and you're standing at some distance $x = D$. I fire the gun at $t=0$ and you die at $t=D/V$. So cause an effect are pretty clear - I fire my gun and as a result of this you die a short time later. (Apologies if this seems unnecessarily bloody :-)
Now suppose my friend Fred is in a spaceship flying past at a (subluminal) velocity $v$. We can use the Lorentz transformations to find out what happens in Fred's rest frame. We'll assume Fred passes me just as I fire, so the gun is fired at the spacetime point $(0,0)$ in both our frames. It just remains to find where in Fred's frame the bullet hits you.
In my frame the bullet hits you at $(t=D/V, x=D)$ so let's use the Lorentz transformations to calculate when the bullet hits you in Fred's frame:
$$\begin{align}
 t' &= \gamma \left( t - \frac{vx}{c^2} \right) \\
    &= \gamma \left( \frac{D}{V} - \frac{vD}{c^2} \right) \\
    &= \gamma \frac{D}{V}\left( 1 - \frac{vV}{c^2} \right)
\end{align}$$
But if we make the bullet velocity $V \gt c^2/v$ that means $1 - vV/c^2$ is negative, so $t' \lt 0$, and this would mean that in Fred's rest frame you died before I fired the gun.
This is where we have a problem with causality. For any superluminal bullet velocity there is a frame where you died before I fired at you. The only way to avoid this is for the bullet velocity to never exceed $c$.


text:
Q: Having troubles creating this object I'm very new to java, and trying to grasp making an object with two different values.
I'm trying to create a Customer object called customer, with the initial values of 1 and cust1, and then display the customer object to the output with toString()
Thanks for any help in advance.
Here's what I have currently.
public class Customer {

private int id;
private String name;

public Customer(int id, String name) {
    this.id = id;
    this.name = name;
    Customer customer = new Customer(1, "cust1");
}

A: Don't create a new object instance within a classes constructor — this will result in a StackoverFlowException.
public class Customer {

    private final int id;
    private final String name;

    public Customer(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

In a separate class you can simply create a new instance by using
Customer customer = new Customer(1, "Name");

A: You have no entry point to your program, which should look like this in your class
public static void main(String[] args)
{
 //objects created here
}

You also create a Customer object as a member of your Customer class which means every Customer object contains another.
You can't set Customer members like this
Customer customer = new Customer(); //you also don't have a no argument constructor
customer = 1; //how would it know where to put this 1?
customer = cust1; //same as above

it would be like this (if they were in the right place, as mentioned above)
Customer customer = new Customer(); //if using this method you will need a no argument constructor
customer.id = 1;
customer.name = cust1;

or like this
new Customer(1,"cust1");

In Summary

*

*You need an entry point

*You are creating Customer with a no argument constructor but you only have one constructor which has two arguments

*You are -for some reason- creating a Customer inside every Customer

*You are not setting members of your Customer object in the correct (or even in a valid) way


text:
Q: get nearest coordinate from sqlite database I have a point coordinate based on two double values x0,y0 both in this format: xx.x (point as decimal separator)
In a database I have a list of lines that are defined by the coordinates x1,y1 as startpoint and x2,y2 as endpoint. Among other columns, (such as line thickness and so on) in the database there are these columns:
id | x1 | y1 | x2 | y2
What I would need is a query that returns whatever line has either the starpoint(x1,y1) or the endpoint(x2,y2) nearest to my basepoint (x0,y0). So the line that starts or ends nearest to my current position.
Thanks

A: SQLite has no square root function, but for comparing distances, we can just as well use the square of the distance:
SELECT *
FROM MyTable
ORDER BY min((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0),
             (x2-x0)*(x2-x0) + (y2-y0)*(y2-y0))
LIMIT 1


text:
Q: Scala XML validation by XSD and parsing I need to validate xml file by xsd, and parse xml if it possible. I have the next example:
import java.io.FileInputStream
import javax.xml.XMLConstants
import javax.xml.parsers.SAXParserFactory
import javax.xml.transform.stream.StreamSource
import javax.xml.validation.SchemaFactory

import org.xml.sax.SAXParseException
import org.xml.sax.helpers.DefaultHandler

import scala.util.Try
import scala.xml.XML

object XMLTup extends App {
  val schema = {
    val factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
    val xsdStream = new FileInputStream("xsd.xsd")
    val schema = factory.newSchema(new StreamSource(xsdStream))
    xsdStream.close()
    schema
  }

  val saxParser = {
    val f = SAXParserFactory.newInstance()
    f.setNamespaceAware(true)
    f.setSchema(schema)
    f.newSAXParser()
  }

  //DOESN'T WORK
  val xml1 = new FileInputStream("xml.xml")
  println {
    Try{XML.withSAXParser(saxParser).load(xml1)}
  }
  xml1.close()

  //WORKS
  val xml2 = new FileInputStream("xml.xml")
  val handler = new DefaultHandler() {
    override def error(ex: SAXParseException)  {
      println("Validation Error!")
    }
  }
  saxParser.parse(xml2, handler)
  xml2.close()
}

When I use scala XML (DOESN'T WORK), I got Success and haven't validation error, but the next code (WORKS) I got "Validation Error" message. Why is it happend? How can I validate XML by XSD with scala XML class?

A: I use scalaxb with sbt (my xsd files are located in subproject genscalaxb).
Add to project/plugin.sbt:
resolvers += Resolver.sonatypeRepo("public")

addSbtPlugin("org.scalaxb" % "sbt-scalaxb" % "1.2.1")

Add to your build.sbt (map is optional - for custom packages):
lazy val `genscalaxb` = Project("genscalaxb", file("genscalaxb")).settings(scalaxbSettings: _*).settings(
  packageNames in scalaxb in Compile := Map(new URI("https://github.com/ajozwik/mvn2sbt") -> "pl.jozwik.gen",
    new URI("http://maven.apache.org/POM/4.0.0") -> "org.maven"),
  sourceGenerators in Compile <+= scalaxb in Compile
)

Put your xsd files to: genscalaxb/src/main/xsd
I use in in function, see in github:
 private def handlePomFile(pomXml: File, parent: Option[MavenDependency]) = {
    val xmlFromFile = Try(xml.XML.loadFile(pomXml)) match {
      case Success(pom) => pom
      case Failure(th) =>
        logger.error(s"${pomXml.getAbsolutePath} failed to be parse")
        throw th
    }
    val pomModel = scalaxb.fromXML[org.maven.Model](xmlFromFile)
    createProjectMap(pomXml.getParentFile, pomModel, parent)
  }

The xsd file is maven-4.0.0.xsd
Xml files - are poms.

A: Surprisingly, it was found that scala XML use NoBindingFactoryAdapter which inherited FactoryAdapter witch inherited DefaultHandler. DefaultHandler have the next method:
public void error (SAXParseException e)
    throws SAXException
{
    // no op
}

You need override this method for handle error message of xml validation. One way to do it is create own object of scala trait XMLLoader and override adapter and parser if necessary:
 //NOW, IT WORKS
  val xml1 = new FileInputStream("xml.xml")
  println {
    Try{
      val loader = new XMLLoader[Elem] {
        override def adapter: FactoryAdapter = new NoBindingFactoryAdapter() {
          override def error(e: SAXParseException) = {
            throw e
          }
        }

        override def parser: SAXParser = saxParser
      }
      loader.load(xml1)
    }
  }
  xml1.close()


text:
Q: Adding unique id attribute to img tag I am trying to add a unique id attribute to each img tag while mapping so that i can use it for some logic else where
How can I do it?
const imgs = image.map(img => (
    <img
      id={???}
      key={img.id}
      src={img.urls.small}
      onClick={onClickHandler}
    />
  ));

I want .map to add 0 to .. on each mapped img id

A: const imgs = image.map((img, index) => {
    <img
      id={index}
      key={img.id}
      src={img.urls.small}
      onClick={onClickHandler}
    />
});

.map method will return the index starting from 0.

A: You can assign the index number.
const imgs = image.map((img, index) => {
    <img
      id={index}
      key={img.id}
      src={img.urls.small}
      onClick={onClickHandler}
    />
});

Check the section List & Keys from React doc:
https://reactjs.org/docs/lists-and-keys.html
And check how map method works:
https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Array/map

A: I don't fully understand what you are trying to do, but try to add an   index as a unique id like that:
image.map((img,index) => (
    <img
      id={index}
      key={img.id}
      src={img.urls.small}
      onClick={onClickHandler}
    />
  ));

A: You can use index as tag id like <img id={index} />, but don't use index as img key because it is an Anti Pattern,
Instead you can use plugins like react-key-index
Assume you have an array of image src, you can make unique id for each array item using react-key-index:
import keyIndex from 'react-key-index';

const images = [
  "src1",
  "src2",
  "src3"
]

var output = keyIndex(images, 1);

The output will be like this:
// output
[
  {
    value: "src1",
    id: "kRf6c2fY"
  }, {
    value: "src2",
    id: "lYf5cGfM",
  }, {
    value: "src3",
    id: "mZfKcGf9"
  }
]

And now you can map it:
const imgs = output.map(img => (
    <img
      id={img.id}
      key={img.id}
      src={img.value}
      onClick={onClickHandler}
    />
  ));

A: if img here needs to have some logic then maybe make it a component of it's own so just a suggestion


text:
Q: MUX input debouncing? I am using a CP2103 to interface with a simple 74HC4051 MUX. I want to use 3 of the I/O ports on the CP2103 to control the input pins of the MUX. The 4th I/O port is being used for something else. The problem is, when switching the I/O ports, there is a delay which the MUX reacts to far too quickly.
If I went from a 0-0-0 input to a 1-1-1, then during the time it takes for the CP2103 to switch all its outputs, on the output of the MUX, I will also see the outputs for 0-0-1 and 0-1-1 go high for about 10uS each. I know this is due to the I/O ports of the CP2103 switching high one by one, rather than simultaneously.
Unfortunately, I can't go into much more detail about what is on those outputs as it is a work thing, but all I can say is even the small 10uS pulse is having an undesired reaction.
So, my question is, is there a MUX out there that has some sort of built in debounce (5mS or something) so these small delays won't register? I would really like to do this without having to get a microprocessor as it seems a bit unnecessary for something like this.
I did think about using capacitors to delay it, but then realised it would just delay the other outputs as well and not actually fix anything.
I hope I have managed to relay my question properly and you guys understand. Feel free to ask any questions and I will try to answer.

A: If your application allows, you could use a Gray code for the mux channel assignments.  That is, choose the channels such that when switching between them, you only ever change one bit of the S[2:0] address word at a time.

A: You can either figure out how to make the outputs change simultaneously (if possible) or you can add some barnacle logic that will allow you to fix it. This is definitely not something that comes up very often.
One example would be to add a 74HC595 shift register to control the address lines. The HC595 has an output latch. So you need three lines to control it- clock data and output latch. You will have to bit-bang the serial output which will take somewhat longer (but you can then have 8 outputs if you need them- if you don't just use the lower order bits and shift three bits in at a time, then latch).

A: The source code of the cp210x Linux driver makes it appear as if the chip itself takes a bitmasked GPIO word controlling all the pins, which could potentially make it possible to perform a fairly coordinated change. However, that driver only seems to expose a one-at-a-time interface. Who knows what you'd find on other operating systems. Most systems however will allow someone with administrative privileges to disconnect the usual driver and talk explicit USB operations to a device instead, so you could perhaps achieve better performance operating the chip directly via something like libusb.
Even if you can change the output bits at the same time though, you still shouldn't be paying un-synchronized attention to the multiplexer result.  You really should put something in to sample that only when it is valid.
Once you have the CP2103 and a multiplexor chip, and have to do something about the glitch issue, you'd probably be better off just getting the lowest end USB enabled MCU you can find and programming it to be a USB controlled MUX which transfers the selected input to the output at a high sample rate, synchronous with any change in the input selection.

A: Use the enable pin.
Make the enable low, only after the address is selected.

A: I can't imagine a situation where I'd need an analogue multiplexer combined with debounce circuits, which by their nature are digital - but do you actually need an analogue multiplexer anyway? For a simple 3 in and 8 out circuit like you describe I'd use a 74HC138 or 74HC238 instead, according to whether the outputs need to be active low or active high.
Depending on exactly what the outputs are driving, you could use an RC filter on each output to filter out the unwanted pulses or you could put the outputs through a debounce circuit such as the MC14490 that has six channels, although that's a relatively expensive component and also requires an external capacitor to set its timing.
Although you've said a microprocessor would bit a bit of an overkill, it's an ideal application for something like the PIC16F505, which comes in a single 14 pin package and would directly replace the 74HC4051 with no additional components and low additional cost.


text:
Q: How to get User's table from Firebase events in BigQuery? I am trying to look at old events based on user's current values. Events from Firebase Analytics are exported in single table together with User data(user data is part of event record).
How can I join old event to current user? Is it possible to export User table separately?
Thanks!

A: You can identify a user with either user_dim.app_info.app_instance_id, user_dim.device_info.resettable_device_id or user_dim.user_id.  You can read more about these fields in this help center article.


text:
Q: How to revoke a user session when using AWS SSO? I'm currently managing a AWS SSO solution using it with AzureAD. For our use case we need to be able to revoke access/session of a user.
In AzureAD it's pretty simple, go to the user, block him, revoke its session. It's done, user needs to relog but he won't be able to do so.
In AWS SSO, it looks a bit harder, I can't seem to find a way to instantly revoke a session. I can disable its access, but once he has a session, even deleting the user/group from AWS SSO will not terminate the session.
This causes quite a problem as this is compliant to my security standards.
Any ideas?
Thanks people

A: An option is to put in place a temporary SCP on the AWS account to deny all actions for the Role session of the user as shown below:
{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "UserRestrictions",
        "Effect": "Deny",
        "Action": "*",
        "Resource": [
            "*"
        ],
        "Condition": {
            "StringEquals": {
                "aws:userId": [
                    "AROAEXAMPLEROLEID:alice@example.com"
                ]
            }
        }
    }
]}

After a day or so (or the max role duration) you could remove the SCP. This is useful if you only have a single role session but in the scenario of an AWS SSO user, the user probably has access to multiple Roles across multiple AWS accounts. Rather than adding multiple SCPs you could add a SCP higher up in the organizational hierarchy that denies actions for all Role sessions for the user as shown below:
{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "UserRestrictions",
        "Effect": "Deny",
        "Action": "*",
        "Resource": [
            "*"
        ],
        "Condition": {
            "StringLike": {
                "aws:userId": [
                    "*:alice@example.com"
                ]
            }
        }
    }
]}


text:
Q: Scrape website for certain text and send e-mail I am fairly new to coding but I have a use case that I want to realize with python.
Use Case:
I'd like to have a python script that checks a certain website for a certain string. If the string is found I'd like to get some kind of notification or e-mail. Maybe you could point me to the right library or code snippets on how I can realize this.

A: The Usecase that you mentioned (Apart from sending notification/E-mail) is called Web Scraping. I have mentioned different python modules below that will help you learn web-scraping.

*

*Beautiful Soup - Beautiful Soup is a Python library for pulling data out of HTML and XML files.

Docs: https://www.crummy.com/software/BeautifulSoup/bs4/doc/

*

*requests - Requests is an elegant and simple HTTP library for Python.

Docs: https://docs.python-requests.org/en/master/

*

*Selenium - Selenium is an umbrella project for a range of tools and libraries that enable and support the automation of web browsers.

Docs: https://selenium-python.readthedocs.io/


text:
Q: I need help parsing some JSON data I am fairly new to parsing json data and I am attempting to parse some json data from an rss feed generator and I am running into a problem where I can successfully print the data I am getting but I can't save the data to an object.
I have looked through tutorials that used decodables/codables mostly but I was able to use the urlSession and jsonSerialization objects for what I needed just fine.
class JSONSongs {

    // initialize song array...
    var songArray: [Song] = []

    func getSongs() {

        let jsonSongUrl = "https://rss.itunes.apple.com/api/v1/us/apple-music/top-songs/all/50/explicit.json"
        let songUrl = URL(string: jsonSongUrl) // convert string to usable url

        // start url session task with apple music api url...
            // we get some data(hopefully), a response code and an error(hoepfully not)
        let songTask = URLSession.shared.dataTask(with: songUrl!) { (data, response, error) in

            // checking for an error
            if error != nil {
                print(Error.self)
                print(error?.localizedDescription)
                return
            } else {

                // lets store our data in a variable
                if let content = data {
                    do {
                        // taking the json data and converting it so we can make objects
                        let json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)
                        //print(json) // making sure data is present

                        // checking to see if our json data is there
                        guard let jsonOne = json as? [String: Any] else {
                            print("invalid operation!")
                            return
                        }

                        // accessing top root of the json file
                        if let feed = jsonOne["feed"] as? [String: Any] {
                            //print("it worked") // testing

                            // accessing the results array where the albums are stored
                                // there are arrays in the nested json data so we need the double brackets to access them
                            if let result = feed["results"] as? [[String: Any]]{
                                for item in result {
                                    // attempting to store data in Song object, this is where problems appear
                                    if let songName = (item["name"] as AnyObject? as? String),
                                        let artistName = (item["artistName"] as AnyObject? as? String),
                                        let coverArt = (item["artworkUrl100"] as AnyObject? as? String),
                                        let artistPage = (item["artistUrl"] as AnyObject? as? String) {
                                        self.songArray.append(Song(songName: songName, artistName: artistName, coverArt: coverArt, artistPage: artistPage))

                                        // printing the data to the console works here but I can't save the data to an object
                                    }
                                }
                            }
                        }

                    } catch {
                        print(error.localizedDescription)
                        print(Error.self)
                        return
                    }
                }
            }
        }
        songTask.resume()
    }
}

All I get is either nil when I try and print a string value or 0 when I try and count the number of objects that are present in the songArray array

A: Basically your code is correct and should work, however this is a version using Decodable.
The songs property will contain the song data
struct Root : Decodable {
    let feed : Feed
}

struct Feed : Decodable {
    let results : [Song]
}

struct Song : Decodable {
    let name, artistName : String
    let artworkUrl100, artistUrl : URL
}

class JSONSongs {

    var songs = [Song]()

    func getSongs() {

        let jsonSongUrl = "https://rss.itunes.apple.com/api/v1/us/apple-music/top-songs/all/50/explicit.json"
        let songUrl = URL(string: jsonSongUrl) // convert string to usable url

        // start url session task with apple music api url...
        // we get some data(hopefully), a response code and an error(hoepfully not)
        let songTask = URLSession.shared.dataTask(with: songUrl!) { [weak self] data, _, error in

            // checking for an error
            if let error = error { print(error); return }
            do {
                // taking the json data and converting it so we can make objects
                let result = try JSONDecoder().decode(Root.self, from: data!)
                self?.songs = result.feed.results
                print(self?.songs)
            } catch {
                print(error)
            }
        }
        songTask.resume()
    }
}


text:
Q: Limit of sequences, how solve for $N$ DEFINTION: The sequence $(a_n)_{n\in\mathbb{N}}$ converges to the limits $a\in\mathbb{R}$, if for all $\varepsilon>0$ a positive integer $N$ exists, so that $\left|a_{n}-a\right|<\varepsilon$, is true for all $n \geq N$.
I have to find out what $N$ is. Normally I would simplify $\left|a_{n}-a\right|<\varepsilon$ as far as possible and solve for $n$. My question is: Can we find out the value of $N$ if we can't solve for $n$? (Just imagine $a_n = p_n$, where $p_n$ is the $n$-th prime number. Of course $a_n$ wouldn't converge, but my point  is you can't solve for $n$ in this example. Only if you have a higher or lower boundary, but let's assume we don't have one.)
I have an idea how solve for $N$, but I need you to show me if I'm right:

*

*Let's just assume that there is a $N$ and $\left|a_{n}-a\right|<\varepsilon$ holds for all $n\geq N$.

*You can do some calculations and derive to your wanted expression. (Expression does not matter)

*You test values for $n$ in this expression. For example set $n=1$, and it doesn't work. After that you set $n=2$ and it does work.

Q1: If the expression holds for $n=x$, where $x$ is a postive integer, does it mean that the expression also holds for $n\geq x$?
Q2: If the expression doesn't hold for $n = x$ but it holds for $n=x+1$, is $N=x+1$?

A: Testing for values does not work because an early value might be very close to the limit but later values are farther away.  We could have the sequence $1,1,1,3,5,34434342,1-2^{-n}$ where $n$ starts from $1$ in the first term that includes it and increases.  Clearly the limit is $1$, but you would find $n=1,2,3$ all are within $\epsilon$ of the limit but as long as $\epsilon \lt 2$ the next three terms are not.  We could even modify that sequence by changing $a_{1000000}$ to $12345$ and not change the limit.  In that case for any reasonable $\epsilon$ you need $N$ to be at least $1000001$  This shows the answer to Q1 is no.  Similarly Q2 is no as my modified example shows.
You don't have to find the minimum $N$ that works, you just have to find one that does for a given $\epsilon$.  If a certain $N$ works, so does $N'=N+1000000$  If it is easier to prove that the larger one works, use it and you are done.  For example, suppose we are summing the inverse squares of the primes.  To prove this sum converges, we can just say that each term is less than the corresponding sum of the inverse squares of all the naturals, which we know converges.  If I knew the $N$ in the second one corresponding to a given $\epsilon$, I could use it for the first as well.


text:
Q: ckediter equiped textbox restricting number of characters While there are a couple of older questions that touch on this topic, they are not dealing with webforms, which is where I am working and the code does not seem to be kicking in.
In a ASP.NET web forms application that needs to collect rtf data, I have enabled several fields with ckeditor to allow rtf input (stored as html). On some of these fields I need a means to limit input.
element to be restricted in the form/table:

        <asp:Label ID="LabelResponseA" runat="server">Response A</asp:Label>

        <asp:TextBox ID="ResponseA" Columns="50" Rows="2" TextMode="MultiLine"
            runat="server" CssClass="ckeditor"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
            Text="* Response A Required" ControlToValidate="ResponseA"
            SetFocusOnError="true" Display="Dynamic"></asp:RequiredFieldValidator>

javascript code block for the restriction of characters:
</script>

A: You can use the editor "key" event and check the editor's body text length.
If your editor's textarea is named ResponseA:
var textLimit = 50;

CKEDITOR.instances.ResponseA.on('key', function (evt) {
    if (CKEDITOR.instances.ResponseA.document.getBody().getText().length > textLimit) evt.cancel();
});

You can expand this bare bones example further to fit your needs.