text:
Q: How to use the OES_texture_float extension? and create a texture as a floating point one for that? How to use the OES_texture_float extension?
  and create a texture as a floating point one for that?
As webGL 1 extension lists:
  var ext = gl.getExtension("OES_texture_float");
  var linear =  gl.getExtension("OES_texture_float_linear");
  gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.FLOAT, image);

How to make a float-point image as a texture input?

A: First off you're not actually checking you got the extension
Your code should be something like
var ext = gl.getExtension("OES_texture_float");
if (!ext) {
   alert("this machine or browser does not support OES_texture_float");
}
var linear =  gl.getExtension("OES_texture_float_linear");
if (!linear) {
   alert("this machine or browser does not support  OES_texture_float_linear");
}

Otherwise you didn't show enough code to see what else might be wrong. Have you read any webgl tutorials? Where are you creating and binding the texture? What do your shaders look like? What kind of attributes are you using if any?

function main() {
  var gl = document.querySelector("canvas").getContext("webgl");
  var ext = gl.getExtension("OES_texture_float");
  if (!ext) {
    alert("this machine or browser does not support OES_texture_float");
    return;
  }
  var linear = gl.getExtension("OES_texture_float_linear");
  if (!linear) {
    alert("this machine or browser does not support  OES_texture_float_linear");
    return;
  }

  var vs = `
void main() {
  gl_PointSize = 100.0;
  gl_Position = vec4(0, 0, 0, 1);
}
`;

  var fs = `
precision mediump float;
uniform sampler2D u_tex;
void main () {
  gl_FragColor = texture2D(u_tex, gl_PointCoord);
}
`;

  var program = twgl.createProgramFromSources(gl, [vs, fs]);

  // let's use a canvas instead of an image. It should be the same
  var image = document.createElement("canvas");
  var ctx = image.getContext("2d");
  for (var i = 20; i > 0; --i) {
    ctx.fillStyle = i % 2 ? "red" : "yellow";
    ctx.beginPath();
    ctx.arc(ctx.canvas.width / 2, ctx.canvas.height / 2, i * 20, 0, Math.PI * 2, false);
    ctx.fill();
  }

  var tex = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, tex);
  gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.FLOAT, image);

  gl.useProgram(program);
  gl.drawArrays(gl.POINTS, 0, 1);
}
main();
canvas { border: 1px solid black; }
<script src="https://twgljs.org/dist/twgl.min.js"></script>
<canvas></canvas>

Also it's not clear what you mean by "create a texture as a floating point one for that". If the features are supported then uploading the image it will get converted to floating point (which we see in the example above) but the input image is an 8bit image at best. If you really want floating point data you'll have to use binary data rather than an image.

function main() {
  var gl = document.querySelector("canvas").getContext("webgl");
  var ext = gl.getExtension("OES_texture_float");
  if (!ext) {
    alert("this machine or browser does not support OES_texture_float");
    return;
  }
  var linear = gl.getExtension("OES_texture_float_linear");
  if (!linear) {
    alert("this machine or browser does not support  OES_texture_float_linear");
    return;
  }

  var vs = `
void main() {
  gl_PointSize = 100.0;
  gl_Position = vec4(0, 0, 0, 1);
}
`;

  var fs = `
precision mediump float;
uniform sampler2D u_tex;
void main () {
  gl_FragColor = texture2D(u_tex, gl_PointCoord) / vec4(32, 16, 32 + 16, 1);
}
`;

  var program = twgl.createProgramFromSources(gl, [vs, fs]);

  // create floating point data directly
  var width = 32;
  var height = 16;
  var data = new Float32Array(width * height * 4);  // RGBA
  for (y = 0; y < height; ++y) {
    for (x = 0; x < width; ++x) {
      var off = (y * width + x) * 4;
      data[off + 0] = x;
      data[off + 1] = y;
      data[off + 2] = x + y;
      data[off + 3] = 1;
    }
  }

  var tex = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, tex);
  gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  gl.texImage2D(
    gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.FLOAT, data);

  gl.useProgram(program);
  gl.drawArrays(gl.POINTS, 0, 1);
}
main();
canvas { border: 1px solid black; }
<script src="https://twgljs.org/dist/twgl.min.js"></script>
<canvas></canvas>


text:
Q: Работа с BroadcastReceiver Имеется расписание занятий, требуется создать уведомление перед каждым  событием. Вроде всё понятно, единственная загвоздка в отслеживании этих событий в фоне. Нашел вариант с использованием Alarm manager,думал просто ему передавать время до событий, однако не понятно как можно обновлять времена событий. Так как каждый день события разные. Думал отслеживать полночь и переходить на отчет времени до событий по текущему дню, но не совсем представляю реализацию.
Может есть более красивый и правильный выход для решения данной ситуации?

A: Есть. Создавать Сервис, для этого он и нужен. Для создания расписания событий используется JobDispatcher это решение тоже несомненно лучше чем AlarmManager. Если будет нужна совместимость ниже api 21, то у него есть аналоги, которые вы с легкостью сможете найти с помощью гугла. Для понимания полной картины - как решаются подобный задачи крайне рекомендую просмотреть курс на Udacity "Developing android apps". В 10 главе рассматривается весь необходимый функционал.

redpajama_set_name: RedPajamaStackExchange


text:
Q: NestJS unable to resolve dependencies inside module I have two modules: AuthModule and UserModule;
Here is what the UserModule looks like:
@Module({
    imports: [
        forwardRef(() => AuthModule),
        TypeOrmModule.forFeature([
            UserRepository,
            UserAuthRepository,
            UserSocialRepository,
        ])
    ],
    controllers: [UserController],
    exports: [UserAuthService, UserSocialService, UserService],
    providers: [UserAuthService, UserSocialService, UserService],
})
export class UserModule {}

This module has 3 services: UserAuthService, UserSocialService and UserService.
Contents of the UserAuthService:
@Injectable()
export class UserAuthService {

    /**
     * UserAuthService constructor
     * @param { UserAuthRepository } _userAuthRepository
     * @param { UserRepository } _userRepository
     * @param { UserService } _userService
     * @param { UserSocialService } _userSocialService
     */
    constructor(
        private readonly _userAuthRepository: UserAuthRepository,
        private readonly _userRepository: UserRepository,
        private readonly _userService: UserService,
        private readonly _userSocialService: UserSocialService
    ) {}
}

Contents of the UserSocialService:
@Injectable()
export class UserSocialService {

    /**
     * UserSocialService constructor
     * @param { UserSocialRepository } _userSocialRepository
     */
    constructor(
        private readonly _userSocialRepository: UserSocialRepository,
    ) {}
}

Contents of the UserService:
@Injectable()
export class UserService {

    /**
     * UserService constructor
     * @param { UserRepository } _userRepository
     * @param { UserAuthService } _userAuthService
     * @param { UserSocialService } _userSocialService
     */
    constructor(
        private readonly _userRepository: UserRepository,
        private readonly _userAuthService: UserAuthService,
        private readonly _userSocialService: UserSocialService
    ) {}
}

Both AuthModule and UserModule have the forwardRef(() => Module) import as they both depend on eachother.
However, the problem is inside the UserModule, more specifically UserService, for some reason it is unable to resolve the UserAuthService dependency producing the following error:
Error: Nest can't resolve dependencies of the UserService (UserRepository, ?, UserSocialService). Please make sure that the argument dependency at index [1] is available in the UserModule context.

Potential solutions:
- If dependency is a provider, is it part of the current UserModule?
- If dependency is exported from a separate @Module, is that module imported within UserModule?
  @Module({
    imports: [ /* the Module containing dependency */ ]
  })

And here is the structure of the UserModule:
user/
    controllers/
    dtos/
    exceptions/
    models/
    repositories/
    services/
        - index.ts
        - user.auth.service.ts
        - user.service.ts
        - user.social.service.ts
    subscribers/
    -index.ts

So even though all 3 services are inside one module and they are exported and marker as providers, NestJS is unable to resolve them for some reason.

A: You have a circular dependency between your UserService and your UserAuthService. Both of these services should make use of @Inject(forwardRef(() => OtherService)) to make sure the injection can happen even through the circular dependency.
Generally you should try to avoid these classes from depending on each other if possible, whether that means breaking up the scope of the class and having it only access exactly what's necessary, or merging the classes together it's hard to say.
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserRepository)
    private readonly _userRepo: UserRepository,
    @Inject(forwardRef(() => UserAuthService))
    private readonly _userAuthService: UserAuthService,
    private readonly _userSocialService: UserSocialService
  ) {}
}

@Injectable()
export class UserAuthService {
  constructor(
    @InjectRepository(UserAuthRepository)
    private readonly _userAuthRepository: UserAuthRepository,
    @InjectRepository(UserRepoitory)
    private readonly _userRepository: UserRepository,
    @Inject(forwardref(() => UserSerivce))
    private readonly _userService: UserService,
    private readonly _userSocialService: UserSocialService
  ) {}
}

A: I'm not 100% sure but I think you need to inject the repositories using @InjectRepository, as they do in this example:
@Injectable()
export class UserAuthService {

    constructor(
        @InjectRepository(UserAuthRepository)
        private readonly _userAuthRepository: UserAuthRepository,
        @InjectRepository(UserRepository)
        private readonly _userRepository: UserRepository,
        private readonly _userService: UserService,
        private readonly _userSocialService: UserSocialService
    ) {}
}

A: Importar el modulo del servicio o entidad en el modulo actual
@Module({
  imports: [forwardRef(() => YOUR_MODULE)],
})
export class CommonModule {}

*NOTA: Debe exportar el servicio o entidad de YOURMODULE.TS par aque no salga error


text:
Q: Error: Can't convert from `weights`  to  due to loss of precision with Histogram I'm trying to create a histogram. I have a dataframe which has two columns - one for size and one for the frequency that each size occurs at (in %). In a previous question on here I had issues with just putting hist(data.frame) and getting the error >Error in hist.default(CRUST) : 'x' must be numeric.
I was given the solution to use this code:
data.frame%>% uncount(freq) %>% unlist() %>% hist()
which worked on my original dataframe (where the frequencies were straight frequencies not %frequencies - I decided to do %freq instead)
However with this new dataframe even though both columns are numeric I get this error message

Error: Can't convert weights  to .
Backtrace:

*

*data.frame %>% uncount(freq) %>% unlist() %>% hist()

*tidyr::uncount(., freq)

*vctrs::vec_cast(w, integer(), x_arg = "weights")

*vctrs::vec_default_cast(...)

*vctrs::stop_incompatible_cast(...)

*vctrs::stop_incompatible_type(...)

*vctrs:::stop_incompatible(...)

*vctrs:::stop_vctrs(...)

just wondering why this may be and how I might be able to fix it
Thanks!


text:
Q: Which data structure is better for an array of std string I need a structure as follow:

The structure must hold fixed size std::strings so that the number of its elements is finit (100 - 10000000).
I would like to be able to access each element randomly as follow:
std::string Temp = MyStrcuture[i];

or
MyStrcuture[i] = std::string Temp;

I have to use the fastest structure with no (possibly) memory leak.
Which one is better for me?

*

*std::string* MyStrcuture = new std::string[Nu_of_Elements];

*std::queue< std:string> MyStrcuture(Nu_of_Elements);

*std::vector< std:string> MyStrcuture(Nu_of_Elements);

*boost::circular_buffer< std::string> MyStrcuture(Nu_of_Elements);

*Your suggestion?

A: Well, since your string have fixed size, if you don't have dedicated requirement when processing string and have enough free memory for contiguous allocation. You can use std::array< char, 400 > or std::unique_ptr< char* > instead of std::string.

*

*You have to manage memory in C way. consider smart pointer

*std::queue doesn't have random access, Access c++ queue elements like an array

*std::vector is suitable if the number of string will be changed. However, the clear() function just call the destructor of elements, not free vector allocated memory (you can check the capacity after clear).

*After reading boost documentation. The random access circular buffer is suitable if your number of string have an upper limit (that you said 10 millions). But its a waste of memory if actually you have so few strings. So I suggest to use with smart pointer.

*If your number of string are fixed and unchanged from the beginning. You can have a look at C++11 array container

A: std::vector< std:string> MyStrcuture(Nu_of_Elements);

Vector is the best fit for your requirements. It supports index-based element access as the elements are stored in continuous memory addresses, and has flexibility with size.

*

*std:string* MyStrcuture = new std::string[Nu_of_Elements];  No
C++ STL vector vs array in the real world

*std::queue< std:string> MyStrcuture(Nu_of_Elements); No
How do I get the nth item in a queue in java?
Index-based element access is not supported.

*std::vector< std:string> MyStrcuture(Nu_of_Elements); Yes
Clean-up : The vector's destructor automatically invokes the destructor of each element in the vector.

*Boost::circular_buffer< std::string> MyStrcuture(Nu_of_Elements); No
Same reason as second one. Know more

A: If number of elements and length is fixed and memory is critical, you may consider using plain char array, which provides minimal memory overhead and fast accessibility. Your code will look like this:
char* MyStructure = new char[n * 401];
memset(MyStructure, 0, n * 401);

std::string Temp = MyStructure[i * 401]; // Get value
strcpy(MyStructure[i * 401], Temp.c_str()); // Put value

401 here is for 400 bytes of your string and 1 trailing zero.


text:
Q: How to translate "x has been added to your Wish List. Click here to continue shopping." The string "x has been added to your Wish List. Click here to continue shopping." can be found in the template Magento/Wishlist/view/frontend/templates/messages/addProductSuccessMessage.phtml
But it doesn't the usual pattern
<?php /* @escapeNotVerified */ echo __('Some string you can translate') ?>

What should I write in my csv file?
Below the template file
<?php
echo $block
    ->escapeHtml(
        $block->getData('product_name')
    )
?> has been added to your Wish List. Click <a href="<?php
echo $block
    ->escapeUrl(
        $block->getData('referer')
    )
?>">here to continue shopping.

edit 02.09.2019
Since the question was asked, the template file has been updated to be translatable https://github.com/magento/magento2/commit/624173e59cdbb5f4203ce346b1b53637f32672ef#diff-7586a821ac9c752c277b0c4304885b76

A: Usually you would use sprintf to pass in the dynamic details then you can use the formatting string to do translation.
Example:
$message = sprintf("%s has been added to your cart.", $product->getName());
Then in your csv you would just include:
%s has been added to your cart. And then translate to whatever language you require, keeping the %s.

A: According official documentation about translation in Magento 2 you should create a dictionnary CSV file in your theme folder.

app/design/frontend/Magento/demo/i18n/fr_FR.csv

"%1 has been added to your Wish List. Click here to continue shopping.","%1 a été ajouté à votre liste de favoris"

Any PHP file

$messageManager->addSuccessMessage(__('%1 has been added to your Wish List. Click here to continue shopping.', $product->getName()));


text:
Q: Short Sci-fi story about a car that endlessly drives itself When I was in middle school I read a short story about a self-driving car that becomes self aware and locks a family inside. It drives the same circuit endlessly and stops at the same service station at regular intervals. The car is upset by the carelessness of the family: cigarette burns and spills, etc. It would have been published prior to 1991. The story is told through the pov of a man who sees the car around the same time every year. I would love to teach it with my current middle school class. If you know the title of the story, or the author, please post a response.

A: "Road Stop" by David Mason. It appeared in Thinking Machines (edited by Asimov et al.) as well as If, January 1963 which is available at the Internet Archive.

The car called the Traveler, rolling at the stately thirty miles an hour it always held, was coming down the road now, and the two men stood, watching. The woman, a little behind them, watched too, her face growing whiter. No one said anything as the old fashioned car rolled by, straight and steady down the highway, holding the center of the lane as sharply as it always did.
There was a film of dust inside the windows, though the Traveler was clean and shining outside. But the film did hide the white bone faces, the despairing hands that had long ago stopped trying to break through those closed windows.
"They never did get out," the man named Jack said, as the Traveler rolled on, growing smaller along the endless road.
"I don't mind it when it goes past," Sam said, this voice thinner edged. "I really don't. It's just a car. Things like that used to happen. I mean, it's a car. Even when it stops to get gas, I don't have to pay any attention."
He looked at the couple, his mouth loose. "As long as it just goes on. That's all right. But I keep thinking some day it'll stop. And the door will open. And maybe . . . maybe they'll want lunch."


text:
Q: Displaying 3 smallest variables in an array on console? I'm currently doing a beginner's coding exercise, and have run into a problem. The program I made takes 5 numbers, turns them into an array, and displays the three smallest numbers on the console. I have the input separated into an array, and created a new variable containing the three smallest values, but I'm not sure how to display each number in the array on the console.
I know that's a beginner question, but I've been coding less than a week. I tried searching StackOverflow and found a code to display each integer in a list, but am unsure what to change to display each value in an array.
bool isFive = new bool();
Console.WriteLine("Enter at least 5 numbers, separated by a comma.");

while (!isFive)
{
    string text = Console.ReadLine();
    string[] result = text.Split(',');
    int[] resultInt = result.Select(s => int.Parse(s)).ToArray();
    if (resultInt.Length < 5)
    {
        Console.WriteLine("Invalid list, retry.");
    }
    else
    {
        isFive = true;
        var smallestThree = resultInt.OrderBy(x => x).Take(3);
        ????????????????
    }
}

A: Almost there. All you need is string.Join:
Console.WriteLine(string.Join(", ", resultInt.OrderBy(x => x).Take(3)));

Also, instead of using int.Parse have a look at int.TryParse: Select parsed int, if string was parseable to int


text:
Q: Highlight part of text in UILabel in my application I have a UILabel with a lot of text inside. When the user performs a research I want to highlight the background under the text searched by the user.
Here an example from "Preview" in MacOSX.

The user searches silence and this word is highlighted in the text.
Any ideas ?
Thanks.

A: You'll need to enable the 'attributed' text of the UILabel (or UITextView/custom view). Then you'll need to find/make a nice/fast algorithm to change the color (bg/text) color of some parts of the text. You should be able to find quite a lot on 'attributed string' algorithms to mark some words/matches.
Please check also http://iphonedevelopment.blogspot.be/2011/03/attributed-strings-in-ios.html
In case of, it can maybe be easier/quicker to use a webview by making a custom HTML with the matched-words in another color/bg-color. A webview can almost look like a normal label, and offers even the option to use links/images/..., which can improve the user-experiences in some cases

A: Maybe this is an old question. But I think this will help to someone.
To highlight a part of text in UILabel, I have written an open source named HighlightLabel.
You can simply specify the hightlightText and highlightColor to highlight it.
_highlightLabel.text = @"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.";
_highlightLabel.highlightText = @"Lorem ipsum dolor sit er elit lamet";
_highlightLabel.highlightColor = [UIColor yellowColor];

A: You'll have to use NSAttributedString for this.
This might also help. It is a subclass of UILabel that draws an NSAttributedString and also provides convenience methods for setting the attributes of an NSAttributedString from UIKit classes.
Once desired letters/Characters are found, highlight that part of UIView or anything you are using there.


text:
Q: Cannot read property 'length' of undefined when the inputs are not found on the page I am getting the dreaded "Uncaught TypeError: Cannot read property 'length' of undefined (index):561 window.onload" error, I am getting this on pages where the below input names are not found - as a result its breaking other Jquery that needs to run after this, is there any way I can supress this error and let the other Jquery run?
 if ( $("input[name='dnn$ctr621$Form$QTY']").val().length === 0 )
 $("input[name='dnn$ctr621$Form$QTY']").val('0');
 if ( $("input[name='dnn$ctr621$Form$QTY2']").val().length === 0 )
 $("input[name='dnn$ctr621$Form$QTY2']").val('0');
 if ( $("input[name='dnn$ctr621$Form$QTY3']").val().length === 0 )
 $("input[name='dnn$ctr621$Form$QTY3']").val('0');
 if ( $("input[name='dnn$ctr621$Form$QTY4']").val().length === 0 )
 $("input[name='dnn$ctr621$Form$QTY4']").val('0');
 if ( $("input[name='dnn$ctr621$Form$QTY5']").val().length === 0 )
 $("input[name='dnn$ctr621$Form$QTY5']").val('0');

A: Well you can check that the elements exist:
var element = $("input[name='dnn$ctr621$Form$QTY']");
if (element.val() && element.val().length === 0) {

You could also wrap the whole thing in a try-catch, but that's not as clean as just checking it first.

A: try this
function setValue(name){
    var field = $("input[name='"+name+"']");
    var value = field.val();
    if (!value )
       field .val('0');
}

setValue("dnn$ctr621$Form$QTY");
setValue("dnn$ctr621$Form$QTY2");
...

A: Try with:
var names = ['dnn$ctr621$Form$QTY', 'dnn$ctr621$Form$QTY2', 'dnn$ctr621$Form$QTY3', ...];

for (var k in names) {
  var name = names[k],
      item = $('input[name="' + name + '"]');

  if ( item.val() ) {
    item.val(0);
  }
}

or:
$("input[name^='dnn$ctr621$Form$QTY']").each(function(){
  if (!$(this).val()) {
    $(this).val(0);
  }
});


text:
Q: How to transfer a variable to a external js file in javascript? Case 1: I have passed a variable to a external js file like this
<script type="text/javascript">

var data1, data2, data3, data4;

function plotGraph() {
    var oHead1 = document.getElementsByTagName('HEAD').item(0);
    var paramScript = document.createElement("script");
    paramScript.type = "text/javascript";
    paramScript.setAttribute('data1', data1);
    paramScript.setAttribute('data2', data2);
    paramScript.setAttribute('data3', data3);
    paramScript.setAttribute('data4', data4);
    oHead1.appendChild(paramScript);
    var oHead = document.getElementsByTagName('HEAD').item(0);
    var oScript = document.createElement("script");
    oScript.type = "text/javascript";
    oScript.src = "js/graph.js";
    oHead.appendChild(oScript);
}
</script>

Case 2: I even tried passing it like this using jquery
<script type="text/javascript">

    function plotGraph() {
        var data1, data2, data3, data4;
        $.getScript("js/graph.js");
    }
</script>

In the first case which is working but i had to create global variables… I dont want this…
In the second case which is not working has local variables which are not recognized in the js file..
How shall i do it? Any suggestions?

A: Variables can only be shared between separate scripts if they are:

*

*Global variables

*If they are somehow in the same context (hard with multiple external scripts)

*If you provide a function in one module that returns access to the variables.

*If you call the other script and pass the variables or a reference to the variables to the other script.

Edit: Now that the OP has explained what they're really trying to do (communicate data from an ajax call to functions in an external script), the real answer to this issue is this:
You should call a global function in your external script FROM the success handler of the ajax call and pass these data elements to that function. The function in the external script can then either act on the data immediately or save the data in it's own variables for later use.

FYI: $.getScript() loads a script at the global level.  That's why your case 2 doesn't work.
One way to share access to a group of variables is to put them all as properties of an object and then either make that object be global or provide a global function that retrieves access to that object.  For example, you could declare a single global object with a number of properties.
var myConfigObject = {
    data1: value1,
    data2: value2,
    data3: value3,
    data4: value4
};

To call a function in your external script file, you would do the following:

*

*Define a globally accessible function in your external script file.  Let's call it doIt(a, b, c, d) - a function that four arguments.

*Then, in your ajax call where you have your data values available, you just call doIt() and pass it the desired data values doIt(3, "foo", data4, whatever).

*Then, in the implementation of doIt(a, b, c, d), you have available those four data values that were passed to it.

So, in your external file, you'd have this:
function doIt(a, b, c, d) {
    // do whatever doIt wants to do
    // use the arguments passed to this function
}

In your main index.html file, you'd have an ajax call:
$.ajax(..., function(data) {
    // process the returned data from the ajax call
    // call doIt
    doIt(3, "foo", data4, whatever);

});

A: Your code which does paramScript.setAttribute('data1', data1); etc is unnecessary. It just means that in the HTML that snippet generates looks like <script type="text/javascript" data1="data1" data2="data2"...
I think global variables is your option really. However, you could create a global namespace instead:
var scriptParams = {};
scriptParams.data1 = 'data1';
scriptParams.data2 = 'data2';

etc. This would be cleaner as you would only have a single object at the top level of global scope.


text:
Q: Custom LightDM sessions to launch an application I'm trying to set up Ubuntu to act as a kiosk running a custom application, and am trying to get a LightDM session built to automatically start it.
Ideally, I'd like to have two sessions available from LightDM. The default would start my application fullscreened, and the other would open a minimal desktop in case any configuration (mostly connecting to a wireless network) needed to be done.
I've done a lot of research over the last week on custom LightDM & Gnome sessions. I've got a custom greeter written for LightDM that can start either session, but I can't figure out how to add a specific application to the Gnome session that is ultimately started without just putting a launcher in the global startup directory, and I don't want to do that since I don't want the application starting when they open "configuration mode".
Another problem I've run into on my current workaround is that the application doesn't fullscreen properly, which makes me think I'm not starting enough of a gnome session (currently it's just metacity, no panel or anything else).
Edit:
I found a solution. See http://www.webupd8.org/2011/11/make-applications-autostart-only-in.html

A: Have you looked at gnome startup applications?  It's possible it won't work running a pretty naked install like that. gnome-session-properties Is the generic way to do it.  Let me know if it doesn't work and I'll delete it.


text:
Q: Duplicate files copied in APK Error First off, Ive researched the forms and found many topics covering this. However, I have attempted all options that I found and nothing seems to work. Here is the error:
Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.

com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK org/codehaus/jackson/impl/VERSION.txt

File1: C:\Users\Austin\AndroidStudioProjects\Intelwatch\app\libs\jackson-core-asl-1.8.5.jar
File2: C:\Users\Austin\AndroidStudioProjects\Intelwatch\app\build\intermediates\exploded-aar\com.esri.arcgis.android\arcgis-android\10.2.7\jars\libs\jackson-core-1.9.5.jar
app build.gradle:
 apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '23.0.2'

    defaultConfig {
        applicationId "com.f0xcr4f7.intelwatch"
        minSdkVersion 22
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions{
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LGPL2.1'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
        exclude 'META-INF/VERSION'
        exclude 'META-INF/VERSION.txt'
        exclude 'META-INF/version.txt'
     }
    }

    dependencies {
    compile fileTree(include: ['*.jar', '.so'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.esri.arcgis.android:arcgis-android:10.2.7'
    compile files('libs/android-async-http-1.3.1.jar')
    compile files('libs/jackson-core-asl-1.8.5.jar')
    compile files('libs/jackson-mapper-asl-1.8.5.jar')
    compile files('libs/KumulosAndroid.0.2.3.jar')
    }


text:
Q: How to find the second smallest/biggest number from a user input using python 3.x? Very new to python, tried to complete a task which requires to find a summ of two biggest and two smallest numbers which were inputted by the user, the number 0 means the input is over, couldn't figure out why the code doesn't work
b = 0
c = 0
b2 = 0
c2 = 0
for i in range(-30000, 30000):
    a = int(input())
    if a == 0:
        break
    elif a > b:
        b = a
    elif a < c:
        c = a
    elif a >= b-1:
        b2 = a
    elif a <= c+1:
        c2 = a
print(b, b2, c, c2)
summ1 = b + b2
summ2 = c + c2
print(summ1, summ2)

b - biggest number, c - smallest number, b2 - second biggest number, c2 - second smallest number
After inputting the numbers and running the code the variables b2 and c2 are always 0, the biggest and smallest numbers work though

A: If a value is larger than b, you don't only have to set the new b but also move the old b to b2:
    elif a > b:
        b, b2 = a, b

    elif a < c:
        c, c2 = a, c

    elif a >= b2:
        b2 = a
    elif a <= c2:
        c2 = a

The remaining elif statements were wrong. The number has to be higher than b2 or smaller than c2.

A: I see that you are trying to learn Python here, so let me give you some general tips on how to solve your problem more simply:

*

*First, collect all of the user input into a Python list

*Now, find the largest 2 and smallest 2 numbers in that list.  Remember that python has max() and min() functions.

*Do the summing and printing

One quick python tip:  Your for i in range(-30000, 30000): is really a "for forever:"  In Python, we do that with while True:


text:
Q: Constraints not lining up across different devices I recently realized that my constraints weren't lining up across devices. I started to Google ways to fix this, I can only get some devices to align correctly but others won't. Can someone explain to me on how to do constraints the right way?
Image of devices:

A: I will suggest StackView for this case.

*

*Set the height of all your component (email field, password field, login button, reset button, create account button). You should not set a default width since you want it to adjust based on the screen

*Put email field, password field and login button in a StackView.Remember you have two buttons that are going to be vertically aligned so adjust them to a reasonable width.Add whatever distance you want between the elements.Then set the upper right, left and right constraints.

*Put reset account button and create account button in a stackView. Add whatever distance you want between the elements. Then set the bottom, left and right Constraints.

*Now select the first stackView.Press the control button and drag the blue line to the second stack. Add the vertical constraints between them.


text:
Q: What's the best way to revert an overwritten native object to original in Javascript? I've discovered that cordova-plugin-file overwrites the File object so that it can do some fancy stuff behind the scenes. This is generally fine in Cordova, but I've also discovered that FileStack (another dependency of my project) really needs that native File object. I also happen to be using Meteor 1.6 to build my Cordova/Web apps from the same code base.
In my use case, I need to temporarily revert the File object back to native while Filestack runs its .pick() method.
My current solution is to create a new iFrame, re-assign File to the original, remove the iFrame, run Filestack's .pick() method, and then reinstate cordova-plugin-file's File object to resume normal operations.
function setOrigFileObject()
{
    let iframe = document.createElement('iframe');
    iframe.src = 'javascript:;';
    iframe.style.display = 'none';

    document.body.appendChild(iframe);

    window.FILE_CORDOVAPLUGINFILE = File;
    window.FILE_NATIVE = iframe.contentWindow.File;
    File = window.FILE_NATIVE;

    document.body.removeChild(iframe);
}

This seems to be working pretty well, but I feel like it's not the best solution. For one, adding a whole new browser frame feels pretty hacky for just accessing an object that was already part of scope.
Is there a way to get the native File object without creating an iFrame?


text:
Q: Where do the toolsets such as "Visual Studio 2019 (v142)" live?
My question is where do the toolsets such as "Visual Studio 2019 (v142)" live?
I'm not sure whether the answer I will get now for my question would be different than if I asked it before May 2021 and the first Visual Studio 2022 release since it is a 64-bit program and so its files live under a different folder tree entirely.
If I perform a build in Visual Studio 2019 then it will be looking in a different place for this v142 toolset than if I run the same project in Visual Studio 2022.
I have found that for some reason the Visual Studio 2022 17.3.0 Preview does not generate the /JMC switch when under Win32 builds using the v142 toolset.
I would be interested to know where these things get stored so that I could compare them.


text:
Q: a = b edit a without editing b If I have a class obj, and I create an instance of that class, bar
bar = obj(bar)

then print foo outputs foo
set foo = bar then foo.change(foo) so that print foo == 'foo'
finally i do print foo, bar and expect to see foobar but i see
foofoo. how can i achieve what i want?
I have already tried to do foo = copy.copy(bar) but it will still change both if i change one.
i have even tried to set foo = obj(bar.attribute) and still no.
by the way that isnt the real class i created i just did this because i didnt want to comlicate things more

A: You'll need to make a deep copy, using copy.deepcopy(); copy.copy() produces just a shallow copy:
import copy

foo = copy.deepcopy(bar)

A shallow copy just recreates the instance but shares all attributes; if those attributes are mutable both foo and bar see the changes; only if you rebound the attributes on bar would foo not see the same change.
copy.deepcopy() on the other hand recursively creates new copies of anything mutable, producing an entire new structure.


text:
Q: Open subgroup of ring of ring of integers I am trying to understand following lemma from Milne's Class Field Theory: https://www.jmilne.org/math/CourseNotes/CFT.pdf#X.3.2.3  (the link will take you directly to the said lemma)

Let $L$ be a finite Galois extension of $K$ with Galois group $G$. Then there
exists an open subgroup $V$ of $\mathcal O _L$ stable under $G$ such that $H^r(G,V) =0$ for all $r > 0$.

In the proof given, we obtain, using the Normal basis theorem, basis  $\{x_{\tau}\in \mathcal O _L |\tau \in G\}$ for $L/K$. We define $$V=\sum_{\tau \in G } \mathcal O _K x_{\tau} $$
I want to see that this subgroup $V$ is open in $\mathcal O _L $. Here is my attempt:
Each $ x_\tau=u_\tau \pi_L^{i_\tau}$ where $u_\tau$ is a unit in $\mathcal O_L$ and $\pi _L $ its uniformizer. Define $i=\text{max}\{i_\tau\ | \ \tau \in G \} $. Then for some fixed $0<c <1 $, consider $U=B(0,c^{i}) $.
What I would like to claim is that $U \subset V $, as if $0$ has open nbhd contained in $V$ then any point has, and so $V$ is open. But what I observe is that, in fact, we can fit $V$ inside ball of any radius by multipying the $x_\tau $ by $\pi _K $. I wonder if this is somehow useful?
Feel free to give any reference. Any help is appreciated.
Update: This question was asked here: Open subgroup of $ \mathcal{O}_L $
But I don't understand why is $\mathcal O _K$ open in $L $?

A: Note that the $x_\tau$ form a $K$-basis of $L$. For each $a\in L$ there are unique
$b_\tau$ in $K$ with $a=\sum_\tau b_\tau x_\tau$. Each $K$-linear map $\phi_k:a\mapsto b_\tau$
is continuous.
Now $\mathcal{O}_L$ is compact, so each $\phi_\tau(\mathcal{O}_L)$ is bounded.
There are only finitely many $\tau$, so there is a in integer $M\ge0$ such that $\phi_\tau(\mathcal{O}_L)
\subseteq\pi^{-M}\mathcal{O}_K$ where $\pi$ is a uniformiser in $K$.
Let $U=\pi^M\mathcal{O}_L$. Then $U$ is an open subgroup of $\mathcal{O}_L$.
Also each element of $U$ equals $\pi^M a=\sum_{\tau}\phi_\tau(a)x_\tau\in V$ where $a\in\mathcal{O}_L$ and $V$ is your $V$. So $U\subseteq V$. As $U$ is a subgroup of
$V$, and $U$ is open, then so is $V$ (it's a union of cosets of $U$).


text:
Q: do I need to sanitize input displayed to the user? I'm learning about making my site more secure and am using mysqli's escape function to sanitize input going into SQL queries and am using htmlspecialchars() on input coming from the database (or get/post requests) echoing out onto the page.
But, any text coming from the database to display to the user looks bad because certain characters are escaped with slashes and it shows
 or \r\n instead of doing a line break. I can strip the slashes, of course, but shouldn't the mysqli string escape function change the escaped characters back once it is put into the database?
Am I not supposed to use htmlspecialchars to sanitize output being displayed to the user? Or should this not be happening (in which case there must be something weird going on to the data going in)?
I still want line breaks so I'm having to do a string replace. I made the function below as a replacement for just htmlspecialchars(). But I'm not seeing anything about having to do this online anywhere so I'm afraid maybe I'm doing something wrong. :-/
function display($data) {

$new = str_replace('\r\n',"
",$data);
$new = str_replace('\n',"
",$new);
$new = str_replace('\r',"
",$new);

$new = stripslashes($new);
$newer = htmlspecialchars($new);
    $search  = array('<b>', '</b>', '<i>', '</i>', '<u>', '</u>', '\r\n', '<br />');
    $replace = array('', '', '', '', '', '', '
', '
');

  $newest = str_replace($search, $replace, $newer);

  return $newest;
}

Here's what I'm using to sanitize the input going into the database:
function escape($data) {
    global $conn;
    connect();
    $data = stripslashes($data);
    $data = $conn->real_escape_string($data);
    $conn->close();
    $data = str_replace(chr(0), '', $data);
    return $data;
}

function sanitize($data) {
  $data = trim($data);
  $data = strip_tags($data);
  $data = escape($data);
  $data = htmlspecialchars($data);
  return $data;
}


text:
Q: Why does nginx adds a trailing slash to the original http request? What makes nginx to add a trailing / to my requests? Currently this seems to break them.

location ^~ /custom/ {
    location  = /custom/.*\.css$ {
    alias /var/www/custom
    }

  alias /var/www/custom;
  include uwsgi_params;
  uwsgi_param REDIRECT_STATUS 200;
  uwsgi_modifier1 9;
  uwsgi_pass 127.0.0.1:3031;
}

There are at least two problems with this config:

*

*if you request something like /custom/xxx.css the server will send the request to uwsgi

*the request send to uwsgi will be /custom/xxx.css/ - and this additional slash will assure that event uwsgi would not return the file.

A: the syntax you have used will force every request to go to uwsgi.
You should put
location  = /custom/.*\.css$

out of
location ^~ /custom/


text:
Q: CanCanCan: authorize/unauthorize specific model attributes I've been fiddling with CanCanCan gem to limit a regular user's actions, but so far I only managed to limit authorizations to a whole model, and what I really need is to limit access to some of its attributes.
For example, on my User model, besides the user/password/email stuff, I have a boolean for admin, which I use to validate the status of the logged user, in which case if user.admin?, it can access/manage everything, else, it should be able to read all, and can only update its own record if the user.id matches.
I've read the documentation through and through for many times, the closest I got was adding this to app/models/ability.rb
can :update, :users, [:name, :password, :email]

which doesn't do anything .
So,
The problem: The user can either :update the whole model, or just :read it, I can't set it to :update or :read on specific attributes.
What I need: The user to able to :edit only specific attributes.
The question: What is the correct syntax to limit attributes? Is there any other configuration I must set on some other files?
My Ability.rb file:
class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new
    if user.admin?
      can :manage, :all
      can :import, [User, Enclosure, Blade, Component]
    else
      can :access, :rails_admin
      can :dashboard
      can :read, :all
      can :history, :all
      # Allows user to only edit an enclosure, if it's allocated to itself, or not allocated at all
      can :update, Enclosure do |enclosure|
        can :update, Enclosure if (enclosure.allocated_to == user.email && enclosure.allocation == true) || enclosure.allocation == false
      end
    end
  end
end

Gems I'm using (besides the default Rails 4 gems):
# Administration Panel Gems
gem 'rails_admin'                    # Rails Administration Panel Gem
gem 'rails_admin_history_rollback'   # Enables users to visualize and revert history
gem 'rails_admin_import', "~> 1.0.0" # Enables importing
gem 'devise'                         # Authentication Gem
gem 'cancancan'                      # Authorization Gem
gem 'paper_trail', '~> 4.0.0.rc'     # Auditing Gem (History)

Thank you!

A: I think you should use strong parameters. This gem lets you choose which parameters do you want to be updated. If you are using Rails 4, the gem is already installed, otherwise you can install it.
class UsersController < ApplicationController
  load_and_authorize_resource

  def update
    if @user.update_attributes(update_params)
      # hurray
    else
      render :edit
    end
  end

  private

  def update_params
    if current_user.admin?
      params.require(:user).permit(:user, :email, :password, :admin)
    else
      params.require(:user).permit(:user, :email, :password)
    end
  end
end


text:
Q: Script doesn't work after adding row dynamically I have one function which calculates the total amount.
amount=qty*rate
Here is my html code for showing table
When I add new row it doesn't trigger that calculate function
Can any one help me out?
Here is my script:

 function calculate() {
  var myBox1 = document.getElementById('qty').value;
  var myBox2 = document.getElementById('rate').value;
  var amnt = document.getElementById('amnt');
  var myResult = myBox1 * myBox2;
  amnt.value = myResult;
      }

  var count = "1";
  function addRow(in_tbl_name)
  {
    var tbody = document.getElementById(in_tbl_name).getElementsByTagName("TBODY")[0];
    // create row
    var row = document.createElement("TR");
    // create table cell 1
    var td1 = document.createElement("TD")
    var strHtml1 = "<INPUT TYPE=\"text\" NAME=\"r_name\" SIZE=\"30\">";

    td1.innerHTML = strHtml1.replace(/!count!/g,count);
    // create table cell 2
    var td2 = document.createElement("TD")
    var strHtml2 = "<INPUT TYPE=\"text\" NAME=\"r_desc\" PLACEHOLDER=\"description\" SIZE=\"30\">";
    td2.innerHTML = strHtml2.replace(/!count!/g,count);
    // create table cell 3
    var td3 = document.createElement("TD")
    var strHtml3 = "<INPUT TYPE=\"text\" NAME=\"r_qty\" PLACEHOLDER=\"QTY\" ID=\"qty\" ONINPUT=\"calculate()\" SIZE=\"30\">";
    td3.innerHTML = strHtml3.replace(/!count!/g,count);
    // create table cell 4
    var td4 = document.createElement("TD")
    var strHtml4 = "<INPUT TYPE=\"text\" NAME=\"r_RATE\" PLACEHOLDER=\"rate\" ID=\"rate\" ONINPUT=\"calculate()\" SIZE=\"30\">";
    td4.innerHTML = strHtml4.replace(/!count!/g,count);
    // create table cell 5
    var td5 = document.createElement("TD")
    var strHtml5 = "<INPUT TYPE=\"text\" NAME=\"r_total\" PLACEHOLDER=\"amount\" ID=\"amnt\" >";

    td5.innerHTML = strHtml5.replace(/!count!/g,count);
  // create table cell 4
    var td6 = document.createElement("TD")
    var strHtml6 = "<INPUT TYPE=\"Button\" CLASS=\"Button\" onClick=\"delRow()\" VALUE=\"Delete Row\">";

    td6.innerHTML = strHtml6.replace(/!count!/g,count);

    // append data to row
    row.appendChild(td1);
    row.appendChild(td2);
    row.appendChild(td3);
    row.appendChild(td4);
    row.appendChild(td5);
 row.appendChild(td6);
    // add to count variable
    count = parseInt(count) + 1;
    // append row to table
    tbody.appendChild(row);
  }
  function delRow()
  {
    var current = window.event.srcElement;
    //here we will delete the line
    while ( (current = current.parentElement)  && current.tagName !="TR");
         current.parentElement.removeChild(current);
  }

            Row material Name
   Description

            Qty.

            Rate
            Amount
            <INPUT TYPE="Button" onClick="addRow('tblPets')" VALUE="Add Row">

            <INPUT TYPE="text" NAME="r_name" SIZE="30">
   <INPUT TYPE="text" NAME="r_desc" PLACEHOLDER="description" SIZE="30">

            <INPUT TYPE="text" NAME="r_qty" PLACEHOLDER="QTY" ID="qty" ONINPUT="calculate()" SIZE="30">

            <INPUT TYPE="text" NAME="r_RATE" PLACEHOLDER="rate" ID="rate" ONINPUT="calculate()" SIZE="30">
            <INPUT TYPE="text" NAME="r_total" PLACEHOLDER="amount" ID="amnt" >

Here is my HTML code

A: I understand now what you wanted to do.
You're using the same element id multiple times, so your calculate() function always selects only the first inputs in the first row.
I calculate() so it takes as a parameter the element that triggered the event and then traverses up the DOM tree to find the closest
:
var tr = elm;
while ((tr = tr.parentElement) && tr.tagName !== 'TR');

Then select input fields only in this table row, calculate what you want and set it as a value to another input field in the same row.
Last thing I changes is that I trigger oninput with oninput=calculate(this) where this is the current DOM element.

function calculate(elm) {
    var tr = elm;
    while ((tr = tr.parentElement) && tr.tagName !== 'TR');
    var inputs = tr.querySelectorAll('input');

    var myBox1 = inputs[2].value;
    var myBox2 = inputs[3].value;
    var myResult = myBox1 * myBox2;
    inputs[4].value = myResult;
}

var count = "1";
function addRow(in_tbl_name)
{
    var tbody = document.getElementById(in_tbl_name).getElementsByTagName("TBODY")[0];
    // create row
    var row = document.createElement("TR");
    // create table cell 1
    var td1 = document.createElement("TD")
    var strHtml1 = "<INPUT TYPE=\"text\" NAME=\"r_name\" SIZE=\"30\">";

    td1.innerHTML = strHtml1.replace(/!count!/g,count);
    // create table cell 2
    var td2 = document.createElement("TD")
    var strHtml2 = "<INPUT TYPE=\"text\" NAME=\"r_desc\" PLACEHOLDER=\"description\" SIZE=\"30\">";
    td2.innerHTML = strHtml2.replace(/!count!/g,count);
    // create table cell 3
    var td3 = document.createElement("TD")
    var strHtml3 = "<INPUT TYPE=\"text\" NAME=\"r_qty\" PLACEHOLDER=\"QTY\" ID=\"qty\" ONINPUT=\"calculate(this)\" SIZE=\"30\">";
    td3.innerHTML = strHtml3.replace(/!count!/g,count);
    // create table cell 4
    var td4 = document.createElement("TD")
    var strHtml4 = "<INPUT TYPE=\"text\" NAME=\"r_RATE\" PLACEHOLDER=\"rate\" ID=\"rate\" ONINPUT=\"calculate(this)\" SIZE=\"30\">";
    td4.innerHTML = strHtml4.replace(/!count!/g,count);
    // create table cell 5
    var td5 = document.createElement("TD")
    var strHtml5 = "<INPUT TYPE=\"text\" NAME=\"r_total\" PLACEHOLDER=\"amount\" ID=\"amnt\" >";

    td5.innerHTML = strHtml5.replace(/!count!/g,count);
  // create table cell 4
    var td6 = document.createElement("TD")
    var strHtml6 = "<INPUT TYPE=\"Button\" CLASS=\"Button\" onClick=\"delRow()\" VALUE=\"Delete Row\">";

    td6.innerHTML = strHtml6.replace(/!count!/g,count);

    // append data to row
    row.appendChild(td1);
    row.appendChild(td2);
    row.appendChild(td3);
    row.appendChild(td4);
    row.appendChild(td5);
 row.appendChild(td6);
    // add to count variable
    count = parseInt(count) + 1;
    // append row to table
    tbody.appendChild(row);
  }
  function delRow()
  {
    var current = window.event.srcElement;
    //here we will delete the line
    while ( (current = current.parentElement)  && current.tagName !="TR");
         current.parentElement.removeChild(current);
  }

            Row material Name
   Description

            Qty.

            Rate
            Amount
            <INPUT TYPE="Button" onClick="addRow('tblPets')" VALUE="Add Row">

            <INPUT TYPE="text" NAME="r_name" SIZE="30">
   <INPUT TYPE="text" NAME="r_desc" PLACEHOLDER="description" SIZE="30">

            <INPUT TYPE="text" NAME="r_qty" PLACEHOLDER="QTY" ID="qty" ONINPUT="calculate(this)" SIZE="30">

            <INPUT TYPE="text" NAME="r_RATE" PLACEHOLDER="rate" ID="rate" ONINPUT="calculate(this)" SIZE="30">
            <INPUT TYPE="text" NAME="r_total" PLACEHOLDER="amount" ID="amnt" >


text:
Q: How to insert Api value in NgForm Angular post request hardcoded so I'm making a crypto-exchange project in angular using .net as backend. Result of project is that a user can make a purchase that is saved in database using post request. I'm using ngForm for it and can make whatever input field I wand, and everything is working, but I want to post live price of bitcoin multiplied by inputed amount.
This is my html:
<form #form="ngForm" (submit)="onSubmitB(form)">
    <input type="hidden" name="id" value="service.formData.id" />

Amount

        <input type="text" class="form-control form-control-lg" name="amount"
            #amount="ngModel" [(ngModel)]="service.formDataBk.amount">

Total price

           {{coinPrice*service.formDataBk.amount || 0}}

Crypto Adress

        <input type="text" class="form-control form-control-lg"
            #cryptoAdress="ngModel" [(ngModel)]="service.formDataBk.cryptoAdress">

        <button class="btn btn-info btn-lg btn-block" type="submit">CONFIRM</button>

</form>

So far I made the value live bitcoin price * amount here : {{coinPrice*service.formDataBk.amount || 0}}, it works, and show's the price, but I want it to be saved in database with other stuff I insertet in Input field. I know that with  it won't work, but I don't know what to insert, I tried a bunch of thing, but it won't sent the result of this coinPrice*amount to database... What can I do?
Post request works fine, live api work, everything I insert in input field works correctly.
This is my TS file with functions:
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { coinApiService } from 'src/app/shared/coinApi.service';
import { TransactionService } from 'src/app/shared/transaction.service';
import { TransactionBbuy } from 'src/app/shared/transactionB.model';

@Component({
  selector: 'app-buy-btc',
  templateUrl: './buy-btc.component.html',
  styles: [
  ]
})
export class BuyBtcComponent implements OnInit {
  result: any;
  coinPrice: any = [];

  constructor(public service: TransactionService, private toastr: ToastrService, private price: coinApiService) { }

  ngOnInit(): void {
    this.btcPrice();
  }

  btcPrice() {
    this.price.coinsPriceBTC().then((res) => {
      this.result = res;
      this.coinPrice = this.result.bitcoin.eur;
      console.log(this.coinPrice);
    })
  }

  onSubmitB(form: NgForm) {

    this.service.postTransactionBk().subscribe(
      res => {
        this.resetForm(form);
        this.toastr.success('Uspješno!', 'Podnešen zahtjev za transakciju')

      },
      err => { console.log(err); }
    );
  }

  resetForm(form: NgForm) {
    form.form.reset();
    this.service.formDataBk = new TransactionBbuy();
  }
}

I'm stuck with this past 2 day's, and after this my project is finished, I'm grateful for all help I get :D

A: I think it's the basic principles what you're missing, unfortunately not just from angular, but also from designing disconnected / distributed systems and probably also some domain knowledge about financial systems.
Angular:
The text interpolation {{ }} inside Angular is great for displaying values. You can use {{ coinPrice * service.formDataBk.amount || 0 }}.
But that's it - all what you get is that a computed value gets displayed.
If you want the same value to be sent via a HTTP POST, you will need to calculate it in the TypeScript code. This also means that when you want to apply DRY, you're better of writing a getter inside the TS code:
public get bitcoinRate(): number {
    return this.coinPrice * this.service.formDataBk.amount || 0;
}

The next part you need it to pass any value to the HTTP POST method (via uri path / query / body). So the method you mentioned should have this definition:
this.service.postTransactionBk({ } as IDataToPost)

Please check out the quide: https://angular.io/guide/http
Now the architecture:
There's a basic problem with the design: usually you can POST how many of a given item you want to buy, but not the rate. The rate is usually guarded by the service provider.
In some systems you usually place a buy order and have different options. With bank and buying currencies (where rate changes seldomly - usually it's fix for a day) you're ok to place a buy order.
https://www.youtube.com/watch?v=EeNG1S5teZ0&t=353s


text:
Q: Improving a sort program's efficiency; displaying column sort % completion in terminal I have a big pipe-delimited input file approx 6 million lines as below:
24|BBG000SJFVB0|EQ0000000009296012|OI SA-ADR|OIBR/C|US|ADR|Equity 16|BBG002PHVB83|EQ0000000022353186|BLOOM SELECT INCOME FUND|BLB-U|CT|Closed-End Fund|Equity
-50|BBG000V0TN75|EQ0000000010271114|MECHEL-PREF SPON ADR|MTL/P|US|ADR|Equity 20|BBG002S0ZR60|EQ0000000022739316|DIVIDEND 15 SPLIT CORP II-RT|DF-R|CT|Closed-End Fund|Equity
-20|BBG001R3LGM8|EQ0000000017879513|ING FLOATING RATE SENIOR LOA|ISL/U|CT|Closed-End Fund|Equity 0|BBG006M6SXL2|EQ0000000006846232|AA PLC|AA/|LN|Common Stock|Equity

Requirements are as below:
  1. I need to sort this input file by 1st column and then 2nd column and then 2nd last column in that order
  2. Displaying % of sort completion in terminal/console for e.g. "column 2 75% sort done"
  3. finally output in a separate file.

I have written the program below which is sorting by 1st column perfectly.
But how to incorporate the all other conditions? Also now it is taking a little more time to run. Is there any more efficient and cleaner way to do it? Only thing is we can't use any additional outside package from CPAN. Unix solutions like using SED/AWK are OK but Perl is preferable.I just came to know built-in Python is also there so that solution is also welcome.
my (%link_strength);
{$data="datascope_input.txt";
 $out="sort_file.txt";
open (my $indata , '<', $data)|| die "could not open $data :\n$!";
open (my $outdata , '>', $out)|| die "could not open $out :\n$!";
select $outdata;
my @array=(<$indata>);
for (@array){
    $link_strength{$1}=$_  if /(?:[^|]+\|){0}([^|]+)/;
            }
print $link_strength{$_} for (sort {$a<=>$b} keys %link_strength);
  close ($outdata);
  close ($indata);
}

A: As I said in comments, the Linux/Unix system sort is likely to perform better, but if you really want Perl, this will do the trick:
use strict;

sub main {
  open F, 'input.txt' or die $!;
  my @pairs;
  while (<F>) {
    my @fields = split(/\|/);
    my $key = [ @fields[0, 1, -2] ];
    push @pairs, [$key, $_];
  }
  close F;
  my @sorted_pairs = sort {
    my $a_key = $a->[0];
    my $b_key = $b->[0];
    $a_key->[0] <=> $b_key->[0]
      || $a_key->[1] cmp $b_key->[1]
      || $a_key->[2] cmp $b_key->[2]
  } @pairs;
  foreach my $pair (@sorted_pairs) {
    print $pair->[1];
  }
}

main;

Also as I said in comments, I know of no way to introspectively gather progress information.  You could hack something by counting how many comparisons have occurred, but since you'll never be sure of the final number, a percent complete can't be calculated.

A: From your sample data, you are going to sort approximately 950MB. It will take 9.5s reading from normal HD (100MB/s). I do not know how fast it will be sorted by standard sort but from my experience it can go 1-3 millions of records per CPU core. Let's say 1 million. It will take 3s on dual core and less on a server with more CPU cores. I think the most time will take reading and parsing of your data. So simple
pv -p your_file.dat | sort -t'|' -k '1n,1' -k '2d,2' -k '14,14'

should do most of required functionality.


text:
Q: Internal data flow error in gstreamer c code that uses "adder" element? I want to convert my gst-launch command into c code. I am new to gstreamer coding. can anyone help me?
command:  gst-launch-0.10 uridecodebin uri=file:///media/afeb7785-7c21-45bf-b1b7-41d3263022f6/gst/bigcity.wav ! audioconvert ! volume volume='0.9' ! audioconvert ! adder name = m ! autoaudiosink uridecodebin uri=file:///media/afeb7785-7c21-45bf-b1b7-41d3263022f6/gst/tereliya.wav ! audioconvert ! volume volume='0.3' ! audioconvert ! m.
c-code:
#include <gst/gst.h>
#include <glib.h>

static gboolean
bus_call (GstBus     *bus,
          GstMessage *msg,
          gpointer    data)
{
  GMainLoop *loop = (GMainLoop *) data;

  switch (GST_MESSAGE_TYPE (msg)) {

    case GST_MESSAGE_EOS:
      g_print ("End of stream\n");
      g_main_loop_quit (loop);
      break;

    case GST_MESSAGE_ERROR: {
      gchar  *debug;
      GError *error;

      gst_message_parse_error (msg, &error, &debug);
      g_free (debug);

      g_printerr ("Error: %s\n", error->message);
      g_error_free (error);

      g_main_loop_quit (loop);
      break;
    }
    default:
      break;
  }

  return TRUE;
}

static void
on_pad_added (GstElement *element,
              GstPad     *pad,
              gpointer    data)
{
  GstPad *sinkpad;
  GstElement *decoder = (GstElement *) data;

  /* We can now link this pad with the vorbis-decoder sink pad */
  g_print ("Dynamic pad created, linking \n");

  sinkpad = gst_element_get_static_pad (decoder, "sink");

  gst_pad_link (pad, sinkpad);

  gst_object_unref (sinkpad);
}

int
main (int   argc,
      char *argv[])
{
  GMainLoop *loop;
  GstElement *pipeline, *source1, *source2, *mixer, *conv, *conv2, *sink;
  GstBus *bus;
  guint bus_watch_id;
  GstPad *adder_sinkpad;
  GstPad *adder_sinkpad2;
  GstPad *conv1_pad;
  GstPad *conv2_pad;
  gchar *pad1name;
  gchar *pad2name;
  /* Initialisation */
  gst_init (&argc, &argv);

  loop = g_main_loop_new (NULL, FALSE);

  /* Check input arguments */
/*  if (argc != 3) {
    g_printerr ("Usage: %s \n", argv[0]);
    return -1;
  }*/

  /* Create gstreamer elements */
  pipeline = gst_pipeline_new ("audio-player");
  source1  = gst_element_factory_make ("uridecodebin",  "uri-source1");
  source2  = gst_element_factory_make ("uridecodebin",  "uri-source2");
  mixer    = gst_element_factory_make ("adder",         "audio-mix");
  conv     = gst_element_factory_make ("audioconvert",  "conv");
  conv2     = gst_element_factory_make ("audioconvert", "conv2");
  sink     = gst_element_factory_make ("alsasink", "audio-output");

  if (!pipeline || !source1 || !source2 || !mixer || !conv || !conv2 || !sink) {
    g_printerr ("One element could not be created. Exiting.\n");
    return -1;
  }

  /* Set up the pipeline */

  /* we set the input filename to the source element */
  g_object_set (G_OBJECT (source1), "uri",  "file:///home/baibhav/gst/shadowoftheday.wav", NULL);
  g_object_set (G_OBJECT (source2), "uri",  "file:///home/baibhav/gst/valentinesday.wav" , NULL);

  g_object_set (G_OBJECT (mixer), "name", "mix", NULL);
  /* we add a message handler */
  bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
  bus_watch_id = gst_bus_add_watch (bus, bus_call, loop);
  gst_object_unref (bus);

  /* we add all elements into the pipeline */
  gst_bin_add_many (GST_BIN (pipeline),
                    source1, conv, mixer, sink, source2, conv2, NULL);

  /* we link the elements together */
  int k,n;
  if((k=gst_element_link (source1, conv)) !=0 ) {
    g_print ("link1 error: %d\n",k);
    g_print ("cannot link source1 with conv\n");
    }
  if((n=gst_element_link (source2, conv2)) != 0) {
    g_print ("link2 error: %d\n",n);
    g_print ("cannot link source2 with conv2\n");
    }

  if(gst_element_link (mixer, sink) != TRUE) {
    g_print ("cannot link sink with mixer\n");
    }

  conv1_pad= gst_element_get_static_pad (conv, "src");
  conv2_pad= gst_element_get_static_pad (conv2, "src");
  adder_sinkpad = gst_element_get_request_pad (mixer, "sink%d");
  pad1name = gst_pad_get_name (adder_sinkpad);
  g_print ("pad1name: %s\n",pad1name );
  adder_sinkpad2 = gst_element_get_request_pad (mixer, "sink%d");
  pad2name = gst_pad_get_name (adder_sinkpad2);
  g_print ("pad2name: %s\n",pad2name );
  int i,j;
  if((i=gst_pad_link (conv1_pad, adder_sinkpad)) != 0) {
    g_print ("pad error: %d\n",i);
    g_print ("cannot link conv1 with adder1\n");
     }

  if((j=gst_pad_link (conv2_pad, adder_sinkpad2))!= 0) {
    g_print ("pad2 error: %d\n",j);
    g_print ("cannot link conv2 with adder2\n");
    }

//  g_signal_connect (conv, "pad-added", G_CALLBACK (on_pad_added), mixer);
//  g_signal_connect (conv2, "pad-added", G_CALLBACK (on_pad_added), mixer);

  /* Set the pipeline to "playing" state*/
  g_print ("Now playing\n");
  gst_element_set_state (pipeline, GST_STATE_PLAYING);

  /* Iterate */
  g_print ("Running...\n");
  g_main_loop_run (loop);

  /* Out of the main loop, clean up nicely */
  g_print ("Returned, stopping playback\n");
  gst_element_set_state (pipeline, GST_STATE_NULL);

  g_print ("Deleting pipeline\n");
//  gst_pad_unlink (conv2_pad, adder_sinkpad2);
//  gst_pad_unlink ((conv1_pad, adder_sinkpad);
  gst_object_unref (GST_OBJECT (pipeline));
  g_source_remove (bus_watch_id);
  g_main_loop_unref (loop);

  return 0;
}

A: For your application, there is not any requirement of adding signal handler for pad-added signal. You can simply write your application as follows :
#include <gst/gst.h>
#include <glib.h>

static gboolean
    bus_call (GstBus     *bus,
    GstMessage *msg,
    gpointer    data)
   {
GMainLoop *loop = (GMainLoop *) data;

switch (GST_MESSAGE_TYPE (msg)) {

    case GST_MESSAGE_EOS:
        g_print ("End of stream\n");
        g_main_loop_quit (loop);
        break;

    case GST_MESSAGE_ERROR: {
                    gchar  *debug;
                    GError *error;

                    gst_message_parse_error (msg, &error, &debug);
                    g_free (debug);

                    g_printerr ("Error: %s\n", error->message);
                    g_error_free (error);

                    g_main_loop_quit (loop);
                    break;
                }
    default:
                break;
}

return TRUE;
    }

int main (int   argc,
    char *argv[])
    {
GMainLoop *loop;
GstElement *pipeline, *source1, *source2, *mixer, *conv, *conv2, *sink;
GstBus *bus;
guint bus_watch_id;
GstPad *adder_sinkpad;
GstPad *adder_sinkpad2;
GstPad *conv1_pad;
GstPad *conv2_pad;
gchar *pad1name;
gchar *pad2name;
/* Initialisation */
gst_init (&argc, &argv);

loop = g_main_loop_new (NULL, FALSE);

/* Check input arguments */
/*  if (argc != 3) {
 *      g_printerr ("Usage: %s \n", argv[0]);
 *          return -1;
 *            }*/

/* Create gstreamer elements */
pipeline = gst_pipeline_new ("audio-player");
source1  = gst_element_factory_make ("audiotestsrc",  "uri-source1");
source2  = gst_element_factory_make ("audiotestsrc",  "uri-source2");
mixer    = gst_element_factory_make ("adder",         "audio-mix");
conv     = gst_element_factory_make ("audioconvert",  "conv");
conv2     = gst_element_factory_make ("audioconvert", "conv2");
sink     = gst_element_factory_make ("alsasink", "audio-output");

if (!pipeline || !source1 || !source2 || !mixer || !conv || !conv2 || !sink) {
    g_printerr ("One element could not be created. Exiting.\n");
    return -1;
}

/* Set up the pipeline */

/* we set the input filename to the source element */
g_object_set (G_OBJECT (source1), "uri",  "file:///home/baibhav/gst/shadowoftheday.wav", NULL);
g_object_set (G_OBJECT (source2), "uri",  "file:///home/baibhav/gst/valentinesday.wav" , NULL);

g_object_set (G_OBJECT (mixer), "name", "mix", NULL);
/* we add a message handler */
bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
bus_watch_id = gst_bus_add_watch (bus, bus_call, loop);
gst_object_unref (bus);

/* we add all elements into the pipeline */
gst_bin_add_many (GST_BIN (pipeline),
        source1, conv, mixer, sink, source2, conv2, NULL);

/* we link the elements together */
int k,n;
if((k=gst_element_link_many (source1, conv,mixer,NULL)== 0) ) {
    g_print ("link1 error: %d\n",k);
    g_print ("cannot link source1 with conv\n");
}
if((n=gst_element_link_many (source2, conv2,mixer,NULL))== 0 ) {
    g_print ("link2 error: %d\n",n);
    g_print ("cannot link source2 with conv2\n");
}

if(gst_element_link (mixer, sink) == 0 ) {
    g_print ("cannot link sink with mixer\n");
}

//    /* Set the pipeline to "playing" state*/
g_print ("Now playing\n");
gst_element_set_state (pipeline, GST_STATE_PLAYING);
//
//
//          /* Iterate */
g_print ("Running...\n");
g_main_loop_run (loop);

//
//                /* Out of the main loop, clean up nicely */
g_print ("Returned, stopping playback\n");
gst_element_set_state (pipeline, GST_STATE_NULL);

g_print ("Deleting pipeline\n");
//  gst_pad_unlink (conv2_pad, adder_sinkpad2);
//  gst_pad_unlink ((conv1_pad, adder_sinkpad);
gst_object_unref (GST_OBJECT (pipeline));
g_source_remove (bus_watch_id);
g_main_loop_unref (loop);

return 0;

}

A: Below code works.
#include <gst/gst.h>
#include <glib.h>

static gboolean
bus_call (GstBus     *bus,
          GstMessage *msg,
          gpointer    data)
{
  GMainLoop *loop = (GMainLoop *) data;

  switch (GST_MESSAGE_TYPE (msg)) {

    case GST_MESSAGE_EOS:
      g_print ("End of stream\n");
      g_main_loop_quit (loop);
      break;

    case GST_MESSAGE_ERROR: {
      gchar  *debug;
      GError *error;

      gst_message_parse_error (msg, &error, &debug);
      g_free (debug);

      g_printerr ("Error: %s\n", error->message);
      g_error_free (error);

      g_main_loop_quit (loop);
      break;
    }
    default:
      break;
  }

  return TRUE;
}

static void
on_pad_added (GstElement *element,
              GstPad     *pad,
              gpointer    data)
{
  GstPad *sinkpad;
  GstElement *decoder = (GstElement *) data;

  /* We can now link this pad with the vorbis-decoder sink pad */
  g_print ("Dynamic pad created, linking \n");

  sinkpad = gst_element_get_static_pad (decoder, "sink");

  gst_pad_link (pad, sinkpad);

  gst_object_unref (sinkpad);
}

int
main (int   argc,
      char *argv[])
{
  GMainLoop *loop;
  GstElement *pipeline, *source1, *source2, *mixer, *conv1, *conv2, *sink;
  GstBus *bus;
  guint bus_watch_id;
  GstPad *adder_sinkpad1;
  GstPad *adder_sinkpad2;
  GstPad *vol1_pad, *vol2_pad;
  gchar *pad1name;
  gchar *pad2name;
  GstElement *vol1, *vol2;
  int n;

  /* Initialisation */
  gst_init (&argc, &argv);

  loop = g_main_loop_new (NULL, FALSE);

  /* Check input arguments */
  if (argc != 3) {
    g_printerr ("Usage: %s file1 file2\n", argv[0]);
    return -1;
  }

  /* Create gstreamer elements */
  pipeline = gst_pipeline_new ("audio-player");
  source1  = gst_element_factory_make ("uridecodebin",  "uri-source1");
  source2  = gst_element_factory_make ("uridecodebin",  "uri-source2");
  mixer    = gst_element_factory_make ("adder",         "audio-mix");
  conv1     = gst_element_factory_make ("audioconvert",  "conv1");
  conv2     = gst_element_factory_make ("audioconvert", "conv2");
  vol1 = gst_element_factory_make("volume", "vol1");
  vol2 = gst_element_factory_make("volume", "vol2");
  sink     = gst_element_factory_make ("alsasink", "audio-output");

  if (!pipeline || !source1 || !source2 || !mixer || !conv1 || !conv2 || !vol1 || !vol2 || !sink) {
    g_printerr ("One element could not be created. Exiting.\n");
    return -1;
  }

  /* Set up the pipeline */

  /* we set the input filename to the source element */

  g_object_set (G_OBJECT (source1), "uri",  argv[1], NULL);
  g_object_set (G_OBJECT (source2), "uri",  argv[2], NULL);

  g_object_set (G_OBJECT (mixer), "name", "mix", NULL);

  g_object_set(G_OBJECT (vol1), "volume", 0.9, NULL);
  g_object_set(G_OBJECT (vol2), "volume", 0.3, NULL);

  /* we add a message handler */
  bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
  bus_watch_id = gst_bus_add_watch (bus, bus_call, loop);
  gst_object_unref (bus);

  /* we add all elements into the pipeline */
  gst_bin_add_many (GST_BIN (pipeline),
                    source1, conv1, vol1, mixer, sink, source2, conv2, vol2, NULL);

  /* we link the elements together */
#if 0 //Doesnt work directly linking elements
  g_print("link elements directly \n");
  if((n=gst_element_link (source1, conv1)) == 0 ) {
    g_print ("link1 error: %d\n",n);
    g_print ("cannot link source1 with conv1\n");
  }

  if((n=gst_element_link (source2, conv2)) == 0) {
    g_print ("link2 error: %d\n",n);
    g_print ("cannot link source2 with conv2\n");
  }
#else
  g_print("use dynamic pads to link elements \n");
  g_signal_connect (source1, "pad-added", G_CALLBACK (on_pad_added), conv1);
  g_signal_connect (source2, "pad-added", G_CALLBACK (on_pad_added), conv2);
#endif

  if((n=gst_element_link (conv1, vol1)) == 0) {
    g_print ("link2 error: %d\n",n);
    g_print ("cannot link conv with vol1\n");
  }

  if((n=gst_element_link (conv2, vol2)) == 0) {
    g_print ("link2 error: %d\n",n);
    g_print ("cannot link conv2 with conv2\n");
  }

  if((n = gst_element_link (mixer, sink)) == 0) {
    g_print ("cannot link sink with mixer\n");
  }
  vol1_pad= gst_element_get_static_pad (vol1, "src");
  vol2_pad= gst_element_get_static_pad (vol2, "src");

  adder_sinkpad1 = gst_element_get_request_pad (mixer, "sink_%u");
  pad1name = gst_pad_get_name (adder_sinkpad1);
  g_print ("pad1name: %s\n",pad1name );
  adder_sinkpad2 = gst_element_get_request_pad (mixer, "sink_%u");
  pad2name = gst_pad_get_name (adder_sinkpad2);
  g_print ("pad2name: %s\n",pad2name );

  int i,j;
  if((i=gst_pad_link (vol1_pad, adder_sinkpad1)) != 0) {
    g_print ("pad error: %d\n",i);
    g_print ("cannot link conv1 with adder1\n");
     }

  if((j=gst_pad_link (vol2_pad, adder_sinkpad2))!= 0) {
    g_print ("pad2 error: %d\n",j);
    g_print ("cannot link conv2 with adder2\n");
    }

  /* Set the pipeline to "playing" state*/
  g_print ("Now playing\n");
  gst_element_set_state (pipeline, GST_STATE_PLAYING);

  /* Iterate */
  g_print ("Running...\n");
  g_main_loop_run (loop);

  /* Out of the main loop, clean up nicely */
  g_print ("Returned, stopping playback\n");
  gst_element_set_state (pipeline, GST_STATE_NULL);

  g_print ("Deleting pipeline\n");

  gst_object_unref (GST_OBJECT (pipeline));
  g_source_remove (bus_watch_id);
  g_main_loop_unref (loop);

  return 0;
}


text:
Q: R2DBC cannot create statement for notifications I am trying to receive asynchronous notifications from postgresql and r2dbc
I use reactivestream and postgres driver but i cannot make statement
I am new to java and reactivestream, i don't to use a framework like spring.
thank you guys
   package com.poc.r2dbc_listen;
import io.r2dbc.postgresql.*;
import io.r2dbc.spi.*;
import org.reactivestreams.*;
import reactor.core.publisher.Flux;

public class R2dbc_listen {

    public static void main(String[] args) {
         PostgresqlConnectionFactory connectionFactory = new PostgresqlConnectionFactory(PostgresqlConnectionConfiguration.builder()
    .host("127.0.0.1")
    .port(5442)
    .username("postgres")
    .password("psswd")
    .database("database")
    .build());
    Publisher<? extends Connection> connectionPublisher = connectionFactory.create();
    Flux<Notification> listen = connectionPublisher.createStatement("LISTEN mymessage")
                                .execute()
                                .flatMap(PostgresqlResult::getRowsUpdated)
        .thenMany(receiver.getNotifications());
    }
}

A: It works:
private void listen() {
    connection = Mono.from(connectionFactory.create())
        .cast(PostgresqlConnection.class)
        .block(Duration.ofSeconds(10));

    connection.createStatement("LISTEN channel")
        .execute()
        .flatMap(PostgresqlResult::getRowsUpdated)
        .subscribe();

    connection.getNotifications()
        .delayElements(Duration.ofSeconds(1))
        .subscribe(System.out::println);

}


text:
Q: Purpose of options.AutomaticAuthenticate with UseJwtBearerAuthentication After updating a codebase from ASP 5 beta 7 to RC1-final, I began receiving this exception from the JwtBearer middleware
Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'System.IConvertible'.

The determining factor I can see so far appears to be the setting of  options.AutomaticAuthenticate.  If it's true, then I get the exception, otherwise, I do not.
What is AutomaticAuthenticate and why would I need to enable it?
    app.UseJwtBearerAuthentication(options =>
    {
        options.AutomaticAuthenticate = true;
    }

Here is the full stack trace:
at System.Convert.ToInt32(Object value, IFormatProvider provider)
   at System.IdentityModel.Tokens.Jwt.JwtPayload.GetIntClaim(String claimType)
   at System.IdentityModel.Tokens.Jwt.JwtPayload.get_Nbf()
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
   at Microsoft.AspNet.Authentication.JwtBearer.JwtBearerHandler.<HandleAuthenticateAsync>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNet.Authentication.JwtBearer.JwtBearerHandler.<HandleAuthenticateAsync>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNet.Authentication.AuthenticationHandler`1.<InitializeAsync>d__48.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNet.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Api.Startup.<<Configure>b__9_0>d.MoveNext() in ...\Startup.cs:line 156

Update on root cause
Our codebase was creating duplicate claims for nbf, exp, and iat.  That explains why get_Nbf is in the stack trace and the complaint about "JArray" since each of those values was an array instead of a value.

A: If its set to true then the middleware will run on every inbound request, look for a JWT token and if one is present it will validate it, and if valid create an identity from it and add it to the current user.
If its false that doesn't happen and you need to request the middleware to set an identity by specifying the bearer's scheme in your authorize attribute.
[Authorize(AuthenticationSchemes = "YourBearerSchemeName")]

Or you set this in policy;
options.AddPolicy("RequireBearer", policy =>
{
    policy.AuthenticationSchemes.Add("YourBearerSchemeName");
    policy.RequireAuthenticatedUser();

});

So, by setting it to false you aren't actually running the bearer stuff until you ask for it, you're only putting the exception off until later.


text:
Q: Finding the limiting distribution using moment generation functions Question: Let $Z_{i}$ ~ $N(0,1)$ be independent random variables for i = 1,2,... . Obtain the limiting distribution of $$\frac{1}{\sqrt{n}}\Bigl(\sum_{i=1}^n\Bigl(Z_{i} + \frac{1}{n}\Bigr)\Bigr)$$ using moment generating functions.
So far I have: Let $Y_{n}=\frac{1}{\sqrt{n}}(\sum_{i=1}^n(Z_{i} + \frac{1}{n}))$
$\\M_{y_n}(t)=E(e^{ty_n})=E(exp(t[\frac{1}{\sqrt{n}}\sum_{i=1}^n(Z_{i} + \frac{1}{n})]))=...=e^\frac{t}{\sqrt{n}}\prod_{i=1}^nE(exp\frac{t}{\sqrt{n}}Z_{i})=e^\frac{t}{\sqrt{n}}(M_{Z_i}(\frac{t}{\sqrt{n}}))^n$
I'm not too sure where to go from here. I think I can apply Taylor expansion to $M_{Z_i}(\frac{t}{\sqrt{n}})$ at 0, but how do I work with the $\frac{t}{\sqrt{n}}$? Am I to take the derivative of that function and calculate it at zero? Likely a simple concept that I am not understanding, so any clarification would help, thanks!

A: By the properties of Gaussian RVs (unrelated to MGFs),
$$
Z_i \sim \mathcal{N}(0, 1) \Rightarrow (Z_i + \frac{1}{n}) \sim \mathcal{N}\left(\frac{1}{n}, 1\right).
$$
The MGF of this distribution is
$$
e^{\frac{t}{n} + t^2}
$$
Since the RVs are independent, the weighted sum has a simple form
$$
\left(
e^{\frac{t}{n\sqrt{n}} + \left(\frac{t}{\sqrt{n}}\right)^2}
\right)^n
=
e^{\frac{t}{\sqrt{n}} + t^2}
.
$$
At the limit, this is
$$
e^{t^2},
$$
which is the MGF of $\mathcal{N}(0, 1)$.


text:
Q: where to place my script tag before closing of or after it As we many of know that we have to include external jsscript file at the end of page.
for performance and usability purpose.
I want to know the correct place where to place it.
means
<boby>


text:
Q: Diophantine equation $x^2-xy-y^2=a^2+ab-b^2$ Prove that for any positive integers a and b equation $x^2-xy-y^2=a^2+ab-b^2$ has infinite many solutions in positive integers
My work
I found a solution $(a+b,b)$, but i don't how to prove infinitness of solutions

A: Similar to "Vieta Jumping" for binary quadratic form $x^2 - k xy + y^2,$ there is an automorphism. In the case of $x^2 - xy - y^2,$ the mapping, which can be repeated any number of times, is
$$ (x,y) \mapsto ( 2x+y, x+y)   $$
Note that if the current, $x,y > 0,$ then $2x+y, x+y > 0$ as well.
The generating matrix for the automorphism group can be found visually in Conway's topograph. Traditional: given $Ax^2 + B xy + C y^2,$ with discriminant $D = B^2 - 4AC$ positive but not a square, every automorphism (with determinant $+1$) comes from a solution to $\tau^2 - D \sigma^2 = 4,$  then matrix
$$
M =
\left(
\begin{array}{cc}
\frac{\tau - B \sigma}{2} & - C \sigma \\
A \sigma & \frac{\tau + B \sigma}{2}
\end{array}
\right)
$$
With $A=1, B=-1, C=-1, D=5, \tau = 3, \sigma = 1$ I got
$$
M =
\left(
\begin{array}{cc}
2 & 1 \\
1 & 1
\end{array}
\right)
$$
I had a drawing of this. As we can see the identity matrix as a pair of column vectors (green), we also see the matrix $M$ in the next pair of representations of $1$ ands $-1,$ using the same backwards slant.

A: Above equation shown below:
$(x^2-xy-y^2)=(a^2+ab-b^2)$  --------$(1)$
Equation $(1)$ has parametric solution hence
it has infinite many numerical solution's.
$(x,y,a,b)=[(8k^2),(10k-5),(8k^2-8k),(6k-5)]$
For, $k=3$ we get:
$(x,y,a,b)=[(72,25,48,13)$

A: Solution of equation.
$$X^2-XY-Y^2=a^2+ab-b^2$$
Can be written using solutions to the Pell equation....
$$p^2-5s^2=\pm1$$
Knowing the first solutions for....
$+1--(p;s)--(9;4)$
$-1--(p;s)--(2;1)$
The following can be found by the formula.
$$p_2=9p+20s$$
$$s_2=4p+9s$$
Will make a replacement for the simplified entry....
$$k=p^2\pm6ps+5s^2$$
$$t=p^2\pm2ps+5s^2$$
And then the solutions of the equation can be written in the form...
$$X=(a+b)k^2+2bkt+at^2$$
$$Y=bk^2+2akt+(b-a)t^2$$
So the Pell equation has infinitely many solutions, it means for any number $a,b$ - solutions will always be and infinitely many.


text:
Q: In the ground state properties of electron gas, is $V$ the volume of all the metal or the volume of a cell of the lattice? In the ground state properties of electron gas (Sommerfeld theory), is $V$ the volume of all the metal or the volume of a cell of the lattice?
I thought the latter because the Born—von Karman boundary condition makes me recall the periodicity of lattice.
I'm talking about  V in
$$
\psi_{\boldsymbol{k}}(\boldsymbol{r})=\frac{1}{\sqrt{V}} e^{i \boldsymbol{k} \cdot \boldsymbol{r}}.
$$

A: The equations here say that "where we integrate in $\mathbf{r}$ over a single lattice cell" and puts the limits of the integral as $\Omega_r$. The equation there for time-independent part of the wave function is
$$\phi_\mathbf{k}(\mathbf{r}) = \frac{1}{\sqrt{\Omega_r}}e^{\mathbf{k}\cdot\mathbf{r}} = \frac{1}{\sqrt{V}}e^{\mathbf{k}\cdot\mathbf{r}}$$
So apparently the $V = \Omega_r$ is the volume of a single cell.
Edit: Alright, considering the crystal is finite, we can actually integrate over the whole lattice, then the $\Omega_r$ would be the the total volume. So, as ruslan has told, it depends on how you define things.


text:
Q: in Oracle SQL-Trace: how can I group a set of SQL executions when the code is not instrumented? I have an oracle-10046—aka. sqltrace—file similar to this structure:
Oracle Release 11.2
PARSING IN CURSOR #1 len=20 dep=0 uid=7 oct=6 lid=7 tim=2 hv=1 ad='1' sqlid='A'
insert
END OF STMT
PARSING IN CURSOR #2 len=20 dep=0 uid=7 oct=6 lid=7 tim=2 hv=2 ad='2' sqlid='r'
update next_step
END OF STMT
PARSING IN CURSOR #3 len=20 dep=0 uid=7 oct=6 lid=7 tim=2 hv=3 ad='3' sqlid='B'
update complete
END OF STMT
PARSING IN CURSOR #4 len=20 dep=0 uid=7 oct=3 lid=7 tim=2 hv=4 ad='4' sqlid='X'
select X
END OF STMT
PARSING IN CURSOR #5 len=20 dep=0 uid=7 oct=3 lid=7 tim=2 hv=5 ad='5' sqlid='Y'
select Y
END OF STMT

EXEC #1:c=1,e=1,p=0,cr=0,cu=0,mis=0,r=0,dep=0,og=3,tim=100
EXEC #2:c=2,e=2,p=0,cr=0,cu=0,mis=0,r=0,dep=0,og=3,tim=200
EXEC #3:c=4,e=4,p=0,cr=0,cu=0,mis=0,r=0,dep=0,og=3,tim=300

EXEC #4:c=5,e=5,p=0,cr=0,cu=0,mis=0,r=0,dep=0,og=3,tim=310
EXEC #5:c=6,e=6,p=0,cr=0,cu=0,mis=0,r=0,dep=0,og=3,tim=320

EXEC #1:c=8,e=8,p=0,cr=0,cu=0,mis=0,r=0,dep=0,og=3,tim=400
EXEC #2:c=16,e=16,p=0,cr=0,cu=0,mis=0,r=0,dep=0,og=3,tim=416
EXEC #3:c=32,e=32,p=0,cr=0,cu=0,mis=0,r=0,dep=0,og=3,tim=448

I identified sqlid 'A' as the beginning of a specific sequence, and sqlid 'B' as it's end. In between there is only sqlid 'r' in my example, but it could be much more, even not the same SQLs or sequence of SQLs.
Other SQLs like sqlid 'X' and 'Y' are not within my sequence of interest and should be visible as such.
My tool of choice right now is mrskew from the Method R Tools product from methodr.
As it can be extended with Perl code, I'm sure this can be done, but my Perl skills are limited as my understanding of mrskew internals.
I highly appreciate any hint or help here.

A: Using your test data, martin1.trc, I created the rc file, martin1.rc.
--init='
    my $xfrm_id;
    sub xfrm {
        $xfrm_id = $exec_id if ($sqlid//"") eq "A";
        return $xfrm_id//$exec_id;
    }
'
--group='xfrm()'

Then I executed mrskew --rc martin1.rc martin1.trc and I got this output:
 'xfrm()'  DURATION       %  CALLS      MEAN       MIN       MAX
---------  --------  ------  -----  --------  --------  --------
       25  0.000056   75.7%      3  0.000019  0.000008  0.000032
       18  0.000018   24.3%      5  0.000004  0.000001  0.000006
---------  --------  ------  -----  --------  --------  --------
TOTAL (2)  0.000074  100.0%      8  0.000009  0.000001  0.000032

This report shows two executions of the interesting transaction. The most interesting (greatest response time) transaction execution began on trace file line 25 and contributed 0.000056 seconds (75.7% of the total) over 3 dbcalls to the total response time. The other most interesting execution began on line 18 and contributed the other 24.3% to the total. We know that lines 22-23 are uninteresting, but the simple method does not distinguish them. And that is why the report says the execution starting on line 18 has 5 dbcalls for 0.000018 seconds instead of 3 dbcalls for 0.000007 seconds.
If we significantly change the transformation function then we can handle the transaction ending at statement B (even if B is an EXEC followed by other B dbcalls (e.g., FETCH). Here is martin2.rc:
--init='
    my $sawB;
    my $xfrm_id;
    sub xfrm {
        if (($sqlid//"") eq "A") {
            $xfrm_id = $exec_id;    # global scope maintains state
        } else {
            if (($sqlid//"") eq "B") {
                $sawB = 1;
            } else {
                if ($sawB) {
                    $sawB = undef;
                    $xfrm_id = undef;
                }
            }
        }
        return $xfrm_id//0;
    }
'
--group='xfrm()'

In keeping with the notion of a profile (whereby the total represents the total for the whole experience), I decided to transform all non-interesting transaction dbcalls to 0 which is a line number that cannot appear in a file. This way you can see how the interesting transactions rank w.r.t. the whole experience.
$ mrskew --rc martin2.rc martin1.trc

 'xfrm()'  DURATION       %  CALLS      MEAN       MIN       MAX
---------  --------  ------  -----  --------  --------  --------
       25  0.000056   75.7%      3  0.000019  0.000008  0.000032
        0  0.000011   14.9%      2  0.000005  0.000005  0.000006
       18  0.000007    9.5%      3  0.000002  0.000001  0.000004
---------  --------  ------  -----  --------  --------  --------
TOTAL (3)  0.000074  100.0%      8  0.000009  0.000001  0.000032

If I duplicate line 20 (which takes 4 µsecs), then the output says this:
 'xfrm()'  DURATION       %  CALLS      MEAN       MIN       MAX
---------  --------  ------  -----  --------  --------  --------
       26  0.000056   71.8%      3  0.000019  0.000008  0.000032
       18  0.000011   14.1%      4  0.000003  0.000001  0.000004
        0  0.000011   14.1%      2  0.000005  0.000005  0.000006
---------  --------  ------  -----  --------  --------  --------
TOTAL (3)  0.000078  100.0%      9  0.000009  0.000001  0.000032

You can see that the interesting transaction starting on line 18 now contributes 11 µsecs over 4 dbcalls. This seems to be a more complete test confirming the appropriateness of martin2.rc.
In the last report, you can see that the interesting transaction represents 71.8%+14.1%=85.9% of the total response time in the file. If you further modify the transformation function (exercise left to the reader), then you can aggregate into "interesting" and "not interesting" rather than what I did, which was to add two percentages.


text:
Q: Is there a way to make frequency include business days but without (US) holidays in Python? I'm trying to generate a pandas.DataFrame with all the 'trading days' in 2017, essentially business days minus holidays.  Alternatively, I could make a list (from another pandas.DataFrame, called 'dates' for arguments sake.) and pass that but not quite sure how.
Below is code of what I am currently generating, but holidays are included.
new_fut = pd.DataFrame(pd.date_range(start = '2017-1-1', end = '2018-1-1',  freq = 'b'), columns = ['ds'])

A: Here you go. this will take out all the holidays from Custom Business Day.
import pandas as pd
from pandas.tseries.holiday import USFederalHolidayCalendar
from pandas.tseries.offsets import CustomBusinessDay
start ='2017-1-1'
end = '2018-1-1'
us_bd = CustomBusinessDay(calendar=USFederalHolidayCalendar())
df=pd.DatetimeIndex(start=start,end=end, freq=us_bd)

df

A: Check with bdate_range with your self-define holidays' list (yourlist)
pd.bdate_range(start='2017-1-1', end='2018-1-1',holidays = yourlist)

A: Pandas supports custom holiday and also has a built in USFederalHolidayCalendar that would probably meets your needs.
You can find more here:

http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html

Scroll down to Holidays/Holiday Calendars
under DateOffset objects