text:
Q: Error in Downloading data from mysql to Android getting error related to javascript in downloading data from mysql to android
...when i show the string downloaded it shows a html page which i included in image...kindly help me to get out of it soon.
Downloaded String "sb" is made as Toast here and it shows like this:

Code:
public class Download extends AsyncTask<Void,Integer,String>{
Context c;
String address;
ProgressDialog pd;
public Download(Context c,String address){
    this.c=c;
    this.address=address;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    pd.dismiss();
    if(s!=null){
        Toast.makeText(c,s,Toast.LENGTH_SHORT).show();
    }
    else{
        Toast.makeText(c,"download failed",Toast.LENGTH_SHORT).show();
    }
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    pd=new ProgressDialog(c);
    pd.setTitle("Download");
    pd.setMessage("Fetching Data...");
    pd.show();
}

@Override
protected String doInBackground(Void... params) {
    String data=downloaddata();
    return data;
}
public String downloaddata() {
    InputStream is=null;
    String line=null;
    try {
        URL url = new URL(address);
        HttpURLConnection con=(HttpURLConnection) url.openConnection();
        is=con.getInputStream();
        BufferedReader br=new BufferedReader(new InputStreamReader(is));
        StringBuffer sb=new StringBuffer();
    if(br!=null){
        while ((line=br.readLine())!=null) {
        sb.append(line+"\n");
        }
        br.close();is.close();con.disconnect();
    }
        else{
        return null;
    }
        return sb.toString();
    }
    catch (MalformedURLException e){
        e.printStackTrace();
    }
    catch (IOException e){
        e.printStackTrace();
    }
    finally {
        if(is!=null){
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}
}

A: You should define for what purpose you are opening connection.
HttpURLConnection con=(HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");

And also you are not connected with your connection.
You must write
con.connect();
for connecting.
Once connected with your network then you can use your code  to get the stream data
InputStream inputStream = urlConnection.getInputStream();
May these will help you.

A: It's not error Something related to Web scraping
For more info Check this thread


text:
Q: Not able to retrieve value of ng-model(Used with ng-repeat) Being new in angular js ,just trying some basic example & came across this issue.
I am creating a table using ng-repeat where a json array is the data source. The table has a quantity column and an add button.
I want to increase the value of quantity once I click on the add button.By understanding is since it is a two way data binding if I increase the value bind to ng-model it will reflect in the view, which is not happening
JS
angular.module('DemoApp',[]).controller('TableController',['$scope',function($scope){
  $scope.dataset = [json data ];
      $scope.add = function($event){
        // get $scope.bookQuantity,add 1
        var _m =$scope.bookQuantity;
        console.log(_m) // consoling undefined;
      }
    }])

I followed this link but still not able to resolve the issue.
I have created this Plunker which may help to understand the problem.

A: try like this. you should change your solution for this. i pass bookId as parameter to function and when action do it plus bookQuantity field in array.

// Code goes here

angular.module('DemoApp',[]).controller('TableController',['$scope',function($scope){

  $scope.dataset = [{
bookId: "1001",
bookName: "Wings",
bookPrice: 224,
bookQuantity: 4
    },{
bookId: "1002",
bookName: "Turning",
bookPrice: 142,
bookQuantity: 3
},{
bookId: "1003",
bookName: "Playing",
bookPrice: 402,
bookQuantity: 2
},{
bookId: "1004",
bookName: "Steve Jobs",
bookPrice: 418,
bookQuantity: 2},{
bookId: "1005",
bookName: "History",
bookPrice: 207,
bookQuantity: 2
}]

  $scope.add = function(bookId){
    angular.forEach( $scope.dataset,function(item){

        if(item.bookId == bookId)
          item.bookQuantity = item.bookQuantity + 1;
      });

    console.log($scope.dataset);
  }

}])

          {{data.bookId}}
          {{data.bookName}}
          {{data.bookPrice}}
          {{data.bookQuantity}}
          <input type = "button" value ="Add" data-id ="{{data.bookId}}" ng-click = "add(data.bookId)">

A: try this :-
*.html

      ...
      ...
      .
      <input type = "button" value ="Add" data-id ="{{data.bookId}}" ng-click = "add(data)">

*.js
$scope.add = function(record){
   record.bookQuantity  = record.bookQuantity + 1;
   console.log(record.bookQuantity); // consoling not undefined;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How HID scancodes are mapped to evdev codes? To send letter 'a', a HID device sends this scan code: 00 00 04 00 00 00 00 00.
Value which corresponds to character 'a' is <AC01> (found in /usr/share/X11/xkb/symbols/us). According to /usr/share/X11/xkb/keycodes/evdev, <AC01> is mapped to by button code 38 (this is what we must get from the device).
evtest /dev/input/event# shows code 30. Why?

A: Keycode in /usr/share/X11/xkb/keycodes/evdev is keycode from evtest + 8 (see MIN_KEYCODE in evdev.c).
This is how to find scancode corresponding to a given keycode:
https://source.android.com/devices/input/keyboard-devices#hid-keyboard-and-keypad-page-0x07
NOTE: scancodes are used in addition to keycodes for the following reason:
The Linux internal event subsystem has defined a standard set of key codes that are hardware independant, able to represent any scan code from any type of keyboard whether AT, XT or USB. There are names assigned to the key codes based on the common US ASCII key cap labels. The key codes are defined in /usr/include/linux/input-event-codes.h. For an example #define KEY_A 30.


text: Q: How to check if a directory is watched by filesystemwatcher? I am trying to create a utility method to which I will pass the path of the directory and it will return the instance of FileSystemWatcher that is watching that directory (if any). I don't find any helpful resources on the internet. Please provide your thoughts whether it is feasible and if yes how can I achieve the same?


text:
Q: SL DVI-D + HDMI = DL DVI-D, Possible? Using Intel HD 3000 graphics card, is it possible to combine the bandwidth of a single link DVI-D and HDMI (using an adapter?) and support a monitor with resolution 2560x1600 monitor instead of 2 1920x1200 monitors?

A: First, the reverse:
A single connector with a dual-link DVI port usually drives a single display.
It is not capable of getting split in two and driving two independent low resolution displays.
You can use extra hardware to clone the signal and drive two monitors (with identical contents on the screen) or you can use extra hardware like the (now older)
Matrox dualhead2go's
Both options require extra hardware.

Vice versa, you can not combine two single-link DVI connections into a dual-link DVI connection. Not without using extra hardware. (and I have found none of those during a quick search on the web).
However, assuming such hardware exists:

*

*You will need some active (high resolution, else why would you need dual-link) convertors. These are unlikely to be cheap.

*Entry level video cards (easily surpassing the performance of a HD3000) are cheap and do come with dual-link DVI.

PS: If you do search the web, do not get confused with the DMS59 connector, you can not use that 'reversed' to solve you problem. Even though it looks a lot like DVI.


text:
Q: Quaternions, torque, and impulse. In a physics simulation I have a solid ball of mass $m$ and moment of interia $M$ (which is a diagonal matrix with all entries equal to ${2\over5}mr^2=i$). Its instantaneous rotation is given by a quaternion $q$.
This body is touching another rotating body which applys a force $f$ at a point $p$ measured from the centre of the ball. $f$ resolves into a push into the radius (which we can disregard here) and a tangential torque $f^T$.
The simulation advances in a time step of $t$ seconds. How should I update $q$?
I have a basic understanding of quaternions but not enough familiarity to approach this. Computational efficiency matters so I'd like to avoid converting $q$ into a matrix and back again. I imagine that $f^T$ and $p$ combine to some kind of "impulse" rotation $r_t$ so I can just do $q \to qr_t$. Is this at all the right way to do it?

A: I don't know the term "instantaneous rotation", so I don't know whether you mean the instantaneous orientation or the instantaneous angular momentum or angular velocity; whichever one you mean, the other one seems to be missing from your state description. I also don't know what to make of a force resolving into a push and a torque, since a torque doesn't have the same dimensions as a force. Further it's unclear to me what you mean by "$f^T$ and $p$ combine", since $f^T$ is a force or a torque and $p$ is a point. I'll restate the problem in a form and notation that I understand, and I hope you'll be able to map that onto what you're doing.
The orientation of the body at time $t$ can be described by a quaternion $s(t)$ corresponding to the rotation required to get to that orientation from some reference orientation. Its rotational state can be described by either its angular momentum $L$ or its angular velocity $\omega$; since the body is symmetric and its moment of inertia $I=\frac25mr^2$ is a scalar, these two are proportional to each other, $L=I\omega$. The angular velocity can be regarded as an element of the Lie algebra of the quaternions, specified by a three-dimensional vector whose direction is the instantaneous axis of rotation and whose magnitude is the instantaneous angular speed. The body's orientation evolves according to $\dot s(t)=\Omega(t)s(t)$, where the dot denotes differentiation with respect to the time $t$ and $\Omega(t)=(0,\omega(t))$ is the purely imaginary quaternion corresponding to the angular velocity $\omega(t)$. In the absence of torques, the angular velocity is constant and the motion can be integrated to $s(t)=\exp(\omega t)s(0)$, where $\exp$ is the exponential map from the Lie algebra to the quaternions,
$$\exp(x)=\left(\cos|x|,\sin|x|\frac x{|x|}\right)\;.$$
A torque is by definition a rate of change of the angular momentum. A force $F$ acting at a point $p$ exerts a torque $\tau=r\times F$ on the ball, where $r$ is the vector from the ball's centre to $p$. This causes the angular momentum to change according to $\dot L=\tau$, so the angular velocity changes according to $\dot\omega=\tau/I$. Section $3$ of this paper gives what might be called a closed form for the resulting motion, but it's rather complicated and I gather you want to approximate the motion in finite time steps $\Delta t$. Since $\omega$ changes linearly, its update is exactly given by $\omega(t+\Delta t)=\omega(t)+\Delta t\tau/I$. To update the orientation $s$, you could take the average angular velocity $\bar\omega=\omega(t+\Delta t/2)=\omega(t)+\Delta t\tau/(2I)$ during the time step and update $s$ according to $s(t+\Delta t)\approx\exp(\bar\omega\Delta t)s(t)$. If you want, you can also approximate the exponential map by
$$
\exp(x)\approx\left(\sqrt{1-|x|^2},x\right)
$$
for small time steps.
I hope you can translate that into how you're thinking about the problem; if not, feel free to ask.


text:
Q: Thoughts on how to implement paging for a detail page I am curious as to what people would thing is the best way to implement this.
On my overview page, I have a data grid which is sortable and has custom filtering written for it. When you click on an item in the grid, it loads a separate page with details.
I would like to implement result paging through on the detail page keeping in the same order as the previous page data grid.
Now I've thought of a few ways to do this:

*

*Change the link to be a postback and handle the sort order programatically

*Sort filter and sort settings on application of the settings in the session

*Pass the filter and sort settings on the query string to the detail page

None of these seem very clean to me, and option 3 is the only cogent option I've thought of.
Am I missing something? Is there a more elegant way to do this?

A: It is preferable to have url access to any details view that may be needed independently of the master.
Of course, you can have both postback and GET access, but begin with the url and querystring. I have had to fix numerous postback-only views to support direct urls, when the need has eventually arised.
If the filters and sort order are very complex and would require an elaborate querystring parameter scheme, I would think hard what is really needed for url access. Complex settings are best passed in a serializable .NET object in the Session or ViewState. You'll get .NET type safety and avoid error-prone querystring/form/cookie parsing. Session would be better if you need to pass these settings from another page of the application.


text:
Q: query using value from request gives no result while it should I have a javascript file that will send a value to a json file that has c# in there and sql queries to retrieve from the database.
I already ensured that the value has been retrieved, but my query doesn't give any result while it should.
JS:
$.postJSON('/path/path/html.aspx', {
            action: 'myAction', id: $(this).val(), sectiontext: chosensection
        }, function (j) {

          //some func

        });

    });

this above code in JS that will send values to html.aspx, values are sent im sure. But, when I use it in the query as request["chosensection"] it gives no result
and when i use a string that has the same value as request["sectiontext"] gives result.


text:
Q: jQuery in mvc application How to use jQuery in mvc 2 application for fetching data from database using datatable?

A: jQuery does not allow you to fetch data directly from database. In order to receive such data you have to make an Ajax call to your backend class (controller). Controller can call model, which can retrieve and maybe prepare needed data. Then you just return it (JSON format is preferable).

A: I think your objective is to show a tabular data on the UI.  If i'm right, then can you try using JqGrid? As Ventus said, Json format is preferable

A: HI,
you have to create ajax that talks to your controller and fetch data from the controller. This way you have control. I do not thing you can do it straing, unless you have some flash app with everything encoded inside, tho this is not wise.
Use controller and pass results to your front end app

A: install nuget package Install-Package jquery.datatables for datatable refer to : https://www.nuget.org/packages/jquery.datatables
imlpement datatable like :
https://datatables.net/examples/basic_init/zero_configuration.html


text:
Q: Can a variable take a single value? Take a variable $x$, say that I could define a range of permissible values of $x$ is a singleton set, there is exactly one value of $x$ that I consider permissible, obviously a constant is exactly like this, a symbol that I associate as having a specific value. In this case an expression like:
$x+1=2$ is true for all $x∈D$ where $D=$ {$1$}
However, in the case of $x$ as a constant we would have.
$x+1=2$ is true as $x=1$
There is obviously little difference between these two. But do mathematicians draw any clear distinction between the these?


text:
Q: How to test method that uses external package to interact with DB I am trying to test a function, which is part of the business logic layer of a struts application. I am facing problem because the code is dependent on external functions in a organization wide used jar.
public CustomObject getCustomObject(String id){
        CustomObject customObject = new CustomObject();
        QueryObject sql = createSqlStatement(id); // EXTERNAL jar
        Result result = execute(sql); // EXTERNAL jar
        ArrayList list = result.getResulList(); // EXTERNAL jar

        // Logic to use the list object to fill the customObject
        // I can see an error here, that could have been
        // caught in unit test

            return customObject ;
        }

Now the problem is testing the logic of filling up the object.
The Junit4 test that I have written is:
    @Test
    public void testCustomObject()  {
        CustomObject customObjectwActual = new CustomObject();
        CustomObject customObjectExpected = new CustomObject();

           // set properties of customObjectExpected here

        customObjectwActual = getCustomObject(id); // Exception here

        assertEquals(customObjectExpected , customObjectwActual );
    }

The exception is thrown because "the external jar classes are loaded at the time of startup of struts application" as per the developers explanation. I am new to Java and struts. Is my approach wrong? Is there a way to "load" these external jar classes in the setUpBeforeClass() in someway?
Please let me know if anything is unclear.
EDIT 2:
Sorry, my question is unclear. I have these external jars in my classpath. It compiles fine, and it actually loads the external jar's classes. The SQL queries are stored in an xml file. These external jars have their own xml file with SQL statements as well. It is failing to load one of these two xml files.
Further, even if they load correctly, I actually dont want to call the database. Is there  some way to mock these calls?

A:
Is there a way to "load" these external jar classes in the
  setUpBeforeClass() in someway?

You just need to include these jars in your class path. Classes are loaded at runtime automatically when you use them

I am new to Java and struts. Is my approach wrong?

There is nothing specific to Struts. Its plain core java that external classes you are using in your project must be included in your class path

Is there some way to mock these calls?

Well if you mock these calls ,whats the use of writing the DB testcases which does test DB Interaction
I also suggest using IDE like eclipse as its very helpful for development like providing compilation issues upfront, formatting etc


text:
Q: Xcode: How do I build my .app project also as a Shared Library? First I am using Xcode 3.2.5 on a MAC OS X 10.6
I have an Cocoa Application project that builds and runs fine.  I have some functions in this project that I am exporting out using:
#define CORE_EXPORT __attribute__ ((visibility ("default")))

extern "C" {
    CORE_EXPORT IUIEventHandler* GetIUIEventHandler();
}

If I want another dynamic library project to be able to link to my original Cocoa Application so it can use the exported GetIUIEventHandler function, what do I need to do?
Do I need to build the original Cocoa Application also as a Dynamic Library also?  Or is there a way to link the executable of the Cocoa Application?

A: A single Xcode project is composed of several targets. Each target produces a product. A product is something like an application or a shared library.
Each file in a project can belong to zero or more targets, but typically belongs to one.
I would re-organize your project to have two targets, one would be a shared library or framework, and the other would be a application.
You'll probably wind up with a lot of your generic code in the framework, and only very application specific concepts in the app. This usually has the side-effect of clarifying your code, and helping maintain some good abstractions. Many projects are structured this way, even when the framework is only used by one client, so that they can get the benefits of the cleaner design that it guides you towards.

A: This answer is kind of dirty but it works.  I used the linker flag -undefined dynamic_lookup on my library that needs to import the functions from the main app executable, and I don't link in any library that holds the functions that need to be imported.
This forces the linker to not worry undefined symbols and to mark them as should link at load time.  When the app loads my library that was built with -undefined dynamic_lookup it will link up the undefined symbols itself.
This is where I found my answer:
http://lists.apple.com/archives/xcode-users/2008/Dec/msg00002.html


text:
Q: Google Places API Getting Image Flutter I'm trying to make a weather app which gives you information about the weather of your location, I can get user location using geolocation and it's working, so with sending latitude and longitude to Google Places API, I want to get picture of the location where the user is. I wrote a function for it but having this error.Here Is the API doc https://developers.google.com/places/web-service/search
Exception has occurred.
RangeError (RangeError (index): Invalid value: Valid value range is empty: 0)

     Future getImage(double lat, double long) async {
            //THIS FUNCTION SUPPOSED TOGENERATE PHOTO REFERENCE
            http.Response response = await http.get(
                "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$long&radius=1500&key=$apiKeyImageCity");
            var data = response.body;
            String photoRef =
                jsonDecode(data)['results'][0]['photos'][0]['photo_reference'];

//with using photo ref trying to get actual image
http.Response image = await http.get(
                "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=$photoRef&key=$apiKeyImageCity");
            return image;
          }

OUTPUT OF DATA
════════════════════════════════════════════════════════════════════════════════
I/flutter (31143): {
I/flutter (31143):    "html_attributions" : [],
I/flutter (31143):    "next_page_token" : "CqQCFgEAAAlw1Lhod46jN326VCclcpZ7M5BIK_aq57oyPW0rKwC65zpTHq0ZOz8OlX46OZS-_80kwd3lXbVPFIcsobdirbzYxilvVjzwozYTruylXZXpYC8c8gAkx84wK2splwrzHimr_0rb6AzNu-S8DVa9RTaxIJe3W9nu1ybN0YXBwpjKLj-qjtuUPZYAeKCkjM8tvtUKPtgLvMMDFLAKc90qvGJtTaSciqYObOxiGm86YE7JlHQlG1ZnE09BYAtMZWyz7Vbpnv4OE9fJjjlFsRR4mSIPlpggr0fnbFKJh6AA0ghtyCysB17MB6kWGCPAdy749cZQNH9AIEhEun_97E5DivN_JXnyr1SdA4XY-zcAI7xS-qVpvevRaFCgms41Oxmc_RIQR22nRF3VEmMnzvhw4HaD8BoUtqZFQDpEd69E3NteSBAUlsXKg7Y",
I/flutter (31143):    "results" : [
I/flutter (31143):       {
I/flutter (31143):          "geometry" : {
I/flutter (31143):             "location" : {
I/flutter (31143):                "lat" : 41.0082376,
I/flutter (31143):                "lng" : 28.9783589
I/flutter (31143):             },
I/flutter (31143):             "viewport" : {
I/flutter (31143):                "northeast" : {
I/flutter (31143):                   "lat" : 41.199239,
I/flutter (31143):                   "lng" : 29.4288049
I/flutter (31143):                },
I/flutter (31143):                "southwest" : {
I/flutter (31143):                   "lat" : 40.811404,
I/flutter (31143):                   "lng" : 28.595554
I/flutter (31143):                }
I/flutter (31143):             }
I/flutter (31143):          },
I/flutter (31143):          "icon" : "https://maps.gstatic.com/mapfiles/place_ap

A: Problem solved
import 'package:clima/services/location.dart';
import 'package:clima/services/networking.dart';
import 'package:clima/utilities/constants.dart';

class CityImage {
  Location userLocation = new Location();
  Future<dynamic> getImageData() async {
    await userLocation.getCurrentLocation();
    NetworkHelper networkHelper = new NetworkHelper(
        "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${userLocation.latitude},${userLocation.longtitude}&radius=1500&key=$apiKeyImageCity");
    var imageData = await networkHelper.getData();
    return imageData;
  }
}

void getImage() async {
    CityImage cityImage = new CityImage();
    cityImageData = await cityImage.getImageData();
    Navigator.push(context, MaterialPageRoute(
      builder: (context) {
        return LocationScreen(
          weatherData: weatherDataLocation,
          imageData: cityImageData,
        );
      },
    ));
  }


text:
Q: GeoLite2 accuracy in "Country" level MAXMIND info shows that GeoLite2 is less accurate than GeoIP2 DB when "City" resolution is required.
If only "Country" resolution is required – is the accuracy of the two DB equivalent?
Thanks in advance,
Gil

A: From MAXMIND accuracy page and from another question in stackoverflow, we know that the GeoLite2 is less accurate than GeoIP2 in "city" level. There is no information regarding the country level.


text:
Q: mongodb lookup with collection and dynamic query output I have some dynamic query for a collection
var condition = dynmic_query
db.collection.find(condition)

is giving me an output
now what I need whatever I am getting from previous query need to lookup with an another collection.
I am scared if this is not possible yet in mongodb
[https://jira.mongodb.org/browse/SERVER-22497]
I did some google but not getting idea how to achieve this one
I have to execute this query in node.js
Please help
Thanks

A: It sounds like you need the Aggregation Framework with the $lookup pipeline stage with a $match pipeline. It's a bit like doing a JOIN from the SQL world. Here's an example:
db.orders.aggregate([
   {
      $lookup:
         {
           from: "warehouses",
           let: { order_item: "$item", order_qty: "$ordered" },
           pipeline: [
              { $match:
                 { $expr:
                    { $and:
                       [
                         { $eq: [ "$stock_item",  "$$order_item" ] },
                         { $gte: [ "$instock", "$$order_qty" ] }
                       ]
                    }
                 }
              },
              { $project: { stock_item: 0, _id: 0 } }
           ],
           as: "stockdata"
         }
    }
])

A: You can not use one query output in second query. But you need to handle this at your code level.
hit one query and kept result in one variable then use that result to search in another query.
Mongodb is not meant for complex fetch. That's the whole reason it gives you high performance.


text:
Q: How does one consume Bugsnag from singleton? I have an ASP.NET core application that implements a singleton service.
I would like errors to be sent to Bugsnag so I've added IClient bugsnag to my constructor but am getting the following error during startup:

Cannot consume scoped service 'Bugsnag.IClient' from singleton

I cannot find anything in the Bugsnag docs that mentions IClient being scoped or how to construct a singleton instance to use in my application.
As mentioned in the comments, a possible solution would be to use IServiceScopeFactory to create a scope to use in the singleton. This is not ideal because the whole reason for using Bugsnag is to have something that catches all unhandled errors in the application and reports them to a central point for monitoring.
UPDATE: since posting the question I came across a GitHub issue addressing this problem.

A: In short, you couldn't register the service as singleton , since the IClient has been registered as scoped but it called in the singleton service.
When we have a scoped instance, each time we load the page, a new instance of our ChildService is created and inserted in the parent service.
Whereas when we do a singleton, it keeps the exact same instance (Including the same child services). When we make the parent service a singleton, that means that the child service is unable to be created per page load.
ASP.NET Core is essentially stopping us from falling in this trap of thinking that a child service would be created per page request, when in reality if the parent is a singleton it's unable to be done. This is why the exception is thrown.
If you want to use iclient in the singleton service, it's impossible. The right way is make that singleton service to scoped.

Update:
As @JHBonarius says, we could inject the IServiceScopeFactory to the singleton sercive and manage the scope service.
More details, you could refer to below codes:
public class Singleton : ISingleton
{

    private readonly IServiceScopeFactory scopeFactory;

    public Singleton(IServiceScopeFactory scopeFactory)
    {
        this.scopeFactory = scopeFactory;
    }

    public void MyMethod()
    {
        using(var scope = scopeFactory.CreateScope())
        {
            var db = scope.ServiceProvider.GetRequiredService<yourservice>();

            // when we exit the using block,
            // the IServiceScope will dispose itself
            // and dispose all of the services that it resolved.
        }
    }
}


text:
Q: Raid set add member: com.apple.StorageKit error 118 I have a failed RAID set, and am trying to add a replacement drive.  Every time I try to repair, add member, or add spare, it fails immediately with com.apple.StorageKit error 118.  Does anyone know what this error means?  Any suggestions on how to resolve?

A: I know this is quite late to answer but I came across the same error today while trying to add a new member to a failed RAID1 volume.
The issue is, Disk Utility doesn't tell you the whole story.
Running the same operation through the terminal will give you the correct error message when executing diskutil appleRAID add member diskX /Volumes/RaidVolumeName:
Error: -69797: The RAID set cannot be modified because it is currently rebuilding
To avoid getting this error, you need to disable autorebuild on the RAID disk:
diskutil appleRAID update AutoRebuild 0 diskX (diskX is the virtual raid disk)
Then reboot.
After you reboot, it won't be rebuilding anymore and you can add the member, either via Terminal, or Disk Utility.
HTH others.


text:
Q: how to call parent page javascript from iframe inside an update panel What i am trying to do is i want to call a javascript function in the parent page to scroll the window to the TOP. I have one master page with a JS function "top" for scrolling page to the top, inside Master Page there is updatepanel and inside update panel there is iframe.Every time when iframe loads i want the masterpage to be on top.
Solutions i have tried:

but i am getting compile time error tht onload cant be added to iframe becz it is inside an update panel
i know my question is not very clear.still expecting some response.

A: Assumption: both the iframe and parent window are from the same domain.
You can do this to retrieve the reference to the iframe's parent DOM element:
var iframeParent = window.parent.document;

With that reference, you can access the parent's functions that are in the global scope, so in your case the "top function" for scrolling the page?


text:
Q: How to install .NET Portability Analyzer on Visual Studio 2017 (Mac) The .NET Portability Analyzer is a good tool and gives good insights when we are planning to migrate old applications.
I can't download the .vsix file and get Visual Studio to install it on Mac and I can't find a way to locate it via the extensions (adding repository).
I am happy to use the Console version of the app but would love to see that in action within the IDE.
Note: I did notice the question "Installing extension on Visual Studio 2017 mac which is closed. The answer tells me why things are different in Visual Studio Mac but I don't see a way out to installing the Portability Analyzer.


text:
Q: Ajax xmlHTTPRequest I'm trying to get the content of a page with AJAX and I get no result..
this is the code:

And this is the div in the body:

Let AJAX change this text

<button type="button" onclick="onSumResponse()">Change Content</button>

What I get after the click is blank div.
 EDIT:  This code was taken from w3schools
 EDIT 2 :  This is the code in vbscript that works:
GotothisURL = "http://www.arihav.com"
Set GetConnection = CreateObject("Microsoft.XMLHTTP")
GetConnection.Open "get", GotothisURL, False
GetConnection.Send
ResponsePage = GetConnection.responseText

A: AJAX does not allowed to access a different server due to origin policy if you want to request another host better use curl or JSON


text:
Q: Fade elements as they reach the top of the page? So I'm using jQuery script like so;
$(window).scroll(function(){
    $(".element").css("opacity", 1 - $(window).scrollTop() / 700);
  });

to hide an absolutely positioned, flexbox element as it is scrolled out of the top of the page. I have other content further down on the page that I would like to apply this same set of rules on; I would like them to be at 100% opacity when they're visible towards the bottom of the page and then have them fade out as the user scrolls, but this only seems to work on the first element that's shown in the window initially. I'm not sure why this is - I've played around with the 700 value but it never seems accurate for the elements further down the page.
Here's a jsfiddle
The content that I'm doing with this is both text and images. I'm thinking that this might not be possible in the way I had hoped - IF I can get this to work, ideally a text block is faded out from the top to the bottom instead of the entire element at once, but I understand that with this method that is probably not possible.

A: I suggest that you use a common class for all the elements for which the fading behavior is intended. You may also use a combination of selectors. The main issue with your implementation is that you can only listening to the viewport's scroll position, ignoring the fact that different elements on the page have different vertical distances from the top of the document. You will have to compute the position of the element relative to the top of the viewport instead.
Therefore, to do this, you will have to:

*

*Iterate through each element that you want to fade when scrolling

*Calculate its vertical offset relative to the top of the viewport (which is basically the element's top offset position minus the current scroll position)

*If this offset crosses a certain threshold (can be a pixel value, or a percentage of the viewport height), start computing the fade

In my proof-of-concept example below, I have:

*

*Applied a common class to all items that are to be faded

*Added rudimentary settings, so that the fade out starts only when the element is more than halfway up the viewport (the top half of the viewport can be seen as the "fade zone")

*Linear interpolation between the opacity value and the position of the element within the "fade zone"

$(window).scroll(function() {
  // Setting: Start fading halfway up the page
  var startPos = 0.5;

  // Cache window object
  var $w = $(window);

  // Basically, we go through each element and check its relative position within the viewport
  $('.scrollFade').each(function() {

    // Get current relative position in viewport, based on the top edge
    var pos = $(this).offset().top - $w.scrollTop();

    // Get viewport height
    var vh = $w.height();

    if (pos < vh * startPos) {
      // If element has past the starting threshold, we fade it
      $(this).css('opacity', pos / (vh * startPos) * 1);
    } else {
      $(this).css('opacity', 1);
    }
  });
});
.textblock {
  position: absolute;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  bottom: 0px;
}

.extratext {
  margin-top: 500px;
}

div {
  height: 100vh;
}

    hey hey hey!

    Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up
    one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum
    et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section
    1.10.32.

A: This is how I would do it:
.topGradient{
    height: 100px;
    width: 100%;
    background:linear-gradient(rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0));
    position: fixed;
    top:0;
    z-index: 100;
}

.bottomGradient{
    height: 100px;
    width: 100%;
background:linear-gradient(to top, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0));   position: fixed;
    bottom:0;
    z-index: 100;
}

Here is the JSFiddle demo
What I did was create 2 div and place them at the top and bottom of the window. Then I set them above all other elements using z-index and then gave them a gradient back having transparency, thus giving you the fade-in/out effect of the elements as you mentioned.

A: You need to get the elements position on the page and use it as an offset to when the fade starts. Here is an updated fiddle.
$(window).scroll(function(){
    $(".textblock").css("opacity", 1 - $(window).scrollTop() / 700);
    var offsetTop = $(".extratext").offset().top;
    $(".extratext").css("opacity", 1 - ($(window).scrollTop() - offsetTop) / 700);
  });

A: fadeAtTop(el) {
    const startPos = 0.25;
    const $window = $(window);
    const viewportHeight = $window.height();

    el.toArray().forEach(el => {
      const $el = $(el);
      let position = $el.offset().top - $window.scrollTop();
      let opacity = position < viewportHeight * startPos ? position / (viewportHeight * startPos) * 1 : 1;

      $el.css('opacity', opacity);
    });
  }


text:
Q: Displaying object details in a ListView in Android As part of an Activity, I have a class encapsulating functionality for a single object and want to display details of the object in a ListView when a particular button is pressed.
Attempt One:
If I pass the ListView and this to the object to store (!) and then try to call the ArrayAdapter, I get a runtime error:

Source not found

Code segment (method within the class)...
private void displayTouch(Touch lasttouch) {

    String mLine = "";
    /* Build up line of analysis */
    ...
    /* Display line */
    mAnalysis[lasttouch.mSequence] = mLine;
    mViewAnalysis.setAdapter(new ArrayAdapter<String>     (mActivity,R.layout.simplerow,mAnalysis));
} // End of method displayTouch

Attempt Two
If I try to display data in the ListView from within the OnClick Listener, I get an error message in Eclipse:

The constructor ArrayAdapter (new View.OnClickListener(){}, int, String[] is undefined.

Code segment (within the OnClick Listener of the Activity)...
/* Record details */
OnClickListener CourtListener = new OnClickListener() {
    public void onClick(View v) {
        ...
        /* Analyse  */
        ...
        /* Capture  analysis */
            lRoster.setAdapter(new ArrayAdapter<String> (this,R.layout.simplerow,playerArray));
        } // End of event onClick
    }; // End of listener CourtListener

In this code playerArray is dimensioned within the Activity's onCreate;
Both attempts have weaknesses of approach (in addition to not working) so I'll re-factor once I can get something working.
Essentially, how do I display data generated within an object to a ListView within an Activity from the OnClick Listener of another View in the same Activity?  Everything is within one package and within the Activity.

A: Perhaps this blogpost might help: Putting custom objects in ListView


text:
Q: Custom ComboBox focus doesn't shift to select elem and eventBubble doesn't stop. Works fine in IE but not on others Here I have created a custom combobox where user can select values from the dropdown either by clicking on the arrow image given beside the input text field or by clicking on the text field.
This code is working fine on IE 11. On Google Chrome, when i click on the arrow image I am able to select the value from the dropdown. But when I click on the text field, I am not able to select the values.
Here the onclick event gets fired properly, but the input text(combo-box) opens the dropdown and the focus doesn't shift to the dropdown. Now as the focus is not there on the dropdown, chrome behaves weirdly and doesn't select the option when I click on it.
Now, when I try to shift the focus by coding to the dropdown, then the input onblur event gets fired and the dropdown closes.
So basically it doesn't open.
I have tried this on JSFiddle but it doesn't replicate on IE. I would suggest you to use pastebin link http://pastebin.com/aGmT0srm and test it on your machine.
JSFiddle link
<select size="8" name="sel_vData_30" id="sel_vData_30" style="display:none;"
       onblur="comboselect_onblur(vData_30,this)"
       onchange="comboselect_onchange(this, vData_30)"
       onkeyup="comboselect_onkeyup(13, this, vData_30)"
       onclick="comboselect_onchange(this, vData_30)" >
    <option value=""></option>
    <option value="Office">Office</option>
    <option value="Plant">Plant</option>
    <option value="Sales">Sales</option>
    <option value="Service Technician">Service Technician</option>
    <option value="Transportation">Transportation</option>
</select>

I want this to work on cross browser especially on Chrome.
Any insights or suggestions are welcome.
Thank you!

A:
But when I click on the text field, I am not able to select the
  values.

Removing the onblur="combotext_onblur(vData_30,sel_vData_30)" from your <input> fixes the described issue for IE 11, FF 38 and Chrome 43.
Working fiddle: https://jsfiddle.net/n0369z7j/6/

A: You can do this via custom code but it is fairly complex as the browser compatibilities are difficult to take care of for default form elements.
Its better recommended to use already tested and maintained js plugin like:
http://select2.github.io/examples.html
Your code will be much cleaner and efficient.


text:
Q: How to implement a custom loss function with canned estimators in Tensorflow? I am new to tensorflow.
Question: How can I add a custom loss function to a canned estimator like DNNLinearCombinedRegressor?
Thank you in advance for your help!

A: I did not find a loss_fn argument to pass in to DNNLinearCombinedRegressor. But it looks straightforward to define any custom estimator:
A good reference is the code for DNNLinearCombinedRegressor.
I believe you need following steps:

*

*define a custom loss_fn (what ever you like)

*define or use a RegressionHead that uses the custom loss_fn defined above.

*pass the custom head to your own Regressor. Of course, you might need to copy/build your own model_fn as well.


text:
Q: Empty collections not present in JSON request I have a Sinatra app and I'm updating some stuff in a mongoDB database with some PUT-requests.
In javascript, the actual values I'm posting are:
entity: {
    config: someString,
    parameters: parameterArray, // EMPTY [ ]
    dt: dtArray, // EMPTY [ ]
}

I'm doing this via jQuery ajax.
On the server side I get the following:
params[:entity] #=> config = someString

But the empty arrays are missing. Why is this? I need them! The same route will handle both empty arrays and no parameter at all in a different way...


text:
Q: UITableView Not Being Updated iOS I am downloading a string with the contents of a file online and separating these components by string into an array.
Once the download is finished I am calling a method to update my tableview to display these values.
- (void)updateTableView {
    tableView.delegate = self;
    tableView.dataSource = self;
}

Basically in this method I set the delegate and dataSource so the table view gets updated using this method...
- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] init];
    cell.textLabel.text = [arrayDownloaded objectAtIndex:indexPath.row];
    return cell;
}

But the issue is is that the table view doesn't get updated until I "touch" the view.
Like all the data is loaded and the method has been called but not until I tap on anywhere on the screen does the tableview get updated?
Why is this and how can I make it update as soon as I set the delegate and dataSource?
-Henry

A: Just reload the tabledata after finishing the downloading.
- (void)updateTableView
{
    tableView.delegate = self;
    tableView.dataSource = self;
    [tableView reloadData];
}

A: I figured the solution. Rather than calling [self updateTableView]; to call the following method...
- (void)updateTableView {
    [tableView reloadData];
}

I needed to do [self performSelectorOnMainThread:@selector(updateTableView) withObject:nil waitUntilDoneNO];
Some people are calling this an iOS bug since if you are not on the main thread numberOfRowsInSection gets called but cellForRowAtIndexPath doesn't.
Just a strange thing that I saw happening in my app. Hopefully this helps future developers.
-Henry

A: If you aren't already doing this somewhere, you need to call [tableView reloadData] after you've applied your changes.


text:
Q: what is difference between tanstack/react-query and react-query As these are downloadable from npm with their names with different sizes. In which scenarios we must downloads tanstack react query and for which react-query.

A: As far as I can tell the author chose to publish the new v4 version on @tanstack/react-query whilst keeping the v3 version on react-query.
So most likely, you want the latest version, which is @tanstack/react-query.
This is detailed here: https://tanstack.com/query/v4/docs/guides/migrating-to-react-query-4#react-query-is-now-tanstackreact-query

A: Tanstack Query, formerly known as React Query v3 (react-query), aims to make the React Query async state manager, available to frameworks beyond React, and comes with a variety of new features.
For example, Tanstack Query exists now for:

*

*React @tanstack/react-query (React Query v4)

*Svelte @tanstack/svelte-query

*Solid @tanstack/solid-query

*Vue @tanstack/vue-query


text:
Q: Which specifier to use to print the max/min value of long double? As a new C programming learner, I'm trying to understand which specifier I should use in printf to display the maximum and minimum values of a long double type. Per the following StackOverflow answer, I can use %Lg: https://stackoverflow.com/a/18797417/1536240
But that doesn't seem to do the trick. I've tried %e, %f, %Lf, %g and %Lg, but it's not working. Here's the relevant part of my code I'm having issues with (the rest of the stuff I'm doing's working fine):
printf("**long double**\nStorage size: %d bytes \t Minimum value: %Lg
\t Maximum value: %Lg\n", sizeof(long double), LDBL_MIN, LDBL_MAX);

I've included these header files at the top:
#include <stdio.h>
#include <limits.h>
#include <float.h>

I'm kinda lost here.
EDIT: Sorry for not explaining what the output is. I'm using %Lg right now, and I'm getting this in the terminal.

A: While you should provide the obtained results in your question, your mistake likely is to use %d to print the result of sizeof, which should be printed with %zu.
This causes undefined behavior. For some platforms, the rest of printf's arguments, on the stack, will be misinterpreted because the width of int does not match the width of size_t.

A: You should use "%Lf" or "%Lg" for a long double, and %zu (since and including C99) for the sizeof return type size_t.
Currently the behaviour of your program is undefined: %d is not appropriate for a size_t type.


text:
Q: how to delete a terraform state file when the azure resources are removed using terraform? We are building a temp review app in terraform. Currently when review app is finished with the resources are destroyed with terraform using terraform apply -destroy. What i need to do is also remove the terraform state file for this infrastructure from the azure container. Could I use terraform -destroy to also remove the state file and how can i do this?

A: One of the workaround you can follow,
When we are using terraform destroy that time our resource detailed also  removed from terraform.tfstate by removing from portal itself.
So to remove any particular resource from .tfstate you can try something like below;
First would suggest you to after destroy the file list the state file you have then remove those.
This below command is used to get the available instances which are in state file.
 terraform state list

After listing those try with below which will remove from .tfstate file as mentioned by @Ansuman Bal i have also tried and it works fine .
terraform state rm "azurerm_resource_group.example"

OUTPUT DETAILS FOR REFERENCE:-

NOTE:- This aforementioned cmdlts will remove the instance/resources from .tfstate file only not from portal. Only terraform destroy can do that.
For more information please refer this SO THREAD| Terraform - Removing a resource from local state file.


text:
Q: AngularJS function doesn't run I have the following angular factory and controller.

var app = angular.module("carForm", []);

app.factory("dataService", ['$http', function getData($http) {
    function getCars(){
        return $http({
            method: 'GET',
            url: '/data.json'
        }).then(function (response){
            console.log(response.data);
            return response.data
        },function (error){
            console.log("product error");
        })
    };
    return { getCars : getCars }
}]);

app.controller("dataSort", ['dataService', '$scope', function(dataService, $scope) {
    dataService.getCars().then(function(response){
        cars = response;

        $scope.make = [];
        for (key in cars){
            item = cars[key];
            console.log(item);
            $scope.make.push(item);
        }

        $scope.model = [];
        for (key in cars[$scope.selectMake]){
            item = cars[item][key_2]
            $scope.model.push(item)
        }
    })

    search = function(cars){
        cars[$scope.selectMake][$scope.selectModel][$scope.selectType]
    }

}]);

      Make
      <select id="inputState" class="form-control">
        <option ng-model="selectMake" selected>Select make</option>
        <option ng-repeat="item in make">{{ item }}</option>
      </select>

      Model
      <select id="inputState" class="form-control">
        <option ng-model="selectModel" selected>Select model</option>
        <option ng-repeat="item in model">{{ model }}</option>
      </select>

      Type
      <select id="inputState" class="form-control">
        <option ng-model="selectType"selected>Select make type</option>
        <option ng-repeat="item in type">{{ model }}</option>
      </select>

I don't believe either factory or controller are running. Nothing is logged in console, neither the data or the error message. Angular is properly linked to my form as there is no {{ }} also the ng app is declared at the top of the html in the body tag using ng-app="carForm". The JS page is correctly linked to the html as when I console.log outside the angular function it prints. Angular is loaded before my JS script in the head tag, I cant figure out what I'm doing wrong.

A: Your factory is uncorrected, because you didn't pass your function in return
Right way to make a factory
app.factory("dataService", ['$http', function($http) {
   var x = {};
   return x;
}]);

But even you change the code it's not work on your controller because
  you want to return response.data in $http as promise and this not happens, in
  the case you need $q as injection in your service.

var app = angular.module("carForm", []);

app.factory("dataService", ['$http', '$q', function ($http, $q) {
    var factory = {}

    factory.sample = function() {
        console.log("in factory!");
        return [1,2,3]
    }

    factory.getCars = function() {
        var deferred = $q.defer();
        $http.get("api").then(function(response){
           deferred.resolve(response.data);
        })
        return deferred.promise;
    }

    return factory;
}]);

app.controller("dataSort", ['dataService', '$scope', function(dataService, $scope) {
    $scope.items = dataService.sample();

    //uncomment when your api was ready

    //dataService.getCars().then(function(response){
    //    console.log(response);
    //})
}]);

{{item}}

A: Your factory is not correctly implemented Please change it like this.
app.factory("dataService", ['$http', function($http) {
    function getCars(){
        return $http({
            method: 'GET',
            url: '/data.json'
        }).then(function (response){
            console.log(response.data);
            return response.data
        },function (error){
            console.log("product error");
            })
        };
        return { getCars : getCars }
}]);


text:
Q: C code int to string not working Here is my code which uses itoa() function , seems not working. Let me make it clear, I am working on C.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void main()
{
    int i,j;
    for(i = 0;i<= 4; i++)
    {
        for (j = 0; j <= 9; j++)
        {
            //printf("Hi\n");
            char fileName[10]="A";
            char append[2];

            itoa(i,append,10);
            strcat(fileName,append);

            itoa(j,append,10);
            strcat(fileName,append);

            printf("i=%d j=%d\n", i,j);
            printf("%s\n", fileName);
            //FMS()
        }
        //printf("Anuj=%d\n",i );
    }
}

Output
RC4Attack.c:(.text+0x5e): undefined reference to itoa'
RC4Attack.c:(.text+0x8e): undefined reference toitoa'
collect2: error: ld returned 1 exit status

A: There's no itoa in standard C library. Instead, use sprintf.
sprintf(string_value, "%d", integer_value);

EDIT
Use snprintf to guard against buffer overflow as well.
snprintf(string_value, max_size, "%d", integer_value);

A: I had a similar issue two weeks ago,
I solved it by using sprtinf instead of itoa.
http://www.cplusplus.com/reference/cstdio/sprintf/

Did it look like this?
include <stdio.h>
#include <string.h>
#include <stdlib.h>

void main()
{
int i,j;
for(i = 0;i<= 4; i++)
{
    for (j = 0; j <= 9; j++)
    {
        //printf("Hi\n");
        char fileName[10]="A";
        char append[2];

        sprintf(filename,"%s%d",fileName,i);
        sprintf(filename,"%s%d",fileName,j);

        printf("i=%d j=%d\n", i,j);
        printf("%s\n", fileName);
    }
}
}

A: I can offer you 2 solutions:
1.) You could try to use a different c-compiler, some may work
2.) You could write this function easily yourself. Its only a small piece of code (see the following link)
http://en.wikibooks.org/wiki/C_Programming/C_Reference/stdlib.h/itoa
Also you could use a former thread about this topic which may help in your case:
Where is the itoa function in Linux?
Greetings
Marius


text:
Q: Using module-wide variables in Powershell 2.0 I've written a module to work with IBMs ClearCase through Powershell. At first it just contained a couple of often used functions, but now I'm expanding it. Most of the commands have to use a ClearTool object ($ct = new-object ClearCase.ClearTool), but I'd rather not have to recreate that object in every function call as it's a bit of overhead.
I also create a ClearCase view in many of these functions, but I can simply check for existence of the view and decide not to recreate it.
My question is, what's the best pattern for this? I can have a "create ct object" function and put the onus on the calling code to maintain it, but I don't think I like that method. Is it possible to have a module-wide variable for the ClearTool object and have Powershell check to see if it's filled before trying to recreate it each time?
Thanks!

A: In the end I created a couple of module-wide variables. I could hide them if necessary, although I haven't explicitly done that yet. I have a single function to create a view which must be called before doing any actual work and included in that is code to create the ClearTool object. I also have code to set the module-wide variables with the correct ClearTool object for use in other functions and the name of the view.
In the code of each of the functions if the ClearTool object ($ct) has not yet been set, they return an error condition.


text:
Q: Best way to send and process variable sized data On this page...
http://lab.2toria.com/reflex/index2.php
When the user has dragged and dropped blocks onto the grid, I want to be able to send the positions in some form to a php script that will save them into a table that simply records the coordinates (eg "x1y2", "x1y3", etc) into rows.  The fields in my table so far are VERY simple (blockID, blockCoords)
What would be the best way to do this?  I'm after your opinion on two things:-
1)  Using jQuery ajax, how could I send a string containing the coordinates as a list?  Would it be best to create an xml string, or is there another way I've not thought of...and how would I do this
and..
2)  Based on the method used to send the data (xml, or whatever), how would I then process the data in the receiving php script to save the data into a table.  I know how to save records etc, just wanting to know how best to deal with this situation.

A: $('element').droppable({
    drop:function(event, ui){
        $.ajax({
            url: '/path/to/my/file.php',
            type: 'POST',
            data: {'left' : ui.helper.position().left,
                   'top': ui.helper.position().top},
            success: function(data){
              //do something with the response from the server
            }
        });
    }
});

And in /path/to/my/file.php
if(isset($_POST['left'])):
    $db = new mysqli('connection info here');
    $q = $db->prepare('INSERT INTO some_table (left, top) VALUES (?,?)'); //prepare the statement
    $q->bind_param('ss', $_POST['left'], $_POST['top']); //safe binding
    if(FALSE !== $q->execute()):
        return 'Query Executed!';
    endif; //execute the statement
    return false;
endif;

So in the php file we're simply checking for the existence of the $_POST variable left. We assume top will be available also. We make a mysqli connection, prepare a safe statement, bind the parameters as strings, using the $_POST left/topvalues. Then we check if the execution didn't return false (returns true/false), and if it didn't, we pass a value and exit out of the conditionals all together. If not, the return false will fire by default.
Edit
From your comment, you want to save the actions that the user performs until ready to actually perform the insert, that's easily doable as well.
var dc = 0,
    drops = {};

dc will be the dropcount, and drops will be an object.
$('element').droppable({
    drop: function(event, ui){
        drops[dc] = {'left' : ui.helper.position().left, 'top' : ui.helper.position().top};
        dc++;
    }
});

In the above, we simply increment through the drops object, storing the information for the left/top values on each drop.
$('.save').click(function(e){
    e.preventDefault();
    $.ajax({
        url: 'test.php',
        type: 'POST',
        data: {'drops': drops},
        success: function(data){
            console.log(data);
        }
    });
});

Here, we have a save button with a class of save, we prevent the default action, then we sent the drops object to the server.
if(isset($_POST['drops'])):
    //same process as outlined above, use a helper function to insert the rows
endif;

Now we check for the existence of the $_POST variable 'drops', we'll employ the same tactics as above. I would simply recommend a helper function saveDrops($obj), iterating the returned drops and performing a save for each obj passed in.

A: 1) Yep, use jQuery ajax posting the coords and block id.
2) They will be available to php in the $_POST variable.
See:jQuery Post


text:
Q: How to get total numbers of nested divs under multiple individual divs? Here how can i get the total numbers of divs of class = "row ehi-pd", under each divs of class = "panel-content"?
As shown in the picture.
it should give the output for each class = "panel-content" section separately, not combining all of them.
for example:
for 1st "panel-content" : 6
for 2nd "panel-content" : 5
for 3rd "panel-content" : 3

A: use find_elements_by_xpath and take the length count.
totalcount= len(driver.find_elements_by_xpath("//div[@class='panel-content']/div[@class='row ehi-pd']"))
print(totalcount)

A: Good with @kajal solution but just want to add other option using css.
Using CSS:
panels = driver.find_elements_by_css_selector('.panel-content')
for panelNum in range(len(panels)):
    #get the divs count
    panelDivs = len(panels[panelNum].find_elements_by_css_selector("div.row.ehi-pd"))
    print str(panelNum+1) + " panel-content:" + str(panelDivs)

A: To print the total numbers of nested <div> tags with class attribute as  row ehi-pd within the ancestor <div> tag  with class attribute as  panel-content you can use either of the following Locator Strategies:

*

*css_selector:
print(len(driver.find_elements_by_css_selector("div.panel-content div.row.ehi-pd")))

*xpath:
print(len(driver.find_elements_by_xpath("//div[@class='panel-content']//div[@class='row ehi-pd']")))


text:
Q: Stratification of Groups for A/B Testing I'm looking to balance test and control groups for running an A/B test so that the two groups are comparable, based on multiple different metrics.
I have a list of customers along with their spend in a set period of time, average frequency of purchase and average spend per purchase.
Has anybody faced a similar task, and can share their script for this?
N.B. I'm a newbie to coding.


text:
Q: Why there is a mistake IllegalArgumentException(Camera2API) i am working with Camera2API
there is my code
public class MainActivity extends AppCompatActivity {

private static Context context;
private CameraManager mCameraManager = null;
public static final String LOG_TAG = "mistake";
private final int CAMERA1 = 0;
private final int CAMERA2 = 1;
private CameraHelper[] myCameras = null;
private Button mButtonOpenCamera1 = null;
private Button mButtonOpenCamera2 = null;
private TextureView mImageView = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    context = this;

    //получаем обьект камера менеджер
    mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    mImageView = (TextureView) findViewById(R.id.image_view);

    // Получения списка камер в устрйстве
    String[] cameraList = new String[0];
    try {
        cameraList = mCameraManager.getCameraIdList();
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

    //нужно обязательно не забыть инициализировать массив
    myCameras = new CameraHelper[cameraList.length];

    for (String cameraID : cameraList) {
        System.out.println("cameraID: " + cameraID);
        int id = Integer.parseInt(cameraID);

        // создаем обработчик для камеры
        myCameras[id] = new CameraHelper(mCameraManager, cameraID, getApplicationContext());

        // выводим инормацию по камере
        myCameras[id].viewFormatSize(ImageFormat.YUV_420_888);

        // устанавливаем текстуру для отображения
        myCameras[id].setTextureView(mImageView);
    }

    mButtonOpenCamera1 = (Button) findViewById(R.id.btn_open_camera1);
    mButtonOpenCamera2 = (Button) findViewById(R.id.btn_open_camera2);

    mButtonOpenCamera1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (myCameras[CAMERA2].isOpen()) myCameras[CAMERA2].closeCamera();
            if (myCameras[CAMERA1] != null) {
                if (!myCameras[CAMERA1].isOpen()) myCameras[CAMERA1].openCamera();
            }
        }
    });

    mButtonOpenCamera2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (myCameras[CAMERA1].isOpen())  myCameras[CAMERA1].closeCamera();
            if (myCameras[CAMERA2] != null) {
                if (!myCameras[CAMERA2].isOpen())  myCameras[CAMERA2].openCamera();
            }
        }
    });
}

public static void ToastPrint(String cameraId) {
    Toast.makeText(context, "Open camera  with id: " + cameraId, Toast.LENGTH_LONG).show();
}
}

theri is helper class
public class CameraHelper {
private CameraCaptureSession mSession = null;
private CameraManager mCameraManager = null;
private CameraDevice mCameraDevice = null;
private String mCameraID = null;
private Context context;
private TextureView mTextureView;
private ImageReader imageReader;
private Handler handler;
private Surface jpegCaptureSurface;
private static ByteArrayOutputStream outputStream;

public CameraHelper(@NonNull CameraManager cameraManager, @NonNull  String cameraID, Context context) {
    mCameraManager = cameraManager;
    mCameraID = cameraID;
    this.context = context;

    //нужно разобраться с этой строчкой, она 650 в коде
    handler = new Handler();
}

public static ByteArrayOutputStream getOutputStream() {
    return outputStream;
}

public void viewFormatSize(int formatSize) {

//      Получения характеристик камеры, Для получения характеристик необходимо
//      использовать метод getCameraCharacteristics(String cameraId). Этот метод возвращает объект
//      класса CameraCharacteristics, в котором сконцентрированы параметры по камере. В данном классе
//      сконцентрировано огромное количество параметров
    CameraCharacteristics cc;
    try {
        cc = mCameraManager.getCameraCharacteristics(mCameraID);

        // Получения списка выходного формата, который поддерживает камера
        StreamConfigurationMap configurationMap =
                  cc.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

        // Получения списка разрешений которые поддерживаются для формата jpeg
        Size[] sizesJPEG = new Size[0];
        if (configurationMap != null) {
            sizesJPEG =  configurationMap.getOutputSizes(ImageFormat.JPEG);
        }

        if (sizesJPEG != null) {
            for (Size item : sizesJPEG) {
                System.out.println("w:" + item.getWidth() + " h:" + item.getHeight());
            }
        } else {
            Log.e(MainActivity.LOG_TAG, "camera with id: " + mCameraID + " don`t support format: " +
                    formatSize);
        }

    } catch (CameraAccessException e) {
        Log.e(MainActivity.LOG_TAG, e.getMessage());
    }
}

public boolean isOpen() {
    return mCameraDevice != null;
}

//    В методе openCamera() с помощью нашего менеджера открываем камеры. В параметрах метода
//    указываем, какую камеру открывать, а также обработчик, который будет отслеживать состояния
//    открытия камеры.
public void openCamera() {
    try {
//            я так понимаю что здесь мы проверяем прописан ли у нас доступ к камере в манифесте и
//            если все в порядке то выполняется открытие камеры
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) !=
                PackageManager.PERMISSION_GRANTED) {
            return;
        }

        mCameraManager.openCamera(mCameraID, mCameraCallback, null);

    } catch (CameraAccessException e) {
        Log.e(MainActivity.LOG_TAG, e.getMessage());
    }
}

public void closeCamera() {

    if (mCameraDevice != null) {
        mCameraDevice.close();
        mCameraDevice = null;
    }
}

private CameraDevice.StateCallback mCameraCallback = new CameraDevice.StateCallback() {

    @Override
    public void onOpened(@NonNull CameraDevice camera) {
        mCameraDevice = camera;
        createCameraPreviewSession();
        System.out.println("----------" + mCameraDevice.getId());
        MainActivity.ToastPrint(mCameraDevice.getId());
    }

    @Override
    public void onDisconnected(@NonNull CameraDevice camera) {
        mCameraDevice.close();
        Log.i(MainActivity.LOG_TAG, "disconnect camera  with id:" + mCameraDevice.getId());
        mCameraDevice = null;
    }

    @Override
    public void onError(@NonNull CameraDevice camera, int error) {
        Log.i(MainActivity.LOG_TAG, "error! camera id:" + camera.getId() + " error:" + error);
    }
};

private void createCameraPreviewSession() {

//        для получения изображения нам необходимо использовать  ImageReader. Для получения
//        максимально возможной скорости передачи кадров нам необходимо использовать «сырой формат». То
//        есть, jpeg нам не подойдет, поскольку он будет давать задержку на время конвертации кадра и
//        таким образом у нас возникнет очень низкий fps. Для получения максимальной продуктивности
//        следует использовать ImageFormat.YUV_420_888.
    imageReader = ImageReader.newInstance(640, 480, ImageFormat.JPEG, 2);
    imageReader.setOnImageAvailableListener(onImageAvailableListener, handler);

    //эти 2 строчки пока не понятно зачем нужны
    SurfaceTexture texture = mTextureView.getSurfaceTexture();
    texture.setDefaultBufferSize(640, 480);

    try {
        final CaptureRequest.Builder builder =
                 mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);

        builder.addTarget(jpegCaptu                                                                                reSurface);
//            builder.addTarget(surface);

        //это добавление возможных эффектов
//            builder.set(CaptureRequest.CONTROL_AWB_MODE, CaptureRequest.CONTROL_AWB_MODE_INCANDESCENT);
//            builder.set(CaptureRequest.CONTROL_EFFECT_MODE, CaptureRequest.CONTROL_EFFECT_MODE_SEPIA);
//            builder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_SINGLE);

        mCameraDevice.createCaptureSession(
                Collections.singletonList(imageReader.getSurface()),
//                    Collections.singletonList(surface),
                new CameraCaptureSession.StateCallback() {

                    @Override
                    public void onConfigured(@NonNull CameraCaptureSession session) {
                        mSession = session;
                        try {
                            mSession.setRepeatingRequest(builder.build(), null, null);
                        } catch (CameraAccessException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                    }
                },
                null
        );

    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

private final ImageReader.OnImageAvailableListener onImageAvailableListener =
        new ImageReader.OnImageAvailableListener() {
            @Override
            public void onImageAvailable(ImageReader reader) {
                final Image image = reader.acquireLatestImage();

                jpegCaptureSurface = reader.getSurface();

                handler.post(new ImageSaver(context));
            }
        };

private static class ImageSaver implements Runnable {
    private BufferedOutputStream bos;
    private Context context;

    public ImageSaver(Context context) {
        this.context = context;
    }

    @Override
    public void run() {

        final File pictureFile = getOutputMediaFile();
        if (pictureFile == null) {
            return;
        }
        try {
            bos = new BufferedOutputStream(
                    new FileOutputStream(pictureFile));
            bos.write(convertOutputToByteArray(getOutputStream()));
            bos.flush();

            Toast.makeText(context, "Picture saved: " + pictureFile.getName(),
                    Toast.LENGTH_SHORT).show();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private byte[] convertOutputToByteArray(ByteArrayOutputStream stream) {
        return stream.toByteArray();
    }

    private static File getOutputMediaFile() {
        File mediaStorageDir = new File("/sdcard/", "JCG Camera");

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" +
                timeStamp + ".png");

        return mediaFile;
    }
}

public void setTextureView(TextureView mImageView) {
    mTextureView = mImageView;
}

there is a link to my github:
https://goo.gl/3yaTKo

when i start method openCamera() which in CameraHelper class,
i see the mistake
java.lang.IllegalArgumentException: Null Surface targets are not allowed
at  android.hardware.camera2.impl.CameraDeviceImpl.submitCaptureRequest(CameraDeviceImpl.java:602)
at   android.hardware.camera2.impl.CameraDeviceImpl.setRepeatingRequest(CameraDeviceImpl.java:663)
at   android.hardware.camera2.impl.CameraCaptureSessionImpl.setRepeatingRequest(CameraCaptureSessionImpl.java:204)
at     com.example.aleksey.camera2api.CameraHelper$2.onConfigured(CameraHelper.java:185)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)

why it is going wrong?

A: It looks like you commented out the line that sets the surface in your builder:
//            builder.addTarget(surface);

Also, make sure you're waiting until the surface is ready before invoking anything that depends on it.


text:
Q: How to install .NET Language Pack on Azure Web App? I'm working on a website that uses System.ComponentModel.DataAnnotations
On my local machine, model validation messages are displayed in french but they are in english wehn I deploy the website to Azure.
How can I install Microsoft .NET Language Pack on my Azure Web App ?
Or, is it possible to find the french System.ComponentModel.DataAnnotations.resources.dll and deploy it with the website ? When I put this assembly in the /bin/ folder, it does not change anything. Validation messages are still in en-US.


text:
Q: Display alert dialog after specific time I want to start a timer (i think in this case CountDownTimer) as soon as I get a specific wakelock. Once the countdown timer finishes, i want to display an alert dialog. When the wakelock is released, the timer should be killed. When the timer is running and I get a user activity, I want to kill the previous timer and start a new one (or maybe reset this one)
What would be the best way for me to implement this?

A: Yes you can do it, the only thing you need to do is like this -->

`val dialogListener = DialogInterface.OnClickListener { dialog, which ->
                    when (which) {
                        BUTTON_POSITIVE -> {
                        }
                        DialogInterface.BUTTON_NEGATIVE -> {
                        }
                    }
                }
                val dialog = AlertDialog.Builder(this)
                    .setTitle("YOUR TITLE HERE")
                    .setMessage("YOUR MESSAGE HERE)
                    .setPositiveButton("TEXT OF BUTTON")
                    .setNegativeButton("TEXT OF BUTTON")
                    .create()

    dialog.setOnShowListener(object : OnShowListener {
                    private val AUTO_DISMISS_MILLIS = 5000  //Timer in this case 5 Seconds
                    override fun onShow(dialog: DialogInterface) {
    //if you want to have stuff done by your buttons it's going go be here with a respective call like (dialog as AlertDialog).getButton(The button you want positive or negative)
    then everything you want to happen on it
    *************************************************
                        //here is the timer associated to the button
                        val defaultButton: Button =
                            dialog.getButton(AlertDialog.BUTTON_POSITIVE)
                        val positiveButtonText: CharSequence = defaultButton.text
                        object : CountDownTimer(AUTO_DISMISS_MILLIS.toLong(), 100) {
                            override fun onTick(millisUntilFinished: Long) {
                                defaultButton.text = java.lang.String.format(
                                    Locale.getDefault(), "%s (%d)",
                                    positiveButtonText,
                                    TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) + 1
                                )
                            }
                            override fun onFinish() {
    //everything you wanna do on the moment the timer is off is going to happen here if you wanna open another dialog you need to call it here
                            }
                        }.start()
                    }
                })
                dialog.show()
            }
    `


text:
Q: How to add icons/images to the legend I would like to add icon/images into the legend box as the picture attached (source: https://esajournals.onlinelibrary.wiley.com/doi/10.1002/eap.1973)
Does anyone know about this thing using ggplot?


text:
Q: Autorun macro in Powerpoint 2010 I would like to auto run a macro when my PowerPoint 2010 file opens.
I hope someone would be able to assist.
Thank you in advance!

A: I wrote an article to explain how to do this here

A: Private Sub App_PresentationOpen(ByVal Pres As Presentation)
     Call yourMacro
End Sub


text:
Q: JS file couldnt access laravel variable I am passing an array from my controller.
Now, I put this code inside my Laravel 6.* Blade View,
<script>
    var app = <?php echo json_encode($array); ?>;
</script>

This works just fine.
However, if I put the same piece of line (or any of the following lines) inside my custom app.js file, this doesn't work.
var app = <?php echo json_encode($array); ?>;

var app = {!! json_encode($array->toArray()) !!};

var app = '<?php echo json_encode($array); ?>';

Each time I am getting an invalid syntax error.
I am not sure if this is a valid ques for StackOverflow, but I have already tried all other similar solutions and none of them is working for me.

A: That's because you have no access to write php code in js file or you can use Ajax to get php variable.
In your statement if you put your code in your blade file before including app.js file you will be able to get app variable in your js file.
Ex:
<script>
var app = @json($array)
</script>
<script src="path to your app js file"></script>

And now in your app js file if you print app variable you will see the result
console.log(app); in your app.js file

A: One thing you can do is to move javascript to template and create route to it as:
Route::get('/app.js', function () {
    $result = view('app', ['array' => [1,2,3,5,8]]);
    return Response::make($result, 200)
        ->header('Content-Type', 'application/javascript');
});

Then in resouces\views
<script>
    var app = <?php echo json_encode($array); ?>;
</script>

Common way of doing this is to create end point that returns json only and then use e.g. fetch api or axios library on client side.
Something like this:
Route::get('/app', function () {
    return [1,2,3,5,8];
});

<script>
    fetch(endPointUrl("/app")).then(response => {
        console.log(response);
    }).catch(error => {
        console.error(error);
    })
</script>

Where endPointUrl is just a helper function that creates full url.


text:
Q: Appendix numbering issue I am trying to obtain the following structure (in terms of titles) :

Chapter 5 : Last Title
Annex
  A - Section1Annex
  B - Section2Annex

where Chapter 5 and Annex are referenced as \chapter title.
I managed to "remove" the chapter numbering for the Annex (with addcontentsline and chapter*{Annex} inside a custom made command, "\myChap), so, no problem on that side.
Then, on below the code I wrote :
\chapter{Last Title}
\myChap{Annex}
\appendix
\section{Section1Annex}
\section{Section2Annex}

However, it displays the following structure:

Chapter 5 : Last Title
Annex
  0.1 - Section1Annex
  0.2 - Section2Annex

My problem :
How can I switch these section numbering from 0.1 (resp.0.2) to A (resp. B). I am having difficulties to deal with the \appendix environment.
Thank you in advance for your help.

A: A solution suggestion, since lacking a MWE, \mychap is unknown and not used in here.
\documentclass[12pt]{report}

\usepackage{hyperref}%

\begin{document}
\tableofcontents

\chapter{The last one}

\renewcommand{\appendixname}{Annex}%
\chapter*{\appendixname}

\phantomsection
\addcontentsline{toc}{chapter}{\appendixname}%
% Eventually a \cleardoublepage here
 \cleardoublepage
\renewcommand{\thesection}{\Alph{section}}

\section{AnnexSectionOne}
\section{AnnexSectionTwo}

\end{document}


text:
Q: Facebook opens new Activity for login in my app is a com.facebook.widget.LoginButton from FB-SDK 3.0.
If I Click on this LoginButton, a new and blank Activity is opened with my dialog authentication. I dont know why this is happening and how i can prevent that. I want the dialog authentication flowing over my normal Activity.
Thanks to the com.facebook.widget.LoginButton i have no code in my Application to Login, everything is done by my LoginButton. Just a onActivityResult-Method which handels the login.
https://developers.facebook.com/docs/howtos/androidsdk/3.0/native-login/
Does anybody know an answer?
Thanks


text:
Q: Connect PHP (Google app engine) to SQL Server (Cloud SQL) I would like to know if it's possible to connect PHP running on Google App Engine to SQL Server 2017 running on Google cloud SQL(same project)?
As far as I can see there is no extension available for PHP to connect to SQL Server, or maybe, to blame is my lack of experience with GC's products.
I have done this in the past but with MySQL, and that was really easy but now I seem to be stuck.
Is there a solution to this problem or should I try a workaround using a container?
Thank you!


text:
Q: Render meshlab scene to image Is it possible to render a meshlab scene to an image, like taking a screenshot?  I ultimately want to do this programmatically.
Specifically I'm after something that allows it to be done via MeshlabServer's API.

A: No, it is not possible and it is not planned to do that by the moment.
The reason is that meshlab is focused on polygon mesh processing, not in rendering. For the case of meshlabserver, it is even more focused in processing (that why its input are scripts) and even less focused in rendering (that why it is a console application that do not create a render context).
If you are planning to render a lot of 3D files, I would suggest to use blender instead. A small python script running in the interpreter bundled with blender can do the work you have in mind.


text:
Q: Why can't add semicolon at the last statement in js' for loop? The js's for loop formal format is as below:
for (statement 1; statement 2; statement 3) {
  code block to be executed
}

WHy can't add a semicolon at the end of statement 3 ?
for (statement 1; statement 2; statement 3;) {
  code block to be executed
}

Please tell me the logic instead of rule.

A: These aren't statement terminators like the usual ;, they're a specific part of the for syntax.
As in this:
for (let i = 0; i < 10; ++i) { ... }

Is quite different from this:
let i = 0;
i < 10;
++i;

This is all to do with how the language is parsed and what meaning each symbol has in any given context. Sometimes ; is a statement terminator, but you're probably aware that is not always the case:
let semicolon = ";";

There's two semicolons there, and only one is a statement terminator. One is part of a string. Likewise those inside the for are special.
If you look at the formal definition on MDN you can see for defined as:
for ( init_clause ; cond_expression ; iteration_expression ) loop_statement

Where each of those terms, init_clause, cond_expression and iteration_expression are specific expressions allowed there, and their specific function is defined below that.
The specific syntax of the for statement is inherited from the C version of same.
It's entirely possible that JavaScript could have chosen some other symbol here, like #, and it would work the same way, but that would make JavaScript feel a bit odd for those familiar with C or other C-inspired languages with precisely the same structure like C++ and Java.

A: well the syntax for the for loop is this
for(;;)
{
//anything
}

ex :
for(x=0;x<5;x++)
{
console.log(x);
}


text:
Q: unable to create native thread: possibly out of memory or process/resource limits reached when running JMETER i'm trying to run a load test with Jmeter on mac(linux).
i'm getting the following error:
JMeter: Uncaught exception:
java.lang.OutOfMemoryError: unable to create native thread: possibly out of memory or process/resource limits reached.
mtis-MBP-2:~ mti$ ulimit -a | grep processes
max user processes              (-u) 709
any suggestions?


text:
Q: How to make this python string-to-float function more efficient? I created a small python script that changes a list (of any size in this case a) from a string of numbers as well as a string that has a number and string (million, billion, trillion) to a list of floats and prints it out.
Assume that the phrases 'million', 'billion', and 'trillion' are the only terms that can be used and they are always separated with a space from the number (if there is a number).
The code is below. Is there any way to make the script more concise and efficient?

a = ["10", "1000" , "1.684 million", "356852", "2.5 billion", "3 trillion"]

for i in range(len(a)):

  num_phrase=''

  if ' ' in a[i]:
    num_phrase=a[i].split(" ")[1]

  if num_phrase=="million":
    a[i]=float(a[i].split(" ")[0])*1000000
  elif num_phrase=="billion":
    a[i]=float(a[i].split(" ")[0])*1000000000
  elif num_phrase=="trillion":
    a[i]=float(a[i].split(" ")[0])*1000000000000
  else:
    a[i]=float(a[i].split(" ")[0])

print(list(a))

A: Could use a dict:
d = {'': 1, 'm': 1e6, 'b': 1e9, 't': 1e12}
a = [float(number) * d[unit[:1]]
     for s in a
     for number, _, unit in [s.partition(' ')]]

Or replace those illions with scientific notation:
a = [float(s.replace(' million', 'e6')
            .replace(' billion', 'e9')
            .replace(' trillion', 'e12'))
     for s in a]

Benchmark results with your list times 1000:
Round 1  Round 2  Round 3
3640 us  3618 us  3555 us  original
2747 us  2738 us  2706 us  Kelly1
2258 us  2272 us  2214 us  Kelly2
3759 us  3841 us  3802 us  dim_an
3495 us  3542 us  3562 us  motyzk

Benchmark code (Try it online!):
from timeit import timeit

def baseline(a):
    pass

def original(a):
 for i in range(len(a)):
  num_phrase=''
  if ' ' in a[i]:
    num_phrase=a[i].split(" ")[1]
  if num_phrase=="million":
    a[i]=float(a[i].split(" ")[0])*1000000
  elif num_phrase=="billion":
    a[i]=float(a[i].split(" ")[0])*1000000000
  elif num_phrase=="trillion":
    a[i]=float(a[i].split(" ")[0])*1000000000000
  else:
    a[i]=float(a[i].split(" ")[0])
 return a

def Kelly1(a):
    d = {'': 1, 'm': 1e6, 'b': 1e9, 't': 1e12}
    return [float(number) * d[unit[:1]]
            for s in a
            for number, _, unit in [s.partition(' ')]]

def Kelly2(a):
    return [float(s.replace(' million', 'e6')
                   .replace(' billion', 'e9')
                   .replace(' trillion', 'e12'))
            for s in a]

def dim_an(a):
 multipliers = {
    "million":  10 ** 6,
    "billion":  10 ** 9,
    "trillion": 10 ** 12,
 }
 for i in range(len(a)):
    words = a[i].split()
    if len(words) == 0 or len(words) > 2:
        raise ValueError("Bad string: " + e)

    result = float(words[0])
    if len(words) == 2:
        result *= multipliers[words[1]]
    a[i] = result
 return a

def motyzk(a):
 str_to_num = {
    "": 1,
    "million": 1000000,
    "billion": 1000000000,
    "trillion": 1000000000000,
 }
 for i in range(len(a)):
  num_phrase=''
  if ' ' in a[i]:
    num_phrase=a[i].split(" ")[1]
  a[i]=float(a[i].split(" ")[0])*str_to_num[num_phrase]
 return a

# config
funcs = original, Kelly1, Kelly2, dim_an, motyzk, baseline
a = ["10", "1000" , "1.684 million", "356852", "2.5 billion", "3 trillion"] * 1000
number = 100

# correctness
expect = original(a.copy())
for func in funcs:
    result = func(a.copy())
    print(result == expect, func.__name__)

# speed
tss = [[] for _ in funcs]
for _ in range(3):
    print('Round 1  Round 2  Round 3')
    for func, ts in zip(funcs, tss):
        t = timeit(lambda: func(a.copy()), number=number) / number
        ts.append(t)
        print(*('%4d us ' % (t * 1e6) for t in ts), func.__name__)
    print()

A: If we talk about readability and performance I would change two things here:

*

*I wouldn't call str.split multiple times, it's costly.

*Maybe I would replace multiple ifs with dict It's not necessarily speedup when you have small number of branches, but it makes code more readable from my point of view and helps when you have more strings.

a = ["10", "1000" , "1.684 million", "356852", "2.5 billion", "3 trillion"]

multipliers = {
    "million":  10 ** 6,
    "billion":  10 ** 9,
    "trillion": 10 ** 12,
}

for i in range(len(a)):
    words = a[i].split()
    if len(words) == 0 or len(words) > 2:
        raise ValueError("Bad string: " + e)

    result = float(words[0])
    if len(words) == 2:
        result *= multipliers[words[1]]
    a[i] = result

print(a)

A: a = ["10", "1000" , "1.684 million", "356852", "2.5 billion", "3 trillion"]

str_to_num = {
    "": 1,
    "million": 1000000,
    "billion": 1000000000,
    "trillion": 1000000000000,
}

for i in range(len(a)):

  num_phrase=''

  if ' ' in a[i]:
    num_phrase=a[i].split(" ")[1]

  a[i]=float(a[i].split(" ")[0])*str_to_num[num_phrase]

print(a)

A: Code in my previous answer is written close to the way I would solve problem in production, so it tries to be clear and make some additional checks to make sure invalid strings raise errors, that lowers performance
If we are trying to make fastest solution possible (and we don't care much about validating input) we can use following approach minimizing string modification at all.
a = ["10", "1000" , "1.684 million", "356852", "2.5 billion", "3 trillion"]
def convert(input):
    if " million" in input:
        return float(input[:-8]) * 1000000.0
    elif " billion" in input:
        return float(input[:-8]) * 1000000000.0
    elif " trillion" in input:
        return float(input[:-9]) * 1000000000000.0
    else:
        return float(input)
print([convert(e) for e in a])

Benchmark results (thanks to Kelly Bundy):
Round 1  Round 2  Round 3
4224 us  4164 us  4170 us  original
3129 us  3121 us  3180 us  Kelly1
3043 us  3176 us  3100 us  Kelly2
4381 us  4425 us  4345 us  dim_an
4053 us  4089 us  4119 us  motyzk
2160 us  2187 us  2169 us  dim_an2
  12 us    12 us    12 us  baseline

Try it


text:
Q: Start appium and run nunit test from shell script Here is my script:
node ${APPIUM_PATH}/bin/appium.js
nunit-console AppiumTest.dll

The problem is that when appium starts it takes control over console and I can't run any more commands until it's stopped.
Alternatively I tried this:
node ${APPIUM_PATH}/bin/appium.js &
nunit-console AppiumTest.dll

which lets me run 2 commands simultaneously, but in this case it ignores the delay required for server to start.

A: The issue here is the nunit process should kick off after Appium listener has started. So you have listen to output from the first command and then invoke the nunit. Below is the nodejs version using javascript as it is quite easy in nodejs to listen to output stream from one process and kickoff another process.
Below is the syntax using nodejs . Since appium has already installed nodejs, create a js file (ex : AutoStart.js) in appium directory and run node AutoStart.js
Below is the code which is now on git hub - > link enter link description here
var sys = require('sys')
var exec = require('child_process').exec;
var child;

child = exec("node bin/appium.js",function(error,stdout,stderr){
  if (error !== null) {
    console.log('exec error: ' + error);
  }

  console.log('stdout: ' + stdout);
  console.log('stderr: ' + stderr);

});

child.stdout.on('data',
    function(data){
    var buff = new Buffer(data).toString('utf8');
    console.log( buff);

    if(buff.match(/Appium REST http interface listener/))
    {
        console.log("Server is started");
        var nunitProcess = exec("nunit-console AppiumTest.dll", function(error,stdout,stderr){
              if (error !== null) {
                    console.log('error starting nUnit ' + error);
                  }

        })
    }
    else console.log("not started");

});


text:
Q: Bitnami SonarQube when accessed via URL routes to the IP instead I have recently installed bitnami sonarqube 8.6 on AWS, and then configured DNS to serve it via my domain. I have also gone to sonar settings and changed the default host to point to my domain name as well. What happens is that the moment I hit sonar.mydomain.com it reroutes to the IP address.
I believe bitnami uses apache2 to serve sonar, and there might be settings there that I can use. But I have not been able to find the right config file and even if I found one my apache chops are rudimentary at best. Anyone who has used bitnami sonar on AWS might know how to configure this. Please help!

A: To configure the domain in the Bitnami instances you can run
sudo /opt/bitnami/apps/sonarqube/bnconfig --machine_hostname YOUR_DOAMIN

Rename this tool so that it does not change again at boot time
sudo mv /opt/bitnami/apps/sonarqube/bnconfig /opt/bitnami/apps/sonarqube/bnconfig.disabled

You can check this in the documentation of Bitnami https://docs.bitnami.com/aws/apps/sonarqube/administration/configure-domain/


text:
Q: How to create a loop over multiple columns for the clusWilcox.test function For my data analysis, I need to run clusWilcox.test (clusrank package) for multiple columns in my dataset. This dataset consists of 92 columns, of which colums 1 to 26 are possible independent variables (all factors), and 27 to 92 are dependent variables (all numeric) that I want to test.
If I were to do all the tests manually, it should look like:
clusWilcox.test(column27 ~ treatment + cluster(factor1), data = df)
clusWilcox.test(column28 ~ treatment + cluster(factor1), data = df)

...

clusWilcox.test(column92 ~ treatment + cluster(factor1), data = df)

I though it should be possible to make R do these subsequent test automatically and then give me the output for all these tests at once. I found a code for using the lapply function for a linear model (lm function) that I tried to adapt to the clusWilcox.test, however this does not work.
This is de code I found:
names(df)
varlist <- names(df)[27:92]
models <- lapply(varlist, function(x) {
  lm(substitute(i ~ treatment + factor1, list(i = as.name(x))), data = df)
})
models

This works perfectly for my dataset. So my next step was to adapt this code, as I need to run the  clusWilcox.test instead of a lm. I adapted the code as follows:
names(df)
varlist <- names(df)[27:92]
models2 <- lapply(varlist, function(x) {
  clusWilcox.test(substitute(i ~ treatment + cluster(factor1), list(i = as.name(x))), data = df)
})
models2

However, this code gives the following error message:
Error in `vectbl_as_col_location()`:
! Can't subset columns that don't exist.
✖ Columns `substitute`, `i ~ Treatment`, and `list(i = as.name(x))` don't exist.
Run `rlang::last_error()` to see where the error occurred.
> rlang::last_error()
<error/vctrs_error_subscript_oob>
Error in `vectbl_as_col_location()`:
! Can't subset columns that don't exist.
✖ Columns `substitute`, `i ~ Treatment`, and `list(i = as.name(x))` don't exist.
---
Backtrace:
 1. base::lapply(...)
 2. global FUN(X[[i]], ...)
 4. clusrank:::clusWilcox.test.default(...)
 5. clusrank:::extractVar("x", pars, data)
 7. tibble:::`[.tbl_df`(data, , as.character(pars[[var]]))
 8. tibble:::vectbl_as_col_location(j, length(x), names(x), j_arg = j_arg, assign = FALSE)
Run `rlang::last_trace()` to see the full context.
>
> rlang::last_trace()
<error/vctrs_error_subscript_oob>
Error in `vectbl_as_col_location()`:
! Can't subset columns that don't exist.
✖ Columns `substitute`, `i ~ Treatment`, and `list(i = as.name(x))` don't exist.
---
Backtrace:
     ▆
  1. └─base::lapply(...)
  2.   └─global FUN(X[[i]], ...)
  3.     ├─clusrank::clusWilcox.test(...)
  4.     └─clusrank:::clusWilcox.test.default(...)
  5.       └─clusrank:::extractVar("x", pars, data)
  6.         ├─data[, as.character(pars[[var]])]
  7.         └─tibble:::`[.tbl_df`(data, , as.character(pars[[var]]))
  8.           └─tibble:::vectbl_as_col_location(j, length(x), names(x), j_arg = j_arg, assign = FALSE)
  9.             ├─tibble:::subclass_col_index_errors(...)
 10.             │ └─base::withCallingHandlers(...)
 11.             └─vctrs::vec_as_location(j, n, names)
 12.               └─vctrs (local) `<fn>`()
 13.                 └─vctrs:::stop_subscript_oob(...)
 14.                   └─vctrs:::stop_subscript(...)
 15.                     └─rlang::abort(...)

What did I do wrong, and how I can let R repeat the test multiple times over all the columns?

A: Convert to formula class:
library(clusrank)

#example data
df <- mtcars[, c("vs", "am", "mpg")]
names(df)
# [1] "vs"  "am"  "mpg"

varlist <- names(df)[1:2]
# [1] "vs" "am"

lapply(varlist, function(x) {
  clusWilcox.test(as.formula(substitute(mpg ~ i, list(i = as.name(x)))), data = df)
})

#[[1]]
#
#   Clustered Wilcoxon rank sum test using Rosner-Glynn-Lee method
#
#data:  mpg; group: vs; (from df)
#number of observations: 32;  number of clusters: 32
#Z = 3.9342, p-value = 8.349e-05
#alternative hypothesis: true difference in locations is not equal to 0
#
#
#[[2]]
#
#   Clustered Wilcoxon rank sum test using Rosner-Glynn-Lee method
#
#data:  mpg; group: am; (from df)
#number of observations: 32;  number of clusters: 32
#Z = 3.1291, p-value = 0.001753
#alternative hypothesis: true difference in locations is not equal to 0

Alternatively, I prefer to use paste to construct the formula:
lapply(varlist, function(x) {
  f <- as.formula(paste("mpg ~", x))
  clusWilcox.test(f, data = df)
})


text:
Q: Error when running windows PlaySound(), undefined reference to `__imp_PlaySoundA' So I tried using PlaySound() function from Windows but it returns with 'undefined reference to __imp_PlaySoundA'
Here is my code:
#include <stdio.h>
#include <windows.h>
#include <mmsystem.h>

int main()
{
    LPCTSTR SongFile="C:\\Users\\User1\\Desktop\\AudioPlayer\\mev.wav";
    PlaySound(SongFile,NULL,SND_NODEFAULT);
    return 0;
}

I know that you have to do something with the winmm.lib but I spent like 3 hours looking for this but I have no idea still. I am using mingw as my compiler and am using Visual Studio Code.