text:
Q: How to include JavaScript file or library in Chrome console? Is there a simpler (native perhaps?) way to include an external script file in the Google Chrome browser?
Currently I'm doing it like this:
document.head.innerHTML += '<script src="http://example.com/file.js"></script>';

A: Do you use some AJAX framework? Using jQuery it would be:
$.getScript('script.js');

If you're not using any framework then see the answer by Harmen.
(Maybe it is not worth to use jQuery just to do this one simple thing (or maybe it is) but if you already have it loaded then you might as well use it. I have seen websites that have jQuery loaded e.g. with Bootstrap but still use the DOM API directly in a way that is not always portable, instead of using the already loaded jQuery for that, and many people are not aware of the fact that even getElementById() doesn't work consistently on all browsers - see this answer for details.)
UPDATE:
It's been years since I wrote this answer and I think it's worth pointing out here that today you can use:

*

*SystemJS

*ModuleLoader

*jspm.io
to dynamically load scripts. Those may be relevant to people reading this question.
See also: The Fluent 2014 talk by Guy Bedford: Practical Workflows for ES6 Modules.

A: var el = document.createElement("script"),
loaded = false;
el.onload = el.onreadystatechange = function () {
  if ((el.readyState && el.readyState !== "complete" && el.readyState !== "loaded") || loaded) {
    return false;
  }
  el.onload = el.onreadystatechange = null;
  loaded = true;
  // done!
};
el.async = true;
el.src = path;
var hhead = document.getElementsByTagName('head')[0];
hhead.insertBefore(el, hhead.firstChild);

A: If anyone, fails to load because hes script violates the script-src "Content Security Policy" or "because unsafe-eval' is not an allowed", I will advice using my pretty-small module-injector as a dev-tools snippet, then you'll be able to load like this:

imports('https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js')
  .then(()=>alert(`today is ${moment().format('dddd')}`));
<script src="https://raw.githack.com/shmuelf/PowerJS/master/src/power-moduleInjector.js"></script>

this solution works because:

*

*It loades the library in xhr - which allows CORS from console, and avoids the script-src policy.

*It uses the synchronous option of xhr which allows you to stay at the console/snippet's context, so you'll have the permission to eval the script, and not to get-treated as an unsafe-eval.

A: In the modern browsers you can use the fetch to download resource
(Mozilla docs) and then eval to execute it.
For example to download Angular1 you need to type:
fetch('https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js')
    .then(response => response.text())
    .then(text => eval(text))
    .then(() => { /* now you can use your library */ })

A: If you're just starting out learning javascript & don't want to spend time creating an entire webpage just for embedding test scripts, just open Dev Tools in a new tab in Chrome Browser, and click on Console.
Then type out some test scripts: eg.
console.log('Aha!')

Then press Enter after every line (to submit for execution by Chrome)
or load your own "external script file":
document.createElement('script').src = 'http://example.com/file.js';

Then call your functions:
console.log(file.function('驨ꍬ啯ꍲᕤ'))

Tested in Google Chrome 85.0.4183.121

A: appendChild() is a more native way:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'script.js';
document.head.appendChild(script);

A: I use this to load ko knockout object in console
document.write("<script src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-3.5.0.debug.js'></script>");

or host locally
document.write("<script src='http://localhost/js/knockout-3.5.0.debug.js'></script>");

A: As a follow-up to the answer of @maciej-bukowski above ^^^, in modern browsers as of now (spring 2017) that support async/await you can load as follows. In this example we load the load html2canvas library:

async function loadScript(url) {
  let response = await fetch(url);
  let script = await response.text();
  eval(script);
}

let scriptUrl = 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js'
loadScript(scriptUrl);

If you run the snippet and then open your browser's console you should see the function html2canvas() is now defined.

A: In chrome, your best option might be the Snippets tab under Sources in the Developer Tools.
It will allow you to write and run code, for example, in a about:blank page.
More information here: https://developers.google.com/web/tools/chrome-devtools/debug/snippets/?hl=en

A: You could fetch the script as text and then evaluate it:
eval(await (await fetch('http://example.com/file.js')).text())

A: Install tampermonkey and add the following UserScript with one (or more) @match with specific page url (or a match of all pages: https://*) e.g.:
// ==UserScript==
// @name         inject-rx
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Inject rx library on the page
// @author       Me
// @match        https://www.some-website.com/*
// @require      https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.4/rxjs.umd.min.js
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
     window.injectedRx = rxjs;
     //Or even:  window.rxjs = rxjs;

})();

Whenever you need the library on the console, or on a snippet enable the specific UserScript and refresh.
This solution prevents namespace pollution. You can use custom namespaces to avoid accidental overwrite of existing global variables on the page.


text:
Q: Windows 8 server R2 . Unable to provide DNS name resolution I would like to fix a problem in my LAN (Windows 10 Pro clients on 192.168.140.x subnet). I have a Windows 2008 R2 Server (192.168.140.9) that's mainly used as DHCP server and DNS conditional forwarder (non authoritative). Clients PCs need resolution for both public internet hostnames as also a set of private ones (of hosts located on a remote LAN: 192.168.200.x) for all PC in my local LAN.
The private hostnames should only be solved by DNS servers on the remote LAN itself.
I've configured the DHCP server to assign DNS servers in this order:
8.8.8.8
8.8.4.4
192.168.140.9
192.168.200.8
192.168.200.31

where 192.168.140.9 is my own server acting as DNS. The last two addresses are DNS servers for the remote LAN (but I would like to remove these last two options since they are redundant).
My DNS server is configured as a conditional forwarder of the hostnames located in the remote LAN (trough 192.168.200.8 and 192.168.200.31).
Using nslookup I can clearly see that everything works (if I set the correct DNS server) but Windows seems unable to solve names in the private side and thus many applications fails to locate private servers (NAS, mail server, intranet web server etc). The only way I can arrange DNS order so it works is to set the two private side DNS servers as first in list:
192.168.200.8
192.168.200.31
8.8.8.8
8.8.4.4
192.168.140.9

This something I would like to avoid because I don't want remote DNS to be charged of resolving internet names.
How can I fix this? I cannot change clients network configuration other than changing DHCP / DNS configuration options (of my own server) and of course I cannot change the remote server DNS behaviour.

A: As suggested by Todd I needed to remove all the DNS options except my own (192.168.140.9) from DHCP configuration. I also set the Forwarders section in the Properties of my DNS server in this way:

Now everything seems to work correctly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CRM 2013 Migraton: How to detect CRM 4 javascript I am getting following error while migrating CRM 4 database to cRM 2013 via CRM 2011.
"Setup has detected that there are customizations or solutions that are using the Microsoft Dynamics CRM 4.0 (2007) endpoint. This feature will no longer be supported in Microsoft Dynamics CRM 2013."
CRM was earlier developed by another vendor, so I need to find this javascript.Is there any tool or method to find out about this javascipt of CRM 4 which needs to be migrated.
Thanks

A: You can use the Custom Code Validation Tool released by Microsoft. It will tell you the web resources not compatible with CRM 2013
http://www.microsoft.com/en-us/download/details.aspx?id=30151


text:
Q: Are ConstraintLayout Animations In ScrollView Possible? Whenever I try to apply the ConstraintLayout animations on a scrollable constraintLayout I get the error that I can't cast a ScrollView into a ConstraintLayout, and it sounds reasonable.
Is there a way to make a constraint layout scrollable without using ScrollView as parent? That way I'd be able to use its sweet animations.
Thanks.

A: This a common issue with ConstraintLayout and ScrollView / NestedScrollView. You need to set your ScrollView as a parent of ConstraintLayout and before you do the transition you need to clone your ConstraintLayout
Something like this:
Kotlin:
 ConstraintSet().apply {
        clone(constraintLayoutView);
        clone(this, R.layout.activity_animation) // your transition
    }

Or if you're using java:
  ConstraintSet constraintSet = new ConstraintSet();
  constraintSet.clone(constraintLayoutView);
  constraintSet.clone(this, R.layout.activity_animation);

A: CONSTRAINT SET FOR A CONSTRAINT LAYOUT THAT'S NOT PARENT
I figured it out. This works wonders. I think this may be useful to other developers because I assume it's pretty normal to use a ConstraintLayout inside a ScrollView, for example in login screens.
So now I have 2 Xmls right? The "original" and the transition one.
Original: <ScrollView> <ConstraintLayout><ConstraintLayout> <ScrollView>
Transition: <ConstraintLayout></ConstraintLayout>

Transition XML has no ScrollView because I need to clone a full layout (my transition layout) inside a ViewGroup (ScrollView's child, my constraint layout). If you try to clone a child constraint layout into another child constraint layout it crashes with a .getChild() method, don't know why. But you can clone a ConstraintLayout layout to a ConstraintLayout view.
val constraintSet = ConstraintSet()
constraintSet.clone(this, R.layout.activity_login_transition) // here I'm cloning the whole transition layout
TransitionManager.beginDelayedTransition(login_constraint) //this is only for animation
constraintSet.applyTo(login_constraint) // and here I'm applying it only to my constraint layout. 'login_constraint' is my constraint's ID

And that's it. Hope it worked for you too.
Thanks to Ezequiel Zanetta


text:
Q: postgreSQL Вывод N строку Есть таблица, выводит естественно 6 строк. Как именно вывести 2 строку например.
Select distinct latitude, longitude from russion limit 6
Вывод:
1  ааввав
2  авававава Хочу сделать вывод только этой строки
3  ававававав
4  авававааавав
5  авава
6  ававав


text:
Q: how to write a certain equation in C#? my problem is that i need to write a complex mathematical equation which has me raise x to the power of |y|, both numbers entered by user. I've tried using the code below, but it produces a "CS7036" error:

There is no argument given that corresponds to the required formal parameter 'y' of 'Math.Pow(double, double)'

class Program
{
    static void Main(string[] args)
    {
        double x,y,z,v;
        Console.Write("x=");
        double.TryParse(Console.ReadLine(), out x);
        Console.Write("y=");
        double.TryParse(Console.ReadLine(), out y);
        Console.Write("z=");
        double.TryParse(Console.ReadLine(), out z);
        v=(1+Math.Pow(Math.Sin(x+y)))/
            Math.Abs(x-2*y/(1+x*x*y*y))*Math.Pow(x,Math.Abs(y))+
            Math.Pow(Math.Cos(Math.Atan(1/z)),2);
        Console.Write("v="+v);
        Console.ReadKey();
    }
}

code:
https://code.sololearn.com/cp4fky31p5cD/?ref=app

A: Try to specify second parameter to your Pow:
Math.Pow(Math.Sin(x + y),SECOND)
in
v = (1 + Math.Pow(Math.Sin(x + y))) /
...

A: Update
(After the OP posted the code)
Code
        double x,y,z,v;
        Console.Write("x=");
        double.TryParse(Console.ReadLine(), out x);
        Console.Write("y=");
        double.TryParse(Console.ReadLine(), out y);
        Console.Write("z=");
        double.TryParse(Console.ReadLine(), out z);
        v=(1+Math.Pow(Math.Sin(x+y)))/
        Math.Abs(x-2*y/(1+x*x*y*y))*Math.Pow(x,Math.Abs(y))+
        Math.Pow(Math.Cos(Math.Atan(1/z)),2);
        Console.Write("v="+v);
        Console.ReadKey();

Error

Error   CS7036  There is no argument given that corresponds to the required formal parameter 'y' of 'Math.Pow(double, double)'
Problem
You are calling Math.Pow() with just one parameter: Math.Sin(x + y) and it requires two parameters.
Solution
Check the formula and call the Math.Pow with two parameters, i.e.:
Math.Pow(Math.Sin(x + y), something_here )

Original answer (before OP added the code and error description)
I'm not sure what C7036 is but this snippet outputs 8:
        var x = 2;
        var y = 3;
        var number = Math.Pow(x, Math.Abs(y));
        Console.Write(number);

In this example x and y are ints and number is of type double.


text:
Q: Line integral does not dependent on parametrization
Let $M$ be a smooth manifold and a curve $\Gamma\subset M$ with $C^1$parametrizations $\gamma:[a, b]\to M$ and $\tilde{\gamma}:[c, d]\to M$. If $\omega$ is a $1$-form on $M$, prove that:
$$\int_a^b \gamma^*\omega = \int_c^d \tilde{\gamma}^*\omega$$

My intial idea was to claim that there exists an increasing diffeomorphism $\phi:[a,b]\to[c, d]$ (therefore, orientation preserving) such that $\gamma=\tilde{\gamma}\circ\phi$. And therefore:
$$\int_{[c,d]} \tilde{\gamma}^*{\omega}=\int_{\phi^{-1}([c,d])} \phi^*\circ\tilde{\gamma}^*(\omega)=\int_{[a,b]} (\tilde{\gamma}\circ\phi)^*(\omega)=\int_{[a,b]} \gamma^*\omega$$
However, I'm not sure that such a diffeomorphism always exists, since we only know that $\gamma$ and $\tilde{\gamma}$ are $C^1$, so I'm stuck with this argumentation. Any sugestions? Thanks!

A: You can show that any homeomorphism of between interval is monotonic. Suppose you have $x<y$ and $f(x) > f(y)$. Consider the interval $I = (f(y),f(x))$. Then $f^{-1}(I) = (y,x)$. However $x<y$, so this is a contradiction.


text:
Q: Smartpointers equivalent There is an equivalent codification in C++ with smartpointers for this code?
In External.cpp:
class ExampleClass {...};

ExampleClass* function()
{
  ExampleClass *ptr = new ExampleClass();
  ptr->doSomething();
  return ptr;
}

In Another.cpp i would like to do something like this properly, how?:
ExampleClass *ptr2 = function();

A: There are two actually, you could use either unique_ptr or shared_ptr, look here when to use which: Which kind of pointer do I use when?
I'f you'd opt for the unique_ptr, then you'd get:
class ExampleClass {...};

std::unique_ptr<ExampleClass> function()
{
  std::unique_ptr<ExampleClass> uptr = std::make_unique<ExampleClass>();
  uptr->doSomething();
  return std::move(uptr);
}

//In Another.cpp
std::unique_ptr<ExampleClass> ptr2 = function();
//you could even store the result in a shared pointer!!
std::shared_ptr<ExampleClass> ptr3 = function();

A: I won't really recommend it, but you can return an object that implicitly converts to a raw pointer. It will own it for a short duration, and delete if no-one grabs it.
struct RelinquishOrDelete {
  ExampleClass *_ptr;

  operator ExampleClass*() { auto ret = _ptr; _ptr = nullptr; return ret; }

  ~RelinquishOrDelete() {
    if(!_ptr) {
      cerr << "returned object wasn't taken by a new owner\n";
      delete _ptr;
    }
  }
};

Using it is simple. It will pack and unpack the pointer in this simple case:
RelinquishOrDelete function()
{
  ExampleClass *ptr = new ExampleClass();
  ptr->doSomething();
  return {ptr};
}

// ...

ExampleClass *ptr2 = function();

But of course, it will likely cause unexpected behavior if used in this perfectly reasonable piece of code:
auto ptr3 = function();

A smart pointer with much stricter ownership semantics is really the best approach.


text:
Q: Include assets in engine from main application I have created an admin interface as a Rails engine. In the project I work in at the moment I need to add some custom javascript. I want to keep this in my main app and not add it in my engine.
Perhaps register some javascript or stylesheet files in a config file and let the engine include them.
Any ideas on how I can achieve this?

A: you are asking about ideas, so here is one: just use a convention!
it's common to do this in rails, so why not just do it for your engine. just document how to name the files and what to configure for that (assets need to be configured differently when they should not be included in application.js/css). the admin interface typus does the same thing: http://docs.typuscmf.com/customization/custom_css_and_js.html
in your engine, you can just check if that file is present in the mounting app and include it in that case.
should be pretty straight forward.


text:
Q: Что с файлом archive-product.php в woocommerce? Скопировал файл archive-product.php в папку с темой. theme/wocommerce/archive-product.php
Мне нужно было при выводе товаров определенной категории вывести блок с сообщением.
Я как понял этот файл отвечает за вывод товаров при просмотре категории.
Добавил код.

Но изменений не произошло.
Удалил файл и папку в папке с темой. Пошел напрямую в папку плагина. Вставил там. Тоже ноль реакции.
Что не так?


text:
Q: Running SSIS jobs from SSRS I'm looking for a nice user-friendly interface for starting SSIS jobs:

*

*Users shouldn't need SSMS or other software installed on their desktop

*Users can provide parameter values that are passed through to SSIS

SSRS seems like a possible choice - you can run reports from the web browser, and there's a good interface for providing parameter values.
But how can I kick off a SSIS job from a SSRS report, and pass through the parameter values?

A: I wouldn't use Reporting Services for this task. It is designed to display and show your data, not to manage it.
One way to create a user-friendly interface for SSIS is with an ASP.net website.
http://www.codeproject.com/KB/aspnet/SSIS_DOTNET.aspx

A: SSRS isn't interactive in that way. You can filter and sort, but not call out to other processes without some custom DLL.
I'd consider a simple web app (which is what SSRS is of course) with the code behind calling SSIS via .net

A: You can enable SSRS reports to trigger and show data from SSIS packages - see details here - but note the dire warnings about lack of support and this feature not being production-ready.
Another way ot approach this is to use SSRS to trigger SSIS indirectly - I've done similar things in the past using SSRS to trigger SQL Agent jobs (which can in turn trigger SSIS packages) but that was for packages which didn't require run-time parameters.


text:
Q: What is the distribution of time to absorption for an absorbing Markov chain? I am interested in finding the distribution of time to absorption for a given absorbing Markov chain transition matrix. I've looked at first passage time (where $f_{ij}^{(n)}$ is the probability that the first passage from $i$ to $j$ occurs in exactly $n$ steps).
In my particular case I have a single absorbing state, which I'll call $j$. I think I can find the probability mass function since $P(x=0)=0\cdot f_{ij}^{(0)}, P(x=1)=1 \cdot f_{ij}^{(1)}, \ldots $, but I'm not sure where to go from here.

A: The distribution of a random variable representing time-to-absorption of a Markov chain with a single absorbing state is called a discrete phase-type distribution.
Summarising the wiki article: assume the last row of the $n\times n$ transition matrix corresponds to the absorbing state and let $T$ be the upper left $(n-1)\times(n-1)$ block.  The pmf for the absorption time given initial distribution $\tau$ is then
$$p(k) = \tau T^{k-1} T_0 $$
where $T_0$ is the vector formed by the first $n-1$ entries of the last column of the transition matrix, showing that these distributions are generalisations of the geometric distribution.


text:
Q: SegFault in Producer/Consumer model I'm back with yet another segfault i can't seem to conquer.
I have figured out exactly what it is, it's something with the char* string line. I use it to break up the bytes to GET this pdf file for a school assignment.
Any and all help is appreciated!
void* consumer(void *temp)
{
int* stuff = reinterpret_cast<int*>(temp);
int x = *stuff;
char* string[];
stringstream stream1;
stringstream stream2;
int temp1=0;
int temp2=0;
int sent1=0;
int sent2=0;
ofstream fout;

strcpy(string,request); //SEGFAULT(11) ON THIS LINE, WHEN CALLING "string"
strcat(string,"Byte Range: ");
...

The complete code can be found here; https://www.dropbox.com/sh/dt90ot3z4v5nruy/1H9a5Cyb5A
mgetweb.h and mgetweb.cpp

A: You haven't new memory for string pointer yet, it's undefined behavior to access it.
//  char* string[]; I guess that's not what you intent to do, declaring an array of pointers?

char* string = new char[BIG_ENOUGH_SIZE];
strcpy(string, request);


text:
Q: How stop execution of the staging process in KIT DataManager? I would like to know how to stop the Processor in Staging phase (e.g. this processor in  member performPreTransferProcessing).
Repo on GitHub: https://github.com/kit-data-manager/base
Not sure how to find out what should be changed to go on with the next Processor (if any).
I imagine something like Context.status = CONSTANTS.stopped but lack to find the context.

A: The question was answered by the main contributor of the project … I will answer a bit more excessive still.

performPreTransferProcessing(TransferTaskContainer pContainer) throws StagingProcessorException;
  // signature for AbstractStagingProcessor

The exception StagingProcessorException is located in package
import edu.kit.dama.staging.exceptions.StagingProcessorException;

and can be raised e.g. simply with a message
throw new StagingProcessorException("this ends the processor and renders it unsuccessful");

and of course this should only be raised conditionally, e.g. from one of the two pre-processing members.
But:

*

*data still is first uploaded before the Processor runs

*there is no cleanup swiping it from cache


text:
Q: How to parse the RSS using google api or any other techinques I want to parse the below mentioned RSS in order to get the title, description, image and date. Currently i'm able to get the all other details except image. Im using google api feed to parse the rss. Please can anyone me in this context.
RSS:https://news.google.com/news/feeds?cf=all&ned=in&hl=en&q=cricket&output=rss
// Google Feed API: https://developers.google.com/feed/
// Inspiration: http://designshack.net/articles/javascript/build-an-automated-rss-feed-list-with-jquery/

function parseFeed(url, container) {
    $.ajax({
        url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=5&callback=?&q=' + encodeURIComponent(url),
        dataType: 'json',
        success: function (data) {
            // log object data in console
            console.log(data.responseData.feed);
            // append feed link and title in container
            $(container).append('');
            $(container).append('
' + data.responseData.feed.title + '
');
            // for each entry... *
            $.each(data.responseData.feed.entries, function (key, value) {
                // * create new date object and pass in entry date
                var date = new Date(value.publishedDate);
               // var thumbnail = entry.mediaGroups[0].contents[0].url;
                // * create months array
                var months = new Array(12);
                months[0] = 'January';
                months[1] = 'February';
                months[2] = 'March';
                months[3] = 'April';
                months[4] = 'May';
                months[5] = 'June';
                months[6] = 'July';
                months[7] = 'August';
                months[8] = 'September';
                months[9] = 'October';
                months[10] = 'November';
                months[11] = 'December';
                // * parse month, day and year
                var month = date.getMonth();
                var day = date.getDate();
                var year = date.getFullYear();

                // * assign entry variables
                var title = '
' + value.title + '
';
                var time = '
' + months[month] + ' ' + day + ', ' + year + '
';
                var snippet = '
' + value.contentSnippet + '
';
                var img = '
' + value.thumbnail + '
';
                var entry = '
' + title + time + snippet + '
';
                // * append entire entry in container
                $(container).append(entry);
            });
        },
        // if there's an error... *
        error: function (errorThrown) {
            // * log error message in console
            console.log(errorThrown);
            // * show error message
            alert('Houston, we have a problem.');
        }
    });
}

$(document).ready(function () {
    parseFeed('https://news.google.com/news/feeds?pz=1&cf=all&ned=en&hl=in&q=aishwarya%20rai&output=rss', '#csstricks');
});

A: Just add this to your script
var content = document.createElement("content");
content.innerHTML = value.content;
var images = "";
$(content).find('img').each(function() {
    images += this.outerHTML;
});
var img = '
' + images + '
';

Same answer as here: https://stackoverflow.com/a/26369373/989257
Codepen example: http://codepen.io/janih/pen/JdPMZX


text:
Q: assign bash variable using a ternary like syntax I have the following bash code:
if [ $NOD_ENV = "production" ]; then IS_PRODUCTION=1; else IS_PRODUCTION=0; fi
if [ $IS_PRODUCTION ]; then VALUE="$VALUE_PRODUCTION"; else CDN_HEADER_VALUE="$PRODUCTION"; fi
# etc
fi

I am getting some unexpected output assigning variables this way.  How could I do this better?

A: You need to explicitly test the value of $IS_PRODUCTION:
if [ $IS_PRODUCTION = 0 ]; then  ...

if [ $IS_PRODUCTION ] only tests whether the length of $IS_PRODUCTION is non-zero.
As a side note, [ is actually a program, and you can see the options for it by running /usr/bin/[ --help (the /usr/bin seems important on my system for some reason ...)

A: It's a cool trick to set boolean variable in bash to the string "true" or "false":
if [ $NOD_ENV = "production" ]; then IS_PRODUCTION=true; else IS_PRODUCTION=false; fi
if "$IS_PRODUCTION"; then VALUE="$VALUE_PRODUCTION"; else CDN_HEADER_VALUE="$PRODUCTION"; fi;

What happens here, is that IS_PRODUCTION has the string "true" or "false". Once you run if "$IS_PRODUCTION" the variable is expanded which results in if true or if false. true and false are builtin commands, which get run, and return - zero status for true and non-zero status for false.


text:
Q: How Does the Positive Feedback Bring an Oscillator's Poles on the Imaginary Axis? In an oscillator, there is a positive feedback that injects energy into the system in order to sustain the oscillations. This feedback places the system's poles on the imaginary axis. I'd like to know how the math works, and how exactly the feedback moves the poles from the left half plane on the imaginary axis.

A: For oscillators you can either have linear or relaxation (nonlinear) ones.
For the nonlinear ones, usually you have some type of hysteresis behavior (although this is not a general definition!).
Two examples I can give are the Multivibrator and the 555 IC. The have two operational modes one "charges" and the other one "discarges", and since the transition from charge->discharge and discharge->charge are not at the same point, say,
charge->discharge @ 5V and discharge->charge @ 2V. The system would oscillate between 5 and 2 V, with some waveform that probably is not a pure sinusoidal.
This type of oscillation is usually pretty "self-sustainable" because is is related to some property of the system (its dynamics) and even a lot of noise would have a hard time making it stop oscillating.
If you have the linear one you must have a system with conjugate poles with zero real part (along the imaginary axis), like,
\$ (s-j8)(s+j8),\$ or \$ (s-j8)(s+j8)(s-j20)(s+j20).\$
That means that any noise to the system, such as an impulse \$ \delta(t) \$, will lead to an oscillation that does not decay. For the system,
$$ H(s) = \frac{1}{(s-j8)(s+j8)(s-j20)(s+j20)}, $$
any impulse input will lead this system to have the following output,
$$ h(t) = a \cos(8t)+b \cos(20t).$$
But, regarding the Barkhausen criterion, it states that at the frequency of oscillation
|------->[ P ]--------> Vout
|
|-------[ B ]<-------- Vin

*

*\$ |PB| = 1 \$

*\$ \angle PB = 0 \$
So, for \$ P = \frac{s-1}{(s+1+j)(s+1-j)}\$ and \$ B = k\$ (the gain for a positive feedback), this would oscillate for,
$$  \text{for }\omega = 2, k \geq 0, ~~ \angle PB = 0, $$
$$  \text{we must have }\left| \frac{j2-1}{(j2+1+j)(j2+1-j)} k \right| = 1, $$
$$  \left| \frac{j2-1}{(j2+1+j)(j2+1-j)} k \right| = 1, $$
$$  \left| \frac{1}{2} k \right| = 1, $$
$$  k = 2.  $$
Now, if you analyze the closed-loop transfer function you will reach the same result but the algebra to find the necessary \$ k \$ might be a bit harder,
$$  H(s) = \frac{P}{ 1-kP} = \frac{ \frac{s-1}{(s+1+j)(s+1-j)}}{ 1-k \frac{s-1}{(s+1+j)(s+1-j)}} = \frac{s-1}{ (s+1+j)(s+1-j)-k(s-1)},  $$
$$  H(s) = \frac{s-1}{s^2+ (2-k) s +2+k},$$
With poles at,
$$  s_0 = \frac{k-2}{2}-\frac{\sqrt{k^2-8k-4}}{2},$$
$$  s_0 = \frac{k-2}{2}+\frac{\sqrt{k^2-8k-4}}{2},$$
And with \$ k = 2\$ you get a pole at the imaginary axis (zero real part).
$$  s_0 = 2j, s_0 = -2j.$$

A: Let me answer without any mathematics:
"...could you briefly explain how a nonlinearity can help sustain the oscillations? Also about the Bakhausen criterion, why should the loop gain be equal to 1? In a closed loop system, the loop gain that places the poles on the imaginary axis can be anything depending on the transfer function of the open loop system"

*

*Let me start with a sentence which like most: A harmonic oscillator for sinusoidal signals must be as linear as possible....and for this purpose it must contain a non-linear (amplitude-dependent) part or circuitry.

From system theory we know that for rising (falling) amplitudes the poles of the closed-loop system must be in the right half (left half) of the s-plane. Hence, for constant amplitudes the poles should be directly on the imaginary axis (theoretically !!). However, for a safe start of oscillations at t=0 the poles should have a small positive real part (right half). This requirement is identical with a loop gain slightly above unity. More than that, this is the only practical method to cope for the uncertainties and parts tolerance for each real circuit.
As a consequence, the oscillation will start with continuously rising amplitudes.If we do not allow hard-limiting of the signal caused by the maximum possible voltage of the device (supply voltage), we need a kind of "soft-limiting" effect. For this purpose, a non-linear device is needed which (for rising amplitudes) continuously reduces the loop gain and shifting the poles back to the imaginary axis (diodes, thermistors, controllable FET-resistance, AGC circuitry,...).
However, due to several time constants within the whole circuit the closed-loop poles will be NOT fixed at the imag. axis but will swing around this axis (between the left and the right half of the s-plane). Hence, in most cases the produced signal will carry a slight amplitude modulation - and it is the main task for the designer to keep this amplitude variation within acceptable limits (proper selection for the time constants and the excess loop gain).

*

*Why unity loop gain (Barkhausen criterion)? It should be noted that this criterion is a necessary one only - not a sufficient criterion.

"Unity loop gain" means that - for a single specified frequency only - the complex forward gain of the amplifier can exactly compensate the damping and the phase shift of the feedback network. With other words: The amplifier can produce an output voltage Vout and - at the same time - the corresponding  input voltage which is necessary to allow this value Vout. The amplifier does not need an external signal to produce this output signal Vout.


text:
Q: How do I get a folder to stop forgetting its sorting options? I have a folder (my home folder) which I like to have in icon view and kept arranged by name.
However, every day or so it seems to forget the sorting - although the view options panel seems to think that the option is still valid.   I have to change it to arrange by another criterion and then re-select arrange by name.
This is rather irritating, to say the least.  Does anyone know how to fix the Finder's forgetfulness

A: "Arrange by Name" is a one-time command to arrange the icons. When an item in the folder gets deleted, or new ones added, they don't adhere to this rule, until you force another "Arrange by Name". It looks like this is the behavior you are seeing.
The solution is to choose "Sort by Name", which applies an ongoing rule.


text:
Q: Django get IP only returns 127.0.0.1 I have a webserver set up with gunicorn and nginx and django.
I am accessing it remotely, and with this:
def testIP(request):
    ip_address = utils.get_ip(request)

I just keep getting an ip address of 127.0.0.1 Like i said I am accessing it remotely and thus it should not be giving a local address.
I think it might have something to do with gunicorn, but I want to check here first to see if you guys have any insights.

A: How does get_ip() work?
If nginx is a reverse proxy and gunicorn is the app server, it's always getting requests from nginx on the local machine.
The real ip that nginx sends to the app server is in my case HTTP_X_REAL_IP via the nginx conf line proxy_set_header X-Real-IP $remote_addr;
So you might want to set that, and in your django app account for the different header by either using your new IP header or set request.META['REMOTE_ADDR'] = request.META['HTTP_X_REAL_IP']


text:
Q: Problem with ajax hover menu extender control I downloaded the ajax tool kit and added to my tool box. But when I drag and drop ajax controls on my web form,The below errors I am getting.

*

*Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. The system cannot find the file specified.

*Unknown server tag 'cc1:HoverMenuExtender.

Here is my .aspx code.

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Untitled Page</title>

    <form id="form1" runat="server">

Ajax Control Toolkit Example: Using HoverMenuExtender

        <asp:ScriptManager
            ID="ScriptManager1"
            runat="server"   >
        </asp:ScriptManager>
    <cc1:HoverMenuExtender
            ID="HoverMenuExtender1"
            runat="server"
            TargetControlID="Label1"
            PopupControlID="Panel1"
            PopupPosition="Bottom"   >
        </cc1:HoverMenuExtender>

        <asp:Label
            ID="Label1"
            runat="server"
            Text="Color changeable label."
            Font-Size="XX-Large"
            Font-Names="Comic Sans MS"
            >
        </asp:Label>
        <asp:Panel
            ID="Panel1"
            runat="server"
            Width="300"
            BorderColor="Gray"
            BorderWidth="1"
            CssClass="PanelCSS"
            >
            <asp:RadioButtonList
                ID="RadioButtonList1"
                runat="server"
                RepeatColumns="3"
                OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged"
                AutoPostBack="true"
                >
                <asp:ListItem>Tan</asp:ListItem>
                <asp:ListItem>Crimson</asp:ListItem>
                <asp:ListItem>DarkBlue</asp:ListItem>
                <asp:ListItem>SeaGreen</asp:ListItem>
                <asp:ListItem>OrangeRed</asp:ListItem>
                <asp:ListItem>Magenta</asp:ListItem>
                <asp:ListItem>DeepPink</asp:ListItem>
            </asp:RadioButtonList>
        </asp:Panel>

    </form>

Please solve my problem.
Regards,
N.SRIRAM

A: Do you really have the AJAX Control Toolkit assembly in the bin directory of your ASP.NET application?
If you've there already, have you checked that added reference is compiled for your Microsoft .NET Framework version?
Maybe you've an old version, or you've a newer version and you're using a wrong version of ASP.NET.


text:
Q: How to click a link in only a single class I have elements that can be in one of two state class="icon" or class="icon active".
I thought that $browser.element(:class => /^icon$/).click would click the first button that isn't active but it just clicks the first one it finds regardless of whether or not it also contains "active."
Is the regex wrong?  Or better yet, is there a non-regex way of doing it?

A: This is theoretical, and I apologize for not having the time to construct a fake page and test to see if it works
browser.element(:class => /icon(?!active)$/).click

This works in theory (the regex) matching a line like icon but not icon active but, there may be some under the hood magic that goes on with how class names are matched which might cause it to return the wrong line.
If that does not work let me know, I'll suggest an alternative approach, which while less elegant, ought to work.
For reference I used the Rubular online regex tester along with this SO answer Regular expression to match a line that doesn't contain a word? to some up with that.

A: As mentioned in the comments, the regex you used should work in watir-webdriver. However if you need a solution that will work in both watir-classic and watir-webdriver, you will need to use find.
b.elements.find{ |e| e.class_name == 'icon'}.click

This will only matches elements where the 'class' attribute is exactly 'icon'.
It is slower and less readable, but allows you to bypass watir-classic's method for matching classes. As seen below, watir-classic will check that the regex matches any of the element's classes.
def match_class? element, what
  classes = element.class_name.split(/\s+/)
  classes.any? {|clazz| what.matches(clazz)}
end

A: Failing the ability to use a regex, another option would be to get a collection of matching items, and then inspect them more closely, clicking when you find one that works and abandoning the collection at that point.
browswer.elements(:class => "icon").each do |possible|
  unless possible.attribute_value("class").include? "active"
    possible.click
    break
  end
end

I'm not always a big fan of unless, but in this case it results in readable code, so I used it
for troubleshooting, lets see what is being shown for the class info on the elements in that collection
browswer.elements(:class => "icon").each do |possible|
  puts possible.attribute_value("class")
end


text:
Q: App service alternative to Adobe Flash Media (Server & Live Encoder) I am looking for an alternative to Adobe Flash Media Server and Adobe Flash Media Live Encoder that can offer on the same hardware better performance, quality and overall performance/stability. I will be using a Pinnacle video capturing device to capture the video and transfer it to the server.
What alternative is available in Ubuntu so I can replace the whole Adobe system.

A:
Red5 is an open source Flash server that is written in Java and supports:

*

*streaming audio/video (FLV, MP3, F4V, MP4, AAC, M4A)

*recording client streams (FLV only)

*shared objects

*live stream publishing (Sorenson, VP6, h.264, MP3, AAC and more)

It has installers for OSX and Windows. Also, it can be downloaded as a zip file to be used in any OS.
OR

Mammoth is also an open source Flash streaming server that is built with C++ and can run on Windows and *nix OSs.
It can stream all Flash codecs like h263, h264, mp3, vp6, speex, nellymoser, etc.
By using FFmpeg it has has container support for most formats: mov, flv, mkv, mp3 and more.
The server is still in alpha phase but very promising.
ref http://www.webresourcesdepot.com/free-flash-media-server-alternatives/

A: You can also review Ant Media Server. Ant Media Server Low Latency solutions are awesome.
Ant Media Server is an open source media server that supports:

*

*Ultra Low Latency Adaptive One to Many WebRTC Live Streaming in Enterprise Edition

*Adaptive Bitrate for Live Streams (WebRTC, MP4, HLS) in Enterprise Edition

*SFU in One to Many WebRTC Streams in Enterprise Edition

*Live Stream Publishing with RTMP and WebRTC

*WebRTC to RTMP Adapter

*IP Camera Support

*Recording Live Streams (MP4 and HLS)

*Restream to Social Media Simultaneously(Facebook and Youtube in in Enterprise Edition)

*One-Time Token Control in Enterprise Edition

*Object Detection in Enterprise Edition

The Ant Media Server Github Page: https://github.com/ant-media/Ant-Media-Server
The Ant Media Server Google Group: https://groups.google.com/forum/#!forum/ant-media-server
Also review website: https://antmedia.io

A: RED5 with VLC does a lot of cool streaming. VLC as the encoder and RED5 as the media distribution server. VLC can act as a server as well, but I don't think is will scale as well as you wish.

A: Don't forget about wowza media server, it's not free but it seems it's a little less then adobe. however keep in mind, if you don't own the server with a good backbone service you will likely be renting space on any of the servers, adobe, red5, wowza and what ever else is now available. the rent space plus bandwidth is usually pretty much the same cost no matter which platform you use, just a couple things to keep in mind before you try all the learning curves that each bring with them. If you go with red5 you will need to download and install the dev tools required for coding / programming in java and you will still need one of the newer flash IDE's as well.
red5 uses the eclipse IDE, For instructions on how to install the eclipse plugin, please see the following documentation on the red5.org site:
http://www.red5.org/red5-ide-plugin/
wowza also uses their own version of eclipse as well in their own IDE called wowza IDE2
http://www.wowza.com/
I have tried them all and I found that the support is excellent for wowza, you typically get straight forward answers in a timely manner, the other two mentioned not so much. aside from that it's all up to your skills and / or want to learn new ones.
it's all java based in one form or another anyway.
I'm not going to post adobe site, everyone should know how to get there by now.
I hope this helps someone.


text:
Q: Upload multiple files with REST API in document library with custom properties I am trying to upload multiple documents to the document library, I followed the answer posted on this link, I am able to upload the documents but I have some custom columns in the library, please help me on uploading the documents with custom properties. For e.g. I am uploading documents for a task/project and I want to associate task id/Project id to this document under custom properties.
Thanks

A: For updating custom column while uploading file you use following code with this answer
function upload() {
    // Define the folder path for this example.
    var serverRelativeUrlToFolder = 'SiteAssets';

    // Get test values from the file input and text input page controls.
    var fileInput = jQuery('#getFile');
    var newName = jQuery('#displayName').val();
    var fileCount = fileInput[0].files.length;
    // Get the server URL.
    var serverUrl = _spPageContextInfo.webAbsoluteUrl;
    var filesUploaded = 0;
    for (var i = 0; i < fileCount; i++) {
        // Initiate method calls using jQuery promises.
        // Get the local file as an array buffer.
        var getFile = getFileBuffer(i);
        getFile.done(function (arrayBuffer, i) {

            // Add the file to the SharePoint folder.
            var addFile = addFileToFolder(arrayBuffer, i);
            addFile.done(function (file, status, xhr) {
               //Get ID of File uploaded
                var getfileID = getItem(file.d);
                getfileID.done(function (fResult) {
                    var colObject = new Object();
                    colObject["FileType"] = fileType;
                    var changeItem = updateFileMetadata(libraryName, fResult.d, colObject);
                    changeItem.done(function (result) {
                        filesUploaded++;
                        if (fileCount == filesUploaded) {
                            alert("All files uploaded successfully");
                            //$("#msg").append("
All files uploaded successfully
");
                            $("#getFile").value = null;
                            filesUploaded = 0;
                        }
                    });
                    changeItem.fail(function (result) {

                    });

                }, function () { });

            });
            addFile.fail(onError);
        });
        getFile.fail(onError);

    }

    // Get the local file as an array buffer.
    function getFileBuffer(i) {
        var deferred = jQuery.Deferred();
        var reader = new FileReader();
        reader.onloadend = function (e) {
            deferred.resolve(e.target.result, i);
        }
        reader.onerror = function (e) {
            deferred.reject(e.target.error);
        }
        reader.readAsArrayBuffer(fileInput[0].files[i]);
        return deferred.promise();
    }

    // Add the file to the file collection in the Shared Documents folder.
    function addFileToFolder(arrayBuffer, i) {
        var index = i;

        // Get the file name from the file input control on the page.
        var fileName = fileInput[0].files[index].name;

        // Construct the endpoint.
        var fileCollectionEndpoint = String.format(
                "{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
                "/add(overwrite=true, url='{2}')",
                serverUrl, serverRelativeUrlToFolder, fileName);

        // Send the request and return the response.
        // This call returns the SharePoint file.
        return jQuery.ajax({
            url: fileCollectionEndpoint,
            type: "POST",
            data: arrayBuffer,
            processData: false,
            headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-length": arrayBuffer.byteLength
            }
        });
    }
}

// Display error messages.
function onError(error) {
    alert(error.responseText);
}

function updateFileMetadata(libraryName, item, colPropObject) {
    var def = jQuery.Deferred();

    var restSource = siteUrl + "/_api/Web/Lists/getByTitle('" + libraryName + "')/Items(" + item.Id + ")";
    var jsonString = "";

    var metadataColumn = new Object();
    metadataColumn["type"] = item.__metadata.type;
    //columnArray.push(metadataColumn);
    if (colPropObject == null || colPropObject == 'undefined')// For library having no column properties to be updated
    {
        colPropObject = new Object();
    }
    colPropObject["__metadata"] = metadataColumn;
    jsonString = JSON.stringify(colPropObject);
    var dfd = jQuery.Deferred();
    jQuery.ajax(
    {
        'url': restSource,
        'method': 'POST',
        'data': jsonString,
        'headers':
            {
                'accept': 'application/json;odata=verbose',
                'content-type': 'application/json;odata=verbose',
                'X-RequestDigest': jQuery('#__REQUESTDIGEST').val(),
                "IF-MATCH": item.__metadata.etag,
                "X-Http-Method": "MERGE"
            },
        'success': function (data) {
            var d = data;
            dfd.resolve(d);
        },
        'error': function (err) {
            dfd.reject(err);
        }
    });

    return dfd.promise();
}
/*=====================================================
Get Item for Uploaded Document
=======================================================*/
function getItem(file) {
    var def = jQuery.Deferred();
    jQuery.ajax({
        url: file.ListItemAllFields.__deferred.uri,
        type: "GET",
        dataType: "json",
        headers: {
            Accept: "application/json;odata=verbose"
        },
        success: function (data) {
            def.resolve(data);
        },
        error: function (data, arg, jhr) {
            def.reject(data, arg, jhr);
        }
    });
    return def.promise();
    //return call;
}


text:
Q: Visual Studio Project Backup Right now I am saving my all visual studio projects in C drive.
Now I want to keep copy of that all projects in some other drive, so if my C drive get crashed then also I can access all projects.
So what is best way for that.
If I just make zip of current projects from C drive and paste it in another drive.
And when needed I extract it, then will it work OR any error will come.
Thanks for help in Advance.

A:
If I just make zip of current projects from C drive and paste it in another drive.

Well you could do that but it's rather tedius; error-prone and rather brute-force.  It's difficult to maintain history.
A better choice is to use some form of source control (SC) / software configuration management (SCM).  SC is a tool for maintaining a code repository.  It works by associating metadata about every source file and any changes you make.
e.g.

*

*Git

*Subversion

*Microsoft TFS

*Perforce

*IBM/Rational ClearCase

*Microsoft SourceSafe (ewww, retried thankfully)

Source control not only keeps a copy somewhere else (ideally a different computer) but it also allows you to

*

*keep track of what changed

*rollback a change

*share with your friends or colleges

*integrates nicely with your IDE of choice (VS) or command-line

But in this day and age there are plenty of free cloud-based solutions that offer you more than just acting as a code repository such as stats; wikis; bug tracking; and spiffy charts.  Check out:

*

*Microsoft Visual Studio Team Services (VSTS)

*Github

*Atlassian Bitbucket
Summary
Irrespective of whether you perform manual folder copies or use source control; both will lead to a copy of your code.  However only the latter introduces workflows and due-diligence (via SCM) so that as you code you are unlikely to lose information due to the procedures and safeguards in place.
A word on file backup
If for some absolute reason you decide not to proceed with SC but rather stick with plain-old-file-backup then at least follow the fine wisdom of Scott Hanselman (MSFT) where he talks about file backup best practices:

I've got a number of backups because I practice the Backup Rule of Three.

*

*3 copies of anything you care about - Two isn't enough if it's important.

*2 different formats - Example: Dropbox+DVDs or Hard Drive+Memory Stick or CD+Crash Plan, or more

*1 off-site backup - If the house burns down, how will you get your memories back?

...using apps like CrashPlan.
Scott will most likely agree that his plan wasn't intended for source code but at least you have 3 backups of files as he recommends.
See Also

*

*Hanselman, S, "Is your stuff backed up? Recovering from a hardware failure"

A: Have a look at Visual Studio Team Services. You can add code to source control (I would use Git if I were you) and manage your projects there for free.
Having your code in a source control system has many benefits, like having history of each commit.
Next to that, VSTS has lots of opions like Continuous Integration / Continuous Deployment, Testing, project management support like making your project an Agile project.

A: What will you do if hard drive crash?
Code Management is a practice and there are many tools to help you to manage your code. Try GitHub or bitbucket
Moreover you can also zip the code and save on external disks but check how much risk is involved with your code.

A: You could use a .zip archive to back up your work, but this is slightly laborious and will likely include a number of files you do not need to get up and running again (for example the build output, nuget packages folders, etc.) which will bloat your archives.
A better option would be to use a Version Control System of some kind, which will allow you to back up those parts of the project/solution that actually need to be backed up while ignoring the parts that can be rebuilt from the code. A good walk through of what and why can be found in Version Control By Example, which also includes comparisons about different types of VCS as well as how to perform many of the usual tasks.
There are various free options out there, based on a number of different providers. As some examples, I've used the following services, and all of them will give you a free account, and some will also give you private repositories (so that random members of the public can't see your work if that's what you want):

*

*GitHub - unlimited public repositories, uses Git.

*BitBucket - unlimited private repositories, uses Git or Mercurial

*Visual Studio Team Services - unlimited private repositories, uses Git or TFS

Using an online provider will give you the added benefit of the backups being on a third party - so if your disk fails you'll still have a backup, as well as the other benefits a VCS will provide (the ability to rollback to a specific point in time, annotations about changes, etc.).


text:
Q: Broadcom wifi 14e4:4464 adaptor not found I was able to install Ubuntu 20.04 on a 2018 MacMini using this post. The main remaining issue is that Ubuntu cannot find the wifi adapter. The pci.id (see below) is different from any of the ones listed in this post where it was suggested to create a new post on askubuntu.com for any unlisted pci.id. Thanks in advance for any suggestions you might have
lspci -vnn | grep Network
03:00.0 Network controller [0280]: Broadcom Inc. and subsidiaries BCM4364 802.11ac Wireless Network Adapter [14e4:4464] (rev 03)
    Subsystem: Apple Inc. BCM4364 802.11ac Wireless Network Adapter [106b:07bf]

A: Installing Broadcom Wireless Drivers
is the most in depth
No wifi adapter found Ubuntu 20.04.1 LTS bcm4352/14e4:43b1
is the thread i made when i fixed my problem.
disable secure boot
and install/update your bcmwl-kernel-source
chili555s comments worked for me


text:
Q: DailyRollingLog doesn't works in spring mvc I am trying to achieve daily rolling log using log4j in  my spring application. Here is the code i have tried,
Pom.xml
<!-- Log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>

logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="RollingAppender" class="org.apache.log4j.DailyRollingFileAppender">
       <param name="File" value="${catalina.home}/logs/app.log" />
       <param name="DatePattern" value="'.'yyyy-MM-dd-HH-mm" />
       <layout class="org.apache.log4j.PatternLayout">
          <param name="ConversionPattern" value="[%p] %d %c %M - %m%n"/>
       </layout>
    </appender>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

    <logger name="org.springframework" level="DEBUG"/>
  <root level="DEBUG">
    <appender-ref ref="STDOUT" />
  </root>

</configuration>

I have placed the logback.xml file under /WEB-INF/classes
Here i have tested the xml logics takes a log rolling file in every minutes. If this works then i can modify the DatePattern to "'.'yyyy-MM-dd"
But Its doesnt works out.
Where am i doing mistake?
Even I have tried log4j.properties file like below,
log4j.rootLogger=DEBUG, loggerId
log4j.appender.loggerId=org.apache.log4j.DailyRollingFileAppender
log4j.appender.loggerId.layout=org.apache.log4j.PatternLayout
log4j.appender.loggerId.File=D:\\examples\\logfile.log
log4j.appender.loggerId.DatePattern='.'yyyy-MM-dd-hh-mm
log4j.appender.loggerId.layout.ConversionPattern=%d [%t] %-5p (%F:%L) - %m%n

But still its not taking log file for every minutes !!

A: logback and log4j are totally different things.
You have to use logback jar with logback.xml, or log4j jar with log4j properties.


text:
Q: How would I use the page-id number to alter the CSS of a woocommerce page? I'm using CSS Hero which makes it easy for the element to break down.
On one page the wrapper, which bleeds over to other templates, shows this:
html>body>#wrapper>#main>#content>div
Since I only want the changes to be for this element on this page what would I do? I tried this:
.page-id-89 .html>body>#wrapper>#main>#content>div
Unfortunately, this did not work.


text:
Q: How to get subset of 10K MNIST images from Dataset class in tensorflow? I found the following way to get mnist dataset in tensorflow:
def get_input_fn(dataset_split, batch_size, capacity=10000, min_after_dequeue=3000):

  def _input_fn():
    images_batch, labels_batch = tf.train.shuffle_batch(
        tensors=[dataset_split.images, dataset_split.labels.astype(np.int32)],
        batch_size=batch_size,
        capacity=capacity,
        min_after_dequeue=min_after_dequeue,
        enqueue_many=True,
        num_threads=4)
    features_map = {'images': images_batch}
    return features_map, labels_batch

  return _input_fn

    data = tf.contrib.learn.datasets.mnist.load_mnist()

    train_input_fn = get_input_fn(data.train, batch_size=256)
    eval_input_fn = get_input_fn(data.validation, batch_size=5000)

data variable is Dataset object.
This approach is quite unclear to me and I cannot figure out how to convert 60K dataset into 10K dataset.
When I do the following:
data = tf.contrib.learn.datasets.mnist.load_mnist().take(10000)

I get error:
AttributeError: 'Datasets' object has no attribute 'take'

But docs provide this method:

Thank you for help!

A: This function from contrib module is deprecated. You can use tf.keras.datasets.mnist.load_data(). As per https://www.tensorflow.org/api_docs/python/tf/keras/datasets/mnist/load_data, it returns
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.

So, in order to apply any functions to it you need to load it in a dataset object.
train, test = tf.keras.datasets.mnist.load_data(path='mnist.npz')
dataset_train = tf.data.Dataset.from_tensor_slices((train[0], train[1]))
dataset_test = tf.data.Dataset.from_tensor_slices((test[0], test[1]))

Then you can apply shuffle, batch, take, or any map function to dataset_train or dataset_test objects


text:
Q: How to decrypt PHP Openssl encryption with BASH command I am encrypting a password in PHP, and want to decrypt it on a different box. I am having no luck and I would prefer to be able to decrypt it right from bash and echo it. Below is a snippet of a test in PHP.
$textToEncrypt    = "My super secret information.";
$encryptionMethod = "AES-256-CBC";
$secretHash       = "Testkey";

//To encrypt
$encryptedMessage = openssl_encrypt($textToEncrypt, $encryptionMethod, $secretHash);

//To Decrypt
$decryptedMessage = openssl_decrypt($encryptedMessage, $encryptionMethod, $secretHash);

//Result
echo "Encrypted: $encryptedMessage <br>Decrypted: $decryptedMessage";

I have tried numerous methods to decrypt it on Ubuntu, even storing the data to a file and outputting it to a file. Command tried was:
openssl aes-256-cbc -a -d -k Testkey -in foo.txt -out secrets.txt

Where foo.txt is the value returned from the PHP encryption, and secrets.txt is the output. How can I do this?

A: It bears repeating, as in the comments, that encryption without an IV is dangerous. In fact, the current version of PHP will issue a warning about it. IVs can be randomly generated using the openssl_random_pseudo_bytes() function, and transmitted in the clear along with the encrypted text. They don't have to be secret, the important thing is not to reuse the same key and IV combination, and have a random IV.
So, with that out of the way, if you take a look at the source for the function, it's not passing the password argument as a passphrase, but rather as the key. So for using openssl on the command line, it needs to be in hex and passed to the -K option, not the -k option. But then, you'll get an error back saying "iv undefined" so your PHP needs to be adjusted to include one:
<?php
$textToEncrypt    = "My super secret information.\n";
$encryptionMethod = "AES-256-CBC";
$key              = "Testkey";
$iv               = openssl_random_pseudo_bytes(
                        openssl_cipher_iv_length($encryptionMethod)
                    );

$keyHex           = bin2hex($key);
$ivHex            = bin2hex($iv);

//To encrypt
$encryptedMessage = openssl_encrypt($textToEncrypt, $encryptionMethod, $key, 0, $iv);

//To Decrypt
$decryptedMessage = openssl_decrypt($encryptedMessage, $encryptionMethod, $key, 0, $iv);

//Result
printf(
    "Decrypted message: %s\n\nkeyHex=%s\nivHex=%s\nencryptedMessage=%s\n",
    $decryptedMessage,
    escapeshellarg($keyHex),
    escapeshellarg($ivHex),
    escapeshellarg($encryptedMessage)
);

Once you have these details, you can decrypt from command line (re-using PHP variable names here):
echo -n "$encryptedMessage" | openssl aes-256-cbc -d -a -A -K "$keyHex" -iv "$ivHex"

A: The other way around
#!/bin/bash
#  create in bash keys
echo "generating private key"
openssl genrsa -out privkey.pem 2048
echo "signing private key"
openssl req -new -key privkey.pem -out certreq.csr -subj "/C=RO/ST=AB L=AB/O=None/OU=Department/CN=someweb.com"

echo "create a sign request"
openssl x509 -req -in certreq.csr -signkey privkey.pem -out newcert.pem
# end-of-bash-script
cp ./privkey.pem /path/to/apache/root/<some>

Encrypt some json file
openssl smime -encrypt -aes256 -in ./json.txt -binary -outform DER -out ./json.xxx newcert.pem
# test decrypt here in bash
# openssl smime -decrypt -in json.xxx -inform DER -inkey privkey.pem -out json.dec

Post it as binary to php
curl --request POST --data-binary @./json.xxx http://localhost/<some/>json.php

Then json.php script @ apache root
<?php

    $rkey = file_get_contents("/var/www/html/privkey.pem");
    $pkey = file_get_contents("/var/www/html/newcert.pem");
    $data = file_get_contents("php://input");
    $fenc = tempnam("", "enc");
    $fdec = tempnam("", "dec");
    file_put_contents($fenc,$data);
    // openssl_pkcs7_decrypt ($fenc , $fdec , $pkey, $rkey ); unable to coerce parameter 3 to x509 cert
    system("openssl smime -decrypt -in ${fenc} -inform DER -inkey privkey.pem -out ${fdec}");
    echo  file_get_contents($fdec);
?>


text:
Q: Protractor can't use local properties declared with this. inside .then statement I've been trying to best organise my Protractor e2e tests in a reusable manner using the Page Object model. At the start of every Page Object I will define the elements on the page, followed by the local functions. e.g:
'use strict';

var examplePage = function() {
    // Locators
    this.button1   = $('#button1')
    this.element1  = $('#element1');
    this.element2  = $('.element2');

    // Error Messages
    this.ERROR_ONE = 'There was an error!';

    // Protractor ExpectedConditions instance
    var until = protractor.ExpectedConditions;

    this.doSomeStuff = function() {
        this.button1.click().then(function() {
            browser.wait(until.visibilityOf(this.element1), global.TIMEOUT_INTERVAL_SHORT, this.ERROR_ONE);
            return this.element1;
        });
    };
};
module.exports = examplePage;

My code above is just an example. My real code is very similar.
Sometimes in my code I may need to control the order that the functions are executed to stop the functions from executing too early. However, this causes a completely local scope inside the .then statement. For example, the 'this.ERROR_ONE' property becomes inaccessible so I can't maintain my error messages and 'this.element1' becomes inaccessible.
Has anybody else encountered this and found a solution to this problem? It becomes messy to maintain the same value all over my Page Objects.

A: Protractor team has a good tutorial on PageObject pattern for Protractor frameworks. You cannot use this to declare variables.
You can directly access the objects as shown in the above tutorial -
var examplePage = function() {
    // Locators
    var button1   = $('#button1');
    var element1  = $('#element1');
    var element2  = $('.element2');

    // Error Messages
    var ERROR_ONE = 'There was an error!';

    // Protractor ExpectedConditions instance
    var until = protractor.ExpectedConditions;

    this.doSomeStuff = function() {
        this.button1.click().then(function() {
            browser.wait(until.visibilityOf(element1), global.TIMEOUT_INTERVAL_SHORT, ERROR_ONE);
            return element1;
        });
    };
};
module.exports = examplePage;


text:
Q: Low Pass Filters and Sampling Frequency I am trying to understand the relationship between low pass filters and sampling frequency. Let's say I have a signal data with sampling frequency (sampling rate 500Hz), and the data represent a signal with a (0-200Hz) frequency. I am trying to get rid off the frequencies over 50Hz ( removing the part from 50-200Hz). In butterworth filter they are talking about sampling frequency.  The frequency bands formulas are based on the sampling frequency, like f_cut/f_sampling. These are all related to sampling frequency although I need remove the extra noise with respect to physical frequency which signal has. How does it work?

A: When doing digital filter design you normally work with normalised frequency, which is just the actual frequency divided by the sample rate. So in your example where you want to specify a cut-off of 50 Hz at a sample rate of 500 Hz then you would specify this as a normalised frequency of 0.1. (Note that if you later changed your sample rate to say 1 KHz then your filter would have a cut-off frequency of 100 Hz.)


text:
Q: excluding module/transitive dependencies from Gradle Build I am currently attempting to build a gradle grails 3 project, where it is using Spring-context-support as a transitive dependency under some Spring dependency at compile time as declared in my build file.
My application does depend on the group and artifact/module as a whole(That is, Spring-context-support), however, I need to explicitly get rid of/exclude EhCache from within spring-context-support.
I know syntactically how rid myself of the entire spring-context-support dependency, however I cannot seem to figure out how to remove JUST the caching...
A screen shot is attached to help illustrate what i mean:
this line when uncommented will remove the entire spring-context-support dependency:

Here you see the "cache" package, containing the Ehcache modules that I am trying to get rid of. How would I adjust the exclude declaration to remove this?

A: Gradle (or Maven) will only allow you to exclude a dependency at the artifact level, that is not have the jar on the classpath. There is no first class support for filtering out a set of packages from a dependency.
For that, the easiest would be to repackage your application in a fat jar, filtering out the packages you deem unnecessary.
However the way your question is phrased makes me wonder if there is not a confusion.
What you will find inside org.springframework.cache is not Ehcache code but instead the Spring caching abstraction.
Ehcache library is either a module under group net.sf.ehcache or org.ehcache, and you could very well exclude these.

A: Excluding dependencies is described in the docs: https://docs.gradle.org/current/userguide/managing_transitive_dependencies.html#sec:excluding_transitive_module_dependencies
Good luck!


text:
Q: How to include CSRF from Codeigniter into ajax data I am trying to pass some data into my Controller, but I'm getting a 500 error. After some research, I discovered that it's caused by the CSRF token not being sent.
It seems like I need to include this along with the data: <?php echo $this->security->get_csrf_token_name(); ?>:"<?php echo $this->security->get_csrf_hash(); ?>"
My JS is pretty weak, so I'm a little confused on how to alter this to include the above.

A: The token needs to be passed in the data argument of $.ajax.
This should work but see my notes below.
order['<?php echo $this->security->get_csrf_token_name(); ?>'] = '<?php echo $this->security->get_csrf_hash(); ?>';
However, there are a few bad practices going on here. Mainly you should not use PHP in your javascript because this prevents you from being able to access the javascript as a separate file (this is good because browsers will cache it to make your page load faster and consume less bandwidth).
It's better to store the token in your order <form> html like this..
<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>" />
Then it will get serialized with the rest of your form data.
You can also store the URL in the form's action attribute. This will help your script gracefully degrade and also keeps the URL in one place instead of 2.
<form id="order" method="post" action="<?=base_url()?>admin/category/update_order">

In the $.ajax call, use something like this url: $('#order').attr('action'), assuming #order is the actual form id.

A: CI stores csrf in cookie and you can fetch it from there:
var csrf = $.cookie('csrf_cookie_name');

The downside of this method is that jQuery doesn't natively provide cookie access. So you will need a jquery plugin.

A: You're correct, just add the CSRF token to your post data. You can use jQuery's $.extend function to merge your order object you already created with the CSRF token data, like this:
$.extend(alerts, {
'<?php echo $this->security->get_csrf_token_name(); ?>' :
'<?php echo $this->security->get_csrf_hash(); ?>' });

A: Here's a different approach. Simple function in Auth.php that returns the csrf token name and hash in JSON format. Then, in our javascript, make two ajax calls, the first to grab the csrf creds and insert them into hidden form fields, the second to handle our actual form submit.
// place function in Auth.php controller
public function get_csrf()
{
    $csrf['csrf_name'] = $this->security->get_csrf_token_name();
    $csrf['csrf_token'] = $this->security->get_csrf_hash();

    echo json_encode($csrf);
}

// myFunction()

// html

<form method="post" accept-charset="utf-8">

    <input type="hidden" id="csrftoken" name="" value="" />

    Field 1:

    <input type="text" name="field1" id="field1"  />

    Field 2:

    <input type="text" name="field2" id="field2"  />

    <input type="button" name="submit" value="SUBMIT" onclick="myFunction()" />

</form>

A: I extend form_helper as MY_form_helper.php to serve csrf tokens to my own form generation code - you could use something similar:
    function secure_form() {
        $CI =& get_instance();
        return '<input type="hidden" name='.$CI->security->get_csrf_token_name().' value='.$CI->security->get_csrf_hash().'>';
    }

A: another solution is to use .serialize():
$.post("user/save", $('#frmUser').serialize(),function(html){
        $("#results").html(html);
});

that will find the hidden field that stores the CSRF data.


text:
Q: Is it possible to enable compression with SQL Server 2005 Replication I am sending data across a link with very little bandwidth and I will probably be sending large data files.
I have Merge Replication and Snapshot replication configured at present.
Is it possible to enable compression in SQL Server 2005 replication and if so, how?
Thanks.

A: Google turned up this article on the Microsoft SQL Server Development Customer Advisory Team [sic!] Blog:
SQL Server 2005 Transactional Replication: Benefit of using SubscriptionStreams for low bandwidth, high latency environments
Not exactly what you were asking for, but maybe of value still.


text:
Q: In batch programming, how to use a user key-in input as to print out array content @echo off
set myArray[0]=a1
set myArray[1]=b2
set myArray[2]=c3
set myArray[3]=d4
set myArray[4]=e5
set myArray[5]=f6
set myArray[6]=g7
set myArray[7]=h8
set myArray[8]=i8
set myArray[9]=j9

set /p TEMPCMD:

echo %myArray[%TEMPCMD%]%
echo %myArray[!TEMPCMD!]%
echo !myArray[%TEMPCMD%]!
echo !myArray[!TEMPCMD!]!

I want to print out the array content based on what user key-in index, but none of the case above works in this case... I understand that !variable! is only be used when setlocal EnableDelayedExpansion, but I just take a trial for that...

A: You're right, you can do that with the EnableDelayedExpansion option. It seems that you missed to turn that flag on. Try this:
@echo off
setlocal EnableDelayedExpansion
set myArray[0]=a1
set myArray[1]=b2
set myArray[2]=c3
set myArray[3]=d4
set myArray[4]=e5
set myArray[5]=f6
set myArray[6]=g7
set myArray[7]=h8
set myArray[8]=i8
set myArray[9]=j9

SET /P TEMPCMD=Input index:
echo !myArray[%TEMPCMD%]!

A: Here is another method:
@echo off
set myArray[0]=a1
set myArray[1]=b2
set myArray[2]=c3
set myArray[3]=d4
set myArray[4]=e5
set myArray[5]=f6
set myArray[6]=g7
set myArray[7]=h8
set myArray[8]=i8
set myArray[9]=j9

set /p TEMPCMD=

call echo %%myArray[%TEMPCMD%]%%
pause


text:
Q: Python turtle user input for shape and color I've been trying to write some code to allow for instantaneous results after someone inputs what color and what shape they want it to be in turtle.  Basically, what I mean is that when you get prompted for a color and you say "orange", for example, then the color will instantly change to orange.  Here's the code I've written:
def Turtle(shape):
if shape == "triangle":
    turtle.circle(40, steps=3)
elif shape == "square":
    turtle.circle(40, steps=4)
elif shape == "pentagon":
    turtle.circle(40, steps=5)
elif shape == "hexagon":
    turtle.circle(40, steps=6)

def Shape():
shape = eval(input("Enter a shape: "))
Turtle(shape)

def Turtle(color):
if color == "red":
    turtle.color("red")
elif color == "blue":
    turtle.color("blue")
elif color == "green":
    turtle.color("green")
elif color == "yellow":
    turtle.color("yellow")

def Color():
color = eval(input("Enter a color: "))
Turtle(color)

It works slightly.  After one change is made, say the color turns to blue then it will refuse to do anything after that regardless of the entries made into the user prompts.
P.S. I'm running Python 3.5.2

A: The problem is that you really need to turn over control to the turtle listener using mainloop() and then you no longer can communicate with it via top level function calls like:
color = input("Enter a color: ")

However, since you're using Python 3, we can use the new input dialog feature to dynamically prompt for input and make changes to the current drawing:
import turtle

current_shape = "triangle"

steps = {"triangle": 3, "square": 4, "pentagon": 5, "hexagon": 6}

def onkey_shape():
    shape = turtle.textinput("Shape Selection", "Enter a shape:")
    if shape.lower() in steps:
        turtle.reset()
        set_color(current_color)
        set_shape(shape.lower())
    turtle.listen()  # grab focus back from dialog window

def set_shape(shape):
    global current_shape
    turtle.circle(40, None, steps[shape])
    current_shape = shape

current_color = "red"

colors = {"red", "blue", "green", "yellow", "orange"}

def onkey_color():
    color = turtle.textinput("Color Selection", "Enter a color:")
    if color.lower() in colors:
        turtle.reset()
        set_color(color.lower())
        set_shape(current_shape)
    turtle.listen()  # grab focus back from dialog window

def set_color(color):
    global current_color
    turtle.color(color)
    current_color = color

set_color(current_color)
set_shape(current_shape)

turtle.onkey(onkey_color, "c")
turtle.onkey(onkey_shape, "s")

turtle.listen()

turtle.mainloop()

Make the turtle window active (select it, aka give it focus) then if you press 'C' you'll get a dialog for a new color (from a fixed set) and if you press 'S' you'll get a dialog for a new shape.  The code uses reset() to remove the previous drawing before making a new one with the changes.


text:
Q: Select divs according to various parameters I am new to web scraping and trying to scrape a particular website with certain parameters. Now, I want to fetch divs that satisfies following conditions:

*

*I want to exclude div which has certain class in it.

*I want to exclude div which doesn't have class attribute.

*I want to include div that have a particular id and either doesn't have any class or does have class other than ignored class list.
Now, i have accomplished 2 conditions so far with following code:
classToIgnore = ["class1", "class2", "class3"]

for div in soup.find_all('div', class_=lambda x: x in classToIgnore):
    div.decompose()

for div in soup.find_all('div', class_=False):
    div.decompose()

Now, I don't know how to add 3rd condition here & also want to do all 3 filters within single find_all() statement, if it's possible.

A: When dealing with such complicated conditions, it is always a best practice to wrap it in a separate function. BeautifulSoup allows you to use a function as filter.
from bs4 import BeautifulSoup, Tag
html = """

"""

soup = BeautifulSoup(html, 'html.parser')
classToIgnore = ["c1", "c2"]

# Using decompose to solve cases where
# unwanted classes comes inside wanted classes
for div in soup.find_all('div', class_=lambda x: x in classToIgnore):
    div.decompose()

def my_filter(ele):
    if (
        isinstance(ele, Tag) and
        ele.name == 'div' and
        ele.get('id') == 'myid' and not ele.get('class') or
        ele.get('class')
    ):
        return True

print(soup.find_all(my_filter))

Output
[

,

,

]

A: I may have missed some cases so please try the following with bs4 4.7.1 + which uses :not for exclusions or css And syntax. Note I have altered your class names in the list to be selectors by preceeding with "."
from bs4 import BeautifulSoup as bs

classes_to_ignore = [".class1", ".class2", ".class3"]

html = '''

a

b

c

d

e

f

g

h

i

'''

soup = bs(html, 'lxml')
ignore = ','.join(classes_to_ignore)
divs = soup.select(f"div[id='id1']:not({ignore}), div:not({ignore})[class]")
print(divs)


text:
Q: Creation of monadic yesod form without hamlet My goal is to write a monadic yesod form without usage of hamlet.
Let's say I have such example form:
userForm :: Maybe User -> Html -> MForm Handler (FormResult User, Widget)
userForm u extra = do
  (nameR, nameV) <- mreq textField "" (userName <$> u)
  (passR, passV) <- mreq passwordField "" Nothing
  let userRes = User <$> nameR <*> passR
  let widget = do
    toWidget $ \render -> do
      extra
      -- fvInput nameV?
      -- fvInput passV?
      H.input ! type_ "submit" ! value "Submit"
  return (userRes, widget)

In the case of hamlet usage it will be like that:
let widget = do
  toWidget [whamlet|
            ^{fvInput nameV}
            ^{fvInput passV}
           |]

But the return type of fvInput is FieldView App and I need to convert it to Html to compose with blaze well.
Perhaps, it will be easier to use Input Form for this task(i.e. implementing forms without w/hamlet), but the docs on yesodbook say it doesn't have a proper handling of the wrong input case. I tend to use monadic form here since I want a recreation of user input in the case of failed validation "for free" here. Will it work this way?

A: Use lift with widgetToPageContent:
userForm :: Maybe MyUser -> Html -> MForm Handler (FormResult MyUser, Widget)
userForm u extra = do
  (nameR, nameV) <- mreq textField "" (myUserName <$> u)
  (passR, passV) <- mreq passwordField "" Nothing
  nameContents <- lift $ widgetToPageContent (fvInput nameV)
  passContents <- lift $ widgetToPageContent (fvInput passV)
  let userRes = MyUser <$> nameR <*> passR
  let widget = do
        toWidget $ \render -> do
          extra
          pageBody nameContents render
          pageBody passContents render
          H.input H.! A.type_ "submit" H.! A.value "Submit"
  return (userRes, widget)


text:
Q: Confusion with input type of ADCs in datasheets I'm very much confused with the ADC terminology. I know what a differential amplifier is. And a differential amplifier can take a single-ended(unipolar) source as an input. It can of course better take bipolar inputs. There is also single-ended input amplifier where one end of the differential input is connected to the analog ground. This can only work with unipolar source.
But when it comes to datasheets of the ADCs, what does the following terminology mean?:
-Differential input channel ADCs
-Fully differential input channel ADCs
-Pseudo differential input channel ADCs
-Single ended ADCs
Is the above category about the source types(unipolar or bipolar), or is it about type of the amplifier itself?
For example if you go to this site: http://www.analog.com/en/products/analog-to-digital-converters/precision-adc-20msps/single-channel-ad-converters.html
There is a section called "Input types".
Edit:

A:
Is the above category about the source types(unipolar or bipolar), or
  is it about type of the amplifier itself?

You are confusing input types with power supply types. An ADC can have either single-ended or differential inputs. Its power supply can be unipolar (ground with a single + power feed), or bipolar supply with something like +/- 5 volts.

*

*In terms of compatibility (ideally) you want the power source for the ADC to match the signal power source, unipolar or bipolar. This way a unipolar ADC is not likely to get a input voltage more negative than ground. If so then the input has to be scaled or clamped so it does not go negative. Most MPU's have unipolar ADC inputs so some method is needed to insure the ADC only sees voltages within its range of operation. It can have differential inputs but with a single-ended source the (-) input is connected to signal ground or the (-) output of a differential source.

*Bipolar ADC's are normally standalone types with 12 to 24 bit resolution and may or may not have differential inputs. But the ADC input voltage can go negative close to the negative supply rail. It may have a parallel or SPI port to communicate with a MPU. The cost are higher and much more detail to digital noise isolation is mandatory for these ADC's, which may have very high sample rates.

*Due to their lower cost most ADC's have unipolar power supplies as low as 3.3 volts, with a range of 0 to 3.3 volts. If in a MPU it normally had 10 bits of resolution, but some offer 12 bits of resolution with a single pair of differential inputs. As long as the source stays within the ADC's specified range then there are no damage or ADC reading error issues.

*In some cases manufactures specify a maximum series resistor value to limit current if a over or under voltage condition could happen, usually 1 K to 10 K maximum to avoid errors due to the internal sample/hold capacitor needing a minimum source impedance to charge up quickly during sample time.

*These resistors can be used with low-leakage diodes (not Zener or TVS diodes) to the power/ground rails or dedicated voltage clamps to limit the amount of over/under voltage possible.


text:
Q: How can I stop a SQL script (with GOs) from executing if the USE statement fails? This has been asked many times, but the top rated answer doesn't work.
BEGIN TRY
    USE [**DATABASE**]
END TRY
BEGIN CATCH
    set noexec on
    raiserror('Oh no a fatal error', 20, -1) with log
    return
END CATCH

GO
IF  EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[xxxxx]') AND parent_object_id = OBJECT_ID(N'[dbo].[xxxxxx]'))
ALTER TABLE [dbo].[xxxxx] DROP CONSTRAINT [xxxxxx]
GO

Seems like no matter what I do that IF EXISTS still runs. I've tried GOTO. I've tried set noexec on. I've tried RETURN.
It definitely fails on the USE statement and it definitely continues to run the next block after the first GO.
The point here is that I'm giving this script to other people and they must set the database name before running it. But they'll forget so I need a nice descriptive error message.

A: How about:
IF db_id('myDatabase') is null
    RAISERROR('Oh no a fatal error', 20, -1) with log

PRINT 'Do some stuff'
GO

You can use a parameter (@MyDB) in the db_id function call.
The real question to me is why:

*

*The "USE a non-existent database" command raises a severity 16 error

*The code in the CATCH block attempts to raise a severity 20 error

*But the CATCH block only raises a severity 16 error

Why is that?
--  Edited  ----------------
BOL for the USE statements says (not too clearly, imho):

USE is executed at both compile and execution time and takes effect
  immediately. Therefore, statements that appear in a batch after the
  USE statement are executed in the specified database.

So, presuming here, that error is generated at compile time, so that first "batch" (before the first go) does not get run, and execution jumps straight to the second batch.


text:
Q: WCF UriTemplate won't match a single string parameter with slashes (/'s) Here is the scenario, I have a WCF service call that takes one string parameter and that string has slashes in it (e.g. "123/456.xml").  I want to setup a UriTemplate like this "/{file}" so that I can access the method at http://www.example.com/File.svc/123/456.xml rather than http://www.example.com/File.svc/GetFile?file=123/456.xml.
Is this possible with UriTemplate?

*

*I realize that I could setup a UriTemplate like "/{directory}/{file}" but that is not an option because there is a variable number of directories.

A: Alright, I found a solution on MSDN.  UriTemplates support wildcard segments which basically mean the rest of the path.  So I can specify a UriTemplate like "/{*file}" and it will work as expected.

*

*MSDN docs: http://msdn.microsoft.com/en-us/library/bb675245.aspx

*Better explanation: http://hyperthink.net/blog/uritemplate-match/


text:
Q: Why RandomForestClassifier doesn't have cost_complexity_pruning_path method? In trying to prevent my Random Forest model from overfitting on the training dataset, I looked at the ccp_alpha parameter.
I do notice that it is possible to tune it with a hyperparameter search method (as GridSearchCV).
I discovered that there is a Scikit-Learn tutorial for tuning this ccp_alpha parameter for Decision Tree models.
The methodology described uses the cost_complexity_pruning_path method of the Decision Tree model. This section explains well how the method works. I understand that it seeks to find a sub-tree of the generated model that reduces overfitting, while using values of ccp_alpha determined by the cost_complexity_pruning_path method.
clf = DecisionTreeClassifier()
path = clf.cost_complexity_pruning_path(X_train, y_train)
ccp_alphas, impurities = path.ccp_alphas, path.impurities

However, I wonder why the Random Forest model type in Scikit-Learn does not implement these ccp_alpha selection and pruning concept.
Would it be possible to do this with a little tinkering?
It seems more logical to me than trying to find a good value by searching for hyperparameters (whatever one you use..)


text:
Q: Having issue setting up access token from policy in Vault I am setting up Hashicorp vault on my development environment in -dev mode and trying to use access token created from policies to access to secret which policy is created for but I get "*permission denied" while I try to access to secret from CLI or API. Based on Vault documentation it should work.
The following is what I have done to set up:

*

*Set up docker container using docker run --cap-add=IPC_LOCK -p 8200:8200 -e 'VAULT_DEV_ROOT_TOKEN_ID=roottoken' -v //c/confi
g:/config vault

*Connect to docker container using docker exec -it {docker name} ash. I know it should be bash command but bash doesn't work and ash works!

*After bashing to docker, export VAULT_ADDR='http://127.0.0.1:8200'

*Set the root token in environment variable export VAULT_TOKEN='roottoken'

*Create a secret vault secret/foo/bar value=secret

*Create a policy file called secret.hcl with the content path "secret/foo/*" {
policy = "read"
}

*Create a policy for the secret vault policy-write secret /config/secret.hcl and make sure the policy is created

*Create a token for the policy is just created vault token-create -policy="secret"

*Try to access the policy using API 'http://127.0.0.1:8200/v1/secret/foo' passing X-Vault-Token='token created in step 8' in header

*Getting "*permission denied" error

Would be great is someone can shed a light..


text:
Q: How to display a cell value corresponding to its input from another cell? I am using this kinda dataframe:
A  B  C  D  E
0  1  5  0  0
   2  3  1  0
   3  5  0  7
1  1  3  1  2
   3  3  3  3
2  5  1  2  1

If user input A = 0, B = 2, I need to show C = 3 D = 1 and E = 0 OR \n
If user input A = 1, B = 1, I need to show C = 3 D = 1 and E = 2

A: This is simple selection:
df.query('(A==0) & (B==1)')[['C', 'D', 'E']]


text:
Q: Show that $\sup \{f(x) + g(x) : x \in\ X\} \leq \sup \{f(x) : x \in\ X\} + \sup \{g(x) : x \in\ X\}$ Let $X$ be a nonempty set, and let $f$ and $g$ be defined on $X$ and ave bounded ranges in $\mathbb{R}$. Show that:
$$\sup \{f(x) + g(x) : x \in\ X\} \leq \sup \{f(x) : x \in\ X\} + \sup \{g(x) : x \in\ X\}$$

A: $$\begin{gathered}
  f\left( x \right) + g\left( x \right) \leqslant \sup \left\{ {f\left( x \right):x \in X} \right\} + \sup \left\{ {g\left( x \right):x \in X} \right\},\,\,\forall x \in X \hfill \\
   \Rightarrow \sup \left\{ {f\left( x \right) + g\left( x \right):x \in X} \right\} \leqslant \sup \left\{ {f\left( x \right):x \in X} \right\} + \sup \left\{ {g\left( x \right):x \in X} \right\} \hfill \\
   \Rightarrow \inf \left\{ {f\left( x \right) + g\left( x \right):x \in X} \right\} \leqslant \sup \left\{ {f\left( x \right):x \in X} \right\} + \sup \left\{ {g\left( x \right):x \in X} \right\} \hfill \\
\end{gathered} $$


text:
Q: Cannot read properties of undefined (reading 'map') in ReactNative I am trying to map through my string array, but I get the error:

TypeError: Cannot read properties of undefined (reading 'map')

function AmountOfChoicesListComponent() {
        const amountOfChoices = ['första', 'andra', 'tredje', 'fjärde', 'femte'];

        return (
            <View>
                {amountOfChoices.map((text) => (
                    <>
                    <Title>{text}</Title>
                    <ChoicesComponent />
                    </>
                ))}
            </View>
        );
    }

My array has a value from the beginning. I have tried to use a forEach instead but nothing shows on the screen. I have tried to make the variable into a useState and I get the same error.
When I log the array inside of a useEffect like so:
useEffect(() => {
        dispatch(firebaseAction.geDataFS(docName));
        console.log("MY ARRAYYYYYY: ", amountOfChoices)
    }, []);

my console.log shows my array. I have missed something very small, but I cant seem to understand why I get this error.

A: If you are loading the data asynchronously, you could always test amountOfChoices array to see if it exists and/or has length > 0 before rendering your markup.
If you just want to suppress the error on your first render, you could try changing your map to use the Optional Chaining operator: amountOfChoices?.map(...).


text:
Q: When I use an access token of Microsoft Graph, Access failed and response 400 error I trying to use Microsoft Graph on Java. I succeed to get an access token.
But, when I use this token via HttpURLConnection, my access has been denied and catched 400 error from microsoft server.
    HttpURLConnection con = null;
    String url_str = "https://graph.microsoft.com/v1.0/me";
    String bearer_token = "EwA4A8l6BA...";

    URL url = new URL(url_str);
    con = ( HttpURLConnection )url.openConnection();
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setRequestMethod("GET");
    con.setRequestProperty("Authorization","Bearer " + bearer_token);
    con.setRequestProperty("Host","graph.microsoft.com");
    con.connect();

    BufferedReader br = new BufferedReader(new InputStreamReader( con.getInputStream() )); // Error has been occured here.
    String str = null;
    String line;
    while((line = br.readLine()) != null){
        str += line;
    }
    System.out.println(str);

Here is error message.

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: https://graph.microsoft.com/v1.0/me

But, this access token acquired in Java,
It works normally when used with another program.
Here is my PowerShell source code.(I got the results as expected.)
$response = Invoke-RestMethod `
  -Uri ( "https://graph.microsoft.com/v1.0/me" ) `
  -Method Get `
  -Headers @{
      Authorization = "Bearer EwA4A8l6BA...";
  } `
  -ErrorAction Stop;

What is the cause of this? And how to fix it?

A: Sorry. I solved my problem by myself.
This problem has been occured that my server does not accept the json response.
So, I added an "Accept: application/json" in request header.
Therefore, this is correct source code.
    HttpURLConnection con = null;
    String url_str = "https://graph.microsoft.com/v1.0/me";
    String bearer_token = "EwA4A8l6BA...";

    URL url = new URL(url_str);
    con = ( HttpURLConnection )url.openConnection();
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setRequestMethod("GET");
    con.setRequestProperty("Authorization","Bearer " + bearer_token);
    con.setRequestProperty("Accept","application/json"); // I added this line.
    con.connect();

    BufferedReader br = new BufferedReader(new InputStreamReader( con.getInputStream() ));
    String str = null;
    String line;
    while((line = br.readLine()) != null){
        str += line;
    }
    System.out.println(str);

I hope this post helps someone.


text:
Q: Injectivity of integrals I am trying to show that
$$\int_0^\infty f_1(x) h_1(x) dx = \int_0^\infty f_2 (x) h_1(x) dx \\
\vdots\\
\int_0^\infty f_1(x) h_n(x) dx = \int_0^\infty f_2 (x) h_n(x) dx$$
if and only if $f_1(x) = f_2(x)$, $x \in \mathbb{R}^+$. I know that:

*

*$h_j(x)$ is a real continuous function such that $h_j(x) > 0$ on the interval $(0, a_j)$, where $a_j > b > 0$ for $j = 1,...,n$.

*$f_1(x)$ and $f_2(x)$ are real continuous functions such that $f_i(x) > 0$.

*$f_i(x) h(x) \leq M \exp(-c x), \, i =1,2$ for some $M,\,c \in \mathbb{R}$.

*$0 < \int_0^\infty f_i(x) h_j(x) dx < \infty, \, i = 1,2, \, j = 1,...,n$.

*$0 < \int_0^\infty f_i(x) dx < \infty, \, i = 1,2$.
Would anyone know if this result can possibly be shown? Thank you very much!

A: This seems hopeless without more constraints.  Set $a_j = 2\pi$ for all $j$ and you've transformed this into a problem about Fourier transforms.  We know the set of continuous functions cannot be spanned by a finite basis -- that is we can orthonormalize the $h_j$ and find entire subspaces of functions whose projections onto the $h_j$ all agree, but (would) disagree on extensions of this basis.


text:
Q: Multilayer perceptron with target variable as array instead of a single value I am new to deep learning and I have been trying to use the theano library to train my data. MLP tutorial here has a scalar output value while my use case has an array with a 1 corresponding to the value depicted in the output.
For example (assume the possible scalar values are 0,1,2,3,4,5),
0 = [1,0,0,0,0,0]
1 = [0,1,0,0,0,0]
2 = [0,0,1,0,0,0]

I have only modified the code to read my input and output (output now is a 2 dimensional array or matrix in the parlance of theano). Other parts of the code is as is from the MLP tutorial pasted above.

The error I am getting is in the following function
test_model = theano.function(inputs=[index],
            outputs=classifier.errors(y),
            givens={
                x: test_set_x[index * batch_size:(index + 1) * batch_size],
                y: test_set_y[index * batch_size:(index + 1) * batch_size]}) //line 286

Error stack:
  Traceback (most recent call last):
  File "mlp.py", line 398, in <module>
    test_mlp()
  File "mlp.py", line 286, in test_mlp
    y: test_set_y[index * batch_size:(index + 1) * batch_size]})
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/function.py", line 223, in function
    profile=profile)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.py", line 490, in pfunc
    no_default_updates=no_default_updates)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.py", line 241, in rebuild_collect_shared
    cloned_v = clone_v_get_shared_updates(outputs, copy_inputs_over)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.py", line 92, in clone_v_get_shared_updates
    clone_a(v.owner, copy_inputs_over)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.py", line 131, in clone_a
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.py", line 92, in clone_v_get_shared_updates
    clone_a(v.owner, copy_inputs_over)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.py", line 131, in clone_a
    clone_v_get_shared_updates(i, copy_inputs_over)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.py", line 92, in clone_v_get_shared_updates
    clone_a(v.owner, copy_inputs_over)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/pfunc.py", line 135, in clone_a
    strict=rebuild_strict)
  File "/usr/local/lib/python2.7/dist-packages/theano/gof/graph.py", line 213, in clone_with_new_inputs
    new_inputs[i] = curr.type.filter_variable(new)
  File "/usr/local/lib/python2.7/dist-packages/theano/tensor/type.py", line 205, in filter_variable
    self=self)

  TypeError: Cannot convert Type TensorType(int64, matrix) (of Variable Subtensor{int64:int64:}.0) into Type TensorType(int32, vector). You can try to manually convert Subtensor{int64:int64:}.0 into a TensorType(int32, vector).

I would like to know how to change this theano.function to accommodate the y value as a matrix.

A: You need to define y as T.imatrix() instead of T.lvector().