Q: in regx, is it possible to accurately extract a json scalar value? wish to extract a scalar value from json.

*

*know JSON uses double quotes.

*know datatype of scalar: string, number, date, boolean.

*know scalar will be on first level, ie, not an attribute of an embedded object
{ "want": "string" }  => "string"
{ "want": 123 } => 123
{ "not": { "want": "wrong" }, "want": "right" } => "right
{ "nothing": 0 } => null / not found
do not know how to handle the opening/closing quotes, nor do I know how to handle embedded objects.
is this possible?

this is the best I have come up with so far:
// match `want` attribute
(?:"want"\s*:\s*)

// string, number, boolean or null
(((?:")([^"]*)(?:"))|([-0-9][.eE0-9]*)|true|false|null)

// followed by comma or right bracket
(?:\s*(,|}))

it's good because it

*

*can be run in postgres

*grabs strings

*grabs numbers

*grabs boolean and null
it's bad because it

*

*does not ensure want is a first level attribute

*string value cannot have quote (") inside

A: This expression will get you 50% of the way there:
(?<=:\s*)(".*?"(?<!\\")|\-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?)(?=\s*})

Or, when written as a multi-line regex:
(?x:
    (?<=:\s*)           # After : + space
    (

        ".*?"(?<!\\")   # String in double quotes

        |               # -or-

        \-?             # Optional leading -ve
        (0|[1-9]\d*)    # Number
        (\.\d+)?        # Optional fraction
        ([eE][+-]?\d+)? # Optional exponent

    )
    (?=\s*})            # space + }
)

This will not match your nested object example ({ "not": { "want" ...) or rather, it will match, but on the wrong thing. Also, your final example ({ "nothing": 0 } => null / not found) is difficult because 0 is a valid number. To work around the this problem, I would just check the result in procedural code and replace a result of 0 with null.
The nested objects problem is a whole different ball game though. It's getting into the realm of lexical analysis rather than simple tokenizing. At that point, you might as well just use a JSON library because you'd be writing a full JSON parser anyway. Fortunately, JSON is a simple enough grammar that it wouldn't be that expensive to use a third party library - certainly no more than doing it yourself.
I think the short answer is: from a simple { "name" : <value> } object, yes, but from anything more complicated, no.
For info on the JSON syntax, see http://www.json.org/.


Q: How to hide "Save" button on the MS Dialogue (pop-up) Ribbon? I want to hide the "Save" button in the pop-up window which appears when we add new item.
I tried using javascript getElementById to hide in NewForm.aspx page but it didn't work.
Update:
 I executed the following code, but didn't work.
<script>
    $(document).ready(function(){
        $(".ms-cui-ctl-large .ms-cui-ctl-largelabel:first").text("Request");
     });
</script>

A: I found a way to hide the save button.
<style>
#Ribbon\.ListForm\.Edit\.Commit
    {
        display: none !important;
    }
</style>

A: Assuming you have jQuery included (and who doesn't these days!) it is simply a matter of executing the script below on the NewForm.aspx page after the ribbon is built.
jQuery(".ms-cui-ctl-large .ms-cui-ctl-largelabel:first").text("Request")

If you need a server-based solution, there's also this article from Microsoft.


Q: Simple Ray Tracing with Lambertian Shading, Confusion I didn't see another post with a problem similar to mine, so hopefully this is not redundant.
I've been reading a book on the fundamentals of computer graphics (third edition) and I've been implementing a basic ray tracing program based on the principles I've learned from it. I had little trouble implementing parallel and perspective projection but after moving onto Lambertian and Blinn-Phong Shading I've run into a snag that I'm having trouble figuring out on my own.
I believe my problem is related to how I am calculating the ray-sphere intersection point and the vectors to the camera/light. I attached a picture that is output when I run simply perspective projection with no shading.
Perspective Output
However, when I attempt the same scene with Lambertian shading the spheres disappear.
Blank Ouput
While trying to debug this myself I noticed that if I negate the x, y, z coordinates calculated as the hit point, the spheres appear again. And I believe the light is coming from the opposite direction I expect.
Lambertian, negated hitPoint
I am calculating the hit point by adding the product of the projected direction vector and the t value, calculated by the ray-sphere intersection formula, to the origin (where my "camera" is, 0,0,0) or just e + td.
The vector from the hit point to the light, l, I am setting to the light's position minus the hit point's position (so hit point's coords minus light's coords).
v, the vector from the hit point to the camera, I am getting by simply negating the projected view vector;
And the surface normal I am getting by hit point minus the sphere's position.
All of which I believe is correct. However, while stepping through the part that calculates the surface normal, I notice something I think is odd. When subtracting the hit point's position from the sphere's position to get the vector from the sphere's center to the hit point, I believe I should expect to get a vector where all of the values lie within the range (-r,r); but that is not happening.
This is an example from stepping through my code:
Calculated hit point: (-0.9971, 0.1255, -7.8284)
Sphere center: (0, 0, 8) (radius is 1)
After subtracting, I get a vector where the z value is -15.8284. This seems wrong to me; but I do not know what is causing it. Would a z value of -15.8284 not imply that the sphere center and the hit position are ~16 units away from each other in the z plane? Obviously these two numbers are within 1 from each other in absolute value terms, that's what leads me to think my problem has something to do with this.
Here's the main ray-tracing loop:
auto origin = Position3f(0, 0, 0);
for (int i = 0; i < numPixX; i++)
{
    for (int j = 0; j < numPixY; j++)
    {
        for (SceneSurface* object : objects)
        {
            float imgPlane_u = left + (right - left) * (i + 0.5f) / numPixX;
            float imgPlane_v = bottom + (top - bottom) * (j + 0.5f) / numPixY;

            Vector3f direction = (w.negated() * focal_length) + (u * imgPlane_u) + (v * imgPlane_v);

            Ray viewingRay(origin, eye, direction);

            RayTestResult testResult = object->TestViewRay(viewingRay);

            if (testResult.m_bRayHit)
            {
                Position3f hitPoint = (origin + (direction) * testResult.m_fDist);//.negated();

                Vector3f light_direction = (light - hitPoint).toVector().normalized();
                Vector3f view_direction = direction.negated().normalized();
                Vector3f surface_normal = object->GetNormalAt(hitPoint);

                image[j][i] = object->color * intensity * fmax(0, surface_normal * light_direction);
            }
        }
    }
}

GetNormalAt is simply:
Vector3f Sphere::GetNormalAt(Position3f &surface)
{
    return (surface - position).toVector().normalized();
}

My spheres are positioned at (0, 0, 8) and (-1.5, -1, 6) with rad 1.0f.
My light is at (-3, -3, 0) with an intensity of 1.0f;
I ignore any intersection where t is not greater than 0 so I do not believe that is causing this problem.
I think I may be doing some kind of mistake when it comes to keeping positions and vectors in the same coordinate system (same transform?), but I'm still learning and admittedly don't understand that very well. If the view direction is always in the -w direction, why do we position scene objects in the positive w direction?
Any help or wisdom is greatly appreciated. I'm teaching this all to myself so far and I'm pleased with how much I've taken in, but something in my gut tells me this is a relatively simple mistake.
Just in case it is of any use, here's the TestViewRay function:
RayTestResult Sphere::TestViewRay(Ray &viewRay)
{
RayTestResult result;

result.m_bRayHit = false;

Position3f &c = position;
float r = radius;
Vector3f &d = viewRay.getDirection();
Position3f &e = viewRay.getPosition();

float part = d*(e - c);
Position3f part2 = (e - c);
float part3 = d * d;
float discriminant = ((part*part) - (part3)*((part2*part2) - (r * r)));

if (discriminant > 0)
{
    float t_add = ((d) * (part2)+sqrt(discriminant)) / (part3);
    float t_sub = ((d) * (part2)-sqrt(discriminant)) / (part3);

    float t = fmin(t_add, t_sub);

    if (t > 0)
    {
        result.m_iNumberOfSolutions = 2;
        result.m_bRayHit = true;
        result.m_fDist = t;
    }
}
else if (discriminant == 0)
{
    float t_add = ((d)* (part2)+sqrt(discriminant)) / (part3);
    float t_sub = ((d)* (part2)-sqrt(discriminant)) / (part3);

    float t = fmin(t_add, t_sub);

    if (t > 0)
    {
        result.m_iNumberOfSolutions = 1;
        result.m_bRayHit = true;
        result.m_fDist = t;
    }
}

return result;
}

EDIT:
I'm happy to report I figured out my problem.
Upon sitting down with my sister to look at this I noticed in my ray-sphere hit detection I had this:
float t_add = ((d) * (part2)+sqrt(discriminant)) / (part3);

Which is incorrect. d should be negative. It should be:
float t_add = ((neg_d * (e_min_c)) + sqrt(discriminant)) / (part2);

(I renamed a couple variables) Previously I had a zero'd vector so I could express -d as (zero_vector - d)and I had removed that because I implemented a member function to negate any given vector; but I forgot to go back and call it on d. After fixing that and moving my sphere's into the negative z plane my Lambertian and Blinn-Phong shading implementations work correctly.
Lambertian + Blinn-Phong


Q: Dividing a rectangle into squares This is a rather simple question intuitively, but I can't seem to find a rigorous explanation for this:
suppose we are diving a rectangle into some number of equal sized squares, then they must all be aligned together(such that we can produce theses squares by performing horizontal and vertical cuts on the rectangle).
It makes sense to me, since if we have misalignment, then eventually we are going to reach a position where we can't fit the square. However, this assumes that the squares are originally aligned in the first place...
Any rigorous explanation/counter example to this?

A: I think it should be obvious given that you need to put a square in the corner in the rectangle (if you move it a distance away from one of the sides of the corner, that is less than the length of the square, you'll leave an unfillable gap). And, with that first square in place, you just created a new corner to be filled up, and again you need to put a square exactly in that spot ... etc.  This way, it should be clear that as you go along one side of the rectangle, you need to align all squares, and once that first row is done, the same story applies to the next row, etc. .. until the rectangle is all tiled.

A: Sketch: A corner which is a right-angle forces an orientation for the square which fills it. Once you run out of such corners you have filled the rectangle. Therefore all the squares are forced to have the same orientation.


Q: The type returned from the numeric index must be a subtype of the type returned from the string index In http://www.typescriptlang.org/Handbook#interfaces-array-types
what does it means that
"with the restriction that the type returned from the numeric index must be a subtype of the type returned from the string index."
Can someone give an example?

A: Just for reference, there are two types of index signatures, string and numeric.
String index signature:
[index: string]: SomeType

This says that when I access a property of this object by a string index, the property will have the type SomeType.
Numeric index signature:
[index: number]: SomeOtherType

This says that when I access a property of this object by a numeric index, the property will have the type SomeOtherType.
To be clear, accessing a property by string index is like this:
a["something"]

And by numeric index:
a[123]

You can define both a string index signature and a numeric index signature, but the type for the numeric index must either be the same as the string index, or it must be a subclass of the type returned by the string index.
So, this is OK:
interface SomeInterface {
    [index: string]: Fruit;
    [index: number]: Fruit;
}

Because both index signatures have the same type Fruit. But you can also do this:
interface SomeInterface {
    [index: string]: Fruit;
    [index: number]: Apple;
}

As long as Apple is a subclass of Fruit.


Q: Bootstrap making span width should not exceed image size I have a requirement to show image with a text together on same column where they both share same width. By default, text size will exceed image size if text is big enough. I manage to solve the issue by giving max-width style to span with some javascript code. I wonder is there a way to solve this issue without some Javascript black magic?

<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet" />

   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam a nisi aliquet, tempus felis non, sollicitudin erat. Phasellus dapibus lobortis magna, at maximus dui tincidunt sit amet. Suspendisse fringilla gravida velit, id pharetra libero semper in. Proin in lacus dui. In ultricies suscipit tortor, vel pharetra arcu efficitur non. Donec sed quam tellus. Maecenas lacinia vehicula mauris, eget facilisis metus elementum ut. Aliquam ullamcorper nisl non nunc fermentum pellentesque. Sed at pretium ligula. Quisque sit amet metus porta, scelerisque ligula nec, vulputate tortor. Curabitur blandit, tellus efficitur sollicitudin imperdiet, risus quam molestie risus, a mattis orci mauris bibendum velit. Curabitur volutpat porttitor enim ut fringilla. Nunc sit amet odio bibendum, tempus nulla vulputate, cursus nisl. Praesent tincidunt turpis ac risus ultrices mollis. Phasellus ipsum arcu, pharetra ut lectus luctus, sollicitudin pretium purus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris sagittis maximus ex, in dapibus tellus rhoncus at. Etiam id vestibulum arcu. Aenean sed hendrerit dui, et vehicula mi. Donec posuere sapien ac bibendum lobortis. Phasellus dignissim tempus ante, id tincidunt dolor consequat ut. Morbi aliquam porttitor condimentum. Aenean auctor libero erat, pretium facilisis lacus pharetra id. Etiam ipsum enim, faucibus eu felis id, pharetra blandit lectus. Integer ut metus ac odio bibendum egestas. Suspendisse potenti. Aenean ut feugiat mi. Vestibulum commodo massa dolor, ut tincidunt diam posuere at. Ut quis vehicula nulla, in imperdiet erat. Duis sed eleifend magna. Donec vulputate, lectus vel convallis aliquam, odio justo semper odio, a vulputate ante mauris non nisl. Sed sollicitudin tortor sit amet porta vehicula. Fusce sodales lorem eu dolor sodales, eu scelerisque nisl imperdiet. Duis hendrerit ligula sed tellus finibus dignissim. Proin vitae nibh dictum lorem accumsan finibus sed quis est. In est metus, euismod aliquet posuere a, laoreet ut urna. Nullam nec mauris a metus blandit lobortis. Aenean sed volutpat dolor. Curabitur tristique ligula magna, non elementum orci suscipit rutrum. In efficitur tortor ut enim commodo, sed consequat lacus varius. Morbi lectus ante, suscipit nec metus egestas, iaculis semper nisi. Nam a faucibus arcu, sit amet blandit nulla. Ut leo risus, suscipit id rhoncus et, posuere vitae diam. Cras et porttitor nibh, vel ornare lacus. Etiam nec lectus nunc. Maecenas scelerisque purus sed ex gravida volutpat. Nam vehicula tortor diam, et eleifend orci maximus accumsan. Donec gravida turpis ut interdum rutrum. Phasellus non lobortis quam. Sed quis laoreet lectus. Curabitur eu faucibus massa. Fusce feugiat arcu nec ante ultricies vulputate. Mauris gravida finibus nisl. Fusce suscipit blandit erat nec gravida. Vivamus auctor dapibus augue, sit amet porttitor diam tempor eu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Quisque condimentum eleifend posuere. Aliquam porttitor odio a tincidunt varius. Proin id semper orci. Suspendisse potenti. Aliquam fringilla laoreet cursus. Vestibulum dictum urna in sem elementum, sed lacinia eros tincidunt.

https://jsfiddle.net/p315wutg/


Q: OS X design decisions. Terminate the app on last window close? Unlike Windows, GNOME and most other GUI's, OS X application programs do not all terminate if the main window (or all the windows) of that application are closed.
For example, fire up Firefox, Safari, Word, or most document based apps. Either click the red dot in the corner or type cmdW to close the window. You can see that the menu of that program is still active, and the program is still running. With OS X newbies, sometimes you will see dozens of these windowless zombies running and they wonder why their computer is getting slower.
With some document based programs, there is some sense to not terminating the application if it has no windows. For example, with Safari or Word, you can still type CmdN and get a new document window for whatever that application was designed to do: browse the web (Safari) or type a new document (Word).
Apple is mixed with their design philosophy on this. Some close on the last window closed and some do not. Third party apps are even more mixed.
There are other apps that do close when their red close button is clicked. System Preferences, Dictionary, the Mac App Store, iPhoto and Calculator do terminate when the sole or last window is closed. iCal, Address Book, iTunes, DVD Player do not terminate.
What I find particularly annoying is the applications that do not have a logical "New Document" or "Open" function yet they do not terminate when the document window is closed. Example: fire up iTunes or Address Book and terminate the main window. There sits a zombie with no window and no function other than manually selecting "Quit".
It is easy to close the application after the last window closes. Cocoa even gives you notification of that event. Just add this to your application delegate:
  - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
{
    return YES;
}

My question is this: Is there any reason I should NOT terminate my application after the last window closes? Why is this so variable on OS X software? Unless the app has a "new" or "open" or some other clearly understood reason to not terminate with no window open, the failure to terminate seems like a bug to me.

A: In general, never close a document based application when the last window closes. The user will expect to be able to open a new document without relaunching the application, and it will confuse them if they can't.
For non-document based applications, you need to consider a few things:

*

*How long does it take for my application to open? If it takes more than a second, you should probably not quit.

*Does my application need a window to be useful? If your application can do work without windows, you should not quit.

iTunes doesn't quit because, as Anne mentioned, you don't need a window to play music (question 2). It is also not based on Cocoa, so it is much more difficult to close after the last window, especially since it allows you to open windows for specific playlists so there are an indefinite number of possible windows to be open.
In my opinion, Address Book does not need to stay open. This could be a left-over design decision from older versions of OS X, or it could be that someone at Apple just thought it was better to leave it open (maybe so you can add a contact?). Both iTunes and Address Book provide access to their main interfaces through the Window menu, as well as a keyboard shortcut (Option+Command+1 for iTunes, Command+0 for Address Book).

A: Per Apple's Human Interface Guidelines (a guide for Mac developers):

In most cases, applications that are
  not document-based should quit when
  the main window is closed. For
  Example, System Preferences quits if
  the user closes the window. If an
  application continues to perform some
  function when the main window is
  closed, however, it may be appropriate
  to leave it running when the main
  window is closed. For example, iTunes
  continues to play when the user closes
  the main window.

A: The main iTunes window can be reopened from the 'Window' menu.  Mail.app has similar behavior.  I can't think of any applications that close when the last window is closed, and as such I don't think there's a good reason that your app should behave that way (in fact, i'm surprised its not in Apple's user experience guidelines, it would really bother me!).
One reason why you'd want to close e.g. the iTunes main window but keep the app open is to be able to use the app as sort of a server for third party scripts/applications.  I rarely use the main iTunes interface, but instead control my music with a third party app.  I also write AppleScripts for other apps that I launch instead of interacting with that app's interface.


Q: EF 6 - How to correctly perform parallel queries When creating a report I have to execute 3 queries that involve separated entities of the same context. Because they are quite heavy ones I decided to use the .ToListAsync(); in order to have them run in parallel, but, to my surprise, I get a exception out of it...
What is the correct way to perform queries in parallel using EF 6? Should I manually start new Tasks?
Edit 1
The code is basically
using(var MyCtx = new MyCtx())
{
      var r1 = MyCtx.E1.Where(bla bla bla).ToListAsync();
      var r2 = MyCtx.E2.Where(ble ble ble).ToListAsync();
      var r3 = MyCtx.E3.Where(ble ble ble).ToListAsync();
      Task.WhenAll(r1,r2,r3);
      DoSomething(r1.Result, r2.Result, r3.Result);
}

A: As a matter of interest, when using EF Core with Oracle, multiple parallel operations like the post here using a single DB context work without issue (despite Microsoft's documentation).  The limitation is in the Microsoft.EntityFrameworkCore.SqlServer.dll driver, and is not a generalized EF issue.  The corresponding Oracle.EntityFrameworkCore.dll driver doesn't have this limitation.

A: The problem is this:

EF doesn't support processing multiple requests through the same DbContext object. If your second asynchronous request on the same DbContext instance starts before the first request finishes (and that's the whole point), you'll get an error message that your request is processing against an open DataReader.

Source: https://visualstudiomagazine.com/articles/2014/04/01/async-processing.aspx
You will need to modify your code to something like this:
async Task<List<E1Entity>> GetE1Data()
{
    using(var MyCtx = new MyCtx())
    {
         return await MyCtx.E1.Where(bla bla bla).ToListAsync();
    }
}

async Task<List<E2Entity>> GetE2Data()
{
    using(var MyCtx = new MyCtx())
    {
         return await MyCtx.E2.Where(bla bla bla).ToListAsync();
    }
}

async Task DoSomething()
{
    var t1 = GetE1Data();
    var t2 = GetE2Data();
    await Task.WhenAll(t1,t2);
    DoSomething(t1.Result, t2.Result);
}

A: Check out https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/enabling-multiple-active-result-sets
From the documentation:

Statement interleaving of SELECT and BULK INSERT statements is
  allowed. However, data manipulation language (DML) and data definition
  language (DDL) statements execute atomically.

Then your above code works and you get the performance benefits for reading data.


Q: Displaying data from web api into tables with ajax I have a web api in the url "http://jendela.data.kemdikbud.go.id/api/index.php/ccarisanggar/searchGet", and I intend to display with jquery ajax and inserted into the table, I've been trying to find a tutorial but it's hard to get it

A: By Jquery you can do this way
$.ajax({
  url: 'http://jendela.data.kemdikbud.go.id/api/index.php/ccarisanggar/searchGet',
  type: 'GET',
  success: function (responce) {
  // code to append into your table
  },
  error: function (jqXHR, textStatus, errorThrown) {
  }
});

A: I can't show you the whole code snippet. Anyway, hope this help for you.

        Column 1
        Column 2
        Column 3

A: As mentioned I believe you are using codeigniter as your php framework.
To accomplish your task you need follow below steps :
1.) In view file for eg. myview.php add this

2.)To save the data in the database either create event handler such as button clicks or you can try using setInterval function.
<button id="mybt" onclick="save_to_db()">Save to DB</button>

A: In your HTML tag

In your script tag
var url="http://jendela.data.kemdikbud.go.id/api/index.php/ccarisanggar/searchGet";

$.ajax({
    type: "GET",
    url: url,
    cache: false,
    // data: obj_data,
    success: function(res){
        console.log("data",res);
        //if you want to remove some feild then delete from below array
        var feilds =["sanggar_id","kode_pengelolaan","nama","alamat_jalan","desa_kelurahan","kecamatan","kabupaten_kota","propinsi","lintang","bujur","tahun_berdiri","luas_tanah"];
        var html='';
        html+=`

`;
        $.each(feilds,function(key,val){
            html+=`<th class="${val}">${val}</th>`;
        })
        html+=`

`;

        $.each(res.data,function(key,val){

            html+=`<tr>`;
            $.each(feilds,function(aaa,feild){
                html+=`<th class="${val[feild]}">${val[feild]}</th>`;
            })
            html+=`</tr>`;
        })
        html+=`

`;
        $("#data").html(html);
    },
});


Q: How well do answers bubble up? For context, I mostly use sites of "medium" size and traffic, like unix.SE - it's not clear whether that makes a difference to this question.
From experience, it seems that the effect of good answers "bubbling up" by collecting upvotes over time does not always work as good as I would hope.
If there are some quick initial answers in short time, and they are voted up,
it seems very hard for a later answer to catch up with the votes of the initial answers.
The problem seems to be that the "bubble up" mechanism basically works, but is too slow - it seems that even after multiple years, there is only a little progress in many cases.

It would be very interesting to have some kind of numbers, supporting or rejecting this - or giving any partial hint.
Examples are not of much use, I think;
Are there any existing statistics in this area, or attempts to analyze how effective the mechanism of "bubbling up" of answers by votes works?


Q: "Manifest merger failed with multiple errors, see logs" error in android studio I'm new to kotlin, I'm practicing the basics. Anytime I run a simple code it refuses it run and I get a
Execution failed for task ':app:processDebugAndroidTestManifest'.
> Manifest merger failed with multiple errors, see logs

error.
I don't know what is the cause, please note I am literally running a print("Hello") function
Here's my manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hellokotlin">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.HelloKotlin">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

And Here's my gradle.build:
plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.hellokotlin"
        minSdk 21
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

I get this from the build output (as logcat is empty)
Executing tasks: [:app:generateDebugSources, :app:createMockableJar, :app:generateDebugAndroidTestSources, :app:compileDebugUnitTestSources, :app:compileDebugAndroidTestSources, :app:compileDebugSources] in project C:\Users\user\AndroidStudioProjects\HelloKotlin

> Task :app:preBuild UP-TO-DATE
> Task :app:preDebugBuild UP-TO-DATE
> Task :app:compileDebugAidl NO-SOURCE
> Task :app:compileDebugRenderscript NO-SOURCE
> Task :app:compileLintChecks UP-TO-DATE
> Task :app:generateDebugBuildConfig UP-TO-DATE
> Task :app:generateDebugSources UP-TO-DATE
> Task :app:createMockableJar UP-TO-DATE
> Task :app:preDebugAndroidTestBuild SKIPPED
> Task :app:compileDebugAndroidTestAidl NO-SOURCE

> Task :app:processDebugAndroidTestManifest FAILED
C:\Users\user\AndroidStudioProjects\HelloKotlin\app\build\intermediates\tmp\manifest\androidTest\debug\tempFile1ProcessTestManifest1728079930965623012.xml Error:
    android:exported needs to be explicitly specified for <activity>. Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported` when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.
C:\Users\user\AndroidStudioProjects\HelloKotlin\app\build\intermediates\tmp\manifest\androidTest\debug\tempFile1ProcessTestManifest1728079930965623012.xml Error:
    android:exported needs to be explicitly specified for <activity>. Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported` when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.
C:\Users\user\AndroidStudioProjects\HelloKotlin\app\build\intermediates\tmp\manifest\androidTest\debug\tempFile1ProcessTestManifest1728079930965623012.xml Error:
    android:exported needs to be explicitly specified for <activity>. Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported` when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.

See http://g.co/androidstudio/manifest-merger for more information about the manifest merger.

> Task :app:checkDebugAarMetadata UP-TO-DATE
> Task :app:generateDebugResValues UP-TO-DATE
> Task :app:generateDebugResources UP-TO-DATE
> Task :app:mergeDebugResources UP-TO-DATE
> Task :app:createDebugCompatibleScreenManifests UP-TO-DATE
> Task :app:extractDeepLinksDebug UP-TO-DATE
> Task :app:processDebugMainManifest UP-TO-DATE
> Task :app:processDebugManifest UP-TO-DATE
> Task :app:processDebugManifestForPackage UP-TO-DATE
> Task :app:processDebugResources UP-TO-DATE
> Task :app:compileDebugKotlin
> Task :app:javaPreCompileDebug UP-TO-DATE
> Task :app:compileDebugJavaWithJavac UP-TO-DATE
> Task :app:preDebugUnitTestBuild UP-TO-DATE
> Task :app:javaPreCompileDebugUnitTest UP-TO-DATE
> Task :app:processDebugJavaRes NO-SOURCE
> Task :app:processDebugUnitTestJavaRes NO-SOURCE
> Task :app:checkDebugAndroidTestAarMetadata UP-TO-DATE
> Task :app:generateDebugAndroidTestResValues UP-TO-DATE
> Task :app:javaPreCompileDebugAndroidTest UP-TO-DATE
> Task :app:compileDebugSources UP-TO-DATE
> Task :app:bundleDebugClasses

> Task :app:compileDebugUnitTestKotlin
w: C:\Users\user\AndroidStudioProjects\HelloKotlin\app\src\test\java\com\example\hellokotlin\ExampleUnitTest.kt: (15, 25): This expression will be resolved to Int in further releases. Please add explicit convention call

> Task :app:compileDebugUnitTestJavaWithJavac NO-SOURCE
> Task :app:compileDebugUnitTestSources UP-TO-DATE

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processDebugAndroidTestManifest'.
> Manifest merger failed with multiple errors, see logs

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/7.0.2/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 13s
20 actionable tasks: 4 executed, 16 up-to-date

Thanks for your help in advance.
UPDATE:
I created a new project, a no activity project, and it seems to be going fine. Unlike before I was using a project that has an activity. BUT, I have notice that this is a common issue so I would love if you could explain this to me for future references, thanks for your help.

A: Just update your androidx.test.ext:junit dependency to 1.1.3 or later. This should solve your problem.
androidTestImplementation "androidx.test.ext:junit:1.1.3"

A: It might be due to deprecated gradle features used is incompatible with your Gradle version 8.0
Try running the Gradle build with this command line argument --warning-mode=all.
It will give detailed description of what exactly the deprecated features are used along with links to documentation regarding the fix.


Q: How is the pentaho community server installed on linux? Where can I find the pentaho community files, how is it installed, and how do I access the user console?

A: Pentaho files are found at:
https://sourceforge.net/projects/pentaho/files
The server is in the 'Business Intelligence Server' folder.
Download the zip file of the latest version, and unzip it. Open a terminal at the location of the unziped directory, and then cd into the directory. Now run ./start-pentaho.sh. It is a java application, so make sure you have java installed.
The server is now running, and the 'user console' can be accessed through a web browser at localhost:8080 by default. It was very slow for me, just fyi. The default login is 'admin' and 'password'.


Q: Apache Spark - how to see how many nodes are being used during a job run? I am using Scala Spark 2.4 and want to know the usage of the queue.
How to display how many nodes from a big cluster (100+ nodes) are being utilized for any particular job that is running?
Thanks.


Q: Swift Error: exc_bad_instruction (code=exc_i386_invop subcode=0x0) I've looked on the site for the answer to my problem, but I could not find a solution that would work for me. I am getting the error code every time I run my application on the Iphone 5 simulator. But I do not get the error on Iphone 6 and up. Why is this? It will crash when I press a button or it will crash as soon as I go to the third screen.
func pickQuestion () {

    if (Questions.count  > 0 ) && (numberWrong < 4 ){
    ***qNum = Int(arc4random()) % Questions.count***
    qLabel.text = Questions[qNum].Question
    answerNum = Questions[qNum].Answer

        for i in 0..<buttons.count {

            buttons[i].setTitle(Questions[qNum].Answers[i], for: UIControlState.normal)
        }
        Questions.remove(at: qNum)

}
    else {

        actioncall()

    }
func actioncall () {
    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    let vc: GameOverViewController = storyBoard.instantiateViewController(withIdentifier: "Game Over") as! GameOverViewController
    self.present(vc, animated: true, completion: nil)

}


Q: iterator got by applying begin() on getter method doesn't allow to access to first elements of pointed list I have a object's pointer *myObject with a getter method:
vector<string> getList();

When I create my iterator to run throught my list variable returned by getList() like this:
vector<string>::const_iterator it = myObject->getList().begin();

and I display it:
cout << *it << endl;

It displays me nothing (certainly an empty string).
It's similar for it+1, it+2, it+3, it+4, but from it+5 it displays the right element
Whereas, when I rewrite the code like this:
vector<string> myList = myObject.getList();
vector<string>::const_iterator it = myList.begin();
cout << *it << endl;

Everything works.
Could you help me to understand this problem please?
Thank you.

A: When you do this:
vector<string>::const_iterator it = myObject->getList().begin();

At the end of the line, the iterator it is invalid, because the vector<string> returned by getList() is a temporary value.
However, when you store the vector<string> in a local variable, with
vector<string> myList = myObject.getList();

Then, the iterator remains valid, as long as myList is not destroyed.

A: In the frist case the code has undefined behaviour because the temporary object of type std::vector<std::string> returned by function myObject.getList() will be deleted at the end pf executing the statement. So the iterator will be invalid.
Apart from the valid code in the second example you could also write
const vector<string> &myList = myObject.getList();
vector<string>::const_iterator it = myList.begin();
cout << *it << endl;

that is you could use a constant reference to the temporary object.

A: The problem is that you are returning a copy of vector, it would go out of scope and out of existance, thus be invalid.
What you want to do is return a const reference to your list.
const vector<string>& getList();


Q: Run other code while awaiting This is probably a stupid question, but my current project is stuck until I figure it out.
Say I have this function.
async function AtoB() {
   try{
      await ACheck();
      let quantity = (ABalance - (1 / ABuy));
      quantity = parseFloat(quantity.toFixed(4));
      exchange.createMarketBuyOrder('A/B', quantity)
      trade();
   } catch(err) {
      console.log(err);
   }
}

The function is awaiting another function called ACheck() that looks like this:
async function ACheck() {
   while(ABalance/ABuy < 10) {
   }
   return true;
}

My issue is that ABalance and ABuy are set in another function that gets their values using CCXT. When AtoB() runs, it stops a setTimeout I have in place that calls the price function every 5 seconds. This effectively means that the function will never run since the values for ABalance and Abuy never update.
Is there any way to run the prices function at the same 5 seconds intervals while awaiting ACheck()?
Thanks in advance

A: You are not allowed to block the main thread if you want to run other things async.
Just have your setTimeout run like it does now, when it fires, calculate ABalance/ABuy. If Abalance/Abuy < 10, do nothing and wait for next setTimeout to fire. If not, do the rest.


Q: Magento get salesrule id from product_id (or entity_id) We are using Magento Enterprise 1.10 and I need a way to get the salesrule_id for each product on category pages as well as product detailed pages. This is pretty easy when you're using the cart.
Basically all I want to do is something like this --> Pseudo query
SELECT rule_id FROM salesrule WHERE entity_id = <entity_id)

Do you know of any way to do this outside of the cart. Is there a method I can call with a product id that return's a rule_id if it exists for this product?
Any suggestion would greatly help me.

A: A product does not have sales rules attached to it and there is no inbuilt method to load rules for a given product. On the cart page it is easy because the rule gets applied to the quote and on each item you can get applied_rule_ids which gives you the ids of any matched rules currently applied to the quote item which is not the same as a product object. So for example, you could have multiple sales rules which apply to the same item so applied_sales_rule_ids would give you all the applied rules not just one.
You could try and load a collection of sales rules and add a filter on the product_ids column and then pass in the entity id of the product. This post here explores this with some code examples and may be of some help.

A: Try to use Mage_CatalogRule_Model_Resource_Rule::getRulesFromProduct().


Q: Query a specific time-range and alert at specific time of the day I need to run a rule at 2 am, querying logs from 0 to 2 am, and alert if matches are found.
So far all the rules I created are frequency rules, but I don't know how to achieve the specific time range for the query, and a specific time for the alert, can someone please help?
(I guess the ANY type could let me add my time range as part of the filter....but then how can I run the rule at 2 am every day?)

A: In UTC:
filter:
  range:
    "@timestamp":
      gte: "now/d+0h"
      lt: "now/d+2h"

A: The now is take the time of the server.
filter:
 - range:
   "@timestamp":
      "from": "now-2h"
       "to": "now"

A: if you want your alert to be effective for specific hours only, you can
create an enhancement that drop the alert if the current time doesnt match your needs
check
https://elastalert.readthedocs.io/en/latest/recipes/adding_enhancements.html
regards


Q: Auto Number Name field dependent on picklist value I have a Auto Number standard field (Name) of custom object (Term__c) which is to be dependent on custom field Color__c (picklist) of same custom object.
For each picklist value, such as "red", "blue", "green", Name should start from 0, and for each picklist value it should be incremented on creating more records. We have to use trigger.
Can any one let me know how should I proceed?

A: You cannot modify the behavior of an auto-number field other than to set a display format, which can use the merge fields Y, M, D, and 0, for year, month, day, and the auto-number counter, respectively. You would need to start with a normal text field then update the value in your trigger/process builder/flow.


Q: How can I handle multipart/form-data POST requests in my java servlet? I'm having a very hard time dealing with multipart/form-data requests with my java application server.  From what I have found out, the servlet 3.0 specification provides methods such as HttpServletRequest.getParts(), which would be ideal for processing the form data uploaded to my servlet.
However, this method is part of the 3.0 servlet specification, and my application server (Tomcat 6) does not support this yet.  Even with a valid 3.0 web.xml file and the java EE 6 libs, I get the following exception when trying to call getParts():
java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.getParts()Ljava/util/Collection;

Switching application servers is not really a feasible option for this project.  Are there any third-party libraries available for processing multipart/form-data within java servlets?

A: Tomcat 6 does not and will not support Servlet Specification 3.0. You should attempt doing this on Tomcat 7, but I'm not really sure whether this functionality is present in the beta release that is currently available. The functionality is expected to be present in the production release though.
You could continue using Apache Commons FileUpload like posted in the other answer, or you could use Glassfish (depending on the current phase and type of your project).

A: Check out Apache Commons Fileupload.  It gives you a programmatic API to parse a multipart request, and iterate through the parts of it individually.
I've used it in the past for straightforward multipart processing and it does the job fine without being overly complicated.

A: when we used post method than data are encrypted so we have to used servletfileupload to get requested data and using FileItemIterator  we can get all form data.
i already answer on this link How to process a form sent Google Web Toolkit in a servlet


Q: How does light heat things up? If heat is due to vibration of a material how does light heat the material up?
I placed my phone under the sun (I forgot it was there) and when I picked it up after an hour, I noticed it was extremely hot. So it got me thinking, if light is made of photons and photons are massless. How does a massless particle which collides with the material heat it up? Without mass there would be no force (Newton's second law) which should mean there wouldn't be any vibrations, which means no heat.
I know it's wrong but I'm not sure where I'm wrong. So to reiterate my question: how does light heat up material?

A: We use microwaves: we eat a hot food and become happy. The microwave uses the lights, but their wave length is about micrometers. So we cannot see them.
The light is electro-magnetic field, which can accelerate (charged) particles. So clearly we can heat up materials with light.
Of course, the rest mass of light is zero. However, light has it's energy.


Q: Why is the insantiation of this singleton class giving different values Why do these two statement give different outcomes...

*

*print(Database().id == Database().id) (which gives False)

*but it gives True this way

d1 = Database()
d2 = Database()
print(d1.id == d2.id)

here's the entire code:
import random

class Database:
    initialized = False

    def __init__(self):
        self.id = random.randint(1, 101)

    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Database, cls).__new__(cls, *args, **kwargs)
        return cls._instance

print(Database().id == Database().id)
# False

d1 = Database()
d2 = Database()
print(d1.id == d2.id)
# True

A: __new__() always calls __init__() if the returned instance is of the correct class. This means, every Database() call is still going through and setting a new random value to id.
This id is an instance variable that you have defined, it will not really affect the result of id(), which is why if you do
print(Database() is Database())

it will return True even though the id check returned false. The instance is the same, you just changed id value in between, so they evaluate as False.
In the second case, because the instance is the same, both of them get the value generated by __init__() when you assign d2. You can confirm this by adding a print(d1.id) before and after d2 is assigned.
You need to make use of the initialized boolean to correctly skip the code in __init__()
import random

class Database:
    initialized = False

    def __init__(self):
        if not self.initialized:
            self.id = random.randint(1, 101)
            self.initialized = True

    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Database, cls).__new__(cls, *args, **kwargs)
        return cls._instance

Take a look at issue with singleton python call two times __init__  if you want to see other implementations of a singleton class or alternative approaches that avoid singleton entirely.


Q: Es posible hacer esta consulta en linq? SELECT CL.ClNIt, CL.ClNombresApe, VS.VsFeha, VS.VsValorNeto,
VS.VsValorVisita,SUM(CC.CcValor) AS SumCupos, CL.ClSaldoCupo
FROM Visitas VS
INNER JOIN Clientes CL ON VS.ClNit = CL.ClNIt
INNER JOIN CuposCliente CC ON CL.ClNIt = CC.CcClNit
WHERE CL.ClNIt = 'YMvRBEZ3+aE='
GROUP BY CL.ClNIt, CL.ClNombresApe, VS.VsFeha, VS.VsValorNeto, VS.VsValorVisita , CL.ClSaldoCupo

A: Sería algo así
var resultado = from tabla1 in dbo.context1
                join tabla2 in dbo.context2 on tabla1.id == tabla2.id
                join tabla3 in dbo.context3 on tabla2.id ==tabla3.id
group tabla3 by new { tabla1.valor, tabla2.valor } into g
            select new {
                valor1= g.Key.valor,
                Valor2= g.Key.Valor,
                Total = g.Sum(t3 => t3.valor)
            };


Q: Period with quotes and double quotes Consider the following sentences:
Long ago, "fuego" started with an "h" instead of "f".
There is connection between the words, "bishop" and "episcopal".
Is the period used correctly after the closing quote in both sentences? Or should it go inside the quotes?

A: In British English, yes. The comma placement is correct.

A: Both are possible, as long as you stay consistent. Check out the Guid to Punctuation by Larry Trask (University of Sussex). About ¾ down the linked page ("Quotation Marks and Direct Quotations"), you will find this:

Finally, there remains the problem of whether to put other punctuation
  marks inside or outside the quotation marks. There are two schools of
  thought on this, which I shall call the logical view and the
  conventional view.
The logical view holds that the only punctuation marks which should be
  placed inside the quotation marks are those that form part of the
  quotation, while all others should be placed outside. The conventional
  view, in contrast, insists on placing most other punctuation marks
  inside a closing quote, regardless of whether they form part of the
  quotation. Here are two sentences punctuated according to the logical
  view:
"The only thing we have to fear", said Franklin Roosevelt, "is fear
  itself."
  The Prime Minister condemned what he called "simple-minded
  solutions". And here they are punctuated according to the conventional
  view:
"The only thing we have to fear," said Franklin Roosevelt, "is fear
  itself." The Prime Minister condemned what he called "simple-minded
  solutions." Note the placing of the comma after fear in the first
  example and of the final full stop in the second. These are not part
  of their quotations, and so the logical view places them outside the
  quote marks, while the conventional view places them inside, on the
  theory that a closing quote should always follow another punctuation
  mark.

After that, he goes on to explain why he prefers to "logical way".

A: OK, I finally seem to have found a concrete mandate on this issue after digging a little deeper. Not sure if I should reference my source as a valid one since it's definitely not official but I'll let the readers be the judge. Here's the link: Quotation Marks: Where Do the Commas and Periods Go--and Why?
To quote the article, universal American usage places commas and periods inside the quotation marks, regardless of logic.

~"Diane," she said, "put the book down and go outside for a little
  while."
~"I will in a minute," she replied, "as soon as I finish this
  chapter."

This rule applies even when the unit enclosed at the end of the sentence is just a single word rather than an actual quotation:

~To get to the next page, just press the little button marked "Enter."

The only exception is when that last little item enclosed in quotation marks is just a letter or a number, in which case the period or comma will go outside the closing quotation marks:

~The buried treasure was marked on the map with a large "X".
~The only grade that will satisfy her is an "A".
~On this scale, the highest ranking is a "1", not a "10".


Q: When I tried to generate a table, I got this error "Undefined control sequence", how to fix it? This post gives a convenient approach to generate Latex code and I am trying to reproduce that.
This is a piece of Python code,
>>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
...                    'mask': ['red', 'purple'],
...                    'weapon': ['sai', 'bo staff']})
>>> print(df.to_latex(index=False)) # doctest: +NORMALIZE_WHITESPACE

which generated this Latex code
\begin{tabular}{lll}
\toprule
      name &    mask &    weapon \\
\midrule
   Raphael &     red &       sai \\
 Donatello &  purple &  bo staff \\
\bottomrule
\end{tabular}

I compiled this code and got this table

and this error
Undefined control sequence

l.15 \toprule

The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.

How to fix it?

A: \toprule (and \midrule or \bottomrule) are defined in the booktabs package. It must be included before any use.
This package largely improves the visual appearance of tables by providing rules with varying width and by fixing some line spacing problems. Standard latex uses \hline to draw a rule between lines.
\documentclass{article}

\usepackage{booktabs}

\begin{document}
\begin{tabular}{lll}
\toprule
      name &    mask &    weapon \\
\midrule
   Raphael &     red &       sai \\
 Donatello &  purple &  bo staff \\
\bottomrule
\end{tabular}
\end{document}


Q: sprung into actions or sprung into action? My question here is which is the correct phrase to use? Action with the S or without the S, and why?

A: Without the /-s/. Why? Because it's idiomatic English to say that someone {sprang / sprung} into action and not idiomatic to use actions. It's a standard cliché and, of course, an idiom.


Q: Is there a way to compute this antiderivative by u-substitution? I started by trying to find an expression for $\int \ln(ax^n + b) dx$ where $a,n,b$ are integers $>0$. So naturally I used integration by parts and arrived at $$x\ln(ax^n + b) - \int \dfrac{ax^{n}}{ax^n + b}dx$$ Is there a way to compute $\int \frac{ax^{n}}{ax^n + b}dx$ by u-substitution or any other method?

A: Hint:
In some certain cases depending on the powers, you may use Chebyshev theorem on the integration of binomial differentials for such that integral.

A: Outline:  With a change of variable we end up integrating $\ln(c(t^n+1))$ for some positive constant $c$, and then we only need to find $\int \ln(t^n+1)\,dt$. It is too early to integrate by parts. Instead, factor $t^n+1$ over the reals.
Depending on whether $n$ is odd or even, we get that $t^n+1$ is $t+1$ times a product of irreducible quadratics, or just a plain product of irreducible quadratics. These irreducible quadratics are all of the shape $t^2-(2\cos\theta)t +1$. The logarithm of this product is a sum of logarithms.
We look at the case $n$ even. The case $n$ odd is similar. So we are integrating terms of the shape $\ln(t^2-(2\cos\theta) t+1)$. The integration by parts procedure suggested in the OP works. It is helpful to first complete the square.

A: Solution in which I suppose $n > 0$
There is a way, but you shall know special functions, like the HyperGeometric Special Function.
Let's collect $ax^n$:
$$\int\frac{ax^n}{ax^n\left(1 + \left(\frac{b}{a}x^{-n}\right)\right)}\ \text{d}x$$
With the help of Geometric Series we find
$$\int\sum_{k = 0}^{+\infty} \left(-\frac{b}{a}x^{-n}\right)^k\ \text{d}x = \sum_{k = 0}^{+\infty}\left(-\frac{b}{a}\right)^k\int x^{-kn}\ \text{d}x$$
Integration is trivial, the resulting series is
$$\sum_{k = 0}^{+\infty}\left(-\frac{b}{a}\right)^k \frac{x^{-kn + 1}}{-kn+1}$$
This series does converge to the HyperGeometric Special Function:
$$\sum_{k = 0}^{+\infty}\left(-\frac{b}{a}\right)^k \frac{x^{-kn + 1}}{-kn+1} = x\cdot _2F_1\left[1, -\frac{1}{n}, 1 - \frac{1}{n}, -\frac{b}{a}x^{-n}\right]$$
More on HSF
https://en.wikipedia.org/wiki/Hypergeometric_function


Q: Why do I get this error? 'NoneType' object has no attribute 'shape' in opencv I'm working on real-time clothing detection. so i borrowed the code from GitHub like this:https://github.com/rajkbharali/Real-time-clothes-detection
but (H, W) = frame.shape[:2]:following error in last line.
Where should I fix it?
from time import sleep
import cv2 as cv
import argparse
import sys
import numpy as np
import os.path
from glob import glob
import imutils
from imutils.video import WebcamVideoStream
from imutils.video import FPS

from google.colab import drive
drive.mount('/content/drive')

%cd /content/drive/My Drive/experiment/Yolo_mark-master/x64/Release/

Labels = []
classesFile1 = "data/obj.names";
with open(classesFile1, 'rt') as f:
    Labels = f.read().rstrip('\n').split('\n')

np.random.seed(42)
COLORS = np.random.randint(0, 255, size=(len(Labels), 3), dtype="uint8")

weightsPath = "obj_4000.weights"
configPath = "obj.cfg"

net1 = cv.dnn.readNetFromDarknet(configPath, weightsPath)
net1.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
net1.setPreferableTarget(cv.dnn.DNN_TARGET_CPU)

image = WebcamVideoStream(src=0).start()
fps = FPS().start()
#'/home/raj/Documents/yolov3-Helmet-Detection-master/safety.mp4'

#while fps._numFrames<100:
while True:
#for fn in glob('images/*.jpg'):
    frame = image.read()
    #frame = imutils.resize(frame,width=500)
    (H, W) = frame.shape[:2]

A: The reason behind your error is that the frame is None(Null). Sometimes, the first frame that is captured from the webcam is None mainly because
(1) the webcam is not ready yet ( and it takes some extra second for it to get ready)
or (2) the operating system does not allow your code to access the webcam.
In the first case, before you do anything on the frame you need to check whether the frame is valid or not :
while True:

    frame = image.read()
    if frame is not None:  # add this line

      (H, W) = frame.shape[:2]

In the other case, you need to check the camera setting in your Operating system.
Also, for capturing the webcam frames there is another method based on the VideoCapure class in Opencv that might be easier to debug.


Q: Implementing channels in haskell -- Tackling the awkward squad

In the paper Tackling the awkward squad, Simon Peyton Jones has provided a "possible implementation" of a Channel.
type Channel a = (MVar (Stream a) , -- Read end
                  MVar (Stream a) ) -- Write end (the hole)

type Stream a = MVar (Item a)

data Item a = MkItem a (Stream a)

Now, he implements a function putChan :: Channel a -> a -> IO () like this
putChan (read, write) val
  = do { new_hole <- newEmptyVar ;
         old_hole <- takeMVar write ;
         putMVar write new_hole ;
         putMVar old_hole (MkItem val new_hole) }

The function above takes a MVar out of write, then puts an empty MVar into it.
Then it writes to the old_hole it extracted from write.
The question is, why does it write to old_hole? It has been taken out from write and its scope is limited to the current block only, then what difference does it make?

A:
The question is, why does it write to old_hole? It has been taken out from write and its scope is limited to the current block only, then what difference does it make?

Not quite. old_hole is "in scope" on the read side. You have to look at newChan for the full picture:
newChan = do {
    read <- newEmptyMVar ;
    write <- newEmptyMVar ;
    hole <- newEmptyMVar ;
    putMVar read hole ;
    putMVar write hole ;
    return (read,write) }

So right after calling newChan the "old_hole" from putChan is the same MVar as hole in newChan. And as channel operations progress, that old_hole is always somewhere nested in the MVars of read.
I found the design of linked list-style channels truly difficult to wrap my head around at first. The illustration from that paper does a decent job of showing the structure, but the basic idea is readers "peel off" a layer of MVar to reveal a value, while writers are inserting values "at the bottom" of the pile of MVars, mainting a pointer to the bottom-most one.
By the way this is the design used in Control.Concurrent.Chan


Q: How to use a homescreen widget button to shutdown a service? I have a button whose WidgetProvider kicks off a service with a
PendingIntent. That works just fine. How do I similarly attach an
event handler to the button so that when it is pressed a second time,
it shuts the service down? Is there an appropriate pattern to follow
for something like this?
Thanks.

A: Use a getBroadcast() PendingIntent, where the BroadcastReceiver calls stopService().
Or, use a getService() PendingIntent, where you send a command to your service that has the service call stopSelf().
Or, switch the service to an IntentService, so it shuts down automatically, if that is a better service implementation for your scenario.


Q: override error android studio I'm doing an Android development course using Android Studio but I'm getting a @Override error in one of the examples that I tried to copy/repeat.
Here the code where I get the error
Handler handler = new Handler(){
    @Override //here I get an error, that is not overriding a class
    public void handlerMessage(Message msg) {
        TextView JeroensText = (TextView) findViewById(R.id.JText);
        JeroensText.setText("Lekker bezig!");
    }
};

Anybody how to solve it?

A: There's no handlerMessage(Message message) method on android.os.Handler class, you should override handleMessage(Message message) method (without the 'r')

A: In both cases:
    Handler handler = new Handler(new Handler.Callback () {
        @Override
        public boolean handleMessage(Message msg) {
            TextView JeroensText = (TextView) findViewById(R.id.JText);
            JeroensText.setText("Lekker bezig!");
            return false;
        }
    });

}

and
    Handler handler  = new Handler () {
        @Override
        public void handleMessage(Message msg) {
            TextView JeroensText = (TextView) findViewById(R.id.JText);
            JeroensText.setText("Lekker bezig!");
        }
    };

as you can see there is handleMessage() method, not handlerMessage().
Hope it help

A: Its just a simple miss - remove that extra 'r' from your hanlderMessage method.
Since there is no 'handlerMessage(Message)' method for Handler. Use either
with Callback
Handler handler = new Handler(new Handler.Callback () {
    @Override
    public boolean handleMessage(Message msg) {
        // handle message here
        return true;
    }
});

or
Handler handler  = new Handler () {
    @Override
    public void handleMessage(Message msg) {
        // handle message herer
    }
};


Q: How to show images in dropdownlist options? I need to have a dropdownlist whose options contains text followed by a small image.
Suppose I have a dropdownlist of fruits. I want to show the options as :
Option 1 : small Image of mango then text Mango
Option 2 : small Image of orange then text Orange
.....................
Is it possible to implement in asp.net 2.0?
If yes then please help with sample code.
I don't want to use JQuery.

A: You can do that server side by just placing <asp:Image ImageUrl="some.gif" /> tags in your ASP.NET code. The browser will show them when the page is loaded.

A: You don't need to use JQuery, use CSS background-image property for every <option>.


Q: How can I upload videos into my youtube account without oAuth consent screen using YT data API v3 I want to upload local videos into my youtube account through my web app without oAuth consent screen. I am using node js as server and react js as frontend.

A: You need to understand the difference between private and public data.  Public data is data that is not owned by any user and is available publicly.
Methods like Search List for example access public data available on YouTube.
Private data is data that is owned by a user.  In order to upload to your YouTube account you need permission to upload to that account.
The Videos.insert method as you can see by the documentation requires that the user have consented to your application accessing their YouTube account. They must have consented to your access with one of the following scopes.

So the answer to your question is that you cant. You need to consent to authorization before your application is going to be allowed to upload to YouTube
upload public videos
Please remember that all videos uploaded via the videos.insert endpoint from unverified API projects created after 28 July 2020 will be restricted to private viewing mode. To lift this restriction, each API project must undergo an audit to verify compliance with the Terms of Service. Please see the API Revision History for more details.
Your application will need to go though application verificatin process before any of the videos you upload will be public


Q: How to count the number of columns in Excel table using VBA? Dim housetypes, elements, NumRowsElements, NumColumnsHousetypes

elements = Range("c10:c19")
housetypes = Range("d9:n9")

NumRowsElements = UBound(elements)
NumColumnsHousetypes = UBound(housetypes)

MsgBox ("NumRowsElements is " & NumRowsElements & " NumColumnsHousetypes is " & NumColumnsHousetypes)

I'm not sure why the above code will show me the correct number of row headers (C10 to C19) but not return the correct number of column headers (D9 to N9)?

A: Both elements and housetypes are 2D arrays, not 1D. The first dimension corresponds to the rows, and the second corresponds to columns.
When using Ubound, if dimension (2nd parameter) is omitted, 1 is assumed.
NumRowsElements = UBound(elements, 1)
NumColumnsHousetypes = UBound(housetypes, 2)

will return the results you want.


Q: Mongo Bulk Insert Spring I am working on understanding Mongo's bulk insert method. I want to insert records that have a unique index, and the duplicates simply get skipped over. I understand I will need an unorded bulk insert, but am having issues with the implementation. I already have logic that has been implemented with .saveAll by mapping through and building an object. I am failing to connect the dots on where to explicitly insert into the bulk operation. Can I not pass my object, or do I need map each key to data. In the examples I have read, they use small objects and specify each key.
List<Employee> employees =
      people.getEmployees().stream()
          .filter(criteria)
          .map(
              e -> {
                return PersonObject.builder()
                    .firstName(person.getFirstName())
                    .lastName(person.getLastName())
                    .gender(person.getGender())
                    .salary(employee.getSalary())
                    .weight(person.getWeight())
                    .height(person.getHeight())
                    .school(Schools.SEC)
                    .family(familyOrgins.getFamily())
                    .hairColor(familyOrgins.getHairColor())
                    .eyeColor(familyOrgins.getEyeColor())
                    .city(city)
                    .state(state)
                    .country(country)
                    .build();
              })
          .collect(Collectors.toList());
          result = employeesRepository.saveAll(employees);

I have tried to inserting after the list of objects has been created like below:
      .build();
          })
      .collect(Collectors.toList());
      BulkWriteResult mongoResult = bulkWrite(itemLocations, false);`

I want to insert using a bulk and if last name is the same, then skip over that person insertion.

A: Here is a very small program that performs an Ordered bulkWrite using Spring.  You can change to unordered by changing the enum value on BulkOperations.BulkMode.  This program will insert 3 records, then delete one, then update one.  Because of the filter predicates in the later bulk commands I had to go with an ordered update.  If you are only inserting you could easily get away with a faster unordered bulk command.
Main.java
package com.example.accessingdatamongodb;

import com.mongodb.bulk.BulkWriteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.core.BulkOperations;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

@SpringBootApplication
public class Main implements CommandLineRunner {

    @Autowired
    private MongoOperations mongoTemplate;

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

        // CLEAR THE COLLECTION
        mongoTemplate.remove(new Query(), Customer.class);

        BulkOperations bulkOps = mongoTemplate.bulkOps(BulkOperations.BulkMode.ORDERED, Customer.class);

        for (Integer i = 0; i < 3; i++)
        {
            Customer customer = new Customer();
            customer.firstName = "Barry";
            customer.id = i.toString();
            bulkOps.insert(customer);
        }

        bulkOps.remove(new Query().addCriteria(new Criteria("i").is(1)));
        bulkOps.updateOne(new Query().addCriteria(new Criteria("i").is(2)), new Update().set("name", "Barry"));

        BulkWriteResult results = bulkOps.execute();
    }
}

For completeness here are the other files in the project...
application.properties
spring.data.mongodb.uri=mongodb://localhost:27017/springtestBulkWrite
spring.data.mongodb.database=springtestBulkWrite

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>accessing-data-mongodb</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>accessing-data-mongodb</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver-sync</artifactId>
            <version>4.5.0</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver-core</artifactId>
            <version>4.5.0</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>bson</artifactId>
            <version>4.5.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

SimpleMongoConfig.java
 import com.mongodb.client.MongoClient;
 import com.mongodb.ConnectionString;
 import com.mongodb.MongoClientSettings;
 import com.mongodb.client.MongoClients;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.data.mongodb.core.MongoTemplate;

 @Configuration
 public class SimpleMongoConfig {

     @Value("${spring.data.mongodb.database}")
     private String databaseName;

     @Value("${spring.data.mongodb.uri}")
     private String uri;

     @Bean
     public MongoClient mongo() {
         ConnectionString connectionString = new ConnectionString(uri);
         MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
           .applyConnectionString(connectionString)
           .build();

         return MongoClients.create(mongoClientSettings);
     }

     @Bean
     public MongoTemplate mongoTemplate() throws Exception {
         return new MongoTemplate(mongo(), databaseName);
     }
 }

CustomerRepository.java (not really used in this trivial example)
package com.example.accessingdatamongodb;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface CustomerRepository extends MongoRepository<Customer, String> {

  public Customer findByFirstName(String firstName);
  public List<Customer> findByLastName(String lastName);
  public void deleteByLastName(String lastName);
}

Customer.java
package com.example.accessingdatamongodb;

import org.springframework.data.annotation.Id;

public class Customer {

  @Id
  public String id;

  public String firstName;
  public String lastName;

  public Customer() {}

  public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    return String.format(
        "Customer[id=%s, firstName='%s', lastName='%s']",
        id, firstName, lastName);
  }
}


Q: Mod Rewrite Clean URL's How can I transform:

*

*http://example.com/about.php

*http://example.com/hello/deep.php

*http://example.com/hello/world/deeper.php
Dynamically, into URLs like:

*

*http://example.com/about/

*http://example.com/hello/deep/

*http://example.com/hello/world/deeper/

A: see http://gist.github.com/22877


Q: When classifying images to folders Error Comes Failed to get device properties, error code: 30 Keras     examples
data_226000_227000.h5_286.png
D:/Icorve Project/Learn Neural Networks/Looking Straight/data_226000_227000.h5_286.png
(531, 413)
(531, 413, 3)
(180, 140, 1)
[INFO] loading network...
2020-01-07 09:24:19.310174: E tensorflow/core/grappler/clusters/utils.cc:87] Failed to get device properties, error code: 30
2020-01-07 09:26:35.773432: E tensorflow/core/grappler/clusters/utils.cc:87] Failed to get device properties, error code: 30
[INFO] classifying image...
examples
data_226000_227000.h5_288.png
D:/Icorve Project/Learn Neural Networks/Looking Straight/data_226000_227000.h5_288.png
(531, 413)
(531, 413, 3)
(180, 140, 1)
[INFO] loading network...
2020-01-07 09:30:36.892513: E tensorflow/core/grappler/clusters/utils.cc:87] Failed to get device properties, error code: 30
2020-01-07 09:32:51.847629: E tensorflow/core/grappler/clusters/utils.cc:87] Failed to get device properties, error code: 30
[INFO] classifying image...

When classifying images to folders Error Comes  Failed to get device properties, error code: 30 Keras
Some images are classifying correctly. What this error

A: If you are using two GPU's let's say Intel GPU and NVIDIA GPU, then please choose graphic driver to NVIDIA GPU by opening NVIDIA control Panel.
In case if you are using only one driver then please update NVIDIA GPU graphic driver.


Q: Matplotlib: How to plot with only NAN values? How can I plot a timeseries with timestamps on the x-axis and "data" that contains only NAN on the y-axis using matplotlib?
The goal is to get an empty plot with timestamps on the x-axis and an empty y-axis. Why do I want to have an empty plot? Well, I am creating plots in a loop for every day of the year and it can happen that the timeseries has data gaps (no, interpolation of data gaps makes no sence).
    TIMESTAMP
2019-10-21 12:00:00   NaN
2019-10-21 12:01:00   NaN
2019-10-21 12:02:00   NaN
2019-10-21 12:03:00   NaN
2019-10-21 12:04:00   NaN
                       ..
2019-10-22 11:55:00   NaN
2019-10-22 11:56:00   NaN
2019-10-22 11:57:00   NaN
2019-10-22 11:58:00   NaN
2019-10-22 11:59:00   NaN
Freq: T, Name: df_plot.prec, Length: 1440, dtype: float64

DatetimeIndex(['2019-10-21 12:00:00', '2019-10-21 12:01:00',
               '2019-10-21 12:02:00', '2019-10-21 12:03:00',
               '2019-10-21 12:04:00', '2019-10-21 12:05:00',
               '2019-10-21 12:06:00', '2019-10-21 12:07:00',
               '2019-10-21 12:08:00', '2019-10-21 12:09:00',
               ...
               '2019-10-22 11:50:00', '2019-10-22 11:51:00',
               '2019-10-22 11:52:00', '2019-10-22 11:53:00',
               '2019-10-22 11:54:00', '2019-10-22 11:55:00',
               '2019-10-22 11:56:00', '2019-10-22 11:57:00',
               '2019-10-22 11:58:00', '2019-10-22 11:59:00'],
              dtype='datetime64[ns]', name='TIMESTAMP', length=1440, freq='T')

plt.plot(df_plot.index, df_plot.prec)

results in:
ValueError: view limit minimum -0.001 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units

timeseries is of type datetime64


Q: How to get reproducible result when running Keras with Tensorflow backend Every time I run LSTM network with Keras in jupyter notebook, I got a different result, and I have googled a lot, and I have tried some different solutions, but none of they are work, here are some solutions I tried:

*

*set numpy random seed
random_seed=2017
from numpy.random import seed
seed(random_seed)

*set tensorflow random seed
from tensorflow import set_random_seed
set_random_seed(random_seed)

*set build-in random seed
import random
random.seed(random_seed)

*set PYTHONHASHSEED
import os
os.environ['PYTHONHASHSEED'] = '0'

*add PYTHONHASHSEED in jupyter notebook kernel.json
{
 "language": "python",
 "display_name": "Python 3",
 "env": {"PYTHONHASHSEED": "0"},
 "argv": [
  "python",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}"
 ]
}
and the version of my env is:
Keras: 2.0.6
Tensorflow: 1.2.1
CPU or GPU: CPU

and this is my code:
model = Sequential()
model.add(LSTM(16, input_shape=(time_steps,nb_features), return_sequences=True))
model.add(LSTM(16, input_shape=(time_steps,nb_features), return_sequences=False))
model.add(Dense(8,activation='relu'))
model.add(Dense(1,activation='linear'))
model.compile(loss='mse',optimizer='adam')

A: The seed is definitely missing from your model definition. A detailed documentation can be found here: https://keras.io/initializers/.
In essence your layers use random variables as their basis for their parameters. Therefore you get different outputs every time.
One example:
model.add(Dense(1, activation='linear',
               kernel_initializer=keras.initializers.RandomNormal(seed=1337),
               bias_initializer=keras.initializers.Constant(value=0.1))

Keras themselves have a section about getting reproduceable results in their FAQ section: (https://keras.io/getting-started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development). They have the following code snippet to produce reproducable results:
import numpy as np
import tensorflow as tf
import random as rn

# The below is necessary in Python 3.2.3 onwards to
# have reproducible behavior for certain hash-based operations.
# See these references for further details:
# https://docs.python.org/3.4/using/cmdline.html#envvar-PYTHONHASHSEED
# https://github.com/fchollet/keras/issues/2280#issuecomment-306959926

import os
os.environ['PYTHONHASHSEED'] = '0'

# The below is necessary for starting Numpy generated random numbers
# in a well-defined initial state.

np.random.seed(42)

# The below is necessary for starting core Python generated random numbers
# in a well-defined state.

rn.seed(12345)

# Force TensorFlow to use single thread.
# Multiple threads are a potential source of
# non-reproducible results.
# For further details, see: https://stackoverflow.com/questions/42022950/which-seeds-have-to-be-set-where-to-realize-100-reproducibility-of-training-res

session_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)

from keras import backend as K

# The below tf.set_random_seed() will make random number generation
# in the TensorFlow backend have a well-defined initial state.
# For further details, see: https://www.tensorflow.org/api_docs/python/tf/set_random_seed

tf.set_random_seed(1234)

sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)
K.set_session(sess)

A: Keras + Tensorflow.
Step 1, disable GPU.
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = ""

Step 2, seed those libraries which are included in your code, say "tensorflow, numpy, random".
import tensorflow as tf
import numpy as np
import random as rn

sd = 1 # Here sd means seed.
np.random.seed(sd)
rn.seed(sd)
os.environ['PYTHONHASHSEED']=str(sd)

from keras import backend as K
config = tf.ConfigProto(intra_op_parallelism_threads=1,inter_op_parallelism_threads=1)
tf.set_random_seed(sd)
sess = tf.Session(graph=tf.get_default_graph(), config=config)
K.set_session(sess)

Make sure these two pieces of code are included at the start of your code, then the result will be reproducible.

A: I resolved this issue by adding os.environ['TF_DETERMINISTIC_OPS'] = '1'
Here an example:
import os
os.environ['TF_DETERMINISTIC_OPS'] = '1'
#rest of the code
#TensorFlow version 2.3.1


Q: Tensorflow keras layers.Multiply() TypeError: 'NoneType' object is not subscriptable I'm a beginning on Keras. I'm trying to convert the following R script into Python
1 library ( keras )
2 # we fit j =0 with feature matrix dat .X , claims dat$C1 and volumes dat$C0
3 dat .Y <- as . matrix ( dat$C1 / sqrt ( dat$C0 )) # observed responses
4 dat .W <- as . matrix ( sqrt ( dat$C0 )) # volumes used as offsets
5 q <- 20 # number of hidden neurons
6 # definition of neural network
7 features <- layer_input ( shape = c( ncol ( dat .X )))
8 net <- features % >%
9 layer_dense ( units = q , activation = ’tanh ’) % >%
10 layer_dense ( units = 1, activation = k_exp )
11 volumes <- layer_input ( shape =c (1))
12 offset <- volumes % >%
13 layer_dense ( units = 1, activation = ’ linear ’ , use_bias = FALSE , trainable = FALSE ,weights = list ( array (1 , dim =c (1 ,1))))
14 weights = list ( array (1 , dim =c (1 ,1))))
15 merged <- list ( net , offset ) % >%
16 layer_multiply ()

Below my script python:
input_shape = SelectedMatrix_Tr.shape[1]
net = Sequential ([
    Dense(20, activation="tanh", input_shape=(input_shape,), name="hidden_layer_1"),
    Dense(1, activation=tf.keras.activations.exponential, name="output_layer")
])

offset =  Sequential([
    Dense(
    units=1,
    activation = 'linear',
    input_shape=(None,1),
    #input_dim=1,
    use_bias = True,
    trainable = False,

    kernel_initializer=tf.constant_initializer(1.)

    )
        ])

multiplied = tf.keras.layers.Multiply()([net,offset])

The error arrives at the last line of Multiply. Below the error message:

TypeError                                 Traceback (most recent call
last)  in
----> 1 multiplied = tf.keras.layers.Multiply()([model,offset])
~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\engine\base_layer.py
in call(self, *args, **kwargs)    1021       with
ops.name_scope_v2(name_scope):    1022         if not self.built:
-> 1023           self._maybe_build(inputs)    1024     1025         if self._autocast:
~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\engine\base_layer.py
in _maybe_build(self, inputs)    2623         # operations.    2624
with tf_utils.maybe_init_scope(self):
-> 2625           self.build(input_shapes)  # pylint:disable=not-callable    2626       # We must set also ensure
that the layer is marked as built, and the build    2627       # shape
is stored since user defined build functions may not be calling
~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\utils\tf_utils.py
in wrapper(instance, input_shape)
268     if input_shape is not None:
269       input_shape = convert_shapes(input_shape, to_tuples=True)
--> 270     output_shape = fn(instance, input_shape)
271     # Return shapes from fn as TensorShapes.
272     if output_shape is not None:
~\AppData\Roaming\Python\Python37\site-packages\tensorflow\python\keras\layers\merge.py
in build(self, input_shape)
86   def build(self, input_shape):
87     # Used purely for shape validation.
---> 88     if not isinstance(input_shape[0], tuple):
89       raise ValueError('A merge layer should be called on a list of inputs.')
90     if len(input_shape) < 2:
TypeError: 'NoneType' object is not subscriptable

Any suggestions ?
Thanks !


Q: Using One Model inside another model in Django I am Developing a E-commerce Application with Django
So what I was thinking is getting the category of the Product in a separate Model and list them down in another using choice field in CharField.
So Here is the code for this
This is the model for getting the Categories from the user

class ProjektCat(models.Model):
    id = models.AutoField(primary_key=True)
    Option_Name = models.CharField(max_length=50)
    Option_Number = models.IntegerField()
    Number_Visits = models.IntegerField(default=0)

    def __str__(self):
        return f'{self.Option_Name}'

and here is the code to list those categories as a dropdown in the CharField
class Software_And_Service(models.Model):
    id = models.AutoField(primary_key=True)
    Product_Name = models.CharField(max_length=100, default='')
    projectKats = ProjektCat.objects.all()
    choice = []
    for i in projectKats:
        option = (i.Option_Number, i.Option_Name)
        choice.append(option)
    Cateogary = models.CharField(
        max_length=256, choices=choice)
    Price = models.IntegerField(default=0)
    Description = models.TextField(default='', max_length=5000)
    pub_date = models.DateField(auto_now_add=True, blank=True, null=True)
    image = models.URLField(default='')
    linkToDownload = models.URLField(default='')

    def __str__(self):
        return f'Projekt : {self.Product_Name}'

But it's Showing me an Error that there is no such table in app_name.projektcat
Is there is any solution for this??

A: It's not how you do this. First correctly assign the projectKats field i.e
# You can set max_length as per your choice
projectKats = models.CharField(max_length=50)

You need to do this logic in django forms rather than django models.
So this is how you can do it.
forms.py
from django import forms
from .models import ProjektCat, Software_And_Service

def get_category_choices():
    return [(obj.Option_Name,obj.Option_Name) for obj in ProjektCat.objects.values_list('Option_Name',flat=True).distinct()]

class SoftwareAndServiceForm(forms.ModelForm):
    projectKats = forms.ChoiceField(choices=get_category_choices)

    class Meta:
        model = Software_And_Service
        fields = [
                  'projectKats',
                   # whatever fields you want
                 ]


Q: Can a '.exe' file made through python run on another device with python language not installed? See, I made a python program with about 7 libraries being used and I converted it into a '.exe' file. So, I wondered if I could run this same file on another device with python not installed.
Is it possible?
Please let me know. Thanks.

A: Depends on how you did it. Pyinstaller is a common one that allows you to do that.


Q: How would I go about installing an AverTV Hybrid Volar HX? How can I install the driver to get my AverTV Hybrid Volar HX working on brand new Ubuntu 11.10 computer?
I'am a newby in linux world but Ubuntu looks great. Please give me a hand!

A: This is for 64 bit drivers, but probably the same solution applies to the 32-bit version by just using x86 instead of x64 in filenames. The solution is inspired in the great work by the guys of linuxtv.org

*

*Create a directory called AverTVVolarHX in your home

*Download C038A827H826_Installer_x64_0.10-Beta_091126.zip from AverMedia WebSite to that directory

*Create in same directory patch file aver.patch:
diff -Nr -u0 original/installer/installer.sh modified/installer/installer.sh
--- original/installer/installer.sh     2009-11-13 11:47:33.000000000 +0100
+++ modified/installer/installer.sh     2011-08-28 20:58:38.000000000 +0200
@@ -177,13 +176,0 @@
-       if [[ "$kversion" != "2" || "$kpatchlevel" != "6" ]]; then
-               dialog --backtitle "$BACKTITLE" \
-               --title "Kernel version error" \
-               --msgbox "Installer cannot determine kernel version or the running kernel is not 2.6.x kernel. \n\
-Installer will abort now.
-" \
-               10 $WIDTH
-               log "generate_kdep_string: wrong kernel version ${kversion}.${kpatchlevel}.${ksublevel}. Abort."
-        log_from_file $ksrc/Makefile #s016
-        log_from_file $kobj/Makefile #s016
-               exit
-       fi
-
@@ -994,3 +980,0 @@
-   # check if root
-   log "check if root: EUID=$EUID"
-   if [[ "$EUID" != "0" ]]; then
@@ -998,9 +981,0 @@
-       dialog --backtitle "$BACKTITLE" \
-       --title "ERROR: " \
-       --msgbox \
-       "You must be root to run installer. \
-\nPlease login as root or use 'su' or 'sudo' to abtain root privilege. \
-\nInstaller will now abort." 10 $WIDTH
-       clear
-       exit
-   fi
diff -Nr -u0 original/installer/src/aver/osdep.c modified/installer/src/aver/osdep.c
--- original/installer/src/aver/osdep.c 2009-11-13 11:54:56.000000000 +0100
+++ modified/installer/src/aver/osdep.c 2011-08-28 20:19:19.000000000 +0200
@@ -89 +88,0 @@
-#include &ltlinux/smp_lock.h&gt
@@ -435 +434 @@
-               init_MUTEX(tmp);
+               sema_init(tmp, 1);
@@ -439 +438 @@
-               init_MUTEX_LOCKED(tmp);
+               sema_init(tmp, 0);
@@ -1069,0 +1069 @@
+static DEFINE_MUTEX(dvbdev_mutex);
@@ -1072 +1072 @@
-       lock_kernel();
+       mutex_lock(&dvbdev_mutex);
@@ -1077 +1077 @@
-       unlock_kernel();
+       mutex_unlock(&dvbdev_mutex);
diff -Nr -u0 original/installer/src/aver/osdep_dvb.c modified/installer/src/aver/osdep_dvb.c
--- original/installer/src/aver/osdep_dvb.c     2009-11-13 11:54:57.000000000 +0100
+++ modified/installer/src/aver/osdep_dvb.c     2011-08-28 20:19:36.000000000 +0200
@@ -79 +78,0 @@
-#include &ltlinux/smp_lock.h&gt
@@ -233 +232 @@
-               init_MUTEX(&p-&gtfeedlock);
+               sema_init(&p-&gtfeedlock, 1);
diff -Nr -u0 original/installer/src/aver/osdep_th2.c modified/installer/src/aver/osdep_th2.c
--- original/installer/src/aver/osdep_th2.c     2009-11-13 11:54:57.000000000 +0100
+++ modified/installer/src/aver/osdep_th2.c     2011-08-28 20:20:00.000000000 +0200
@@ -78 +77,0 @@
-#include &ltlinux/smp_lock.h&gt
@@ -80,0 +80 @@
+#include "osdep.h"
@@ -90 +90 @@
-        lock_kernel();
+        SysLockKernel();
@@ -100 +100 @@
-        unlock_kernel();
+        SysUnlockKernel();
diff -Nr -u0 original/installer/src/aver/osdep_v4l2.c modified/installer/src/aver/osdep_v4l2.c
--- original/installer/src/aver/osdep_v4l2.c    2009-11-13 11:54:58.000000000 +0100
+++ modified/installer/src/aver/osdep_v4l2.c    2011-08-28 20:20:19.000000000 +0200
@@ -75,0 +76,2 @@
+#define VFL_TYPE_VTX 3
+
@@ -84 +85,0 @@
-#include &ltlinux/smp_lock.h&gt

*Open terminal
$ cd ~/AverTVVolarHX
$ unzip C038A827H826_Installer_x64_0.10-Beta_091126.zip
$ cd H826D_Installer_x64_0.10-Beta
$ tail -n +115 AVERMEDIA-Linux-x64-H826D-0.10-beta.sh | bzip2 -d | tar xf -
$ patch -l -p1 &lt ../aver.patch
$ cd installer
$ ./installer.sh

*During the installation choose Expert Installation, select /home/&ltyouruser&gt/AverTVVolarHX as the directory for expert installation and finish installation (it just will output the module sources to /home/&ltyouruser&gt/AverTVVolarHX/H826D-expert-install)

*Now you need an hex editor, e.g. ghex, which is in the default repositories. Hex edit file /home/&ltyouruser&gt/AverTVVolarHX/H826D-expert-install/aver/osdep_dvb.o_shipped and replace param_array_get and param_array_set by param_array_ops

*Create in directory /home/&ltyouruser&gt/AverTVVolarHX/H826D-expert-install installer.sh:
#!/bin/bash -i

# get absolute path of this script
BASE=`(cd \`dirname $0\`; pwd)`

TARGET_DIR=/lib/modules/`uname -r`/kernel/drivers/media/dvb/dvb-usb

if [[ "$EUID" != "0" ]]; then
    echo -e "You must be root to run installer.
\nPlease login as root or use 'su' or 'sudo' to obtain root privileges.
\nInstaller will now abort."
    exit
fi

cd "$BASE"

make || { echo "make failed"; exit 1; }

echo -e "\nCopying h826d.ko to $TARGET_DIR/h826d.ko"
cp -r h826d.ko $TARGET_DIR/ || { echo "copy failed"; exit 1; }

echo -e "\nCopying averusbh826d.ko to $TARGET_DIR/averusbh826d.ko"
cp -r averusbh826d.ko $TARGET_DIR/ || { echo "copy failed"; exit 1; }

echo -e "\nRunning depmod -a"
depmod -a || { echo "depmod failed"; exit 1; }

echo -e "\nCleaning"
make clean || { echo "make clean failed"; exit 1; }

echo -e "\nCompleted"

*Finally run installer.sh
$ cd /home/&ltyouruser&gt/AverTVVolarHX/H826D-expert-install
$ chmod +x installer.sh
$ sudo ./installer.sh
The H826D-expert-install directory is the only thing you need for future recompilations, so save it somewhere else. The other files and dirs can now be safely deleted.

A: Please read this


Q: Как получить URL изображения? Безуспешно пробую получить src следующими способом:
Element element = document.select("div.imgTagWrapper").first();
imgUrl = element.attr("src");

или этим
Element element = document.getElementsByClass("imgTagWrapper").first();
imgUrl = element.tagName("src").text();

Из этого HTML

    <img alt="Amanda Uprichard Women's Wren Maxi, Fluro Pink, S"
        src="https://images-na.ssl-images-    amazon.com/images/I/71jou38OlPL._UX342_.jpg"
        data-old-hires="https://images-na.ssl-images-amazon.com/images/I/71jou38OlPL._UL1500_.jpg"
        class="a-dynamic-image  a-stretch-horizontal"
        id="landingImage" data-a-dynamic-image="{"https://images-na.ssl-images-[740,569],"https://images-na.ssl-images-[445,342],"https://images-   na.ssl-images-amazon.com/images/I/71jou38OlPL._UX466_.jpg":[606,466]}"
        style="max-width: 264px; max-height: 342.857px;">

A: Сначала выбираете элементы с тегом img, затем считываете атрибут src:
Document page = Jsoup.parse(s);
Element imageElement = page.select("img").get(0);
String link = imageElement.attr("src");

где s – исходный HTML.


Q: Compiling the "at" command for my mips toolchain While cross compiling with the following command :-
./configure CC=/data/designs/pweth-s-t1501/trunk/software/embedded/ar9341/linux/build/gcc-4.3.3/build_mips/staging_dir/usr/bin/mips-linux-uclibc-gcc --host=mips-linux
During the course of the compilation I am getting this kind of an error.
checking Trying to compile a trivial ANSI C program... configure: error: Could not compile and run even a trivial ANSI C program - check CC.
My question is that does not the binary know that it is being cross-compiled so it is natural that the compiled binary will not be running on my machine.
Can anybody please tell me a workaround for the same problem?


Q: Word for position and direction I'm looking for a word that encapsulates both an object's position and direction.
Similar words:

*

*a "point" has just a position.

*a "vector" has a direction and magnitude

*an "orientation" has just a direction

I'm ideally looking for a short simple word, however I'm also interested in any mathsey words which may describe the concept.

A: In robotics, computer vision and mechanics, pose of an object refers to combination of its position and orientation.
Note that aforementioned word perhaps makes sense in science community and not necessarily in normal daily conversations (the question has mathematics tag after all!).
See als roto-translation and homogeneous transformation.

A: A ray is a mathematical term that specifies a position and direction without magnitude--and in only 3 letters.


Q: FFmpeg: How can I hstack two videos, and scale just one up with scale_cuda? This is a command I used that worked with scale_npp instead of scale_cuda
ffmpeg -c:v h264_cuvid -i "Input1.mkv" -c:v h264_cuvid -i "Input2.mkv" -c:v h264_nvenc -filter_complex "hwupload_cuda,[0:v]scale_cuda=w=1920:h=1080:format=yuv420p:interp_algo=lanczos;[0v][1:v]hstack,hwdownload,format=yuv420p" "output.mkv" -y
But with scale_cuda, the output says this:
[AVFilterGraph @ 0x565389e2a780] Too many inputs specified for the "scale_cuda" filter
But this command, which only involves upscaling and with only 1 video works:
ffmpeg -c:v h264_cuvid -i "Input1.mkv" -c:v h264_nvenc -filter_complex "hwupload_cuda,scale_cuda=w=1920:h=1080:format=yuv420p:interp_algo=lanczos,hwdownload,format=yuv420p" "output.mkv" -y
What would be the correct way to do that 1st command?

A: The following command should work:
ffmpeg -c:v h264_cuvid -i "Input1.mkv" -c:v h264_cuvid -i "Input2.mkv" -filter_complex "[0:v]hwupload_cuda,scale_cuda=w=1920:h=1080:format=nv12:interp_algo=lanczos,hwdownload[0v];[0v][1:v]hstack" -c:v h264_nvenc "output.mkv" -y

*

*[0:v]hwupload_cuda, upload the video stream of Input1.mkv to the GPU.

*hwdownload[0v], downloads the scaled video from the GPU, and gives it the temporary name [0v].
We have to download the video from the GPU before applying hstack, because hstack filter cannot be CUDA accelerated.
The selected format is nv12, for matching the format of (decoded) Input2.mkv.

Testing:

*

*Build synthetic input files (for testing):
ffmpeg -f lavfi -i testsrc=size=192x108:rate=1:duration=10 -c:v libx264 -pix_fmt yuv420p Input1.mkv
ffmpeg -f lavfi -i testsrc=size=1920x1080:rate=1:duration=10 -c:v libx264 -pix_fmt yuv420p Input2.mkv

*Executing the above command.

It's also working without format=nv12:
ffmpeg -c:v h264_cuvid -i "Input1.mkv" -c:v h264_cuvid -i "Input2.mkv" -filter_complex "[0:v]hwupload_cuda,scale_cuda=w=1920:h=1080:interp_algo=lanczos,hwdownload[0v];[0v][1:v]hstack" -c:v h264_nvenc "output.mkv" -y