text:
Q: Can drag be neglected, although the object is in motion? I was researching more about drag and why two things fall at the same time, and I came across Nasa's website (and quite a few more website) which said that, When drag is equal to weight, there is no net external force on the object, and the acceleration becomes zero. The object then falls at a constant velocity. The link to the page is here: https://www.grc.nasa.gov/www/k-12/airplane/falling.html
My question is that, is that information actually true? One reason that says that it is true, is that two objects fall at the same time if left at the same height and same time. This is due to drag becoming equal to weight and then net force is $0$ so $0$ acceleration (according to Nasa's website). But, if you have seen a space probe re-entering earth's atmosphere, you would have probably seen that the front part of the probe sort of catches on fire. Isn't that because of the high drag force, which causes the fire? If you would again go with Nasa, drag should have long ago become equal to weight and been canceled out and it should have not at all caught of fire right? Could someone explain if that information is right or not?

A: If drag is equal to weight (and there are no other forces), then yes the acceleration will be zero.  For objects falling through the atmosphere, this is commonly referred to as terminal velocity.

One reason that says that it is true, is that two objects fall at the same time if left at the same height and same time. This is due to drag becoming equal to weight and then net force is 0 so 0 acceleration (according to Nasa's website).

But the weight and the drag may be very different.  A marble and a feather do not both fall at the same rate.

If you would again go with Nasa, drag should have long ago become equal to weight and been canceled out and it should have not at all caught of fire right?

No, drag forces depend on the density of the atmosphere, which varies with altitude.  As an object descends, drag increases very quickly, much faster than the object can decelerate.

Does that mean that even after drag being equal to weight, drag increases?

If the fluid it falls through is not constant density, then yes the drag can change until the object reaches a new equilibrium speed.
Imagine an object thrown out of an airplane over the ocean.  After a few seconds it reaches the equilibrium speed where drag and weight are equal.  It falls at (roughly) this speed until it hits the water.  At this point drag increases!  The increased drag slows the object.  Once the object has slowed sufficiently, drag once again equals weight (minus buoyancy) and the object sinks at a slower speed than it did through the air.
The density changes for a reentering spacecraft are not as great, but because of the high speed, the forces are huge.  Rather than smacking the surface of the ocean, the reentering craft strikes the increasing density of the atmosphere.

A: A falling object initially speeds up. The drag force, $$D=\frac12 C_dA\rho v^2,$$ thus gradually increases. At some point the increasing drag force becomes equal to the close-to-constant weight, $w=mg$. Then whichever speed the object has reached as this moment doesn't change anymore - it stays constant from here on. This is called the terminal speed. So yes, the NASA quote is correct.
If the drag force quickly becomes equal to the weight, then a lower terminal speed has been achieved because the object accelerated for a shorter time. So, due to varying drag forces, different objects will reach different terminal speeds.

*

*A parachute, for instance, has a large frontal area, $A$, and a shape that effectively "catches" the air, causing a high drag coefficient $C_d$. The drag force is thus higher and becomes equal to the weight of parachute-plus-person at a much lower speed, $v$.

*To your example, an incoming comet typically enters Earth's atmosphere at a fairly high speed, $v$. When drag starts to have an effect, the enormous speed causes an almost immediately enormous drag force* (note that the speeds is squared in the drag formula). This is why its front start burning with the enormous fluid friction it experiences. While burning at the front, it simultaneously is slowed down rapidly. Soon, the drag force is low enough to equal its weight, and then constant (terminal) speed has been reached.
These two scenarios - a parachute and a comet; something dropped from rest and something entering at high speed - illustrate the two different approaches to terminal speed: either the object starts at a lower-than-terminal-speed and speeds up until the drag has increased enough to balance out the weight, or the object starts at a higher-than-terminal-speed and slows down until the drag has reduced enough to balance out the weight.
In the former case, you see speeding up until constant speed, in the latter you see slowing down until constant speed. Only in the latter case can you see burning at the surface.

* Note that the air density, $\rho$, is lower (the air is thinner) high up and increases as the objects come closer to the ground. This would increase the drag force gradually, meaning that the drag force would become larger than the weight. The object will thus decelerate a bit and slow down a bit until they again balance out. This happens gradually. In other words: the terminal speed changes as the object falls - this is clear from the terminal speed formula which includes the air density:
$$\small{v_\text{terminal}=\sqrt{\frac{2mg}{\rho A C_d}}.}$$
The density quickly becomes fairly even and constant when closer to the ground, so the low-altitude skydiver might not experience such changing terminal speed but will indeed fall at a practically constant terminal speed.**
** In fact the gravitational acceleration, $g$, changes as well with altitude, which would also change the terminal speed gradually. But out atmosphere is not that thick (compared to the size of the planet and the extend of the change in $g$), so the density change happens much faster and is much larger than the $g$-change through the atmosphere, making the $g$-change often practically irrelevant, although it might be included in some delicate calculations.


text:
Q: How do I back up Redis sever RDB and AOF files for recovery to ensure minimal data loss? Purpose:
I am trying to make backup copies of both dump.rdb every X time and appendonly.aof every Y time so if the files get corrupted for whatever reason (or even just AOF's appendonly.aof file) I can restore my data from the dump.rdb.backup snapshot and then whatever else has changed since with the most recent copy of appendonly.aof.backup I have.
Situation:
I backup dump.rdb every 5 minutes, and backup appendonly.aof every 1 second.
Problems:
1) Since dump.rdb is being written in the background into a temporary file by a child process - what happens to the key changes that occurs while the child process is creating a new image? I know the AOF file will keep appending regardless of the background write, but does the new dump.rdb file contain the key changes too?
2) If dump.rdb does NOT contain the key changes, is there some way to figure out the exact point where the child process is being forked? That way I can keep track of the point after which the AOF file would have the most up to date information.
Thanks!

A: Usually, people use either RDB, either AOF as a persistence strategy. Having both of them is quite expensive. Running a dump every 5 min, and copying the aof file every second sounds awfully frequent. Except if the Redis instances only store a tiny amount of data, you will likely kill the I/O subsystem of your box.
Now, regarding your questions:
1) Semantic of the RDB mechanism
The dump mechanism exploits the copy-on-write mechanism implemented by modern OS kernels when the clone/fork processes. When the fork is done, the system just creates the background process by copying the page table. The pages themselves are shared between the two processes. If a write operation is done on a page by the Redis process, the OS will transparently duplicate the page (so than the Redis instance has its own version, and the background process the previous version). The background process has therefore the guarantee that the memory structures are kept constant (and therefore consistent).
The consequence is any write operation started after the fork will not be taken in the dump. The dump is a consistent snapshot taken at fork time.
2) Keeping track of the fork point
You can estimate the fork timestamp by running the INFO persistence command and calculating rdb_last_save_time - rdb_last_bgsave_time_sec, but it is not very accurate (second only).
To be a bit more accurate (millisecond), you can parse the Redis log file to extract the following lines:
[3813] 11 Apr 10:59:23.132 * Background saving started by pid 3816

You need at least the "notice" log level to see these lines.
As far as I know, there is no way to correlate a specific entry in the AOF to the fork operation of the RDB (i.e. it is not possible to be 100% accurate).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Feature 'f10fa067-3342-4d85-b5ac-92525d3491a7' for list template '10002' is not installed in this farm I got an error while try to run PSConfig."Feature 'f10fa067-3342-4d85-b5ac-92525d3491a7' for list template '10002' is not installed in this farm"
I did not find this feature neither in FeatureAdminTool nor with PowerShell. Only I find this in AllList table in Content database.Even I did not find in Features Table in Content Database
How to remove SharePoint Feature from Database
Anyone had faced this issue? Please help me to find solution for this.

A: Issue :-
This error happens because a list or library was created in your SharePoint site based on a given list template that is no longer available.
A common scenario for this type of error is a list that was created with a template defined by a feature that has since been uninstalled. This makes the list invalid because the template no longer exists.
Solution :-
Re-install the feature in your SharePoint farm to make the list template available again .
created on a custom template.
I suggest you get list template feature ID via following PowerShell code:
$SPWeb = Get-SPWeb "http://SiteURL"
$SPList = $SPWeb.Lists['ListName']
write-host $SPList.TemplateFeatureId
Then access List Template Gallery (_catalogs/lt/Forms/AllItems.aspx) to check if this template exists or has been checked in.


text:
Q: Blank screen on SlidingMenu when using with Fragment (GMap) So i use SlidingMenu library with a FragmentActivity in my app.
There is a GoogleMap in the layout and a menu on the left side with some content.
When i pull the menu to see it, there is a big black rectangle there, covering my sliding menu content. After i click it once, it is disapearing.
Can anybody has something to say about this?

A: I had the same issue on android 2.3.7 but not in 3.x or later versions. After rotating the view the menu renders fine after.
I found a solution using a custom TransparentSupportMapFragment from: Android MapView With Sliding Menu Obscures Menu

A: Fragment Black screen issue
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.v4.view.ViewPager
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
     </android.support.v4.view.ViewPager>

     <!-- hack to fix ugly black artefact with maps v2 -->
     <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent" />

</FrameLayout>

A: This is a known problem.
You may want to have a look at these issues:
http://code.google.com/p/gmaps-api-issues/issues/detail?id=4639
http://code.google.com/p/gmaps-api-issues/issues/detail?id=4659
Maybe you can find a workaround in comments there.

A: I know this question is too old but since I come here by chance and see there is no accpeted answer I will answer this.Hope it help someone someday.
My solution is add a light layout (about 1dp) with transparent background above the "Shopradar" layout of yours. This worked for me,hope it works for you too ;)


text:
Q: show multiple modal pop up in angularjs I'm using angularjs. What I want to do is to check student id in database by Angularjs, when the user  clicks a button.
If student id exists in database, #modal1 will be shown, otherwise #modal2 will be prompted. Is it possible to do this with angularjs? If possible how..
Html

  {{g.studentId}}
  {{g.studentName}}

        <button type="button" ng-click="act(g)" title="act" data-toggle="modal" data-target="#deleteModal"></button>

#Modal that will be displayed

                confirm delete?

                <button type="button" class="btn btn-primary" ng-click="delete()">Yes</button>
                <button type="button" class="btn btn-default" > No</button>

                Data already existed

Controller
$scope.act = function (g) {
    g.studentId;
}

A: In controller write code
$scope.act = function(g){
    /*
       write code for check student is in database
    */
   if(student_available == true){
       $("#modal1").modal('show');
   }
   else{
       $("#modal2").modal('show');
   }
}


text:
Q: rootfs 100% full debian I have a problem with full rootfs on Debian (on RPi). I noticed I can't start mysql server with error full partition. I tried looking for space hoggers with ncdu.
It all appeared suddenly and I have no idea what to do. I can't even run apt-get remove.
Thanks for your help!
rootfs            3731272 3714888        0 100% /
/dev/root         3731272 3714888        0 100% /
devtmpfs           242988       0   242988   0% /dev
tmpfs               49452     236    49216   1% /run
tmpfs                5120       0     5120   0% /run/lock
/dev/sda1        14872964 3144768 10949652  23% /media/usb0
/dev/sdb1        14872964 3355940 10738480  24% /media/usb1
/dev/sda1        14872964 3144768 10949652  23% /media/usb2
tmpfs               98900       0    98900   0% /run/shm
tmpfs               98900       0    98900   0% /tmp

sudo du / -h --max-depth=1
94M     /opt
5,2M    /bin
333M    /var
109M    /lib
1,8G    /usr
0       /tmp
6,3M    /sbin
16K     /lost+found
8,0K    /boot
4,0K    /selinux
192K    /home
4,0K    /usb
236K    /run
0       /proc
4,0K    /mnt
6,7M    /etc
9,1G    /media
4,0K    /srv
0       /sys
40K     /root
0       /dev
12G     /

du --one-file-system --max-depth=1 --human-readable /
94M     /opt
5,2M    /bin
333M    /var
109M    /lib
1,8G    /usr
0       /tmp
6,3M    /sbin
16K     /lost+found
8,0K    /boot
4,0K    /selinux
192K    /home
4,0K    /usb
0       /run
0       /proc
4,0K    /mnt
6,7M    /etc
36K     /media
4,0K    /srv
0       /sys
40K     /root
0       /dev
2,3G    /


text:
Q: Put Excel array values in cache I have a large database (700.000+ lines in 20 columns) that I import in Excel and do different manipulations on.
An example of such a manipulation is categorizing. For this I use 2 columns: material type and category and output it in a column 'Final Category' by:
IF materialType = "SERV" or category = "SERVICE" then finalCategory = "SERVICE"

What would be the fastest way to perform this calculation?
Currently I use a FOR loop and already disabled application.screenupdating.
I am also wondering, is there a way to put these columns in cache and then run it?
Hope you can help,
Cheers!

A: Let's say that the 'materialType' column is A and the 'category' column is B and the 'finalCategory' column is U. Then you can try this:
Dim strFormula As String

strFormula = "=IF(OR(A1=""SERV"",B1=""SERVICE""),""SERV"","""")"
Sheet1.Range("U1:U700000").Formula = strFormula

This avoids looping over the 700,000 rows and doing an indvidual operation, which can be painfully slow even with no screen updating.


text:
Q: How to make Reactstrap's ListGroup unstyled? I want to remove the boxes around the <ListGroupItems> in Reactstrap's <ListGroup>

A: Simply use Bootstrap's border-0 class under Borders Utility.
<ListGroup>
  <ListGroupItem className="border-0">Item 1</ListGroupItem>
  <ListGroupItem className="border-0">Item 2</ListGroupItem>
</ListGroup>


text:
Q: Translate a string then pass to ng-click I have a jade template which contains a list and it calls a method called change() when an item is clicked. In the example below, I want the change() method to be passed the paramaters "category" and "Jobs" (I'm using Angular Translate and have a translation file with "jobs" mapped to "Jobs"). However, the jade compiler doesn't like that and throws an error sayinf:
Syntax Error: Unexpected token
translate='jobs'

My code is:
ul.dropdown-menu
    li(ng-click='ctrl.change("category", translate='jobs')')
        a(translate='jobs')

change(dimensionKey, dimensionName) {

    console.log('in the change and arguments are ', arguments);

}

How can I translate a string then pass to ng-click?

A: You can use $filter to translate on javascript directly from your translation string ID. Just call the "translate" filter and pass your translation string parameter. For example:
var translate = this.$filter("translate");
var jobsTranslated= translate('jobs');


text:
Q: Querying SQLite database in Thunderbird I want to make a small Add-on for Thunderbird that uses an SQLite database. I've created my database with "SQLite Manager".
The problem is that when I access the database, I get the message that it is empty. But it isn't!
Database:
----------------------------
| table1 | table2 | table3 |
----------------------------
|  ...   |  ...   |  ...   |
|  ...   |  ...   |  ...   |
----------------------------

Here is the JavaScript code. It should return the name of tables, but I get 0.
  Components.utils.import("resource://gre/modules/Sqlite.jsm");
  Components.utils.import("resource://gre/modules/Task.jsm");

  Task.spawn(function() {
    let db;
    let result;
    try {

      db = yield Sqlite.openConnection({ path: "db.sqlite" });
      result = yield db.execute("SELECT name FROM sqlite_master WHERE type='table'");

      alert(result.length);

    } catch (ex) {
      alert("error: " + ex);
    } finally {
      if (db) yield db.close();
    }
  });

Can one tell me what I'm doing wrong?
Is it possible to import and then to read an already existing database in Thunderbird?
Thanks!

A: Looking at the source code for Sqlite.jsm, the path is always relative to the profile. You can however access the backstage pass of the module and copy/paste the code from openConnection. This is the object that holds the unexported symbols available in the module. Like this:
Components.utils.import("resource://gre/modules/FileUtils.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");
var {classes: Cc, interfaces: Ci, utils: Cu} = Components;

function openConnection2(path) {
  let Sqlite = Components.utils.import("resource://gre/modules/Sqlite.jsm", {});
  let file = FileUtils.File(path);
  let identifier = Sqlite.getIdentifierByPath(path);
  let openedOptions = {};

  return new Promise((resolve, reject) => {
    let dbOptions = null;
    Services.storage.openAsyncDatabase(file, dbOptions, (status, connection) => {
      if (!connection) {

        reject(new Error(`Could not open connection to ${path}: ${status}`));
        return;
      }
      log.info("Connection opened");
      try {
        resolve(
          new Sqlite.OpenedConnection(connection.QueryInterface(Ci.mozIStorageAsyncConnection),
                                      identifier, openedOptions));
      } catch (ex) {
        reject(ex);
      }
    });
  });
}

You can pass your own path here, this should be the full path. You can access your database by converting the chrome uri to a file uri:
let uri = Services.io.newURI("chrome://myext/content/db.sqlite", null, null);
let registry = Cc['@mozilla.org/chrome/chrome-registry;1']
                .getService(Ci.nsIChromeRegistry);
let path = registry.convertChromeURL(uri)
                   .QueryInterface(Ci.nsIFileURL)
                   .file.path;

yield openConnection2(path); // in your task

Note that you will need to specify em:unpack in your install.rdf to ensure that the converted uri is actually a file uri and not a jar: uri.


text:
Q: Triggering a State Change Between Sibling Components Total React noob here. I have two sibling Components in my React application. I want to display a Loading message in Component A when a certain method is executed in Component B
I'm familiar with passing state from a parent to child in React, but how can a sibling be notified to display it's loader?
Here's what I have so far
export default class ComponentA extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render(){
    return(
      {/* Loader */}
      { this.state.loading === true &&

      }
    )
  }
}

export default class ComponentB extends Component {
  // Constructor, bindings and stuff...

  getData(){
    // Update Component A's "loading" state here.
    // Once the data is fetched, set "loading" to false
  }
  render(){
    return(

         <button onClick="this.getData"></button>

             {/* ... */}

    )
  }
}

Setting up both Components to inherit state from a Parent Component doesn't seem desirable because I'll have many siblings with nested Components that I'll also want to trigger this loader
Any input is appreciated!

A: In React, data flows from the top, down. You'd need to wrap Component A and B in a parent and keep the state in the parent as a single point of truth.
However, as you have said after a while this can become tedious when dealing with components several levels deep. You don't want to have to keep passing the state down.
I'd suggest looking into Redux (the docs are excellent) as well as the container(smart)/component(dumb) architecture.
In addition to the links above, I'd really suggest taking the time to watch this free tutorial series from Redux's creator, Dan Abramov.
Hope that helps!

A: First of all, you said that Component A is a child component of Component B but I don't see any relationship between the two components. But you can do one of 2 things in my opinion. One is to import Component A into Component B as a child component and pass the data to Component A as props (easy). Second way requires you to understand redux. In this case, I don't see the necessity due to the size of the app. However, basically you can have a mastermind at the top of the React component tree to pass down the state to any component. So updating the store by dispatching the new data from Component B will enable Component A to have an access to the data. Redux would be great from large applications and for data that needs to be distributed in multiple places.


text:
Q: Antonym of "capital" What is the antonym of "capital" (in the sense of city of governmental seat)? A related question: is there a term for referring to the whole set of cities that are not the capital within a country (or state, province)?

A: Provincial. This is the term sometimes used in the UK.

A: The first word that comes to my mind is non-capital.
For example,

What are the largest non-capital cities in the
  world?

Minor, secondary or inferior also come to mind.


text:
Q: Using Ansible variables in testinfra Using TestInfra with Ansible backend for testing purposes. Everything goes fine except using Ansible itself while running tests
test.py
import pytest
def test_zabbix_agent_package(host):
    package = host.package("zabbix-agent")
    assert package.is_installed
    package_version = host.ansible("debug", "msg={{ zabbix_agent_version }}")["msg"]
    (...)

where zabbix_agent_version is an Ansible variable from group_vars. It can be obtained by running this playbook
- hosts: all
  become: true
  tasks:
  - name: debug
    debug: msg={{ zabbix_agent_version }}

command executing tests
pytest --connection=ansible --ansible-inventory=inventory  --hosts=$hosts -v test.py

ansible.cfg
[defaults]
timeout = 10
host_key_checking = False
library=library/
retry_files_enabled = False
roles_path=roles/
pipelining=true
ConnectTimeout=60
remote_user=deploy
private_key_file=/opt/jenkins/.ssh/deploy

the output I get is
self = <ansible>, module_name = 'debug', module_args = 'msg={{ zabbix_agent_version }}', check = True, kwargs = {}
result = {'failed': True, 'msg': "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'zabbix_agent_version' is undefined"}

    def __call__(self, module_name, module_args=None, check=True, **kwargs):
        if not self._host.backend.HAS_RUN_ANSIBLE:
            raise RuntimeError((
                "Ansible module is only available with ansible "
                "connection backend"))
        result = self._host.backend.run_ansible(
            module_name, module_args, check=check, **kwargs)
        if result.get("failed", False) is True:
>           raise AnsibleException(result)
E           AnsibleException: Unexpected error: {'failed': True,
E            'msg': u"the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'zabbix_agent_version' is undefined"}

/usr/lib/python2.7/site-packages/testinfra/modules/ansible.py:70: AnsibleException

Any idea why Ansible can't see this variable when running testinfra's Ansible module while it can see it while running Ansible alone?

A: If zabbix_agent_version is a variable set using group_vars, then it seems as if you should be accessing it using host.ansible.get_variables() rather than running debug task. In any case, both should work.  If I have, in my current directory:
test_myvar.py
group_vars/
  all.yml

And in group_vars/all.yml I have:
myvar: value

And in test_myvar.py I have:
def test_myvar_using_get_variables(host):
    all_variables = host.ansible.get_variables()
    assert 'myvar' in all_variables
    assert all_variables['myvar'] == 'myvalue'

def test_myvar_using_debug_var(host):
    result = host.ansible("debug", "var=myvar")
    assert 'myvar' in result
    assert result['myvar'] == 'myvalue'

def test_myvar_using_debug_msg(host):
    result = host.ansible("debug", "msg={{ myvar }}")
    assert 'msg' in result
    assert result['msg'] == 'myvalue'

Then all tests pass:
$ py.test --connection=ansible --ansible-inventory=hosts -v
test_myvar.py
============================= test session starts ==============================
platform linux2 -- Python 2.7.13, pytest-3.2.3, py-1.4.34, pluggy-0.4.0 -- /home/lars/env/common/bin/python2
cachedir: .cache
rootdir: /home/lars/tmp/testinfra, inifile:
plugins: testinfra-1.8.1.dev2
collected 3 items

test_myvar.py::test_myvar_using_get_variables[ansible://localhost] PASSED
test_myvar.py::test_myvar_using_debug_var[ansible://localhost] PASSED
test_myvar.py::test_myvar_using_debug_msg[ansible://localhost] PASSED

=========================== 3 passed in 1.77 seconds ===========================

Can you confirm that the layout of our files (in particular, the location of your group_vars directory relative to the your tests) matches what I've shown here?

A: I chased an answer to this for days.  Here's what finally worked for me.  Essentially you are using testinfra's Ansible module to access the include_vars function of Ansible.
import pytest

@pytest.fixture()
def AnsibleVars(host):
ansible_vars = host.ansible(
    "include_vars", "file=./group_vars/all/vars.yml")
return ansible_vars["ansible_facts"]

Then in my tests, I included the function as a parameter:
def test_something(host, AnsibleVars):

This solution was taken partially from https://github.com/metacloud/molecule/issues/151
I had an interesting issue where I was trying to include the variables from my main playbook and I was receiving an error of "must be stored as a dictionary/hash" when including the playbook.yml file.  Separating the variables out into the group_vars/all/vars.yml file resolved that error.


text:
Q: Is this a RESTful Web Service? An answer to the following question Difference between RESTful webservice and HttpServlet says "REST is really an architectural style used when designing an API on a server. HttpServlets can be a method of implementing a RESTful web service".
In that case, can i say that if i implement an HTTPServlet that can get a resource, let's say it accepts unique Employee Id and returns Employee object as atleast partially RESTful web service?
For example, Let's say i have written a servlet which accepts a unique employee id, and returns a JSON string that represents an employee object. This object includes Id, name & designation of that employee. The url looks like : http://hostname:port/Rest/Employee/{id}  .
Here id is the unique id for an employee. The following request gets me an employee with id as 1001:
http://hostname:port/Rest/Employee/1001
The response is a string, which looks like:
{"id": "1001", "name":"ayushi", "designation":"software engineer"}

My question here is: Can i call this as a RESTful web service?

A: This link could help you to know the structure of a RESTful service:

*

*Designing a Web API - https://templth.wordpress.com/2014/12/15/designing-a-web-api/
Servlets aren't designed for RESTful services "explicitely" but you can leverage them to implement such services like the way you did.
In fact, servlets don't integrate / define concepts of REST within their APIs. I mean resources, path variables, representations, conneg (content negociation). So you need something above / additional stuff to implement this.
A REST framework like Restlet directly provides such concepts within its API.
Hope it helps you,
Thierry


text:
Q: how to create below mysql query in kohana query builder How can i create below query in Kohana Db Builder
SELECT @i:=0;
UPDATE `table_name`
SET `order` = @i:=@i+1
where `column_name`= '3337'

A: Try to separate queries!
$q1 = DB::query(NULL, "SELECT @i:=0");
$q2 = DB::update('table_name')
        ->set(array('order','=',DB::expr('@i:=@i+1')))
        ->where('column_name','=','3337');

$q1->execute();
$q2->execute();


text:
Q: Shoutcast URL does not stream on JPlayer, but does on another flash player? I'm trying to stream http://gwradio.serverroom.us:4142/;stream.mp3 using JPlayer, but nothing happens when I try to play the stream.
Here's a test of the JPlayer code that has been confirmed to play other streams
var stream = {
    title: "WRGW TEST",
    mp3: "http://gwradio.serverroom.us:4142/;stream.mp3"
},
ready = false;

$("#jquery_jplayer_1").jPlayer({
    ready: function (event) {
        ready = true;
        $(this).jPlayer("setMedia", stream);
    },
    pause: function() {
        $(this).jPlayer("clearMedia");
    },
    error: function(event) {
        if(ready && event.jPlayer.error.type === $.jPlayer.error.URL_NOT_SET) {
            // Setup the media stream again and play it.
            $(this).jPlayer("setMedia", stream).jPlayer("play");
        }
    },
    swfPath: "../dist/jplayer",
    supplied: "mp3",
    preload: "none",
    wmode: "window",
    useStateClassSkin: true,
    autoBlur: false,
    keyEnabled: true
});

$("#jplayer_inspector").jPlayerInspector({jPlayer:$("#jquery_jplayer_1")});

Here is the same URL working with another flash player: http://www.ep.gwradio.com/
Where's the beef? Can anyone help me out with this?

A: Your stream is served via SHOUTcast which does not send standards-compliant HTTP responses.  jPlayer will use native HTML5 audio in your browser, as well as Flash, to play your audio.  Your other player likely has hacks in place needed to support SHOUTcast-style streams.
You can use something like Icecast which follows HTTP specs more closely.

A: Resolved - the issue was the server version of Shoutcast being used. Updating the server version fixed the problem.


text:
Q: passing props from parent to child in react class based component I am new to react and cannot figure out how to pass data received from the server from a parent component to a child component as such:
//parent component
class AlumniComponent extends React.Component {

    state = {
        profile : {},
        error: false
    }

    componentDidMount(){
        Axios.get('https://jsonplaceholder.typicode.com/users/1')
        .then(response=>{
            // console.log(response.data);
            this.setState({profile: response.data})
        })
        .catch(error=>{
            console.log(error);
            this.setState({error: true})
        })
    }

    render() {

        const profile = this.state.profile;

        return(
            <AboutComponent data={profile} tab="about"/>
        );
    }

In my child component:
class AboutComponent extends React.Component {

    constructor(props){
        super(props);

        this.state = {
            data: {
                name: props.data   // <--- the props are coming coming from the parent component !?
            },
            selectedOption: null,
        };
    }

render (){

return (
      <Form.Control type="text" value={JSON.stringify(this.state.data)} disabled />
);
}

the input value comes out as empty object: {"name":{}}

A: I'd try to stay away from storing props inside of state so that your parent and children components don't get out of sync. Instead, use what you need from the props inside of children and then if you need to store some other information based on the props that are passed, use state for that.
Here's an example:

class AlumniComponent extends React.Component {
  state = {
    profile: {},
    isLoading: true,
    error: false
  };

  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/users/1")
      .then(res => res.json())
      .then(data => {
        this.setState({
          profile: data,
          isLoading: false
        });
      })
      .catch(error => {
        this.setState({
          error: error.message,
          isLoading: false
        });
      });
  }

  render() {
    const { profile, isLoading, error } = this.state;

    if (isLoading) {
      return `Loading`;
    }
    if (!isLoading && error) {
      return `Something went wrong`;
    }
    return <AboutComponent data={profile} />;
  }
}

class AboutComponent extends React.Component {
  constructor(props) {
    super(props);

    const initialState = {
       name: this.props.data.name,
       selectedOption: null
    }
    this.state = { ...initialState }
  }

  handleChange = event => {
    this.setState({
      name: event.target.value
    });
  };

  render() {
    const { name } = this.state;

    return <input type="text" value={name} onChange={this.handleChange} />;
  }
}

function App() {
  return (

      <AlumniComponent />

  );
}

ReactDOM.render(
  <App />,
  document.getElementById("app")
)

Also, I don't know what the <Form.Control /> component is expecting for the value property, but make sure you grab the right information that you need instead of passing the entire prop/object into it.
class AboutComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      name: this.props.data.name
    }
  }

  handleChange = (event) => {
    this.setState({
      name: event.target.name
    })
  }

  render() {
    return (
      <Form.Control
        type="text"
        value={this.state.name}
        onChange={this.handleChange}
        disabled
      />
    )
  }
}

A: You forgot this this.props.data but this an anti pattern
 this.state = {
  data: {
    name: this.props.data,
  },
};

You should do it in componentDidMount()
componentDidMount(){
  this.setState({name:this.props.data.name})
}

Then:
 <Form.Control type="text" value={this.state.name} disabled />


text:
Q: How does average treatment effect relate to averages of individual treatment effects? I have a balanced panel with two groups, A and B, and run a standard fixed effects regression. I want to derive how the $\beta$ coefficients of these two regressions are related:
\begin{eqnarray}
y_{it} &=& \beta x_{it} & + \alpha_i + \epsilon_{it} \\
y_{it} &=& \mathbb{I}(i=A) \beta_A x_{it} + \mathbb{I}(i=B) \beta_B x_{it} & +\alpha_i + \epsilon_{it}
\end{eqnarray}
In my application, the case arises that the estimate of the average treatment effect is very far from the unweighted averages of the interacted treatment effect estimates, i.e.
$\hat{\beta} \neq \frac{\hat{\beta}_A + \hat{\beta}_B}{2}$.
So I want to understand how OLS does the "weighting" of the two groups when computing $\hat{\beta}$
What I would ideally like to find is a formula that relates $\beta$, $\beta_i$ and the covariances of my $x_{it}$s.

A: Let $\tilde{y}_{it}$ and $\tilde{x}_{it}$ denote the group-demeaned variables. Now we run three bivariate regressions:
\begin{eqnarray}
\tilde{y}_{it} &=& \beta \tilde{x}_{it} & + \epsilon_{it} \\
\tilde{y}_{it} &=& {\beta}_A \tilde{x}_{it} & + \epsilon_{it} & \text{   if   } i=A \\
\tilde{y}_{it} &=& {\beta}_B \tilde{x}_{it} & + \epsilon_{it} & \text{   if   } i=B \\
\end{eqnarray}
Now write the estimate of each coefficient as a function of expected values:
\begin{eqnarray}
\hat{\beta}_{A} = \frac{Cov(\tilde{x}_{At},\tilde{y}_{At})}{Var(\tilde{x}_{At})} =
\frac{E(\tilde{x}_{At} \times \tilde{y}_{At}) - E(\tilde{x}_{At})E(\tilde{y}_{At})}{ E(\tilde{x}_{At}^2) - E(\tilde{x}_{At})^2} =
\frac{E(\tilde{x}_{At} \times \tilde{y}_{At})}{ E(\tilde{x}_{At}^2)}
\end{eqnarray}
where the last equality follows by definition because the tilde variables have been de-meaned by group. Proceeding analogously for group and then $\beta$, I can write my overall coefficient as:
\begin{eqnarray}
\hat{\beta} =& \left(\frac{E(\tilde{x}_{At}^2)}{E(\tilde{x}_{At}^2) + E(\tilde{x}_{Bt}^2)}\right)\hat{\beta}_A + \left(\frac{E(\tilde{x}_{Bt}^2)}{E(\tilde{x}_{At}^2) + E(\tilde{x}_{Bt}^2)}\right)\hat{\beta}_B  \\
  = & \left(\frac{Var(\tilde{x}_{At})}{Var(\tilde{x}_{At}) + Var(\tilde{x}_{Bt})}\right)\hat{\beta}_A + \left(\frac{Var(\tilde{x}_{Bt})}{Var(\tilde{x}_{At}) + Var(\tilde{x}_{Bt})}\right)\hat{\beta}_B
\end{eqnarray}
Thus, the "average treatment effect" is a weighted average of the individual treatment effects, where the weight is proportional to the variance of the explanatory variable within the group.
Numerical Example
require(dplyr); n = 10^6; set.seed(1)
sim.l <- data.frame(t = 1:n) %>% mutate(
  e.common = rnorm(n),
  x.A = 5 + e.common + rnorm(n),
  x.B = (e.common*4 + rnorm(n))/15,
  y.A = x.A + rnorm(n),
  y.B = x.A + rnorm(n)
)
# most of the variation in x.B is driven by common shock, but var x.B << var x.A
round(cov(sim.l[,-c(1:2)]), digits = 2)

sim.p <- sim.l %>% melt(id.var = 't') %>% mutate(
  var = str_extract(variable,'^(.)'),
  group = str_extract(variable,'(.)$')
) %>% dcast(t + group ~  var, value.var = 'value');
lm(y ~ x:group + group, data=sim.p)
lm(y ~ x + group, data=sim.p)

This reproduces the case where the Average treatment effect (shown in column 2) is almost exactly equal to the treatment effect of group A shown in column 1:
===========================================
             Model 1         Model 2
-------------------------------------------
(Intercept)       -0.00           -0.46 ***
                  (0.00)          (0.00)
groupB             5.00 ***        5.46 ***
                  (0.00)          (0.00)
x:groupA           1.00 ***
                  (0.00)
x:groupB           3.53 ***
                  (0.00)
x                                  1.09 ***
                                  (0.00)
-------------------------------------------
R^2                0.49            0.41
Adj. R^2           0.49            0.41
Num. obs.    2000000         2000000
RMSE               1.24            1.33
===========================================
*** p < 0.001, ** p < 0.01, * p < 0.05

Based on the formula derived above, we can exactly reproduce these coefficients:
      x.A    x.B    y.A    y.B
x.A 2.0032 0.2669 2.0034 2.0028
x.B 0.2669 0.0756 0.2670 0.2667
y.A 2.0034 0.2670 3.0050 2.0038
y.B 2.0028 0.2667 2.0038 3.0045

beta_A = 2.0028/2.0032
beta_B = 0.2667/0.0756
beta   = (0.0756*beta_b   + 2.0028*beta_a)/(2.0028 + 0.0756)


text:
Q: My data has no nan but I keep getting the finite error Context
I am trying to normalise my data to run a ML model. I am using np.log on my data
plt.hist(np.log(Portfolio_rtns['Aveva Returns']))

I also tried this way:
log_Aveva = np.log(Portfolio_rtns['Aveva Returns'])
log_Aveva.hist();

But get this error
ValueError: supplied range of [-inf, -1.2977785811129585] is not finite

I checked my data and even made sure to replace any nan values with 0.
I found this which states to use the np.isfinite. But I feel as though my data distribution is messed up because of it.
Port = np.isfinite(Portfolio_rtns['Aveva Returns'])
plt.hist(np.log(Port));

I also ran this function
# Square root can also make normal distributed data
plt.hist(np.sqrt(Portfolio_rtns['Aveva Returns']));

Though I got the graph, I got this error with it:
358: RuntimeWarning: invalid value encountered in sqrt
  result = getattr(ufunc, method)(*inputs, **kwargs)

Problem
Is there a problem with my data?

A: So having perused around Coursera, I found that using log1p adds 1 to all the zero numbers in the entirety of the data. Also gets rid of the negative. So the solution is:
plt.hist(np.log1p(Portfolio_rtns['Aveva Returns']));

or

*

*data.describe() #'data' being your data.

*Find the minimum of the data

*Add this minimum to the entirety of the data to convert all zero and negative to positive and more than 0.

*Run the data

*After running ML model, convert back to the normal value (this is for the above also)


text:
Q: hovering over a button without triggering a change of the mouse pointer I have a button on my site which activates a pop up contact form.
This button is constructed like this:
Contact

Though I want to remove the "a href" part, so that it can't be seen as a link.
If I use the following:

Contact

Then the a href is removed but the mouse changes into the following when hovering:

Though I'd like it to stay in its normal form when hovering:

Thought it would work with:
Contact

But it doesn't. The mouse stays in its right form when hovering, but the word "Contact" is not visible with this example.
Anyone can think of a solution (without having to make an image for the button)?
Thanks in advance
Steven

A: Add a CSS cursor property to your
 tag or the respective class. (MDN document):
.button {
  /* your other styles */
  cursor: default
}

A: Try this css :
.button{
   cursor: default;
}


text:
Q: Get Mobile Number from iPhone Am I able to get the user's mobile number of the iPhone device? (of cause without asking the user for this information)

A: No. Apple's APIs do not provide access to this information. What's more, attempting to get this information without asking the user is generally considered a huge breach of privacy.

A: You could try to look it up in the address book if you know who the user is.  Otherwise, yeah, the easiest thing to do is ask the user to enter it and store it as a preference.


text:
Q: LabView Control (.ctl) to VB.NET Structure I created a control in LabView.  My LabView code writes data of that type to a binary file.  I want to read this data into a VB Structure.
Can I do this programmatically, or do I need to manually create a corresponding structure?

A: I'm not a .NET programmer, so I can't give a proper answer, but I doubt the data types are compatible (for example, LabVIEW is big endian, whereas VB.NET is little endian, so you would need to reverse the byte order on multibyte values, although I believe later LV versions allow you to change this when flattening the data).
There's a section in the LabVIEW help which describes how LV stores data in memory and flattened (on disk, in your case) and I don't think you'll have any choice other than to write code which will read the binary data and convert it to the VB.NET format (although one option which might be relevant is writing an LV DLL which will read the data and then output it in a cluster which can be imported into VB.NET as a structure. Such a solution will require you to have the LV RTE on every PC where you want to run this).


text:
Q: Capacitor sizing on a voltage regulator output I have an application in which an RFID reader demands 200 mA of current when it attempts to read an RFID tag. For some reason the current switcher power supply either can't supply enough current or can't supply a clean enough voltage and I end up with a poor performance on the reader.
I want to use a standard LM7805CT regulator in place of the switcher, but how large of a capacitor should I use? The datasheet suggests 0.1 uF, but I'm not sure that is large enough since the reader gets turned on and off a lot.
I am regulating down from a 24 V battery (it is pushing the limit of that particular regulator, but I will add active heatskinking to it).

A: The 100 nF capacitor on the output is an important component for the stability of the regulator's control loop. It's not there to catch fast load changes; for that its value is too low.
A voltage regulator needs a short time to respond to load changes. This may seem like an imperfection but it's a requirement actually; a regulator with zero delay would not be stable.
Switching the reader on and off causes fast load changes. It won't be anything like 1 A/µs (which is damn fast), but fast enough to let the 5 V output sag for a moment. Russell calculated a value of 40000 µF to allow a 100 ms holdup, but you won't need that, the LM7805 will respond much faster than that (I would love to see more dynamic performance graphs in datasheets, especially step response!). For 200 mA steps a value of 100 µF should be fine. If you want to add a much larger value, like the 40000 µF it should be at the regulator's input, not the output.
edit
The guys at Diodes do include dynamic performance data in their AP1117 datasheet:

This shows an output voltage spike of a mere 15 mV for a 700 mA load change. The LM7805 is a much older design, and the figures won't be that good, but they give you an idea.
(end of edit)
I second Russell's suggestion for a series resistor to take most of the dissipation away from the regulator. At 200 mA a 56 Ω resistor will still give you 8 V input with a battery voltage of 20 V. The resistor will dissipate 2.25 W, so take a 5 W part for that. At 24 V in the regulator will have to handle 1.6 W, which it can do with a moderate heatsink. (Russell get a much lower dissipation, but he doesn't have any headroom in case the input voltage will sag.)

A: Use an air cooled power resistor in series with the regulator to drop most of the voltage. No heat sink needed. Run regulato at say 8V in. Presistor at 200 mA = VxI = (24-8) x 0.2 = 3.2 Watt. Pregulator = (8-5) x 0.2 = 0.6 Watt.
7805 regulators are very ancient. Better performance modern ones exist.
If your reader does not ever draw > 200 mA then a 1A regulator will handle it with ease if the input supply can provide the current.
Read data sheet. LM7805 says larger capacitors can be used at output if desired.
 C ~= t x I / V
 Where  t = holdup or current supply time
 I = current drawn
 V = voltage droop during time t
 C = capacitance.
At 200 mA, 0.5V droop, 0.1S holdup
 C = 0.1 x 0.2 / 0.5 = 0.04F = 40 mF = 40,000 microfarad.
 Usually much less is OK.
 There is no reason why the regulator cannot do this mostly by itself if Iin is adequate.


text:
Q: Divide each column sum by the sum of the matrix If I have a dataframe:
d = data.frame(sample=c("a2","a3"),a=c(1,5),b=c(4,5),c=c(6,4))
d
    sample a b c
1     a2 1 4 6
2     a3 5 5 4

How do I divide the sum of each column by the sum of the entire dataframe using dplyr so I end up with a dataframe that looks like:
     a b c
1    6/25 9/25 10/25

I tried to do
d <- d %>%
mutate_if(is.numeric, funs(colSums(d)/sum(d)))

but keeps returning erroring.
Thanks in advance!

A: Except for 2a and 2b, in each of these alternatives we could replace the first two components of the pipeline with d[-1] if it is ok to assume that we know that only the first column is non-numeric.
1) Base R With base R we get a straight forward solution:
d |> Filter(f = is.numeric) |> colSums() |> prop.table()
##    a    b    c
## 0.24 0.36 0.40

2) dplyr With dplyr:
library(dplyr)

d %>%
  select(where(is.numeric)) %>%
  summarize(across(.fn = sum) / sum(.))
##      a    b   c
## 1 0.24 0.36 0.4

2a) or
d %>%
  summarize(across(where(is.numeric), sum)) %>%
  { . / sum(.) }

2b) The scoped functions such as the *_if functions are not used these days having been superseded by across but they are still available so if  you want to use them anyways then try this which is close to the code in the question:
d %>%
  summarize_if(is.numeric, sum) %>%
  { . / sum(.) }

3) collapse  With the collapse package, get the numeric variables (nv), sum each column (fsum) and then take proportions.  When I benchmarked it on this data it ran 3x faster than (1), over 100x faster than (2) and 300x faster than (4).
library(collapse)
d |> nv() |> fsum() |> fsum(TRA = "/")
##    a    b    c
## 0.24 0.36 0.40

4) dplyr/tidyr With tidyr and dplyr we can convert to long form, process and convert back.
library(dplyr)
library(tidyr)
d %>%
  select(where(is.numeric)) %>%
  pivot_longer(everything()) %>%
  group_by(name) %>%
  summarize(value = sum(value) / sum(.$value), .groups = "drop") %>%
  pivot_wider
## # A tibble: 1 x 3
##       a     b     c
##   <dbl> <dbl> <dbl>
## 1  0.24  0.36   0.4

A: We could use colSums and the sum of colSums. -1 excludes column1 for calculation
result <- colSums(d[,-1])/sum(colSums(d[,-1]))
result

Output:
   a    b    c
0.24 0.36 0.40

A: One dplyr possibility could be:
d %>%
    summarise(across(-1, sum)/sum(cur_data()[-1]))

     a    b   c
1 0.24 0.36 0.4

Or:
d %>%
    summarise(across(where(is.numeric), sum)/sum(across(where(is.numeric))))

A: Another base R option
> colSums(d[-1] / sum(d[-1]))
   a    b    c
0.24 0.36 0.40


text:
Q: Object reference not set to an instance of an object, Unity Dependency Resolver My IUserService is null, not sure what's going on.
This is my AccountController:
private readonly ICustomMembershipProvider _membershipProvider;

public AccountController(ICustomMembershipProvider provider)
{
     _membershipProvider = provider;
}
//other code omitted

My CustomMembershipProvider:
public class CustomMembershipProvider : MembershipProvider, ICustomMembershipProvider
{
private IUserService _userService;

    public CustomMembershipProvider()
        : this(DependencyResolver.Current.GetService<IUserService>())
    {
    }

    public CustomMembershipProvider(IUserService userService)
    {
        _userService = userService;
    }
//other code omitted

When I try to register a user, and the following method is called, my _userService is null, and that's what is causing the error but not sure why it's happening.
public override MembershipUser GetUser(string username, bool userIsOnline)
{
    var tempUser = _userService.GetByName(username);
//other code omitted

All other dependencies get resolved successfully

A: Adding this answer since I spent multiple hours trying to figure out what this error was referring to. My Project had this warning: Warning: Found conflicts between different versions of the same dependent assembly , since it was a warning I didn't pay attention to it. Well, apparently that was the root of all problems, my Project.Web was using Mvc 3.0, while my Project.Services was using Mvc 4.0, this is why the DependencyResolver.Current.GetService<IUserService>() was not working. After I rolled back my Project.Services to Mvc 3.0, my entire solution worked like a charm! Lesson learned: pay attention to warnings.


text:
Q: How can one clean the data written before in the form? I am currently trying out python's web.py module by making a small form. I wrote one, and received input from the user and wrote them to a (mysql) database table. Every thing is fine, except for one issue. When I run the program and write something in one of the form's fields, it persists to the next time I want to write in that field. How can I reset the field after receiving the data?
this is my code:
import web
import MySQLdb
url=('/search', 'search_by_name')
db=web.database(dbn='mysql' ,db='std',user='root', pw='123456')
tmpl=web.template.render('templates/')

class search_by_name:
   form=web.form.Form(
                      web.form.Textbox('username',vpass,web.form.notnull),
                      web.form.Button('search')
                      )
    def GET(self):
        return tmpl.page( self.form)

    def POST(self):
        form=self.form
        if not form.validates():
            return tmpl.page(form)
        else:
            name=form['username'].value
            a=db.select('student',  where="name=$name", vars=locals())
            row=list(a)
            if row:
                col=row[0]
                return tmpl.table(row,col)
            else:
                return tmpl.message("There isn't student with this name in list")

app=web.application (url,globals())
if __name__=='__main__':
    app.run()


text:
Q: Add imageview in listview with a raw file I want to make a soundboard. For this, I have made a listview with a xml file (for the name and the sound).
For first, I have made a listview with the title of the sound. When we click on it, the sound is played.
MainActivity:
 mSoundPlayer = new SoundPlayer(this);
        Sound[] soundArray = SoundStore.getSounds(this);

        ListView listView = (ListView) findViewById(R.id.listView);

        final ArrayAdapter<Sound> adapter =
                new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, soundArray);

        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                Sound sound = (Sound) parent.getItemAtPosition(position);
                mSoundPlayer.playSound(sound);
            }
        });

I use a xml file for indexing the name of sounds and the sounds.
File : arrays.xml :
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="labels">
        <item>First sound</item>
        <item>Second soung</item>
    </string-array>

    <integer-array name="ids">
        <item>@raw/a1</item>
        <item>@raw/a2</item>
    </integer-array>
</resources>

And for the last, my layout :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="0dp"
    android:paddingRight="0dp"
    android:paddingTop="0dp"
    android:paddingBottom="0dp"
    tools:context="com.clemb.sardboard.MainActivity">

    <ListView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/listView"
        android:numColumns="auto_fit"
        android:gravity="center"
        android:columnWidth="100dp"
        android:verticalSpacing="5dp"
        android:stretchMode="columnWidth"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
</RelativeLayout>

I just want to know how to add a picture before the name of the sound. And can i do it in my array.xml ?
Thank you.

A: You need to create a custom array adapter. Custom Array adapter and Codepath - Custom ArrayAdapter are some examples.

And can i do it in my array?

Not in xml. There is ArrayList for this purpose.

A: I think this question can be answered in this post: How to add an icon to a listview in a fragment
In your scenario, you'd just need to make the appropriate changes to use in an activity, rather than a fragment. Conceptually it should be the same. You're customizing the layout for each list item to include an imageview.

A: You can add images to your array.xml, take a look here Storing R.drawable IDs in XML array
To set the image before the name you need to create your own ArrayAdapter to use with your ListView
SoundItemAdapter adapter =
        new SoundItemAdapter(this, android.R.layout.sound_item, soundArray);

listView.setAdapter(adapter);

... ArrayAdapter
public class SoundItemAdapter extends ArrayAdapter<Sound> {
    private ArrayList<Sound> sounds;
    private int soundItemLayoutId;
    private Context context;

    public SoundItemAdapter(Context context, int soundItemLayoutId, ArrayList<Sound> sounds) {
        super(context, soundItemLayoutId, sounds);
        this.context=context;
        this.soundItemLayoutId = soundItemLayoutId;
        this.sounds = sounds;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolderItem viewHolder;
        if(convertView==null){
            convertView = LayoutInflater.from(context).inflate(soundItemLayoutId, parent, false);
            //set up a ViewHolder to avoid calling findViewById() on every call to getView == smoother scroll
            viewHolder = new ViewHolderItem();
            viewHolder.name = (TextView) convertView.findViewById(R.id.name);
            viewHolder.image = (ImageView) convertView.findViewById(R.id.image);
            // store the holder with the view.
            convertView.setTag(viewHolder);
        } else {
             // return the viewHolder
            viewHolder = (ViewHolderItem) convertView.getTag();
        }

        Sound sound = sounds.get(position);
        if (sound != null) {
            viewHolder.name.setText(sound.name);
            viewHolder.image.setImageDrawable(ContextCompat.getDrawable(context,sound.image));
        }
        return convertView;
        }

    class ViewHolderItem {
        TextView name;
        ImageView image;
    }
}

sound_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeight">

    <ImageView
        android:layout_width="56dp"
        android:layout_height="match_parent"
        tools:src="@android:drawable/ic_media_play"
        android:id="@+id/image" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="start|center"
        android:textAppearance="?android:attr/textAppearanceMedium"
        tools:text="Sound Name"
        android:id="@+id/name"
        android:layout_weight="1" />
</LinearLayout>


text:
Q: how to check the string array is empty or null android? I am new to java. Am unable to check for null. Could you enlighten me on this?
I have string array which has no elements.
I tried this code
String[] k = new String[3];
if(k==null){
    System.out.println(k.length);
}

A: There's a key difference between a null array and an empty array. This is a test for null.
int arr[] = null;
if (arr == null) {
  System.out.println("array is null");
}

"Empty" here has no official meaning. I'm choosing to define empty as having 0 elements:
arr = new int[0];
if (arr.length == 0) {
  System.out.println("array is empty");
}

An alternative definition of "empty" is if all the elements are null:
Object arr[] = new Object[10];
boolean empty = true;
for (int i=0; i<arr.length; i++) {
  if (arr[i] != null) {
    empty = false;
    break;
  }
}

or
Object arr[] = new Object[10];
boolean empty = true;
for (Object ob : arr) {
  if (ob != null) {
    empty = false;
    break;
  }
}

 Reference

A: Very precisely
if(k!=null && k.length>0){
    System.out.println(k.length);
}else
    System.out.println("Array is not initialized or empty");

k!=null would check array is not null. And StringArray#length>0 would return it is not empty[you can also trim before check length which discard white spaces].
Some related popular question -

*

*What is null in java?

*Avoiding "!= null" statements in Java?

A: if (myArray == null)

   System.Console.WriteLine("array is not initialized");

else if (myArray.Length < 1)

   System.Console.WriteLine("array is empty");

A: String k[] = new String[3];

if(k.length == 0 ){

System.out.println("Null");
}

it will display null if there is no item in array.

A: I think you can use this:
if(str != null && !str.isEmpty())

UPDATE
Better solution is this one:
TextUtils.isEmpty(str)


text:
Q: Repeated variable length regexp matching I have an expression
AA-BB/CC/DD

I want to convert this to
<AA-BB> <AA-CC> <AA-DD>

All I can do is configure this as a regexp substitution. I can't figure it out.
AA should match at the beginning of a line. - and / are literal characters, BB,CC and DD are numbers, i.e \d+
So a first draft is ...
^(\w+)([\-/]\d+)+

but I want all matches, not just the greedy one.
(actually this one matches AA-BB-CC-DD too, but that's ok although it's not according to spec)

A: No, you can't do that with regex. Probably with .net, because there you can access all intermediate results of repeated capturing groups ...
Repeating a Capturing Group vs. Capturing a Repeated Group
That is the problem, if you do something like ^(\w+)([\-/]\w+)+ the value stored in group2 is always only the last pattern it matched. Your task is not possible with regex/replace.
I would do something like:
^(\w+)-([\w+\/]+)

Then split the content of group 2 by "/" and combine group1 with each element of the array resulting from the split.


text:
Q: How to test source_gen annotation builders using testBuilder? I have a code generator made using source_gen. It is working properly, but I would like to add tests.
I followed the documentation and took inspiration from built_value by using testBuilder from build_test.
The problem is, when using testBuilder, it cannot properly resolve imports. And therefore throws an error and doesn't trigger my generator.

Error: line 1, column 91 of asset:example/lib/src/truc.dart: Could not resolve annotation for foo() → dynamic\n'

Here's my current test attempt :
import 'package:source_gen/source_gen.dart';
import 'package:test/test.dart';
import 'package:build_test/build_test.dart';
import 'package:my_gen/my_gen.dart';

const input = {
  "example|lib/src/foo.dart": '''
import 'package:my_gen/my_gen.dart';
import 'package:flutter/material.dart';

@stateless
Widget foo() {
  return Center();
}
'''
};

void main() {
  test('', () async {
    await testBuilder(SharedPartBuilder([MyGenerator], "stateless"), input, outputs: {
      "example|lib/src/foo.stateless.g.part": '''
// **************************************************************************
// StatelessGenerator
// **************************************************************************

class Foo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return foo();
  }
}
'''
    });
  });
}

How can I make testBuilder to properly resolve import; and ultimately test by generator?

A: Look at what we do in json_serializable - https://github.com/dart-lang/json_serializable/blob/master/json_serializable/test/json_serializable_test.dart
We don't use build_test. Instead we have a utility library that gets a library reader you can use for testing - https://github.com/dart-lang/json_serializable/blob/master/json_serializable/test/analysis_utils.dart


text:
Q: jquery get radio button value all i want is to use the .get function to retrieve the selected/checked radio button value, i think i got the code right, but the sequence is kinda wrong
$.get('burgerorder_check.php', function(data) {
                inputVal = $('input[type=radio][name=timeslot]:checked').val();
            });

then after i get the inputVal, i want to reload a particular div with that specific input
    setInterval(getData,1000);
    getData();
    function getData(){
    if( inputField ) {
    $("#timeslot").load('burgerorder_check.php?dateselect='+inputField+'&inputselect=a'+inputVal);
    };

any help? So far the inputVal value is null :(
Full block of code :
$(document).ready(function(){
        var inputField;
        var inputVal;

        $("#dateslot").change(function(){
        inputField = $('#dateslot').val();
        });

        $.get('burgerorder_check.php', function(data) {
            inputVal = $('input[type=radio][name=timeslot]:checked').val();
        });

        setInterval(getData,1000);
        getData();
        function getData(){
        if( inputField ) {
        $("#timeslot").load('burgerorder_check.php?dateselect='+inputField+'&inputselect=a'+inputVal);
        };
        };

});

A: $('input[name='radio_button_name']:checked').val()

A: Try this
I hope to be able to help you
Jquery Code:
$("#ssss").bind("change",function(value){
    var test = $(this).children(":checked").val();
    alert(test)
})

HTML Code:

   <input type="radio" name='test'  value="red">  Red

   <input type="radio" name='test' value="green"> Green

   <input type="radio" name='test' value="blue"> Blue

http://jsfiddle.net/5qbG6/6/

A: Try This:
$("input[name='RadioButtonId']:checked").val()

$.get('burgerorder_check.php', function(data) {
                inputVal = $("input[name='timeslot']:checked").val()
            });

A: var timeslot = $("#timeslot:checked").val();
alert(timeslot );


text:
Q: Translating matplotlib plot axes labels in jupyter notebooks I have written a notebook that prepares several plots which I will later embed in an article. However, this article will be publisihed in different languages. I wonder if there is a simple way of translating the strings that appear in a Jupyter notebook, so I can generate the same figures, but with the appropriate language for the plots.
I had in mind something like the Django approach, in which you can compile a po file based on what gettext finds, but I honestly wouldn't know how to get started within a notebook.


text:
Q: If $\kappa$ is infinite and $\kappa$ is not a sum of $<\kappa$ cardinals each less than $\kappa$, then $\kappa$ is regular.
An infinite cardinal $\kappa$ is regular if $\mathrm{cf}(\kappa) = \kappa$.

It is known that if $\kappa$ is regular, then for any family $(\kappa_i)_{i \in I}$ of cardinals $\kappa_i < \kappa$ with $|I| < \kappa$ $\kappa \neq \sum_{i \in I} \kappa_i$.
I want to prove the converse: let $\kappa$ be an infinite cardinal; if for any family $(\kappa_i)_{i\in I}$ of cardinals $\kappa_i < \kappa$ with $|I| < \kappa$ we have $\kappa \neq \sum_{i \in I} \kappa_i$, then $\kappa$ is regular.
One should possbily proceed by contradiction. Assume that $\mathrm{cf}(\kappa) < \kappa$. Then there is an ordinal $\alpha < \kappa$ for which there is a cofinal map $f\colon\alpha\to\kappa$, that is, a map $f\colon \alpha\to\kappa$ so that $(\forall \beta < \kappa)(\exists \gamma < \alpha)(\beta \leq f(\gamma))$. From this we should somehow derive a contradicting by showing that $\kappa$ is equal to $\sum_{i \in I} \kappa_i$ for some family $(\kappa_i)_{i \in I}$ of cardinals.

A: There really is only one option that sticks out: $$\sum_{\gamma\in\alpha}f(\gamma)$$


text:
Q: Double-slit experiment with electron waves and the resulting interference pattern Let's consider a setup where I have two slits separated by distance $a$. Let's say initially, the electron wave passes through the two slits undisturbed and then form an interference pattern. I assume that just as is the case in the classical double-slit experiment, the central bright peak is symmetrically at the center of the observing screen.
Let's say now I have an Aharonv-Bohm setup with a long solenoid that with field B perpendicular to the plane of propagation of the wave.
My question is: Let's say I want to find the shift in the location of the central bright spot once the setup is introduced. The first thing that comes to my mind is to find the relative phase shift, let's call it $\Delta \phi$. Most of the textbooks even go on to find it exactly. How do I use this to find the distance by which the bright spot on the screen is shifted if I know $\Delta \phi$?
Attempt:
So I guess all we need to do is use $\Delta \phi$ to find additional path length travelled by the waves, and then use trigonometric relations to figure out the new central bright spot. Am I on the right track?
Edit: After some more consideration, I have further confusions. Let's say initially if the $B = 0$, then the phase difference between the two waves is denoted by $\delta(B=0)$. For the central bright spot, $\delta(B=0) =0$.However, once $B$ field is non-zero inside the solenoid, the total relative phase-difference is:
$\Delta \phi = \delta(B=0) + \delta_1$. The problem though is now that the central bright spot has shifted, I think that the $\delta(B=0)$ need not be equal to $0$.


text:
Q: Current use of StackFlair In searching for ways to customize and improve the look of my flair, I have found numerous answers pointing to StackFlair as the option of choice.  However, StackFlair seems to be permanently shutdown, causing these answers to be out-of-date.
Is StackFlair still available? Are there alternatives that are currently available and working?  What are the major differences between any alternatives?

A: I asked Rebecca about this a while back and it doesn't seem like she'll be offering StackFlair anymore. However, after talking with her I've decided to try and fix any outstanding issues and rehost it*, so hopefully I can make that happen sometime this week.
While there's always se-flair and the official flair you can find via the "flair" link in your profile, neither of these offer the same level of customization that StackFlair did.
*albeit on a different domain probably, because the current one is being squatted with a minimum $500 bid


text:
Q: Angular doesn't retrieve updated_at in laravel i'm trying to retrieve the updated_at time but it gets the created_at time instead even when i passed it in the angular scope function
and renders the incorrect date on created_at after the update has been made
My console reads when updated

1 second ago

so it works but its not getting passed in the view correctly.
PostController
public function update(Post $post)
{
    //
    $data = request()->validate([
        'body' => 'required|string'
    ]);
    $this->authorize('update', $post);
    $post->update($data);
    $data['id'] = $post->id;
    $data['updatedAt'] = $post->updated_at->diffForHumans();
    $response = new Response(json_encode($data));
    $response->headers->set('Content-Type', 'application/json');

    return $response;

}

public function getPosts()
{
    $posts = Post::with('user')
                 ->with(['likes' => function ($query) {
                            $query->whereNull('deleted_at');
                            $query->where('user_id', auth()->user()->id);
                        }])
                    ->get();
    $response = new Response(json_encode($posts));
    $response->headers->set('Content-Type', 'application/json');

    $data = $posts->map(function(Post $post)
    {
        $user = auth()->user();

        if($user->can('delete', $post)) {
            $post['deletable'] = true;
        }

        if($user->can('update', $post)) {
            $post['update'] = true;
        }

        $post['likedByMe'] = $post->likes->count() == 0 ? false : true;
        $post['likesCount'] = Like::where('post_id', $post->id)->get()->count();
        $post['createdAt'] = $post->created_at->diffForHumans();
        $data['updatedAt'] = $post->updated_at->diffForHumans();
        return $post;
    });

    return response()->json($data);
}

main.js
$scope.updatePost = function(post){

    $http.post('/auth/upost/' + post.id, {
        body: post.body,
        updatedAt:post.updatedAt

    }).then(function(result, status, headers, config){

         $scope.updatedAt = result.data.updatedAt;
         console.log($scope.updatedAt);
         $scope.myposts.push($scope.updatedAt);
    });
};

html

<% post.user.name %>

 <% post.body %>

 <% post.createdAt %> <% post.updatedAt %>

              <button ng-if="post.update" class="btn btn-default" ng-click="textBtnForm.$show()" ng-hide="textBtnForm.$visible">
                Edit
              </button>

            <button ng-if="post.update" type="submit" class="btn btn-primary" ng-click="updatePost(post)">Update</button>

A: this is the correct code my bad for this silly question guys.
 public function getPosts()
    {
        $posts = Post::with('user')
                     ->with(['likes' => function ($query) {
                                $query->whereNull('deleted_at');
                                $query->where('user_id', auth()->user()->id);
                            }])
                        ->get();
        $response = new Response(json_encode($posts));
        $response->headers->set('Content-Type', 'application/json');

        $data = $posts->map(function(Post $post)
        {
            $user = auth()->user();

            if($user->can('delete', $post)) {
                $post['deletable'] = true;
            }

            if($user->can('update', $post)) {
                $post['update'] = true;
            }

            $post['likedByMe'] = $post->likes->count() == 0 ? false : true;
            $post['likesCount'] = Like::where('post_id', $post->id)->get()->count();
            $post['createdAt'] = $post->created_at->diffForHumans();

            // $data['updatedAt'] = $post->updated_at->diffForHumans();
            //calling again if the post has been updated
            $post['createdAt'] = $post->updated_at->diffForHumans();
            return $post;
        });

        return response()->json($data);
    }

main.js
remove this its useless and renders out a box
 $scope.myposts.push($scope.updatedAt);

html
<% post.createdAt %> is all you need it will render both the created time and updated time


text:
Q: How to return last day of month in ngx-bootstrap datepicker angular
Below is my code where I need to display calendar with month and year and when user selects month and year it should display last day of that month with year. I am able to get the date as 01 June 2022 using below code, where as I need date as 30 June 2022

A: Quickest way is using a library like moment (depreacated) or dayjs. Take the date you get from datepicker, and use it with the library to get the end date of the month-year.
Change the dateInputFormat to YYYY-MM-DDDD in the bsConfig.
Inside your getDate() function process the datePicker date to get proper format.
Example code:
const date = '2022-06-01';
console.log('Print date: ', moment(date).endOf('month').format('DD MM YYYY'));

Result:


text:
Q: email, login, logout authentication problem i want to make if user enter same username of other user than show error same as email and login function how to add email authentication...not username and please check my logout function it is right or wrong.Thank you

*

*List item
i want to check username is already exists than show error same as email and please check, my login i want to enter email not username what can i do. my logout function is it right or wrong please tell me.
List item

views.py

from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib import auth

from .models import *

def appofimage(request):
    cats = category.objects.all()
    images = post.objects.all()
    data = {'images': images, 'cats': cats}
    return render(request, 'home.html', data)

def signup(request):
    if request.method == 'POST':
        username1 = request.POST['username']
        firstname1 = request.POST['firstname']
        lastname1 = request.POST['lastname']
        email1 = request.POST['email']
        password = request.POST['password']
        password1 = request.POST['password1']

        # check for error messages

        # username should be under 15 characters
        if len(username1) > 15:
            messages.error(request, "Username must be under 15 characters")
            return redirect('appofimage')

        # password should match
        if password != password1:
            messages.error(request, 'Password do not match')
            return redirect('appofimage')

        # username should be alphanumeric mens does not contain any &*()%$ etc..
        if not username1.isalnum():
            messages.error(request, 'Username Should Only Contain Letters And Numbers')
            return redirect('appofimage')

        myuser = User.objects.create_user(username=username1, email=email1, password=password)
        myuser.first_name = firstname1
        myuser.last_name = lastname1
        myuser.save()
        messages.success(request, 'user has been created')
        return redirect('appofimage')

    else:
        return render(request, 'signup.html')

def login(request):
    if request.method == 'POST':
        username1 = request.POST['username']
        password1 = request.POST['password']

        user = auth.authenticate(username=username1, password=password1)

        if user is not None:
            auth.login(request, user)
            messages.success(request, f"welcome {username1}")
            return redirect('appofimage')
        else:
            messages.error(request, "not valid")
            return redirect('appofimage')

    return render(request, 'login.html')

def logout(request):
    if request.method == 'POST':
        messages.error(request, "Try again")
        return redirect('appofimage')

    else:
        auth.logout(request)
        messages.success(request, "logout successful")
        return redirect('appofimage')

signup.html

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

    <title>SignUp</title>

                <form action="" method="post">
                    {% csrf_token %}

                Username
                <input type="text" class="form-control" name="username" id="username">

                First Name
                <input type="text" class="form-control" name="firstname" id="firstname">

                Last Name
                <input type="text" class="form-control" name="lastname" id="lastname">

                Email address
                <input type="email" class="form-control" name="email" id="email" aria-describedby="emailHelp">
                We'll never share your email with anyone else.

                Password
                <input type="password" class="form-control" name="password" id="password">

                Confirm Password
                <input type="password" class="form-control" name="password1" id="password1">

              <button type="submit" class="btn btn-primary">Submit</button>
            </form>

login.html

<!doctype html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

        <title>Login</title>

                  <form action="" method="post">
                      {% csrf_token %}

                        Username
                        <input type="text" class="form-control" name="username">

                    Password
                    <input type="password" class="form-control" name="password">

                  <button type="submit" class="btn btn-primary">Submit</button>
                </form>

A: First, create your category urls in your urls.py:
urlpatterns = [
    ...
    path('/category/<int:pk>/', views.your_category_view, name="category"),
    ...
]

Then, your posts and your categories are linked together via a ForeignKey in your models. You need to use this in your loop to get the right category for each image. Currently you are calling {{cat.pk}} without looping over the cats and without linking it to the right image. I would replace your images loop (confusing way to call it btw since images is actually posts) with this:
{% for i in images %}

{% endfor %}

A: You need to do the following:

*

*add a view that gives the posts of a particular category. example url will be /category/<pk>

*use the html


text:
Q: Connect to an existing Database in MySQL WorkBench I basically work with Sql Server for my databases. and now I was given a folder contains files with extensions .frm, .ibd and .opt and was asked to ensure the connection with these files (these files are the database as I understood) in order to process the data.
I looked for how to do this a lot but still didn't find a good answer.
I am using Visual Studio 2013 and C#


text:
Q: Java requests to Microsoft Graph API perform ok but return 500 I have a small Java program with 3 methods:

*

*one for getting the token from graph api for authentication bearer token. This is ok, token is ok and returns 200 http

*the other two are for creating a user in Azure AD and assigning an licences.
Taking the first, creating the user. The token is ok, the user is created, and authentication on platform works fine(password is set ok). BUT on response I get 500 http even task is done correctly in AzureAD. If I place same request in PowerShell there is no problem, no error. Please help me with an advice. My method for creating user is:

public static String createUser(String token) {
        String user = "{\n"
                + "  \"accountEnabled\": true,\n"
                + "  \"displayName\": \"displayName-value\",\n"
                + "  \"mailNickname\": \"mailNickname-value\",\n"
                + "  \"userPrincipalName\": \"upn@microsoft.ro\",\n"
                + "  \"passwordProfile\" : {\n"
                + "    \"forceChangePasswordNextSignIn\": false,\n"
                + "    \"password\": \"Complexity2021\"\n"
                + "  },\n"
                + " \"usageLocation\" : \"RO\""
                + "}";
        HttpURLConnection conn = null;
        URL url = null;
        try {
            url = new URL("https://graph.microsoft.com/beta/users");
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Authorization", "Bearer " + token);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.connect();
            OutputStream os = conn.getOutputStream();
            os.write(user.getBytes());
            os.flush();
            int status = conn.getResponseCode();
            System.out.println(status); // 500!!!!! AND THE USER is ok in AzureAD
            switch (status) {
                case 200:
                case 201:
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    br.close();
                    return sb.toString();
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.disconnect();
                } catch (Exception ex1) {
                    ex1.printStackTrace();
                }
            }
        }
        return null;
    }

A: Thanks for reply, I was checked the errorStream and was containing:
{
  "error": {
    "code": "InternalServerError",
    "message": "The MIME type 'text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2' requires a '/' character between type and subtype, such as 'text/plain'.",
    "innerError": {
      "
    }
  }
}

The solution was:
conn.setRequestProperty("Accept", "application/json");

Thank you!

A: You are ignoring the error data returned by the server - but, according to the documentation, it should explain the cause of the 500 status. Suggested code:
        // ...
        System.out.println(status); // 500!!!!! AND THE USER is ok in AzureAD

        // always reads server response
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br =
                new BufferedReader(new InputStreamReader(conn.getInputStream())) {
            String line;
            while ((line = br.readLine()) != null) {
                  sb.append(line + "\n");
            }
        } // <-- br is automatically closed here!

        String output = sb.toString();
        if (status == 200 || status == 201) {
            return output;
        } else {
            // choose a suitable exception, or return null but log error
            throw new FooException("Received error " + status +
                    " while doing Foo; details follow: " + output);
        }
        // ...

I also suggest replacing all your try { } finally { } that free resources with try-with-resources versions -- they are safer (always closing acquired resources) and more readable.


text:
Q: pyparsing infix notation with non-grouping parentheses I'm working on a billing application where users can enter arbitrary mathematical expressions. For example, a line item might be defined as (a + b) * c.
pyparsing handles the order of operations well enough in this case:
import pyparsing as pp

operand = pp.Word(pp.alphanums)
boolean_operator = pp.one_of(['||', '&&'])
comparison_operator = pp.one_of(['<', '<=', '>', '>=', '==', '!='])

infix_pattern = pp.infix_notation(
    operand,
    [
        ('^', 2, pp.OpAssoc.LEFT),
        ('*', 2, pp.OpAssoc.LEFT),
        ('/', 2, pp.OpAssoc.LEFT),
        ('+', 2, pp.OpAssoc.LEFT),
        ('-', 2, pp.OpAssoc.LEFT),
        (comparison_operator, 2, pp.OpAssoc.LEFT),
        (boolean_operator, 2, pp.OpAssoc.LEFT),
    ]
)

print(infix_pattern.parse_string('(a + b) * c'))
# [[['a', '+', 'b'], '*', 'c']]

Users can also enter a handful of well-known functions, including the calling parentheses and arguments. For example, if a line item is defined as a(b) == c(d), pyparsing gets confused:
print(infix_pattern.parse_string('a(b) == c(d)'))
# ['a']

What I would like to see in this case is ['a(b)', '==', 'c(d)']. What do I need to do differently in order to keep the first example working as-is and get the desired behavior from the second example?

A: Okay I think I got it:
import pyparsing as pp

operand = pp.Word(pp.alphanums) + pp.Opt(pp.Literal('(') + ... + pp.Literal(')'))
boolean_operator = pp.one_of(['||', '&&'])
comparison_operator = pp.one_of(['<', '<=', '>', '>=', '==', '!='])

infix_pattern = pp.infix_notation(
    operand,
    [
        ('^', 2, pp.OpAssoc.LEFT),
        (pp.one_of(['*', '/']), 2, pp.OpAssoc.LEFT),
        (pp.one_of(['+', '-']), 2, pp.OpAssoc.LEFT),
        (comparison_operator, 2, pp.OpAssoc.LEFT),
        (boolean_operator, 2, pp.OpAssoc.LEFT),
    ]
)

print(infix_pattern.parse_string('(a + b) * c'))
# [[['a', '+', 'b'], '*', 'c']]

print(infix_pattern.parse_string('a(b) == c(d)'))
# [['a', '(', 'b', ')', '==', 'c', '(', 'd', ')']]

I could combine the a(b) and c(d) with pp.Combine or something but this is fine.


text:
Q: Why this event is not fired on fiddle? This is the code! I really don't know why addTrack is not recognized :
<input type="submit" onclick="addTrack(this);return false" value=" Add ">

function addTrack(param) {
    alert("ciao");
}

Error : Uncaught ReferenceError: addTrack is not defined

A: Set the script insertion mode to no wrap (head) instead of onLoad and it will work as expected.
Updated fiddle here.

A: see working eg
It wasn't defined, because the script was wrapped in the ready eventHandler; it was declared in a different scope(not the public one) and it wasn't visible

A: Moving the function declaration from the jQuery .load() handler to the outer scope (head) solves the problem. Guess the function was only available within the scope of $.load().


text:
Q: Concurrently start function and return early I need to return a response from my FastAPI path operation, but before this I want to send a slow request and I don't need to wait for result of that request, just log errors if there are any. Can I do this by means of Python and FastAPI? I would not like to add Celery to the project.
Here is what I have so far, but it runs synchronously:
import asyncio
import requests

async def slow_request(data):
    url = 'https://external.service'
    response = requests.post(
        url=url,
        json=data,
        headers={'Auth-Header': settings.API_TOKEN}
    )
    if not response.status_code == 200:
        logger.error('response:', response.status_code)
        logger.error('data', data)

@router.post('/order/')
async def handle_order(order: Order):
    json_data = {
        'order': order
    }

    task = asyncio.create_task(
        slow_request(json_data)
    )
    await task

    return {'body': {'message': 'success'}}

A: OK, if nobody wants to post an answer here are the solutions:
Solution #1
We can just remove await task line as alex_noname suggested. It will work because create_task schedules task and we are no longer awaiting for its completion.
@router.post('/order/')
async def handle_order(order: Order):
    json_data = {
        'order': order
    }

    task = asyncio.create_task(
        slow_request(json_data)
    )

    return {'body': {'message': 'success'}}

Solution #2
I ended up with BackgroundTasks as HTF suggested as I'm already using FastAPI anyway, and this solution seems more neat to me.
@router.post('/order/')
async def handle_order(order: Order, background_tasks: BackgroundTasks):
    json_data = {
        'order': order
    }

    background_tasks.add_task(slow_request, json_data)

    return {'body': {'message': 'success'}}

This even works without async before def slow_request(data):

A: The problem is really two-part

*

*the requests library is synchronous, so requests.post(...) will block the event loop until completed

*you don't need the result of the web request to respond to the client, but your current handler cannot respond to the client until the request is completed (even if it was async)

Consider separating the request logic off into another process, so it can happen at its own speed.
The key being that you can put work into a queue of some kind to complete eventually, without directly needing the result for response to the client.
You could use an async http request library and some collection of callbacks, multiprocessing to spawn a new process(es), or something more exotic like an independent program (perhaps with a pipe or sockets to communicate).
Maybe something of this form will work for you
import base64
import json
import multiprocessing

URL_EXTERNAL_SERVICE = "https://example.com"
TIMEOUT_REQUESTS = (2, 10)  # always set a timeout for requests
SHARED_QUEUE = multiprocessing.Queue()  # may leak as unbounded

async def slow_request(data):
    SHARED_QUEUE.put(data)
    # now returns on successful queue put, rather than request completion

def requesting_loop(logger, Q, url, token):
    while True:  # expects to be a daemon
        data = json.dumps(Q.get())  # block until retrieval (non-daemon can use sentinel here)
        response = requests.post(
            url,
            json=data,
            headers={'Auth-Header': token},
            timeout=TIMEOUT_REQUESTS,
        )
        # raise_for_status() --> try/except --> log + continue
        if response.status_code != 200:
            logger.error('call to {} failed (code={}) with data: {}'.format(
                url, response.status_code,
                "base64:" + base64.b64encode(data.encode())
            ))

def startup():  # run me when starting
    # do whatever is needed for logger
    # create a pool instead if you may need to process a lot of requests
    p = multiprocessing.Process(
        target=requesting_loop,
        kwargs={"logger": logger, "Q": SHARED_QUEUE, "url": URL_EXTERNAL_SERVICE, "token": settings.API_TOKEN},
        daemon=True
    )
    p.start()


text:
Q: React Js API call Unit Test Case I m trying to write test cases for my API I call but I don't know what I am doing wrong that I am getting errors like this.
car.test.js
import { getCar } from "../Service/MainScreen/Cars/Car";

describe("Car  API Call function", () => {
  test("it should pass the test", () => {
    const testData = {
      id: 186,
      plate_number: "WW12345",
      status_display: "Aktywny",
      driver_name: "Jakub Nowak",
      driver_id: 181,
      created_at: "2021-08-12T09:07:30Z",
      vin: "WBADM123123123123",
      brand: "Ford",
      model: "Focus",
      "Brand-Model": "Ford/Focus",
      production: "2016",
      registration: "01-12-2020",
      insurance_date: "06-06-2023",
      has_registration_docs: true,
      has_policy_status: true,
      has_certificate: true,
      has_green_card: true,
      has_vehicle_card: true,
      has_car_picture: true,
      fleet_entry: "20-04-2018",
      monitoring_start: "12-08-2021",
      status: "Aktywny",
      Estimaed_distance: 29500,
      Estimaed_fuel: 1475,
      average_fuel: 5,
      claim: 1,
      cost: 1000,
    };

    const response = { json: jest.fn().mockResolvedValueOnce(testData) };
    global.fetch = jest.fn().mockResolvedValueOnce(response);

    return getCar().then((data) => {
      expect(data[0]).toEqual(testData);
    });
  });
});

GetCar
import config from "../../../Config/Api";
export async function getCar() {
  return fetch(config.fakeapi.car, config.fakeHead)
    .then((response) => {
      return response.json();
    })
    .catch((reject) => console.log(reject));
}

Here is the error in the image that I have attached can someone please help me to resolve my test case that I can write also for another API call .

A: testData is NOT array, that's why data[0] gives you undefined. It should be:
const response = { json: jest.fn().mockResolvedValueOnce(testData) };
global.fetch = jest.fn().mockResolvedValueOnce(response);

return getCar().then((data) => {
  expect(data).toEqual(testData);
});


text:
Q: Error installing Quipper - cannot build quipper-utils-0.9.0.0 (Couldn't match type 'Maybe TH.Exp' with 'TH.Exp') Trying to install Quipper (quantum programming language for Haskell), it throws a compilation error:
My build profile: -w ghc-9.0.1 -O1
Preprocessing library for quipper-utils-0.9.0.0..
Building library for quipper-utils-0.9.0.0..

...

[11 of 15] Compiling Quipper.Utils.Template.Lifting ( Quipper/Utils/Template/Lifting.hs, dist/build/Quipper/Utils/Template/Lifting.o, dist/build/Quipper/Utils/Template/Lifting.dyn_o )

Quipper/Utils/Template/Lifting.hs:252:28: error:
    • Couldn't match type 'Maybe TH.Exp' with 'TH.Exp'
      Expected: [TH.Exp]
        Actual: [Maybe TH.Exp]
    • In the second argument of 'mapM', namely 'exps'
      In a stmt of a 'do' block: exps' <- mapM expTHtoAST exps
      In the expression:
        do exps' <- mapM expTHtoAST exps
           return (TupE exps')
    |
252 |   exps' <- mapM expTHtoAST exps
    |                            ^^^^

Quipper/Utils/Template/Lifting.hs:417:20: error:
    • Couldn't match type 'TH.Exp' with 'Maybe TH.Exp'
      Expected: [Maybe TH.Exp]
        Actual: [TH.Exp]
    • In the first argument of 'TH.TupE', namely 'exps''
      In the second argument of '($)', namely 'TH.TupE exps''
      In a stmt of a 'do' block: return $ TH.TupE exps'
    |
417 |   return $ TH.TupE exps'
    |                    ^^^^^
cabal: Failed to build quipper-utils-0.9.0.0 (which is required by
quipper-0.9.0.0). See the build log above for details.

A: I'm pretty sure the bounds on the Quipper package are too lax. There have been quite some changes in Template Haskell in GHC 9.0.1. And the version of the template-haskell library is bound to the GHC version you're using, so you have to use an older version of GHC. I have tested it with GHC 8.8.4 which works.

A: Try installing version 8.6.5 from here: https://www.haskell.org/platform/prior.html. I had the same problem and this worked for me.