text:
Q: How to find whether the type of the element in the list is TextBox or CheckBox in Jquery? My code is like this:

<input id='Checkbox1' type='checkbox' checked />

<input id='features2' type='textbox' />

<input id='Checkbox1' type='checkbox' checked />

In my Code, these Checkboxes and textboxes are dynamically generated using Jquery.
Now I am using $.each() to find which list(li tag) inside the unordered(ul tag) list contains textbox and checkbox.
This search has to be done on the basis of id of the li tag inside the ul tag.
  $("#textbutton").click(function () {

                $.getJSON('@Url.Action("GetFeaturePkId")', function (featurepkid) {

                    var featurespkid = featurepkid;
                    $.each(featurepkid, function (k,v) {
                        if ($(".featuresTest > li.chklist" + v + "").has('input[type="textbox"]')) {
                            alert("textbox");
                        }
                        else  {
                            alert("checkbox");
                        }
                    });
                });
            });

on the above code the featurepkid returns 1 to 20.
I tried this,but failed.
Please kindly advise me on that issue.

A: To get the li tag, you can do this :
var liCheck = $('.featuresTest li').filter(function(){
    return $(this).children('[type=checkbox]').length;
})
var liText = $('.featuresTest li').filter(function(){
    return $(this).children('[type=textbox]').length;
})

A: You can check the tagName property
$(".featuresTest > li").each(function () {
    console.log($(this).children('input').tagName);
});

you can also use the .has() function of jQuery
$(".featuresTest > li").has('input[type="checkbox"]').each(function () {
       // iterate over li's with checkboxes
});

and
$(".featuresTest > li").has('input[type="textbox"]').each(function () {
       // iterate over li's with textbox
});

EDIT:
In response of your comment, I'd say try using children instead of has and check for length
$.each(featurepkid, function (k, v) {
    var $elem = $(".featuresTest > li#chklist" + v);
    if ($elem.children('input[type="textbox"]').length) {
        alert("textbox");
    } else {
        alert("checkbox");
    }
});

A: You can use jQuery :has selector:
$('.featuresTest > li:has(input[type=checkbox]):has(input[type=textbox])')

EDIT: If you want find li inside ul which contains one of this (checkbox/textbox) input types you can use Multiple Selector ("selector1, selector2, selectorN"):
$('.featuresTest > li:has(input[type=checkbox]), .featuresTest > li:has(input[type=textbox])')

Now you can apply .each() method to find ID:
.each(function() {
    console.log( $(this).attr('id') );
});

jsFiddle example

A: As you edited your question I find problem in you javascript code.
In you if you have $(".featuresTest > li.chklist" + v + "").has('input[type="textbox"]') .. and that return array of elements ... if jQuery selector don't find anyting, it return empty array - [].
So statement compare true/false ... but when he get empty array - [] he transform it as [].toString() and this return empty string ... and that is true.
So to answer question you shoud replace
if ($(".featuresTest > li.chklist" + v + "").has('input[type="textbox"]'))

to
if ($(".featuresTest > li#chklist" + v).has('input[type="textbox"]').length)

.length will return count of elements in array ... so when jQuery selector dont find anything it return 0 and thats false instead of true because of empty array.


text:
Q: Pass array by reference using C Yes, I've read this question & answers: Passing an array by reference in C?. I have a similar problem and implemented the same idea from that question.
However, I still get an error from the following code:
#include <iostream>

void FillArray(int** myArray)
{
   free( *myArray ) ;
   * myArray = (int*) malloc(sizeof(int) * 2);

   *myArray[0] = 1;
   *myArray[1] = 2;
}

int main()
{
   int* myArray = NULL;
   FillArray(& myArray);
   return 0;
}

I got the following run-time error right after the FillArray function ends:

Unhandled exception at 0x773115de in Program.exe 0xC00000005: Access violation writing location 0xcccccccccc.

I'm using Visual Studio, opened Visual C++ Empty Project. And the file named main.cpp. Does that mean it's compiled with C++ compiler instead of C compiler? If so, how can I open a file which will be compiled only C compiler? I tried renaming main.cpp with main.c, but still have the same problem. (I'm asking this question, because I read some about "pass by reference" and saw that it's different in C and C++.)
Sorry for this very fundamental question.
I will be appreciated for any help,
Sait.

A: Your problem is one of operator precedence.
The [] operator binds more tightly than the * operator, so
*myArray[1]

is the same as
*(myArray[1]).

This is wrong, as the top level pointer only has enough memory allocated for one pointer.  You want:
(*myArray)[1] = 2;

On a side note, there is no good reason to mix C and C++ like you have.  Obviously you have C++ code here, so prefer new and delete over malloc and free because the latter two do not take into account constructors and destructors for complex objects.

A: Precedence is not working as you expect it to be. Try these:
(*myArray)[0] = 1;
(*myArray)[1] = 2;

(Note: iostream is not C. It's C++.)

A: Good:
int main()
{
   int* myArray = NULL;
   FillArray(& myArray);
   ...

Good:
void FillArray(int** myArray)
{
   * myArray = (int*) malloc(sizeof(int) * 2);

Catastrophically bad:
void FillArray(int** myArray)
{
   free( *myArray ) ;
   * myArray = (int*) malloc(sizeof(int) * 2);
   ...

Better:
void FillArray (int** myArray)
{
   if (myArray)
     free (*myArray);
   *myArray = (int*) malloc(sizeof(int) * 2);
   ...

ALSO:
   *(myArray[0]) = 1;
   *(myArray[1]) = 2;

redpajama_set_name: RedPajamaStackExchange


text:
Q: iphone UITabBarController memory management In my function - (void)viewDidLoad:
FirstViewController *first = [[FirstViewController alloc]init];
    SecondViewController *second = [[SecondViewController alloc]init];
    ThirdViewController *third = [[ThirdViewController alloc]init];
    ForthViewController *forth = [[ForthViewController alloc]init];
    FifthViewController *fifth = [[FifthViewController alloc]init];

    first.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"first" image:[UIImage imageNamed:@"FirstTab.png"] tag:0];
    second.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"second" image:[UIImage imageNamed:@"SecondTab.png"] tag:1];
    third.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"third" image:[UIImage imageNamed:@"ThirdTab.png"] tag:2];
    forth.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"forth" image:[UIImage imageNamed:@"ForthTab.png"] tag:3];
    fifth.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"fifth" image:[UIImage imageNamed:@"FifthTab.png"] tag:3];

UINavigationController *navigationFirst = [[UINavigationController alloc]initWithRootViewController:first];
UINavigationController *navigationSecond = [[UINavigationController alloc]initWithRootViewController:second];
UINavigationController *navigationThird = [[UINavigationController alloc]initWithRootViewController:third];
UINavigationController *navigationForth = [[UINavigationController alloc]initWithRootViewController:forth];
UINavigationController *navigationFifth = [[UINavigationController alloc]initWithRootViewController:fifth];

//    [first release];
//    [second release];
//    [third release];
//    [forth release];
//    [first release];

NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:navigationFirst,navigationSecond,navigationThird,navigationForth,navigationFifth, nil];

[navigationFirst release];
[navigationSecond release];
[navigationThird release];
[navigationForth release];
[navigationFifth release];

self.tabbarController = [[UITabBarController alloc]init];
self.tabbarController.view.frame = CGRectMake(0, 0, 320, 480);
self.tabbarController.viewControllers = array;
[array release];

I intend to add five UINavigationControllers to tabcontroller,if I don't comment the fellowing code,it will crash:
//    [first release];
//    [second release];
//    [third release];
//    [forth release];
//    [first release];

but I want to know what's the problem,I think it is correct to add thees code.

A: you are releasing first object twice. thats why your code is crashing.
replace [first release] with [fifth release]

A: You should release Navigation controllers in the end
UINavigationController *navigationFirst = [[UINavigationController alloc]initWithRootViewController:first];
UINavigationController *navigationSecond = [[UINavigationController alloc]initWithRootViewController:second];
UINavigationController *navigationThird = [[UINavigationController alloc]initWithRootViewController:third];
UINavigationController *navigationForth = [[UINavigationController alloc]initWithRootViewController:forth];
UINavigationController *navigationFifth = [[UINavigationController alloc]initWithRootViewController:fifth];

    [first release];
    [second release];
    [third release];
    [forth release];
    [first release];

NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:navigationFirst,navigationSecond,navigationThird,navigationForth,navigationFifth, nil];

self.tabbarController = [[UITabBarController alloc]init];
self.tabbarController.view.frame = CGRectMake(0, 0, 320, 480);
self.tabbarController.viewControllers = array;

[navigationFirst release];
[navigationSecond release];
[navigationThird release];
[navigationForth release];
[navigationFifth release];

[array release];


text:
Q: Optimization on $X^TX$ with all positive entries Suppose I have an algorithm $\mathit{A}$ that can solve the optimization problem over certain functions $g: Sym(n) \to \mathbb{R}$. Now given $g$, let $f: \mathbb{R}^{k ,n} \to \mathbb{R}$ be another function such that $f(X) = g(X^TX)$, how can I solve the following problem?
$$\begin{array}{ll} \underset{X \in \mathbb{R}^{k, n}}{\text{minimize}} & \displaystyle f(X) \\ \text{subject to} & \displaystyle X \geq \bf{0}\end{array}$$
suppose I also know the basic info of $g$ like its gradient, hessian, and also that $g$ is sufficiently nice (in a sense that the program is solvable).


text:
Q: D3.js Getting event object instead of data after adding 'onchange' event to listitem I used the code showed by this video (see from 24:34 time)
https://www.youtube.com/watch?v=aHJCt2adSWA
to make an interactive bar chart with D3.js Version 7
the video was made in 2020 and used version 5
the strange issue I am facing is that I am getting , when calling console.log(data) in the code below, the event object:

Event {isTrusted: true, type: 'change', target: input, currentTarget:
input, eventPhase: 2, …}isTrusted: truebubbles: truecancelBubble:
falsecancelable: falsecomposed: falsecurrentTarget:
nulldefaultPrevented: falseeventPhase: 0path: (9) [input, li, ul,
div#data, div#app, body, html, document, Window]returnValue:
truesrcElement: inputtarget: inputtimeStamp: 239761.39999997616type:
"change"[[Prototype]]: Event D3JSCHART-interactive1.html:131

instead of the data Array (as the presenter is getting in his video)

const listItems=d3
.select('#data')
.select('ul')
.selectAll('li')
.data(MyData)
.enter()
.append('li');
listItems.append('span').text(data => data.region);
listItems.append('input').attr('type','checkbox').attr('checked',true)
.on('change',(data) => {
console.log(data);
});

below the full code

<title>D3.JS CHART Interactive 06/03/2022</title>

<svg></svg>


text:
Q: Georeferencing with gdal_translate and gdalwarp fails I have been struggling with the georeference plugin in QGIS 3.24 Tisler in Ubuntu (and also in Windows, although it doesn't crash on the latter); first I thought it was my dataset but then tried to follow the example from qgis georeferencer (the spearfish_topo24.tif is already referenced); trying it from the GUI in QGIS will instantly crash, but doing it with the gdal script generated by the plugin (and replacing tmp paths) returns a raster misplaced in somewhere around -18690,-175178, instead of something around 599149,4913720
gdal_translate -of GTiff -gcp 600154 -4.92558e+06 600166 4.92558e+06 -gcp 608530 -4.92499e+06 608497 4.92497e+06 -gcp 594321 -4.92538e+06 594318 4.92534e+06 -gcp 591559 -4.92704e+06 591557 4.92704e+06 "spearfish_topo24.tif" "spearfish_topo24_x.tif"

gdalwarp -r bilinear -order 1 -co COMPRESS=None  -t_srs EPSG:26713 "spearfish_topo24_x.tif" "spearfish_topo24_modified.tif"

what is possibly wrong with my procedure?
EDIT
apparently, the GCP generated with the plugin are wrong, by seeing the magnitude of the numbers


text:
Q: mysql select query help like in shown pictures I have a table in mysql like shown below in picture 1:

Can you tell me how to make a select query which result will be like in picture 2
and to select faster:

A: Assumes that you have a unique constraint on STUD_ID,CLASS,LESSON
SELECT STUD_ID,
       CLASS,
        MAX(CASE WHEN LESSON='MATH' THEN MARK END) AS MATH,
        MAX(CASE WHEN LESSON='CHEM' THEN MARK END) AS CHEM,

        ...
        AVG(MARK) AS `Avg`
GROUP BY STUD_ID, CLASS

(If you really need that ID column that doesn't relate to any ids you can use the technique from here).


text:
Q: Debugger does not stop at breakpoints in Eclipse when debugging on an existing android project I have imported an existing android project into eclipse, using the import existing android project option in eclipse. While debugging, the debugger won't stop at the breakpoints. I have taken the below mentioned steps till now:

*

*Tried executing the application in Debug perspective.

*Enable debug mode in the Android Manifest file.

*Tried placing the breakpoints at various points in the program.

*Uninstalled Eclipse and re-installed again

But none of the above mentioned steps helped.
However, if I try creating a new test android application project and apply breakpoints there, it seems to be working fine. The problem is with the existing android application that has been imported.
PS: The existing android application source code is in a folder other than the default eclipse workspace.

A: Try adding this line to your code. At the onCreate
 android.os.Debug.waitForDebugger();


text:
Q: what does @ mean in case of `pip install  @ path`? I just came across this from a project on GitHub
pip install colorama @ file:///home/conda/feedstock_root/build_artifacts/colorama_1602866480661/work

what does @ do ?
assuming it decides the path where to install, I tried using any path and it wouldn't work like that
Also, why would we want to do so?
Also, what is the significance of file:///
Here is the link to the project
https://github.com/sstzal/DFRF/blob/main/requirements.txt
Thanks for your attention

A: This notation with an @ is specified here in the "Direct references" section of PEP 440.
The part after the @ is a direct reference to a location where the project can be installed from (i.e. the source, not the destination).
It can be URL to a file archive (sdist or wheel), or a VCS repository (git, for example).
The file:// notation is meant for the (local) filesystem protocol (as opposed to the https:// protocol for example).


text:
Q: Automatically Filling Form Fields in MS Access 2010 Hi I have a table Exhibit_Testing with the following fields:
1) ReferenceNo ( Automatic Number)
2) Region_Name
3) Branch_Code
4)Branch_Name
5) AOM
6) Observation
7) Status
8) Date_Recieved
9) Date_Checked
I want to create a Data Entry Form where if I enter Branch_Code then, Region_Name, Branch_Name, AOM are automatically filled.
Please help me in that. Thanks.
Update : The Branch_Code should be in Combo Box format.

A: The Branch_Code combobox's RowSource property should be a query that returns all the fields you want to automatically fill in.
When a particular branch is selected from the combo use the AfterUpdate event to fill in the other fields as follows:
Private Sub cmbBranch_Code_AfterUpdate()
    txtRegion_Name=cmbBranch_Code.Column(1)
    ...
End Sub


text:
Q: How can i iterate through if statement with condition if (i < current Subject nodes inside xml file ) then display data for each Here is my current code which outputs the modules in 1 single input textbox.
XElement root = XElement.Load("Data.xml");
            var subjects = from subject in root.Descendants()
                          where subject.Name.LocalName.Contains("Subject")
                          select new
                          {
                              subname = subject.Element("subjectName").Value,
                              subid = subject.Element("subjectId").Value,
                              subvalue = subject.Element("subjectvalue").Value
                          };

            foreach (var subject in subjects)
            {
                Console.WriteLine(subject);
                //you can use subject like this:
                string subName = subject.subname;
                string subID = subject.subid;
                string subValue = subject.subvalue;
                TextBox[] info = new TextBox[6];

                textBox1.AppendText("Subject Name :  " + subName + "  Subject Id :  " + subID + "  Subject Value :  " + subValue + " " );
            }

How can i alter this code so that i dynamically create a inputtextbox depending on how many  tags currently existing inside my xml file.
here is some code i tried :
 foreach (var subject in subjects)
            {
                Console.WriteLine(module);
                subname = subject.Element("subjectName").Value,
                subid = subject.Element("subjectId").Value,
                subvalue = subject.Element("subjectvalue").Value

            for (int i = 0; i < 2; i++)
            {
                info[i] = new TextBox();
                info[i].Location = new System.Drawing.Point(50, 114 + i * 25);
                info[i].Size = new System.Drawing.Size(300, 15);
                info[i].Text = @"";
                this.Controls.Add(info[i]);

                info[i].AppendText("Subject Name :  " + subName + "  Subject
                Id :  " + subID + "  Subject Value :  " + subValue + " " );
            }
        }

however this code displays the same data on both the dynamically created inputbox field. How can I make it so that the if condition is something like if (i < current Subject nodes inside xml file ) then iterate through them displaying each data into a dymaically created input textbox.
here is how my xml file looks like :
<PersonDetails>
  <Person>Teacher</Person>
  <keystage3>
    <Subject>
      <subjectName>maths</subjectName>
      <subjectId>qq1</subjectId>
      <subjectvalue>20</subjectvalue>
    </Subject>
    <Subject>
      <subjectName>english</subjectName>
      <subjectId>aaa</subjectId>
      <subjectvalue>40</subjectvalue>
    </Subject>
  </keystage3>
  <keystage4>
  </keystage4>
</PersonDetails>

A: As per above explanation, try this:
    int y = 114;
    foreach (var subject in subjects)
    {
            Console.WriteLine(module);
            subname = subject.Element("subjectName").Value,
            subid = subject.Element("subjectId").Value,
            subvalue = subject.Element("subjectvalue").Value

            TextBox box = new TextBox();
            box.Location = new System.Drawing.Point(50, y);
            box.Size = new System.Drawing.Size(300, 15);
            box.Text = @"Subject Name :  " + subName + "  Subject Id :  " + subID + "  Subject Value :  " + subValue + " ";
            this.Controls.Add(box);
            y += 25;
    }


text:
Q: How will send a request for 'course creator' role to admin in moodle? In my moodle site admin can add a user as course creator. But how will newly joined user will inform admin that they want the role 'course creator'. How will send such a request to admin. Please give a solution or suggest a plugin. Thanks in advance.

A: The closest solution to your question is probably Course requests
Under admin check the http://YOURMOODLE/admin/settings.php?section=courserequest page


text:
Q: How can I assign specific cloudlets to specific virtual macines in cloudsim? I have some virtual machines that I splited them into some groups called "Virtual Clusters". Actually I have a list of Vm lists as bellow:
VCs = List <List<Vm>>

in the other hand, I have some cloudlets that I splited them into some groups called Workloads. Actually I have a list of cloudlet lists as bellow:
WDs = List <List<Cloudlets>>

now I need to assign the ith list of cloudlets to ith list of Virtual cluster. actually I need something like this:
for (int i=0; i<VCs.size(); i++)
   for (int j=0; j<VCs.get(i).size(); j++){
   broker.submitVmList (Vcs.get(i));
   broker.submitCloudletList (Vcs.get(i).get(j);
   }

But it doesn't Work and at last it assign all cloudlets to all Vms respectivly!
how can I do this?

A: You can use the following line of code in your loop:
broker.bindCloudletToVm(cloudlet[i].getCloudletId(),vm[i].getId());

Do this after you submit cloudlet list to the broker.


text:
Q: Use of conditional function, condition in definition I have a seemingly trivial problem. I write a definition and I don't know how to introduce conditional functions.
I have a definition that works:
def function_1 (kot):
     if kot == True:
         print ("Yes:")
     else:
         print ("NO:")

It wokrs good
function_1 (False)

No:
or
function_1 (True)

Yes:
But I would like to have such a thing in my definition
def function_1 (kot = True):
     if kot == True:
         print ("Yes:")
     else:
         print ("NO:")

and it doesn't work any more.

A: Because you need to call the function as you did in the above example
def function_1 (kot=True):
 if kot == True:
     print ("Yes:")
 else:
     print ("NO:")

function_1()

output:
Yes:


text: Q: kie-maven-plugin for gradle 5.2.1 I have seen many examples kie-maven-plugin using maven. But i want to know how to make a plugin kie-maven-plugin in gradle project. Seems like that plugin is not avilable in gradle core plugin. I appriciate if someone share github project link


text:
Q: How can I wrap a glyphicon with twitter bootstrap? How can I wrap a glyphicon and a word together so that the icon is centered over or under the word. For an example:

Photography

Rentals

Dance Media

A: If I understand your question correctly, you need to put text-align: center; in the div that contains the text and the icon. Check out this example: http://jsfiddle.net/rahjU/11/


text:
Q: How to do parallel PostgreSQL query exections in Python3.7 docker container? I'm working on moving data from Postgres DB to AWS Redshift using Python3.7. I created an SQL query that retrieves a query set when executed (I'm using where clause to query. So for every query execution, I'll be changing the ID that I'm passing).
I'm going to run this script in Flask docker container which will be ultimately run on Kubernetes.
I have exposed an POST method enpoint in dockerized Flask app on which I'll receiving a list of IDs that needs to be queried on DB and data to be moved to Redshift using Python.
I want to do multithreading for executing multiple queries at once and moving data as there could be lot of IDs in the POST request that I receive.
But, as I'm using Python3.7, I came to know that GIL is going to be a bottleneck and it doesn't matter if how many threads you are running, and there will be only one thread executing at any time.
How do I overcome this problem and make the parallel execution of SQL queries on DB possible and that finally works on Kubernetes.
Can I go with multiprocessing or is there any other better way to achieve this?

A: If you're using Flask app, you can host your app in Gunicorn with multiple workers and threads which allows parallelism by running multiple workers.
Gunicorn launches a master process that can create multiple (configured workers) where each worker can handle an HTTP request independently. The kernel handles the load balancing of request among the workers.
If you add Gevent to the mix, that also provides concurrency per worker i.e. each worker would be able to handle multiple requests concurrently (not in parallel).
Both of these are available as pip packages, Gevent requires the installation of libev.
The support for flask by Gunicorn is ensured by the fact that flask is a WSGI framework and Gunicorn is a WSGI server, they're simply plugged into each other.


text:
Q: Why is this menu wrapping? I have a menu at:
http://www.spotlesswebdesign.com/dqhendricks/index.html
The problem is, when you resize the window small enough, the menu will start wrapping to a second line. I would like to prevent this from happening, and in the past I have use very similar css without getting this problem. How can I stop it from wrapping?
Here is some code:
HTML

                    Home

                    Experiments

                    Contact

CSS
#nav {
    margin: 0 25px;
}

#nav .left {
    float: left;
    width: 9px;
    height: 38px;
    background-image: url('../images/nav/left.png');
}

#nav .right {
    float: right;
    width: 9px;
    height: 38px;
    background-image: url('../images/nav/right.png');
}

#nav .center {
    height: 38px;
    margin: 0 9px;
    background: url('../images/nav/center.png') repeat-x;
}

#nav ul {
    width: 1000px;
    height: 38px;
    margin: auto;
    padding-left: 2px;
    list-style-type: none;
    background: url('../images/nav/divider.png') top left no-repeat;
}

#nav li {
    display: inline;
}

#nav a {
    display: block;
    float: left;
    padding: 0 30px 0 28px;
    height: 38px;
    line-height: 36px;
    text-decoration: none;
    color: #777777;
    background: url('../images/nav/divider.png') top right no-repeat;
}

A: This is a working example I just tested out.
Add white-space: nowrap; to #nav .center and add display: inline-block; to #nav li.
Those two will prevent the contents of the navigation from wrapping and creating a new line.

A: Use min-width to allow it to grow with the page instead of being fixed width.  Should work in IE8 and all other browsers. IE6 can go burn.

A: Add:
overflow: visible

to #nav

A: Set the size of the wrapping DIV:
#nav {
    margin: 0 25px;
    width: 1000px;
}


text:
Q: what is Java API? I know API is a set of rules and protocols.can anyone explain me with example what is a Java API and its functionality...

A: You can find Java API here http://download.oracle.com/javase/6/docs/api/index.html
You could say it is the Java library and you can use it like building blocks for your software and that way speed up your development.
For example:
ArrayList is one of the gazilion classes in the API.
import java.util.ArrayList; // We say the old mighty compiler that we want to use this class

// we create an ArrayList object called myList that will hold objects of type Beer
ArrayList<Beer> myList = new ArrayList<Beer>();

Beer b = new Beer();

myList.add(b); // the class ArrayList has a function add, that adds an object(a Beer);

myList.size(); // will give you the size of the ArrayList.

myList.remove(b); // will remove our beloved Beer :)

If you want to know what else can you do with the ArrayList you should check out the API or when typing myList. CTRL + SPACE will give you all the functions avaible :)
Good luck!

A: Exactly what you described, just for the Java language.
Java API is a set of libraries that are found in the standard Java distribution, and is called the JRE (Java Runtime). So, every time you use something like Integer as a class for representing integers, you're using Java's API.
But since Java is so broad, and boundaries between various distributions (Java SE, Java EE, Java ME) aren't always clear at first sight, the terminology "Java API" might be misleading.
So, treat it as the way you communicate your code to Java's libraries.

A: general api explanation
JAVA API
In a nutshell, the API is used from a user point of view as the reference which classes and methods are available in this specific language

A: The JAVA API is a collection of classes and functions that can be used to create programs....
A programming language is a general term for a computer-program language.....while API is the technical term for the actual set of features implemented using functions and classes...
The Java API is implemented using the JAVA JDK(Java Development Kit) from Oracle/Sun.

A: In simple,
Java APIs are integrated pieces of software that come with JDKs. APIs in Java provides the interface between two different applications and establish communication.
I suggest you to check the following vedio which explains deeply.
https://www.youtube.com/watch?v=u4tw-cIJFuo


text:
Q: PHP fails to open an Excel workbook through COM This code works fine until it gets to the open workbook line and then it fails.
 <?PHP

$file = "C:\\xampp\\htdocs\\php\\test.xls";
openWorkbook($file);

function openWorkbook($file)
{
$excel = new COM("Excel.Application") or die ("ERROR: Unable to instantaniate COM!\r\n");
echo "Application name: {$excel->Application->value}\r\n";
echo "Loaded version: {$excel->Application->version}\r\n";

// FAILS ON THIS LINE!
$Workbook = $excel->Workbooks->Open($file) or die("ERROR: Unable to open " . $file . "!\r\n");
}

Does anyone have any suggestions to why this may be happening? I've looked though a lot of other posts, but no one seems to have this specific issue.

A: I shall assume that there is some reason why you need to use COM and not a 3rd-party library like PHPExcel. If there isn't a specific reason for this, consider switching to one these tried, tested and considerably better supported alternatives.

Your code seems to be correct, I can only imagine you have some kind of permissions problem.
It can be quite difficult to extract sensible error messages from MSO applications in PHP via COM, so here's a couple of things you can try:

*

*Verify that the file extension (.xls in you case) matches the data inside the file - make sure you don't have a CSV file with the wrong file extension, for example. Excel (even when accessed via COM) should be able to handle this, but it will throw up a warning if you open the file in the Excel application.

*Open the file in Excel, type in an empty cell, delete what you just typed, and save it. This will cause Excel to re-encode and write the entire file back to disk, which may also help resolve any corrupt file issues.

*Make sure the file has the appropriate permissions on it. The best way to do this would be to set the file as full permissions for the "Everyone" group, and if this fixes the problem you can then adjust the permissions to the required restrictions.

This is highly unlikely to fix this specific problem (the file open code appears to be identical) but it may assist you a little: some time ago I wrote a very small wrapper library for Excel accessed via COM, which can be found here. Its functionality is very limited, but more methods could be added quite easily; what it mostly brings to the party is a slightly cleaner API and slightly better error handling.


text:
Q: WideImage - Canvas with transparent background We're using a CMS with WideImage built in and no scope to change this, however we've come up against a situation where we need to produce 300x300 images.
However the images that are uploaded at approx 100x100 in jpg and png format with various levels of transparency.
I'm trying to create a 300x300 canvas, and place the 100x100 image inside of it - however I want both the canvas to remain transparent, and the image placed on top to keep its transparency.
I've got
$image = WideImage::loadFromFile( $this->local_path );

$canvas = WideImage::createTrueColorImage(300, 300);
$canvas_bg = $canvas->allocateColor(255, 255, 255);
$canvas->fill(0, 0, $canvas_bg);

$resized_image = $canvas->merge($image);

However this obviously just adds a white background to the canvas, I cant figure out from their documentation how to make it transparent.
Thanks

A: How about:
$image = WideImage::loadFromFile($this->local_path);
$resized_image = $image->resizeCanvas(300, 300, 0, 0);

You can specify the X and Y location of the image within the new canvas as well as its width and height. $image->resizeCanvas(300, 300, "center", "center") works quite well.


text:
Q: Backpressure not being respected in chain with flatMap and multiple observeOn's I am not sure why backpressure is not being respected in this flowable chain.
I have simplified it to the following: There are 3 stages, heavyFlowableBasedOnInput, singleThreadedPieceOfWork and writeFileToDisk. The first 2 stages happen much faster than the final stage, so their output stays memory waiting for step 3, leading to out of memory error/ continuously increasing memory usage.
When I watch the debugger, I notice step 1 happening a lot more often than step 3, even though I have set the buffer size (third argument of observeOn) to a low number (e.g. 1).
Flowable.fromIterable(listOfResources)
        .subscribeOn(Schedulers.io())
        .flatMap { flowableUsing(it) } // small flowable though, ~0-10, mostly 1 to 2 emissions
        .observeOn(Schedulers.single(), false, 1)
        .map { singleThreadedPieceOfWork() }
        .observeOn(Schedulers.io(), false, 1)
        .map { writeFileToDisk() }
        .subscribe()

I have read the documentation for each operator I am using, it looks like all of them have some backpressure support (e.g. passing through backpressure BackpressureKind.PASS_THROUGH, honours downstream backpressure BackpressureKind.FULL). I have no clues as to why I am overloading the  queue/ buffer for writeFileToDisk.
I did read Why doesn't my RxJava Flowable respect backpressure when using observeOn? I understand that observeOn creates an "asynchronous boundary", but I don't know how this affects backpressure.
An image of memory usage going up steadily

A: From akarnokds blog:

Backpressure, the way of preventing buffer-bloat with reactive flows,
is a cornerstone of RxJava. Most operators that don't have timing
aspects in them apply and honor backpressure. Unfortunately, flatMap
by default can only say it honors backpressure but doesn't apply it
towards its main input.
This means that when you use the common overload of flatMap or merge,
the operator will request Long.MAX_VALUE from its upstream and realize
it all at once. This unbounded behavior leads to an unbounded number
of active subscriptions to the generated inner Observables.
This property doesn't cause much trouble if the inner Observables are
short or infrequently emitting, but if there is an asynchronous
boundary after flatMap, let's say, observeOn, items can quite easily
pile up in flatMap and degrade performance considerably.

I think I fixed it by specifying the maxConcurrency parameter in the flatMap overloaded function:
kotlin
Flowable.fromIterable(listOfResources)
        .subscribeOn(Schedulers.io())
        .flatMap({ flowableUsing(it) }, false, 1, 5) // <-- the maxConcurrency and bufferSize
        .observeOn(Schedulers.single(), false, 1)
        .map { singleThreadedPieceOfWork() }
        .observeOn(Schedulers.io(), false, 1)
        .map { writeFileToDisk() }
        .subscribe()

Alternatively, this wasn't a fix. I might have just reduced the performance so much that this memory issue doesn't occur anymore.
Pending more reading/ understanding


text:
Q: FLASK REST API returns 400 on POST I'm building a REST API for a simple Todo application using flask and SQLAlchemy as my ORM. I am testing my API using Postman. I'm on a windows 10 64-bit machine.
A GET request works and returns the data that I've entered into my database using python.

I'd like to try to add a task now. But when I POST my request, I receive an error.

My route in flask looks like this.
#add task
@app.route('/todo/api/v1.0/tasks', methods=['POST'])
def create_task():
    if not request.json or not 'title' in request.json:
        raise InvalidUsage('Not a valid task!', status_code=400)
    task = {
        'title': request.json['title'],
        'description': request.json['description'],
        'done': False
    }
    Todo.add_todo(task)
    return jsonify({'task': task}), 201

And the method it's calling on the Todo object looks like this.
def add_todo(_title, _description):
    new_todo = Todo(title=_title, description=_description , completed = 0)
    db.session.add(new_todo)
    db.session.commit()

What I've tried
I thought that maybe the ' in my Postman Params was causing an issue so I removed them. But I still get the same error.
Then I thought that maybe the way that Postman was sending the POST was incorrect so I checked to make sure that the Content-Type headers was correct. It is set to application/json
Finally, to confirm that the issue was that flask didn't like the request, I removed the check in the add task route to make sure the request had a title. So it looks like this.
if not request.json:

And I get the same error. So I think that the problem must be with how I'm actually sending the POST rather than some kind of formatting issue.
My entire code looks like this.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import json
from flask import jsonify
from flask import request

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///todo.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(300), unique=False, nullable=False)
    description = db.Column(db.String(), unique=False, nullable=False)
    completed = db.Column(db.Boolean, nullable=False)

    def json(self):
        return {'id': self.id,'title': self.title, 'description': self.description, 'completed': self.completed}

    def add_todo(_title, _description):
        new_todo = Todo(title=_title, description=_description , completed = 0)
        db.session.add(new_todo)
        db.session.commit()

    def get_all_tasks():
        return [Todo.json(todo) for todo in Todo.query.all()]

    def get_task(_id):
        task = Todo.query.filter_by(id=_id).first()
        if task is not None:
            return Todo.json(task)
        else:
            raise InvalidUsage('No task found', status_code=400)

    def __repr__(self):
        return f"Todo('{self.title}')"

class InvalidUsage(Exception):
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        Exception.__init__(self)
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        rv = dict(self.payload or ())
        rv['message'] = self.message
        return rv

@app.route('/')
def hello_world():
    return 'Hello to the World of Flask!'

#get all tasks
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
    return_value = Todo.get_all_tasks()
    return jsonify({'tasks': return_value})

#get specific task
@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['GET'])
def get_task(task_id):
    task = Todo.get_task(task_id)
    #if len(task) == 0:
        #raise InvalidUsage('No such task', status_code=404)
    return jsonify({'task': task})

#add task
@app.route('/todo/api/v1.0/tasks', methods=['POST'])
def create_task():
    if not request.json or not 'title' in request.json:
        raise InvalidUsage('Not a valid task!', status_code=400)
    task = {
        'title': request.json['title'],
        'description': request.json['description'],
        'done': False
    }
    Todo.add_todo(task)
    return jsonify({'task': task}), 201

#update task
@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['PUT'])
def update_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        raise InvalidUsage('No provided updated', status_code=400)
    if not request.json:
        raise InvalidUsage('request not valid json', status_code=400)
    if 'title' in request.json and type(request.json['title']) != unicode:
        raise InvalidUsage('title not unicode', status_code=400)
    if 'description' in request.json and type(request.json['description']) != unicode:
        raise InvalidUsage('description not unicode', status_code=400)
    if 'done' in request.json and type(request.json['done']) is not bool:
        raise InvalidUsage('done not boolean', status_code=400)
    task[0]['title'] = request.json.get('title', task[0]['title'])
    task[0]['description'] = request.json.get('description', task[0]['description'])
    task[0]['done'] = request.json.get('done', task[0]['done'])
    return jsonify({'task': task[0]})

#delete task
@app.route('/todo/api/v1.0/tasks/<int:task_id>', methods=['DELETE'])
def delete_task(task_id):
    task = [task for task in tasks if task['id'] == task_id]
    if len(task) == 0:
        raise InvalidUsage('No task to delete', status_code=400)
    tasks.remove(task[0])
    return jsonify({'result': True})

@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response

if __name__ == '__main__':
    app.run(debug=True)

EDIT:
Turns out I wasn't setting the request type in POSTMAN correctly. I've updated it to 'application/json' in the header. Now I'm receiving a different error.

Bad Request Failed to decode JSON object: Expecting value: line 1
  column 1 (char 0)

I've tried all the previous steps as before but I continue to get this error.

EDIT 2:
Per a response below, I tried putting the values into the body of the POST. But I still get back a 400 response.

A: From the image [second postman screenshot] it looks like you pass data in query string but create_task() expects them in request body.
Either replace all occurrences of request.json with request.args in create_task() (to make it work with query params) or leave it as it is and send data in request body.
curl -X POST http://localhost:5000/todo/api/v1.0/tasks \
-H "Content-Type: application/json" \
-d '{"title":"Learn more flask","description":"its supper fun"}'

Also, take a look at Get the data received in a Flask request.

EDITED
Update your add_todo to something like
@classmethod
def add_todo(cls, task):
    new_todo = cls(title=task["title"], description=task["description"], completed=0)
    db.session.add(new_todo)
    db.session.commit()

Related: generalised insert into sqlalchemy using dictionary.


text:
Q: Update controls while printing using printdocument in Winforms I am printing a panel with all its controls Inside. My problem is that I want to make a counter Inside this panel and increase its value for each pages printed. I tried incrementing the counter Inside my PrintPage event but this isn't working. Would it be possible to add multiple printpage events with increased counter for every page ? Here's my not working code. Thanks for giving me advices about how I could do this printing...
 private void PrintPage(object o, PrintPageEventArgs e)

    {
        try
        {
            if (File.Exists(toPrint) && nbrPrint < nbrPages)
            {

                Rectangle m = panel1.ClientRectangle;

                Bitmap imaag = new Bitmap(m.Width, m.Height);
                panel1.DrawToBitmap(imaag, m);

                e.Graphics.DrawImage(imaag, e.MarginBounds);
                nbrPrint++;
                compteurPrint++;
                cpt.Text = compteurPrint.ToString();
            }
        }
        catch (Exception)
        {

        }
    }

nbrPrint is the pages printed, nbrPages the number of pages asked to print, compteurPrint the value I need to print in the page (which needs to be incremented), cpt is the label (Inside panel1) in which I show compteurPrint.
Since I do this:
 pd.PrintPage += PrintPage;
 pd.Print();

Can I do:
while (nbrPrint < nbrPages)
{
     pd.PrintPage += PrintPage;
     compteurPrint++;
}
pd.Print();

I think it would be the same result as what I'm currently doing…
Thanks for help !

A: You need to set the HasMorePages property on PrintPageEventArgs to tell it that there are more pages to print.
private void PrintPage(object sender, PrintPageEventArgs e)
{
  try
  {
    if (File.Exists(toPrint) && nbrPrint < nbrPages)
    {
      Rectangle m = panel1.ClientRectangle;

      Bitmap imaag = new Bitmap(m.Width, m.Height);
      panel1.DrawToBitmap(imaag, m);

      e.Graphics.DrawImage(imaag, e.MarginBounds);
      nbrPrint++;
      compteurPrint++;
      cpt.Text = compteurPrint.ToString();
      e.HasMorePages = true; // Set this to true as long as there are more pages to print. It defaults to false.
    }
  }
  catch (Exception)
  {

  }
}

Checkout the Microsoft documentation for an example: PrintDocument.PrintPage


text:
Q: debugging with netbeans and xdebug won't work - netbeans don't start browser Try and error.. did not helped me after 2 hours even with "googling" around. No one seems to have my problem or there is a easy solution that i don't see.
My phpinfo() show xdebug just fine:
version         2.1
xdebug.remote_enable    On
xdebug.remote_handler   dbgp
xdebug.remote_host      localhost
xdebug.remote_mode      req
xdebug.remote_port      9000

My netbeans listen to port 9000 (but just on ipv6; may be this is the problem):
tcp6       0      0 :::9000                 :::*                    LISTEN      5290/java

Netbeans is reachable through telnet:
$ telnet localhost 9000
Trying 127.0.0.1...
Connected to localhost.

But netbeans does not start the browser until i click the "stop" button. Then it opens up a browser with ?XDEBUG_SESSION_START=netbeans-xdebug. How to disable ipv6 for netbeans? I don't want to disable the entire ipv6 support (ipv6 support in enabled in phpinfo()). Any other ideas?
Version:
OS: Ubuntu 12.04 LTS
Apache: 2.2.22
PHP-CGI: 5.3.10
Netbeans: 7.2
Java: 1.7.0_05

A: I had the same problem as the browser not coming up and following is what fixed the problem.
There are actually 3 potential locations where you can specify the debugging port

*

*Php.ini -- {xdebug.remote_port=9000}

*In Netbeans IDE under - preferences - php - general {debugger port =9000; session ID= netbeans-xdebug}

*In the run configurations - Advanced  !! DONT set this one - it refers to 'Debugger Proxy' if you set this the browser window will not come up until you have maintained the same proxy settings in the netbeans - preferences - general  tab.

PS: all of the above or on a Mac..

A: I had a bad run configuration in project. Netbeans was waiting for a debugging proxi on localhost:9000. I did not remember to set this setting. If someone has the same problem check this configuration too.

A: In my case the problem the project URL under Project properties in Run configuration was pointing to a subdirectory instead of the root directory of the server, after i changed to localhost everything was fine.
I found the answer after reading this article.
http://shinephp.com/netbeans-7-0-php-waiting-for-connection-to-xdebug/


text:
Q: Mount encrypted .dmg from terminal using list of possible passwords? I have an external drive with an encrypted disk image that I've forgotten the password to-- but I know it's a combination of 4-5 passwords I was using at the time it was encrypted. I generated a list of all the combinations I think it could be (with character variations I use, such as @ for 'a'), and I'd like to automate trying each of them as there are several hundred guesses.
I'm using '''echo -n 'Password' | hdiutil attach -stdinpass /path/Disk.dmg''' to try to mount the disk from terminal on Mac, and I know this works using a test disk image I made.
So, is there a way I can pass the list of password guesses to terminal instead of having to paste them in? I've considered using Automator on Mac but it won't take my code above in the "do shell script" command.
Thanks for your help!

A: cat yourfile.txt | while read line; do hdiutil attach -stdinpass /path/DMG.dmg; done


text:
Q: Android: How to make pagination with instagram API I have 29 photos on my instagram account and I want to show all these photos on my app. But I know that instagram just let me retrieve 20 photos and I also know that I can use pagination to get more photos. The problem is: I don't know how to paginate, do you know how to do it? do you know any tutorial?
Oh, I've read in some questions that some persons had used a counter parameter on URL like this: https://api.instagram.com/v1/users/self/feed?count=-1&access_token=ACCESS-TOKEN  but it didn't work with me =(

A: The response object you get from the Instagram API will have a pagination object, this object contains a property called next_url. This is the URL you need to use to get the next page. Here is an example:
You request the original feed with the following URL:
https://api.instagram.com/v1/users/self/media/recent?access_token=TOKEN

This gives a response like:
{
   "pagination":{
      "next_url":"https://api.instagram.com/v1/users/319505/media/recent?access_token=TOKEN&max_id=407185589491099817_319505",
      "next_max_id":"407185589491099817_319505"
   },
   "meta":{
      "code":200
   },
   "data":["omitted"]
}

Requesting the URL in next_url will return the next page, and so on for each additional page.

A: If you only need to get 29 photos, you can specify a count of 29, not -1. For retrieving more than 33 (limit set by Instagram), you can check out a Instafetch, a script I wrote.
Instafetch will get as many media items as you specify, in exchange for a higher API call count, as well as being slower.


text:
Q: Angular 5 + How to move the cursor character by character using keyboard left/right options in IE 11 I am using Angular 5 with Ag-Grid Enterprise Addition. I am using IE11 browser. Unfortunately in the grid, the cursor gets stuck and not moving to next characters in the input box using keyboard left/right options. So, I thought of explicitly moving the cursor to next characters. I am using Javascript range for that. I am getting the error at this line document.getSelection().addRange(range). Please find the below code of the custom NumericComponent ,screenshot of input box and error. I am not sure if this is the right approach. Can anyone guide me how to fix this issue ?
<input #input  id="numericinput" style="width: 100%; height: 100%;" (keydown)="onKeyDown($event)" [(ngModel)]="value" (dblclick) = "$event.target.select()">
              <button (click)="clear()" style="position:absolute;top:5px;right:2px;cursor:pointer;color:grey;background-color:white;border:none;">
                <span>❌</span>
              </button>

onKeyDown(event): void {
        var key = event.which || event.keyCode;
        if(key === 37 || key === 39){
          let error ;
          event.stopPropagation();
          let inputDocument = document.getElementById('numericinput');
          let range = document.createRange();
          range.collapse(true);
          range.setEnd(inputDocument.firstChild, 0);
          range.setStart(inputDocument.firstChild, this.input.element.nativeElement.value.length);
          document.getSelection().removeAllRanges;
          document.getSelection().addRange(range);
        }
        if (!this.isKeyPressedNumeric(event)) {
            if (event.preventDefault) event.preventDefault();
        }

    }

A: Below is the solution from which I achieved the task
var key = event.which || event.keyCode;
        var iCaretPos = 0;
        if(key === 37 || key === 39){
            //Left or right
          let inputDocument = document.getElementById('numericinput');
          const element : HTMLInputElement = <HTMLInputElement>inputDocument;
          event.stopPropagation();
          let selectionStart = 0;
          if(key === 39 && this.iCaretPos < element.innerHTML.length+1){
                selectionStart = this.iCaretPos;
                this.iCaretPos = this.iCaretPos +1;
          }else if(key === 37 && this.iCaretPos !== 0){
                selectionStart = this.iCaretPos;
                this.iCaretPos = this.iCaretPos -1;
          }
          let selectionEnd = this.iCaretPos;
            if (element.setSelectionRange) {
                element.focus();
                element.setSelectionRange(selectionStart, selectionEnd);
            }
        }


text:
Q: How to refresh jqgrid using the response data returned from the edit I am using the inlineNav edit options for Adding and Editing rows.  The data is being updated to the database correctly, but I can't find a way to refresh the grid after a successful save without posting back to the server.
All of the Questions & Answers that I find recommend doing
    $.('grid').trigger('reloadGrid');
But that seems unnecessary if the response from the server already contains the required data.  It is primarily an issue when adding a new record and the ID value is displayed as jqg1.
I am using ASP.NET MVC4, with jqGrid 4.4.4.
Here is my view

  $(document).ready(function () {
    var emptyMsgDiv = $('
No school codes to display.
');
    var grid = $('#tblSchools');

    grid.jqGrid({
        datatype: 'json',
        viewrecords: true,
        url: '@Url.Action("SchoolsGridData")',
        editurl: '@Url.Action("EditSchoolsGridData")',
        colNames: ['School ID', 'Name', 'SACE Number', 'School Code', 'LEA Code', 'DFEE Code', 'Active'],
        colModel: [
                    { name: 'SchoolId', index: 'SchoolId', width: 80, key: true },
                    { name: 'Name', index: 'Name', width: 190, editable: true },
                    { name: 'SaceSchoolNumber', index: 'SaceSchoolNumber', width: 105, editable: true, sortable: false },
                    { name: 'Code', index: 'Code', width: 105, editable: true, sortable: false },
                    { name: 'LeaCode', index: 'LeaCode', width: 80, editable: true, sortable: false },
                    { name: 'DfeeCode', index: 'DfeeCode', width: 80, editable: true, sortable: false },
                    { name: 'Active', index: 'Active', width: 80, editable: true, sortable: false }
        ],
        shrinkToFit: true,
        height: "100%",
        caption: 'School list',
        rowNum: 10,
        rowList: [10, 15, 20],
        emptyrecords: 'No school codes to display.',
        pager: '#schoolsPager',
        loadComplete: function () {
            var count = grid.getGridParam();
            var ts = grid[0];
            if (ts.p.reccount === 0) {
                grid.hide();
                emptyMsgDiv.show();
            } else {
                grid.show();
                emptyMsgDiv.hide();
            }
        }
    }).trigger('reloadGrid', [{ page: 1 }]);

    emptyMsgDiv.insertAfter(grid.parent());

    grid.jqGrid('navGrid', "#schoolsPager", { edit: false, add: false, del: true });
    grid.jqGrid('inlineNav', '#schoolsPager', {
        addParams: {
            position: "last",
            addRowParams: {
                "keys": true,
                "aftersavefunc": function (rowid, response) {
                    alert('row: ' + rowid + ', response: ' + $.param(response));
                }
            }
        },
        editParams: {
            "aftersavefunc": function (rowid, response) {
                alert('row: '+rowid+', response: '+response);
            }
        }
    });

  });
</script>

Maintain Schools

and my Controller
public JsonResult EditSchoolsGridData(string oper, string SchoolId, string Name, string SaceSchoolNumber, string Code, string LeaCode, string DfeeCode, string Active)
{
  [Update Logic]

  return SchoolsGridData(string.Empty, "asc", 1, 10);
}

[HttpGet]
public JsonResult SchoolsGridData(string sidx, string sord, int? page, int? rows)
{
  [Get data logic]
}

I can see the response json being displayed in the aftersavefunc, but can't find a way to bind it to the grid.
Is what I'm trying to do even possible?

A: You can use the addRowData method which will set the data to grid with our reloading the grid
jQuery("#tblSchools").jqGrid('addRowData', response.SchoolId, response, "first");

See the jqgrid methods wiki for more details


text:
Q: Opengl vertex color always leads to a black triangle My first triangle works well if the color is specified in the fragment shader. When I add a vertex color to the buffer the triangle is always black.
A minimal code with the issue:
type
    OGLfloat = float32
    OGLuint = uint32
    OGLint = int32

const
    GLFW_CONTEXT_VERSION_MAJOR = 0x00022002
    GLFW_CONTEXT_VERSION_MINOR = 0x00022003
    GLFW_OPENGL_PROFILE = 0x00022008
    GLFW_OPENGL_CORE_PROFILE = 0x00032001

const
    GL_COLOR_BUFFER_BIT = 0x00004000
    GL_DEPTH_BUFFER_BIT = 0x00000100
    GL_ACCUM_BUFFER_BIT = 0x00000200
    GL_STENCIL_BUFFER_BIT = 0x00000400
    GL_ARRAY_BUFFER = 0x8892
    GL_ELEMENT_ARRAY_BUFFER = 0x8893
    GL_FALSE = 0.char
    GL_STATIC_DRAW = 0x88E4
    GL_FLOAT = 0x1406
    GL_VERTEX_SHADER = 0x8B31
    GL_COMPILE_STATUS = 0x8B81
    GL_INFO_LOG_LENGTH = 0x8B84
    GL_FRAGMENT_SHADER = 0x8B30
    GL_LINK_STATUS = 0x8B82
    GL_TRIANGLES = 0x0004
    GL_UNSIGNED_INT= 0x1405
    GL_VERSION = 0x1F02

const
    POSITION_LENGTH = 3
    COLOR_LENGTH = 3

const
    WINDOW_W = 640
    WINDOW_H = 480

var
    colorDataOffset = 3 * sizeof(OGLfloat)

    vertices = @[OGLfloat(0.0), 0.5, 0, 1, 1, 1,
                         0.5, -0.5, 0,  0, 0, 0,
                         -0.5, -0.5, 0,  0, 0, 0]

    indices = @[OGLuint(0), 1 , 2]

# initialisation using glfw and glew
var glfwErr = glfwInit()
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3)
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3)
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE)
var winHandle = glfwCreateWindow(WINDOW_W, WINDOW_H)
glfwMakeContextCurrent(winHandle)
var glewErr = glewInit()

# shaders sources
var
    shadID:OGLuint
    vertSrc:cstring = """
        #version 330 core
        layout (location = 0) in vec3 aPos;
        layout (location = 1) in vec3 aColor;

        out vec3 inColor;

        void main()
        {
            gl_Position = vec4(aPos, 1.0f);
            inColor = aColor;

        }
        """
    fragSrc:cstring = """
        #version 330 core
        out vec4 FragColor;
        in vec3 inColor;

        void main()
        {
            FragColor = vec4(inColor, 1.0f);
        }

        """
# create the shader program
proc send_src(vert:var cstring, frag:var cstring):OGLuint =
    var success:OGLint
    # vertex
    var vertexShader = glCreateShader(GL_VERTEX_SHADER)
    glShaderSource(vertexShader, 1, addr vert, nil)
    glCompileShader(vertexShader)
    # Check compilation errors.
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, addr success)
    if bool(success) == false:
        echo(" vertex shader compilation failed (send_src)")
    else:
        echo("vertexShader compiled (send_src)")

    # fragment
    var fragmentShader = glCreateShader(GL_FRAGMENT_SHADER)
    glShaderSource(fragmentShader, 1, addr frag, nil)
    glCompileShader(fragmentShader)
    # Check compilation errors.
    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, addr success)
    if bool(success) == false:
        echo("fragment shader compilation failed (send_src)"
    else:
        echo("fragmentShader compiled (send_src)")

    # Shader program
    result = glCreateProgram()
    glAttachShader(result, vertexShader)
    glAttachShader(result, fragmentShader)
    glLinkProgram(result)
    # Check for linkage errors.
    glGetProgramiv(result, GL_LINK_STATUS, addr success)
    if success == 0:
        echo ("program linking failed (send_src)")
    else:
        echo ("shader linked (send_src)")

    glDeleteShader(vertexShader)
    glDeleteShader(fragmentShader)

glViewport(0, 0, WINDOW_W, WINDOW_H)
shadID = send_src(vertSrc, fragSrc)

var VAO, VBO, EBO:OGLuint
glGenVertexArrays(1, addr VAO)
glGenBuffers(1, addr VBO)
glGenBuffers(1, addr EBO)
glBindVertexArray(VAO)
glBindBuffer(GL_ARRAY_BUFFER, VBO)
glBufferData(GL_ARRAY_BUFFER, vertices.len * sizeof(OGLfloat),
             addr vertices[0], GL_STATIC_DRAW)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.len * sizeof(OGLuint),
             addr indices[0], GL_STATIC_DRAW)
# Position layout
glVertexAttribPointer(0, POSITION_LENGTH, GL_FLOAT, GL_FALSE, 6 * sizeof(OGLfloat),
                      nil)
glEnableVertexAttribArray(0)
# Color layout
glVertexAttribPointer(1, COLOR_LENGTH, GL_FLOAT, GL_FALSE, 6 * sizeof(OGLfloat),
                      addr colorDataOffset)
glEnableVertexAttribArray(1)
glBindBuffer(GL_ARRAY_BUFFER, 0)
glBindVertexArray(0)
glUseProgram(shadID)

while bool(glfwWindowShouldClose(winHandle)) == false:
    glClearColor(0.2, 0.3, 0.3, 1.0)
    glClear(GL_COLOR_BUFFER_BIT)
    glBindVertexArray(VAO)
    glDrawElements(GL_TRIANGLES, OGLint(indices.len), GL_UNSIGNED_INT, nil)
    glfwSwapBuffers(winHandle)
    glfwPollEvents()

glDeleteVertexArrays(1, addr VAO)
glDeleteBuffers(1, addr VBO)
glDeleteBuffers(1, addr EBO)
glfwDestroyWindow(winHandle)
glfwTerminate()

A: First see OpenGL 4.6 API Compatibility Profile Specification; 10.3.9 Vertex Arrays in Buffer Objects; page 409

... When an array is sourced from a buffer object for a vertex attribute, [...] the offset set for the vertex buffer [...] is used as the offset in basic machine units of the first element in that buffer's data store.

This means that the 6th parameter of glVertexAttribPointer has to be the offset of the color attribute, encoded to a pointer.
When you do addr colorDataOffset in
glVertexAttribPointer(1, COLOR_LENGTH, GL_FLOAT, GL_FALSE, 6 * sizeof(OGLfloat),
                      addr colorDataOffset)

then you create a pointer, but the value of the pointer is the address of colorDataOffset - see The addr operator.
What you have to do is to cast colorDataOffset to an pointer type by cast[pointer](colorDataOffset), the value of the pointer has to be the value of colorDataOffset - see Type casts and Types:
glVertexAttribPointer(1, COLOR_LENGTH, GL_FLOAT, GL_FALSE, 6 * sizeof(OGLfloat),
                      cast[pointer](colorDataOffset))


text:
Q: how to use flutter(dart) file in android studio i made the project with flutter using android studio,
and i carried out the coarse "Right click the Project root folder -> Flutter -> Open Android module in Android Studio." to use some function.
When I open different project, it is opened in existing flutter setting lilke this (photo 2).

But when I open that (carried out the practice 'open android module in android studio') project, it is opened in real android studio setting like this(photo1).

but i want to use the project in existing setting(like photo2) from now(like photo 1).
i want to use dart file... how can i do?
Flutter is my first coding, so I'm nooblette to using all program.
Please save me. thankyou....

A: You have opened the android folder as a project simply close the project and open a new project as root of your fluter project then it will open as a flutter project as you shown in first picture..


text:
Q: iOS UICollectionView - how to make first cell appear at the bottom of the collection view? I'm using UICollectionView with a flow layout - it has the first item at top left.
How can I modify flow layout so the first item is at bottom left and more items are added above?
Maybe there's a comprehensive list of example layouts provided by Apple that I can take a look at?

A: I would suggest that you make your own implementation of the UICollectionViewFlowLayout and reverse the x positioning yourself.
http://www.techotopia.com/index.php/Subclassing_and_Extending_the_iOS_6_Collection_View_Flow_Layout#Subclassing_the_UICollectionViewFlowLayout_Class


text:
Q: Is 26GB root (excluding /home) unusally large? I use a system with a / partition and no /home partition (I'm working on changing that) and noted that my root was rather large.
I ran the commands :
cd /
and
sudo du -sh --exclude=home
the du command returned :
26G
This struck me as odd because I remember reading that 12GB is "comfy" for the size of a root partition, given that was in regard to Ubuntu 14.something.
Am I doing something wrong? Is this related to not having a separate /home partition? Or is this normal?

A: When I only exclude /home I get:
$ sudo du -sh --exclude=home
du: cannot access './run/user/1000/gvfs': Permission denied
du: cannot access './proc/14676/task/14676/fd/4': No such file or directory
du: cannot access './proc/14676/task/14676/fdinfo/4': No such file or directory
du: cannot access './proc/14676/fd/3': No such file or directory
du: cannot access './proc/14676/fdinfo/3': No such file or directory
241G    .

A more accurate picture can be seen using:
$ sudo du -sh --exclude={home,media,mnt,proc,run,sys,tmp,tmpfs,var}
13G .

There you go 13 GB for "normal" versus 241 GB for "unusually large". Of course you need to use cd / before executing above commands.
In my case most of the excess baggage is in /mnt which contains two Windows installations and two Ubuntu installations (in addition the one mounted at /).
In /run or /media you can have your phone or USB sticks mounted. In /sys and /proc there are temporary virtual file systems created. In /var there are log files which can grow quite large but are empty on new installations. In /proc lies running processes which in the first instance generate error messages but are excluded in the second instance.
Even more space can be taken off the total because I have 15 kernels installed:
$ ll /boot/vmlinuz* | wc -l
15

The kernel files can be found here:
$ sudo du -sh usr/src lib/modules boot
2.0G    usr/src
4.1G    lib/modules
1.1G    boot

The directories total 7.3 GB but there are other non-kernel files there. In reality the total is 6.5 GB:

Using this script: How to selectively purge old kernels all at once

Summary

This struck me as odd because I remember reading that 12GB is "comfy"

Taking everything above into account 12 GB is "comfy":
$ sudo du -sh --exclude={home,media,mnt,proc,run,sys,tmp,tmpfs,var,boot,usr/src,lib/modules}
5.6G    .

That said when today 1 TB drives are the normal HDD size and 256 GB or 512 GB is the normal SSD size, comparing 13 GB or 26 GB for a Ubuntu installation seems insignificant.
Personally on a typical 500 GB system I would allocate 400 GB to Windows (includes gaming) and 100 GB to Ubuntu (includes two or three installations).


text:
Q: VSCode appears to automatically be adding an import to the top of scripts I am working on a Python project in VSCode with multiple files containing functions, being called from other files, like I have many other times.
However, I noticed that, sometimes, the following line appears at the top of some files:
    from asyncore import read

I removed it, and now once I checked the file after altering others, it's back! It is making me go mad. It even is in the git push I did, although I am sure I removed it before sending it. Does anyone know what this is? Thank you.

A: You can disable it by adding this line to your user or workspace settings (File>Preferences>Settings, or Code>Preferences>Settings).
"python.analysis.autoImportCompletions": false

This Pylance extension setting is documented here.  Turning of this setting is similar to this SO:answer except for Python instead of typescript.


text:
Q: add unique constraint to existing table column In mysql, when creating a table, you can append:
unique(username)

but i dont know how to alter a table to add that containt.
I was trying:
alter table Company constraint unique (username)

A: I mixed up the syntax.
alter table Company add constraint unique (username);

but this will fail if there are duplicates... So either drop and recreate if it is a sample db, or delete out duplicates.


text:
Q: Programming LS-iG5A I have got this LS iG5A VFD to control speed of my
rotary cutter machine. I have attached a momentary
On/Off switch to start stop the motor and also
connected a 10k POT to control its speed
My question is.... I want to program my VFD such that
it should start only when the POT is set to Zero and
when it starts it should go from 0-10Hz and maintain
until i turn the POT and increase the speed.
Please suggest how can it be achieved.

Thank you Raefield
Actually why I am doing this is to prevent the operator from starting the machine on the speed previously set when it was turned off.
Like, the machine was stopped because there was some issue and now after correcting that when we start it instead of going from 0 to 55 where it was previously running the system should stop and when the POT is at zero then start and go from 0 to 10 and wait there so the operator may see that the problem for which the machine was stopped is now over and the operator may increase the speed at his will.
While reading the manual which is not very self explanatory there is an option called Multi Step Speed Functions, is it something which is for my purpose
Thank you once again
Anxiously awaiting reply
Kindest regards
Kagazwala

A: Having it always start from 0-10Hz with no speed command yet is a simple task, using what most drives call the "minimum speed setting", usually one of the programmable features (you will have to consult your manual for that). Having it not start unless the pot is set to zero is, I think not possible with the standard settings of any VFD that I am aware of. Generally the Start / Stop commands are separate from the Speed commands, and when you hit Start, it starts at whatever the speed command setting is. If using a potentiometer, that means wherever the previous user had left it set. There are a couple of possible variants that I've used however. Whether or not that specific VFD is capable of them is, again, something you would have to determine by reading their manual.
Variant 1. Many VFDs have an option available wherein the VFD is always in a Run state, and you set up the Speed Pot as both the speed control AND the Run / Stop control. How that works is that at some analog value on the pot, let's say 5%, the speed is Zero, meaning stopped. So to "Start" the drive, you move the pot to a value above 5%, and to Stop it, you turn it back down below 5% again. When you do this, you can usually ALSO still have the "Stop" button be functional as a Stop command, but you would not be able to re-start it until you move the pot back to below the threshold again.
Variant 2. Many VFDs have a function called a "MOtorized Potentiometer (often abbreviated MOP) as a speed input option. In that, you increase the speed by closing an assigned input ("UP"), and decrease it by closing another one ("DOWN"). Then you can often "trick" the drive into accepting the UP input as ALSO being the "Start" command, and in conjunction with the aforementioned "minimum speed" setting, you can have the VFD always start when you hit a push button wired to the UP input at that minimum speed, then increase or decrease based on how long you hold the UP or DOWN buttons.
In both cases you must pay close attention in the manual as to how you control the response to a power loss during operation: do you want the VFD to to re-start automatically upon restoration of power, or do you want the user to be forced to re-start it manually? That's a VERY important safety issue.


text:
Q: Color dendrogram branches based on external labels uptowards the root until the label matches From question Color branches of dendrogram using an existing column, I can color the branches near the leaf of the dendrogram. The code:
x<-1:100
dim(x)<-c(10,10)
set.seed(1)
groups<-c("red","red", "red", "red", "blue", "blue", "blue","blue", "red", "blue")
x.clust<-as.dendrogram(hclust(dist(x)))

x.clust.dend <- x.clust
labels_colors(x.clust.dend) <- groups
x.clust.dend <- assign_values_to_leaves_edgePar(x.clust.dend, value = groups, edgePar = "col") # add the colors.
x.clust.dend <- assign_values_to_leaves_edgePar(x.clust.dend, value = 3, edgePar = "lwd") # make the lines thick
plot(x.clust.dend)

generates a dendrogram as shown in:
However, I want to color the branches up towards the root until the all the leaves in the current branch have the same labels. Even if there is a single mismatch switch to the default color of black. I want the resulting dendrogram to look like
What I want is little  different from using color_branches like
x.clust.dend <-color_branches(x.clust.dend,k=3)

because it colors based on its own clusters not based on some external labels.

A: The function you are looking for is branches_attr_by_clusters. Here is how to use it:
library(dendextend)

x <- 1:100
dim(x) <- c(10, 10)
set.seed(1)
groups <- c("red","red", "red", "red", "blue", "blue", "blue","blue", "red", "blue")
dend <- as.dendrogram(hclust(dist(x)))

clusters <- as.numeric(factor(groups, levels = c("red", "blue")))
dend2 <-
  branches_attr_by_clusters(dend , clusters, values = groups)
plot(dend2)

This function was originally created to display the results of dynamicTreeCut. See the vignette for another example.


text:
Q: Check whether sets are closed, open, compact or connected
Let $f:\mathbb{R}\to\mathbb{R}$ be a continuous function.
$A=\{(x,y)\in\ \mathbb{R}^2:x^2+y^5=1$}
$B=\{(x,x\sin\frac{1}{x})\in\ \mathbb{R}^2:0<x\leq1\}\cup\{(0,0)\}$
$C=\{x\in\mathbb{R}:f(x)=0\}$
(1) Which of the above set are necessarily open?
(2) Which of the above set are necessarily closed?
(3) Which of the above set are necessarily compact?
(4) Which of the above set are necessarily connected?

I think that A is closed, compact and connected. Am I right?
And I have no idea for B.
For C,
If $f(x)=\sin x$,
$C=\{n\pi:\text{ for all } \ n\in\mathbb{Z}\}$ , so it is not connected and compact.
How to check it is open or closed?

A: C is the inverse image of a closed set {0}
by a continous function, hence closed.
Same is true of the circle A, which also
being bounded makes it compact.
B is not open.  It is closed and bounded, hence compact.
The point (1,sin 1) is not an interior point.
B is also compact.


text:
Q: Why does UdpClient instantiation cause a ConfigurationException? I recently added a configuration section to my App.confg file. Although I realize the section was invalid, my application actually ran, up until it hit this line:
this.udpClient = new UdpClient();

at which point it gave the following exception:
System.Configuration.ConfigurationErrorsException

with the message:
"Configuration system failed to initialize"

and inner exception message (same type of exception):
"Unrecognized configuration section AppDefaults. (<filename goes here>)"

Why does instantiating a UdpClient access your app config, and why does it throw a configuration exception, instead of a Socket Exception (with inner configuration exception), like the method states it will?

A: The reason that it was trying to access the config when creating the UdpClient object is because the UdpClient and TcpClient classes are only wrappers around the Socket classes. The Socket class has a configuration section for it where socket settings can be stored and read from the config file. Since there was a problem with the config file and it was invalid you received the configuration exception when it was trying to look for that section in the config file. It makes sense because the problem was with reading the config file before it even gets to create the underlying Socket.
Link to MSDN info on Sockets Configuration Section


text:
Q: How to call and API endpoint on initialize. Value is still null I am trying to get user information from an API. For this, I created a user object. I want to call the function and store it in a user. But the problem is, that I cannot use await and wait till all the data is there.
So instead of async and await, I tried to use .then and fill userInfo with the data. But now the email value is not showing. It is showing 'loading...'.
If I use Future I cannot do user.email.
Is it better to use FutureBuilder? Or try and use Async and Await (the call takes 2.5 seconds)
Here is the code
class Addressbook extends StatefulWidget {
  const Addressbook({Key? key}) : super(key: key);

  @override
  State<Addressbook> createState() => _AddressbookState();
}

class _AddressbookState extends State<Addressbook> {
  User? userInfo;
  Future<User> getUserInformation() async {
    User user = await UserService().getUserById(12345);
    return user;
  }

  @override
  void initState() {
    // TODO: implement initState
    getUserInformation().then((response) {
      userInfo = response;
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Mijn adresboek'),
        centerTitle: true,
        elevation: 0.5,
        titleTextStyle: const TextStyle(
          fontSize: 21,
          color: Colors.black,
          fontWeight: FontWeight.bold,
        ),
      ),
      body: Text(userInfo?.email ?? "loading..."),

    );
  }
}

What do I want to archive?
I want to display user data on the screen. In this case I want to show the email.
What is the problem?
User is not filled with data on init (probably because it is still loading to get the data).
My question
How can I solve this problem? Is async await a solution or should I use FutureBuilder? Can you give me a working sample?
Thanks for helping!

A: You can use futurebuilder or you can use in  initstate to fetch api

  @override
  void initState() {
    // TODO: implement initState
    Future.delayed(Duration(seconds: 10), () {
      setState(() {
        userinfo = "response";
      });
      // userinfo = "response";

    });
    super.initState();
  }

Inside the widget
Text(userinfo != null ? userinfo.toString() : "loading..."),

SAmple Code
import 'package:flutter/material.dart';
//import 'package:pucon/home.dart';

void main() => runApp(MyApp());

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String? userinfo = null;
  String? userinfo2 = null;

  @override
  void initState() {
    // TODO: implement initState
    Future.delayed(Duration(seconds: 10), () {
      setState(() {
        userinfo = "response";
      });
      // userinfo = "response";
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: ListView(
        shrinkWrap: true,
        children: [
          Text(""),
          Text(""),
          Text(userinfo != null ? userinfo.toString() : "loading..."),
          Row(
            children: [
              FutureBuilder(
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    return Container(
                        child: Text(userinfo2.toString()), );
                  } else {
                    return SizedBox(
                      child: CircularProgressIndicator(),
                      height: 45,
                      width: 45,
                    );
                    // else
                    //   return Container(
                    //     child: CircularProgressIndicator(),
                    //     height: 45,
                    //     width: 45,
                    //   );
                  }
                },
                future: _future(),
              ),
            ],
          )
          // InsertData(),
        ],
      ),
    );
  }

  _future() async {
   await Future.delayed(Duration(seconds: 5), () {
     userinfo2 = "Completed";
      // setState(() {
      //
      // });
      // userinfo = "response";
    });
  }
}


text:
Q: Text input field won't submit when pressing enter I have a text input that I am trying to use to create new tags via hooks. However, when I enter in the value and press enter, nothing happens. I Googled it and was told to make the input type=text but this has not fixed it. Here is the code:

import React, { useState } from 'react';
import AddIcon from '@mui/icons-material/Add';
import MaximizeIcon from '@mui/icons-material/Maximize';

import './styles.css';

const Card = ({ id, pic, name, email, company, skill, average, grades }) => {

  const [clicked, setClicked] = useState(false);
  const [tags, setTags] = useState([]);

  return (

{name}

Email: {email}

Company: {company}

Skill: {skill}

Average: {average}

        <input
          type='text'
          placeholder='Add a tag'
          onSubmit={(e) => {
            setTags(...tags, e.target.value);
            console.log(tags);
          }}
        />

        {clicked && (

            {grades.map((grade, index) => (

{`Test ${index}: ${grade}%`}

            ))}

        )}

      <button onClick={() => setClicked(!clicked)}>
        {!clicked ? (
          <AddIcon fontSize='large' />
        ) : (
          <MaximizeIcon fontSize='large' />
        )}
      </button>

  );
};

export default Card;

How do I make it submit a new tags to the setTags hook?

A: You can use keyDown Event
onKeyDown = {
  (e) => {
    if (e.key === 'Enter') {
      setTags(...tags, e.target.value);

    }
  }
}


text:
Q: jQuery click event not working to close modal window I've made a light box with jQuery and can get the modal window to close if I select to use the body tag as the target to click and close. However, if I change it to my .closeBtn, nothing will happen. I've tried several variations of what I know to get it to work, but no luck. Any information would be most appreciated.
Cheers

// USING JQUERY CDN

$( document ).ready(function() {
       $('.lightbox-trigger').click(function(e) {
        e.preventDefault();
        let image_href = $(this).attr("href");
        if ($('#lightbox').length > 0) {
            $('#content').html('');
            $('#lightbox').show('fast');
        } else {
            let lightbox =
            '
' +
                '
×
' +
                '
' +
              '' +
                '
' +
                '❮' +
                '❯' +
            '
';
            $('body').append(lightbox);
        }
         $('.gallery-container').addClass('lightbox-active');
    });

    $('.closeBtn').on('click', '#lightbox', function() {
        $('#lightbox').hide();
      $('.gallery-container').removeClass('lightbox-active');
    });
});
// END OF FUNCTION
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  background-color: black;
}

body {
  color: white;
  font-family: 'Montserrat';
}

/* ///////////////////// NAVBAR //////////////////////// */
.navbar-style {
  box-shadow: 0 4px 2px -2px #333;
}

.nav-logo {
  width: 10%;
}

.nav-custom img {
  width: 64px;
}

.icon-bar {
  background: white;
}

/* ///////////////////// NAVBAR //////////////////////// */

/* ///////////////////// MAIN AREA //////////////////////// */

.slogan h1 {
  font-weight: 200;
  font-size: 1.2rem;
  margin-top: 2rem;
  margin-left: 2rem;
}

.background-img img {
  width: 80%;
}

.button {
  margin-top: 2rem;
  margin-left: 2rem;
  background-color: black;
}

.blurb {
  font-family: 'League Script', cursive;
  font-weight: 100;
  margin-top: 2rem;
  margin-left: 2rem;
}

/* ///////////////////// FRONT GALLERY //////////////////////// */

.gallery-container {
  display: flex;
  justify-content: center;
  border: solid 1px white;
  margin: 0, auto;
}

.flex-column {
  justify-content: space-between; /* have images appear as a four sided block */
  max-width: 250px;
}

/* ---------- LIGHTBOX ---------- */

#lightbox {
  position: fixed;
/*  ^keeps lightbox window in the current viewport  */
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  background: rgba(0,0,0,.7);

}

/* LIGHTBOX CLOSE BUTTON */
#lightbox .closeBtn {
  text-align: right;
  margin-right: 20px;
  font-size: 3rem;
}

.closeBtn {
  cursor: pointer;
}

/* LIGHTBOX IMAGE */
#lightbox img {
  box-shadow: 0 0 25px #111;
  max-width: 300px;
}

#content {
  display: flex;
  justify-content: center;
}

#content img{
  position: fixed;
  top: 0;
  margin-top: 4rem;
  width: 100%;
}

/* BLUR BACKGROUND WHEN LIGHTBOX IS ACTIVE */
.lightbox-active {
  filter: blur(5px);
}

/* LIGHTBOX ARROWS */
.arrowBTN {
  position: absolute;
  text-decoration: none;
  color: white;
  font-size: 2rem;
  text-align: center;
  margin-top: 25%;
  transform: translateY(-25%);
  width: 3rem;
  height: 3rem;
  border-radius: 50%;
  background-color: rgba(255,255,255,0.5);
}

.prev {
  left: 0;
  margin-left: 1rem;
}

.next {
  right: 0;
  margin-right: 1rem;
}

#lightbox a {
  text-decoration: none;
   color: white;
}

#lightbox a:hover {
   background-color: rgba(255,255,255, 0.2);
}

@media screen and (min-width: 1650px) {
  .flex-column {
    display: flex;
    justify-content: space-evenly;
  }
}

img {
  margin: 5px;
}

/* ///////////////////////////////////// */

A: This is not fully functional since you did not specify how you implemented the lightbox functionality (a plugin?) but that is not the question, the question is how to implement the click - here I show a static div for a lightbox inside #first-container however, if you wished to insert one dynamically that could also be done.
I showed how to add a second one as well.  I just cloned the first one with all the attached event handlers and appended it to the second container, then triggered an image that pointed to with with a data attribute- key here is the click event handler works for the close button since it is attached to the lightbox-container class

$(function() {
  $('.lightbox-trigger').on('click', function(event) {
    event.preventDefault();
    let imageHref = $(this).attr("href");
    let targetBox = $(this).data('targetlightbox');
    //console.log("tb:",targetBox);
    //target or default selector set for targetBox
    targetBox = targetBox ? targetBox : '.lightbox-thing:first';
    console.log("tb:",targetBox);
    let lightBox = $(targetBox);
    lightBox.find('.lightbox-content').find('.lightbox-img').attr('src', imageHref);
    lightBox.show('fast');
    $('.gallery-container').addClass('lightbox-active');
  });
  $('.lightbox-container').on('click', '.closeBtn', function(event) {
    $(event.delegateTarget).find('.lightbox-thing').hide(); // the lightbox
    $('.gallery-container.lightbox-active').removeClass('lightbox-active');
  });

  /* add a second lightbox - by cloning first one */
  /* rather than embed in script, I just cloned the prior one here but it IS dynamic */
  let newBox = $('.lightbox-container:first').find('.lightbox-thing').clone(true);
  newBox.addClass('new-lightbox');
  // console.log("nb:",newBox.length);
  // console.log(newBox.attr('class'));
  $('#second-container').append(newBox);
  // console.log("appended:",$(".lightbox-thing").last().attr('class'), $('.lightbox-trigger').last().data('xx'));
  $('.lightbox-trigger').last().trigger('click');//trigger click on last which has a target
 // $('.lightbox-trigger').eq(2).trigger('click');
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  background-color: black;
}

body {
  color: white;
  font-family: 'Montserrat';
}

.icon-bar {
  background: white;
}

.slogan h1 {
  font-weight: 200;
  font-size: 1.2rem;
  margin-top: 2rem;
  margin-left: 2rem;
}

.background-img img {
  width: 80%;
}

.button {
  margin-top: 2rem;
  margin-left: 2rem;
  background-color: black;
}

.blurb {
  font-family: 'League Script', cursive;
  font-weight: 100;
  margin-top: 2rem;
  margin-left: 2rem;
}

.gallery-container {
  display: flex;
  justify-content: center;
  border: solid 1px white;
  margin: 0, auto;
}

.flex-column {
  justify-content: space-between;
  max-width: 250px;
}

.lightbox-container {
  position: fixed;
  /*  ^keeps lightbox window in the current viewport  */
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  background: rgba(0, 0, 0, .7);
  border: solid yellow 1px;
}

.lightbox-container .closeBtn {
  text-align: right;
  margin-right: 20px;
  font-size: 3rem;
}

.closeBtn {
  cursor: pointer;
}

.lightbox-container img {
  box-shadow: 0 0 25px #111;
  max-width: 300px;
}

.lightbox-content {
  display: flex;
  justify-content: center;
}

.lightbox-container .lightbox-content img {
  position: fixed;
  top: 0;
  margin-top: 4rem;
  width: 100%;
}

.lightbox-active {
  filter: blur(5px);
}

.arrowBTN {
  position: absolute;
  text-decoration: none;
  color: white;
  font-size: 2rem;
  text-align: center;
  margin-top: 25%;
  transform: translateY(-25%);
  width: 3rem;
  height: 3rem;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.5);
}

.prev {
  left: 0;
  margin-left: 1rem;
}

.next {
  right: 0;
  margin-right: 1rem;
}

.lightbox-container a {
  text-decoration: none;
  color: white;
}

.lightbox-container a:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

@media screen and (min-width: 1650px) {
  .flex-column {
    display: flex;
    justify-content: space-evenly;
  }
}

img {
  margin: 5px;
}

×

    ❮
    ❯

A: This is because, you are trying to click a button that is generated dynamically.
Try this,

$('body').on('click', '#lightbox .closeBtn', function() {
        $('#lightbox').hide();
      $('.gallery-container').removeClass('lightbox-active');
    });


text:
Q: php explode elements in an array how could I explode each elements in an array?
Array
(
    [0] => countryId:2, productId:1, status:1, pId:18, xId:pdgje5566
)

please see below for above array:
$searchfor = $xId;

header('Content-Type: text/plain');

$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";

// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){

   print_r($matches[0]);
   //echo implode("\n", $matches[0]);

}

please advise, thanks.

A: foreach ($array as &$value) {
  $arr = array();
  foreach (explode(', ', $value) as $el) {
     $ret = explode(':', $el);
     $arr[$ret[0]] = $ret[1];
  }
  $value = $arr;
}


text:
Q: Unable to get the hash value for CSV file inside my power shell I have this CSV file, and i want to build a hash table for it and query its values:-

I wrote this powershell script, to read data from sharepoint list and from the csv file:-
Connect-PnPOnline -Url "https://**.sharepoint.com" -UseWebLogin
$SourceID = @()
$DestinationID = @()

Import-Csv c:\test.csv |
  foreach-object { $hash = @{} } { $hash[$_.sourceid] = $_.destinationid }

for($ii=1; $ii -lt 4;$ii++){

$ListItem = Get-PnPListItem -List "InvoiceDetails" -Id $ii -Fields "InvoiceNumber"

 foreach($item in $ListItem){

$n = "'"+$item["InvoiceNumber"]+"'"
$n
$hash['1']
$hash[$n]
$hash['+$n+']
}
}

now i am getting weird results:-
$n will return correct value from SharePoint such as '1', '2', etc..
hash['1'] will return correct value of 10 from the csv file
while combining both values such as $hash[$n] or $hash['+$n+'] will not return any thing.. any advice?


text:
Q: Get current city and country from CLGeocoder? I've been all over the internet trying to find out how to get the city and country from CLGeocoder. I can get the longitude and latitude easily but I need the city and country information, and I keep running into deprecated methods and such, any ideas? It basically needs to get the location, then have an NSString for the country, and an NSString for the city, so I can use them to look up more info or put them on labels, etc.

A: You need to revise your terminology a bit - CLGeocoder (and most geocoders) won't give you a 'city' per-se - it uses terms such as 'Administrative Area', 'Subadministrative Area', etc. The CLGeocoder object will return an array of CLPlacemark objects which you can then query for the information you need.  You init a CLGeocoder and call the reverseGeocodeLocation function with a location and a completion block.  Here's an example:
    if (osVersion() >= 5.0){

    CLGeocoder *reverseGeocoder = [[CLGeocoder alloc] init];

    [reverseGeocoder reverseGeocodeLocation:self.currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
     {
         DDLogVerbose(@"reverseGeocodeLocation:completionHandler: Completion Handler called!");
         if (error){
             DDLogError(@"Geocode failed with error: %@", error);
             return;
         }

         DDLogVerbose(@"Received placemarks: %@", placemarks);

         CLPlacemark *myPlacemark = [placemarks objectAtIndex:0];
         NSString *countryCode = myPlacemark.ISOcountryCode;
         NSString *countryName = myPlacemark.country;
         DDLogVerbose(@"My country code: %@ and countryName: %@", countryCode, countryName);

     }];
    }

Now note that the CLPlacemark doesn't have a 'city' property. The full list of properties can be found here: CLPlacemark Class Reference

A: You can get city, country and iso country code using this (Swift 5):
private func getAddress(from coordinates: CLLocation) {
    CLGeocoder().reverseGeocodeLocation(coordinates) { placemark, error in
        guard error == nil,
            let placemark = placemark
        else
        {
            // TODO: Handle error
            return
        }

        if placemark.count > 0 {
            let place = placemark[0]
            let city = place.locality
            let country = place.country
            let countryIsoCode = place.isoCountryCode
        }
    }
}


text:
Q: What does the field  in the audit logs mean? I see this in the Eventdata field of audit log reports for the event 'Audit mask change'
<NewAuditMask>15295</NewAuditMask>
<NewAuditMask>0</NewAuditMask>
<NewAuditMask>256</NewAuditMask>

Is there some way to find out what these numbers actually mean?
Can the Sharepoint object model be used to find what these numbers mean?
MSDN is not very helpful on this topic.

A: To store settings about actions and events that are audited SharePoint uses SPAuditMaskType enumeration.
public enum SPAuditMaskType
{
   All = -1,
   None = 0,
   CheckOut = 1,
   CheckIn = 2,
   View = 4,
   Delete = 8,
   Update = 16,
   ProfileChange = 32,
   ChildDelete = 64,
   SchemaChange = 128,
   SecurityChange = 256,
   Undelete = 512,
   Workflow = 1024,
   Copy = 2048,
   Move = 4096,
   Search = 8192,
}

So, if you want to know if a new audit mask includes one of the actions, you can use code like this:
string newAuditMask = "15295";
SPAuditMaskType flags = (SPAuditMaskType)Enum.Parse(typeof(SPAuditMaskType), newAuditMask);
if(flags & SPAuditMaskType.Workflow != SPAuditMaskType.None)
{
   //mask contains Workflow action
}


text:
Q: Read First Line of XML I have a String containing the text of an XML file. The string was formed from an input stream, but I don't think that's relevant.
The string seems okay, as:
System.Diagnostics.Debug.WriteLine("iString = " + iString);

outputs:
iString = <?xml version="1.0"?>
<DiagReport>
<LicensingData>
  <ToolVersion>6.3.94</ToolVersion>
  <LicensingStatus>SL_LICENSING_STATUS_NOTIFICATION</LicensingStatus>
</LicensingData>
</DiagReport>

I then convert the String to a StringReader
StringReader strReader = new StringReader(iString);

And the StringReader to an XmlTextReader
XmlTextReader reader = new XmlTextReader(strReader);

Before even proceeding with my code, though, I want to check that the first node of the XML is <DiagReport>. Is there a way I can do that using the member functions of XmlTextReader?

A: From http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.movetocontent.aspx
if (reader.MoveToContent() == XmlNodeType.Element && reader.Name == "DiagReport")
{
// Good to go
}

A: You can loop through until you get the first element (which would be the root).
private string root = "";
while (reader.Read())
{
   //check if it's an element
   if (reader.NodeType == XmlNodeType.Element)
   {
       //get the element name
       root = reader.Name;

       //break out of this while loop as we only want the first element
       break;
   }
}

if(root == "DiagReport")
{
}

A: Just start reading from the reader.  It should be one of the first things you read so you can check then.  Otherwise just match a regex against the string before creating the reader.  However the reader isn't as heavyweight as a dom parser it's pretty much a wrapper around a sax parser so it processes the file incrementally.


text:
Q: Adding functionality to a static website using ruby on rails I am new to ruby on rails.
I have a website with a lot of static pages. I want to add a number of dynamic pages to the website and these I am going to develop in ruby on rails. The functionality offered by these pages will be triggered when the user clicks on one of the buttons which is on one of the static pages. I am thinking that I will put the dynamic pages in a directory and one of them will be called(executed) when the button, which is on one of the static pages, is clicked. I do not need to change the content of existing static pages.
Is it possible to add such dynamic pages to existing static website? If yes, how? Do I need to change routes?

A: you have to do it the other way round - put your static pages into your rails applications 'public' folder - if a file identified by an url exists, rails will serve these file, if no file exists, rails will try to find a suitable controller/action ...

A: I would recommend that you set up the Rails app and then move all the static content to the public folder. Rails will prefer those files. Then begin to create your dynamic content with the Rails app and just link to the dynamic pages / "actions" from your static pages.


text:
Q: BeautifulSoup and lxml in Jupyter notebook I'm having trouble with BeautifulSoup and lxml running inside a Docker container that serves jupyter notebooks.
I've installed lxml via sudo pip install lxml, and if I run an interactive python interpreter, all works fine:
    >>> from bs4 import BeautifulSoup as bs
    >>> bs('test','lxml')

test

If I run the same code inside a Jupyter notebook, it gives me the following error
    FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml.

sys.executable returns /opt/ds/bin/python3 in both cases.
Any help is greatly appreciated!

A: I had the same issue. Saved, closed and opened the program again and its working fine now, no extra import statements needed. My guess is the Restart and Run All would also do the same.. basically kernel (I'm running a jupyter notebook) had to be restarted to be able to use the lxml I'd just installed using pip.


text:
Q: Generating hfc-key-store cryptomaterial without Fabric-CA .hfc-key-store wallet used by HFC SDK uses user certificates generated by Fabric-CA to connect to Fabric platform.
Is there a way to generate these certificates without Fabric-CA?
I assume it would involve re-purposing of Org user certificates generated by cryptogen. However, I would appreciate if someone can point me to a documentation that tells how to do it.


text:
Q: fractional numbers in java android? How do I write a fractional equation in layout of apk android  like this ;

A: That's probably LaTeX (pronounced Lahtech or Laytech), a C-based rendering engine, at work.
I suggest you look at projects like AndroidMath if you want to use this in your own android apps.