text:
Q: issue with install newest version of ruby on cetos Please help!!!
I have issue with installing new version of ruby in my Centos6.
I'l try install it using rvm :
/usr/local/rvm/bin/rvm install 1.9.2

And got the next message :

Error running 'requirements_centos_libs_install libyaml-devel
  readline-devel libffi-devel sqlite-devel', showing last 15 lines of
  /usr/local/rvm/log/1439995406_ruby-1.9.2-p330/package_install_libyaml-devel_readline-devel_libffi-devel_sqlite-devel.log
  If you don't want/need both architectures anymore then you
         can remove the one with the missing update and everything
             will work.
You have duplicate versions of libffi installed already.
    You can use "yum check" to get yum show these errors.
...you can also use --setopt=protected_multilib=false to remove
    this checking, however this is almost never the correct thing to
    do as something else is very likely to go wrong (often causing
    much more problems).
Protected multilib versions: libffi-3.0.5-3.2.el6.i686 != libffi-3.0.9-1.el5.rf.x86_64
  ++ return 1
  ++ return 1 Requirements installation failed with status: 1.

I try to remove this lib but again fail :

Error: Trying to remove "yum", which is protected

Can somebody explain where I fail? Please! Thx all!
p.s. I'm update the system (in case if answer will be "yum update") :)

A: Try to remove lib :
rpm -e --nodeps libffi

and again try to install ruby.


text:
Q: Set Home Flexipage as Org Default via the API I have a new Lightning Home Page that I would like to push out to my customers and set it automatically as the Org Default via the metadata API. Salesforce documentation here makes it sound like its a possibility by setting the sObjectType as null but its not working. So I am wondering now if its even possible to set the home page as a default programmatically. Any thoughts?
{
actionName: "View",
comment:
  "Action override updated by Lightning App Builder during activation.",
content: "My_New_Home_Page_Layout",
formFactor: "Large",
skipRecordTypeSelect: "false",
type: "Flexipage",
pageOrSobjectType: "null",
},

redpajama_set_name: RedPajamaStackExchange


text:
Q: Different integral results within equivalent conditions I input 3 functions as following,
g[n_, r_]=(2*Z^(3/2)*Hypergeometric1F1[1 - n, 2, (2*r*Z)/n])/(E^((r*Z)/n)*n^(3/2));
g1[n_, r_]=g[n,r]/.Z->m Z;
g2[n_, r_]=g[n,r]/.Z->m Z \[Alpha];

How ever the following three integral results shows

Third Integral
Integrate[g2[n, r] g2[1, r] (m Z \[Alpha])/r r^2, {r, 0, \[Infinity]},
     Assumptions ->
     n \[Element] Integers && n > 1 && m > 0 && Z > 0 && \[Alpha] > 0]

MMA says that the third integral does not converge. But since $mZ\alpha$ always product together, I expected that the third integral should just be the first integral with $Z\to mZ\alpha$. How to understand such results?
My MMA version number is 11.0.0.0 and the platform is Linux x86(64-bit).


text:
Q: Algolia Import Statements aren't working (Kotlin/Algolia) Some of the import statements and code specified by the tutorial is highlighted as incorrect. Algolia instantsearch Android documentation can be found here. I dont understand why I keep receiving the following errors. Any guidance would help.
[Issue #1][2]


text:
Q: In SSRS custom code, can we create a function that call another function? In the Custom code section, if I defined function 1 first, in the next line, can I define function 2 that calling function 1? If not, how can I get around it?

A: Yes, you can. Artificially simple example:
Function SumSum(a as decimal, b as decimal) as decimal
Dim c as Decimal
c = a + b
Return c
End Function

Function OtherFunction(a as decimal, b as decimal) as decimal
Dim c as Decimal
c = SumSum(a,b)
Return c
End Function

OtherFunction will use the SumSum function to sum a and b.


text:
Q: How to mock getResourceAsStream method using PowerMockito and JUnit? I try to mock getResourceAsStream method which I invoke in constructor.
public Conn() {
    stream = Conn.class.getClass().getResourceAsStream(PATH);
}

For mock framework I prefer Mockito + PowerMockito.
    @RunWith(PowerMockRunner.class)
    @PrepareForTest(Conn.class)
    public class ConnTest {

        @Mock
        private InputStream streamMock;

        private Conn conn;

        @Before
        public void before() {
            initMocks(this);
        }

        @Test
        public void test() {
            PowerMockito.mockStatic(Conn.class);
            PowerMockito.when(Connector.class.getResourceAsStream("/prop.properties")).thenReturn(streamMock);
            conn = new Conn();
        }

        @After
        public void after() {
            reset(streamMock);
        }
     }

But method thenReturn doesn't return a mock. How can I fix it?

A: You can abstract getting the resource to a class.
class StreamFetcher {

InputStream fetchStream(String path) {
return StreamFetcher.class.getClass().getResourceAsStream(path);
}

}

and in your class
class Conn {
public Conn(StreamFetcher streamFetcher) {
    stream = streamFetcher.fetchStream(PATH);
}
}

That way you don't even have to do a mock - you can create your own impl for tests that does whatever you need it to do.
Also you can actually abstract more and maybe process the Stream somehow. I don't know the business context so can't really help you on this one.

A: It doesn't return a mock because the code-under-test new Conn() does not call
Connector.class.getResourceAsStream(...)

it calls
Conn.class.getResourceAsStream(...)

Your code worked by changing the method stubbing to:
PowerMockito.when(Conn.class.getResourceAsStream("/prop.properties")).thenReturn(streamMock);

A: You can do like below:
    @RunWith(PowerMockRunner.class)
    @PrepareForTest(Class.class)
    public class ConnTest {

        @Mock
        private InputStream streamMock;

        private Conn conn;

        @Before
        public void before() {
            initMocks(this);
        }

        @Test
        public void test() {
            PowerMockito.mockStatic(Class.class);
            PowerMockito.when(Connector.class.getClass().getResourceAsStream("/prop.properties")).thenReturn(streamMock);
            conn = new Conn();
        }

        @After
        public void after() {
            reset(streamMock);
        }
     }

Here you are stubbing resource on top of a class object, that is why Class.class you need to prepare for test by using @PrepareForTest(Class.class) and PowerMockito.mockStatic(Class.class);.
I am not sure whether it'll work for constructor or not but for a method which is calling getClass.getResourceAsStream("anyString") it's working fine(I have tested).


text:
Q: What do you call a person who gets hungry easily? Is there a word to describe a person who gets hungry easily? If there is, are there any antonyms for it?

A: Someone with a fast metabolism generally gets hungry more easily, as s/he burns up consumed calories more quickly than does someone with a slow metabolism.
You could describe someone who eats small amounts frequently as a grazer or a snacker.
(See also: Teenager.)

A: Merriam Webster defines ravenous as 'being very greedy or eager for food.' Also, gluttonous refers to a person who overeats.
Gourmand is sometimes used as a synonym for 'glutton.'
Bulimia refers to an eating disorder characterized by consuming large amounts of food. This links to an explanation of bulimic.


text:
Q: update column data into a table without removing the existing data? I am trying to update one column data with the existing data but i don't want to remove previous record also.
IF i do update query the previous record will delete.
I want both records in the same table.
Can you please help me how to do this?
Example:
Table: transformation_target_metadata

For dataSetType = 'Knipper' table is already existed.I need to perform all the changes for dataSetType = 'Synergistixs'

datasetname     dataSetType    Name
Knipper         knipper        comma
Knipper         Knipper        VendorName
Knipper         Knipper        Brand

datasetname     dataSetType         Name
Knipper         Synergistixs        comma
Knipper         Synergistixs        VendorName
Knipper         Synergistixs        Brand

When i trigger the below query the output will come like this:
select * from transformation_target_metadata where datasetname in('Knipper') and dataSetType in('Knipper');

datasetname     dataSetType    Name
Knipper         knipper        comma
Knipper         Knipper        VendorName
Knipper         Knipper        Brand

select * from transformation_target_metadata where datasetname in('Knipper') and dataSetType in('Synergistixs');

datasetname     dataSetType         Name
Knipper         Synergistixs        comma
Knipper         Synergistixs        VendorName
Knipper         Synergistixs        Brand

A: You seem to want insert:
insert into transformation_target_metadata (datasetname,     dataSetType, Name)
    select datasetname,  'Synergistixs', Name
    from transformation_target_metadata
    where dataSetType = 'Knipper';


text:
Q: Connecting to VPN through a custom client OK, here goes:
I have a CentOS server set up to accept PPTP connections and tunnel the users traffic through my server.
I am sharing this with my friends and family, and everytime they want to connect they have to go into control panel, and connect to the network manually. To set up the network, they go through a wizzard that Windows has to set up a new VPN connection for them, and they put in the IP address, username and password.
I wanted to make a really simple client for them to use. When it's first installed and they click "Connect", the program must make the new network (like they were going through the wizard), and every time after that just swap over to use the VPN network. If they click "Disconnect", it will go back to using their regular LAN network.
I would ideally like to code this in .NET, as that is where I have a lot of experience, but I have no idea where to start.
Could anyone point me in the right direction? Maybe some code samples?
Help would be greatly appreciated, thanks. =]

A: Ah, much easier to understand - thanks for the clarification!
At the risk of sounding like I'm an OpenVPN fanatic, look at openvpn, particularly the Access Server here.  I think you'll find it does exactly what you need.
OpenVPN is open source, so it's 100% code samples and as customizable as you like. (Be careful what you ask for! :-) )
Good luck!


text:
Q: Replacing numbers of which you only know certain digits If I have a list of numbers like this:
list = {0.3565127, 0.8656421, 0.231479879, 0.39698787, 0.536987651},

which are all between 0 and 1, each having lots of digits, and whose precision is not known (and also not important). I don't know their exact values. (It could be a list of hundreds of numbers, so we don't know each of them exactly).
Yet I know some of them have the form 0.?969?????????, where the ?s represent digits I do not know; besides; the digits known are all within the first five digits behind the decimal point.
So, how can I construct a pattern object (like x_^2 for symbols) for replacing numbers that match the pattern?

A: It seems that OP wants a pattern object for use in replacement rules, so this does the trick,
{0.969, 0.0969, 0.00969, 0.3565127, 0.8656421, 0.231479879,
  0.39698787, 0.536987651} /.
 a_ /; MatchQ[
    First[RealDigits[a, 10, Automatic, -1]], {_, 9, 6, 9, __}] -> 4
(* {0.969, 4, 0.00969, 0.356513, 0.865642, 0.23148, 4, 0.536988} *)

edit Thanks as always to @J.M. for helping me write better Mathematica code.

A: Inspired by Jason B:
Select[list,
  MatchQ[
    TakeDrop[
      If[Negative[#2], ArrayPad[#1, {Abs[#2], 0}], #1],
      Clip[#2, {0, \[Infinity]}]
    ] & @@ RealDigits[#] &,
    {{}, {_, 9, 6, 9, __}}
  ] &
]

{0.396988}

Where the first list in patterns specifies the pattern for digits on the left side of the decimal point and the second for those on the right.
For earlier versions TakeDrop can be replaced with Through[{Take, Drop}[##]] &

Old answer
Not exactly pattern matching, but working:
Select[
 list,
 Mod[Floor[# 10^4], 10^3] == 565 &
]

{0.356513}

Same approach, slightly modified:
Pick[
   list,
   Mod[Floor[list 10^4], 10^3],
   565
]

Probably slower string approach:
StringCases[
  ToString[#, InputForm] & /@ list,
  StartOfString ~~ _ ~~ "." ~~ Repeated[_, {2}] ~~ "65" ~~ __ ~~ EndOfString
] // Flatten // Map[ToExpression]

{0.356513}

or, matching your question the best:
Cases[
    ToString[#, InputForm] & /@ list,
    _?(StringMatchQ[#, RegularExpression[".\\...698.*"]] &)
] // Flatten // Map[ToExpression]

{0.396988, 0.536988}


text:
Q: Why is the Search Crawler visiting spending so much time on apparently empty sites? I am currently capturing usage data for the site collections in my organisations MOSS 2007 deployment and I have noticed some oddities in the search crawlers behavior.
Part of the data being captured is Site Size, Distict users per day over 30 days and yesterday and crawler hits on the site collection over 30 days and per day. Some very busy sites with gigabytes of stored data accessed daily (the main intranet portal for example) recieve only a single daily hit on average from the search crawler whilst an out-of-date meeting space with no content on it and no visitors (currently scheduled for deletion) recieved 11 crawler hits yesterday and an almost unused teamsite whose only traffic was me checking the usage stats recieved 126 hits.
Can someone with a decent understanding of Search in MOSS 2007 do me a favour and explain what is happening here and why please?

A: could be a number of things!
the search crawl is behaving as it should! ;)
now there is a difference with looking up (crawling) to actually indexing. If somthing has changed than an index would be performed and depending on the type would issue a full crawl or a partial crawl.
so what me need to know is what is the search crawl shedule look like? are you running full crawls on the weekend? are partial crawls set daily out of hours? also like to know when are these crawls occuring and where/how are you capturing usage data???
just because no one visits the empty site which you have doesnt mean the search service is not going to crawl that area!
are you getting the data from the managed search service application?
it could be that on the busy sites people are veiwing rather than adding or ammending?
1) where are you getting data from?
2) what is you search config like for partial and full crawls?
3) when is the crawls occuring on your data and over how many days?
so lets explain a possible senario ;)
the usage stats with 126 hits! i presum thats a site you made to store the stats. If so then those stats are going to be updated or added are they not?? if so then this would issue a schedueld task in the timer service for a crawl. The search crawl would then save this url or data in a temp location and it would check against the database where it stores the full crawl log to check against to see any changes, if so it would update accordingly (partial crawl).
the main busy site (intranet), you need to know if this has the correct search topology on this site location for incremental crawls and full crawls. 1 hit is very odd unless its running very frequent?
the outdated meeting space could be updating due to a list.update or web.update being called even tho nothing was updated??
without looking at the log you could be guessing all day! to look at the log you need to go to this locatiom:

1 Open the administration page for the Shared Services Provider (SSP).
2 To open the administration page for the SSP, do the following:
3 On the top navigation bar, click Application Management.
4 On the Application Management page, in the Office SharePoint Server Shared Services section, click Create or configure this farm's
  shared services.
5 On the Manage this Farm's Shared Services page, click the SSP whose administration page you want to open.
6 On the Shared Services Administration Home page, in the Search
  section, click Search settings.
7 On the Configure Search Settings page, in the Crawl Settings section,
  click Crawl logs.
8 On the Crawl Log page, on the left navigation bar, you can click
  either View by hostname, by which you can find the URLs that begin
  with a specific hostname and path, or View by URL, by which you can
  filter the crawl log.

why look at the log?

The crawl log tracks information about the status of crawled content.
  This log allows you to verify whether crawled content was added to the
  index successfully, whether it was excluded because of a crawl rule,
  or whether indexing failed because of an error. Additional information
  about the crawled content is also logged, including the time of the
  last successful crawl, the content source (there could be more than
  one), the content access account used, and whether any crawl rules
  were applied.

what to filter on:

All integer properties (such as startAt, TotalEntries, and MessageId)
Log time
Message type
URL

http://msdn.microsoft.com/en-us/library/office/ms553190%28v=office.12%29.aspx
http://technet.microsoft.com/en-us/library/cc263379%28v=office.12%29.aspx
dive in deep with the working out of how search service works and why:
http://social.technet.microsoft.com/wiki/contents/articles/228.search-architecture-in-microsoft-office-sharepoint-server-2007.aspx
http://blogs.msdn.com/b/sharepoint_strategery/archive/2012/10/30/sp2010-search-explained-crawling.aspx


text:
Q: Помогите сверстать В макете попалось такое вот нестандартное окошечко. Может быть кто-то сталкивался с подобным?
В этом окошечке будет размещаться текст. Возможно ли сделать данное окно кодом, чтобы было точь-в-точь как на макете? У меня наибольшую трудность вызывает сделать выпирающий снизу элемент.
Буду очень благодарен за помощь.

A:

body {
  background: rgb(60, 65, 60);
}

.rectangle {
  width: 200px;
  border: 1px solid white;
  border-radius: 8px;
  transform: skewX(10deg);
  position: relative;
  margin-left: 20px;
  margin-top: 20px;
}

.rectangle .text {
  z-index: 4;
  position: relative;
  color: white;
  padding: 20px;
  transform: skew(-10deg);
}

.rectangle:after {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 8px;
  left: 7px;
  top: 7px;
  background: grey;
}

.rectangle:before {
  content: '';
  position: absolute;
  width: 21px;
  height: 21px;
  border-radius: 4px;
  bottom: -14px;
  background: grey;
  left: 50%;
  transform: translate(-50%, 0) rotate(45deg) skew(-10deg);
}

This is text


text:
Q: How to cleanly disconnect JFrog X-ray from Artifactory? I was looking at a trial of jFrog X-ray.
Setup was pretty easy. During install I had to provide the Artifactory URL and a Join key.
All was fine. Now I would like to disconnect X-ray from Artifactory.
What is the right way of doing this without having any impact on my Artifactory Repos?
Thanks
Kristian

A: JFrog Xray can be disabled or disconnected from Artifactory by just unchecking the Xray Enabled option by going to the Administration module, then to Xray Security and Compliance | Advanced, and clicking Settings.
Xray


text:
Q: Considering interior points in solving Karush-Kuhn-Tucker (KKT) conditions I'm reading a material on optimization, specifically KKT conditions. The material says to check for optima in boundary points only and not in interior points. But if we don't check interior points, won't we miss many local optima that are interior points? A detailed setup is given below.
Description
Consider a non-linear constrained optimization problem with inequality conditions $g_i(\mathbf{x})$ $i = 1,2,...,m$.
I will define some notations from the material I am referencing in regards to this problem.
Let $\mathbf{x}^*$ be a point satisfying the conditions.
Define $J$ as the set of indices $j$ for which $g_j(\mathbf{x}^*) = 0$.
Also, we define three sets,
$S:$ set of points satisfying $g_i(\mathbf{x}^*) \leq 0$ for all $i = 1,2,...,m$
$S_{E}:$ set of points satisfying $g_i(\mathbf{x}^*) \leq 0$ for all $i = 1,2,...,m$ and
$g_{j}(\mathbf{x}^*)=0$ for all $j$ in $J$
$S_{N}:$ set of points satisfying $g_i(\mathbf{x}^*) \leq 0$ for all $i = 1,2,...,m$ and
$g_{j}(\mathbf{x}^*)<0$ for at least one $j \in J$
From these definitions, $S=S_{E} \cup  S_{N}$ and $S_E \cap S_{N} = \emptyset$
One result in the material: If $\mathbf{x}^{*}$ is a local minimum of $f(\mathbf{x})$ within $S,$ it should be also a local minimum within $S_{E}$.
From the above result, it is sufficient if we check the Karush-Kuhn-Tucker conditions only for the set $S_E$, i.e. only border points of the constrained set.
Won't we miss some local minimum present in the interior point of the constrain set by ignoring the interior points?
Or does the result stated above hold true under certain additional conditions which has not be considered here?


text:
Q: AJAX Calls with Text Links I want to make POST Ajax calls when users click on text links.
One way to do it is to create many forms and make the submit button a text link. Then with jQuery I will fetch the variables from the form and submit them with Ajax.
This will create something like the following:
<form><input type="hidden" name="unique-id" value="1"></form>
<form><input type="hidden" name="unique-id" value="2"></form>
<form><input type="hidden" name="unique-id" value="3"></form>

Now with jQuery I will use .click() Event handler and send a POST request with the "unique-id" value (from the scope in which the link click was from).
It looks very complicated and messy and I was wondering if there is a better way to do that.
Thanks
Joel

A: You don't need a form to do an Ajax post, You feed the data into the Ajax call itself:
$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success
  dataType: dataType
});

See: http://api.jquery.com/jQuery.post/

A: Why not just use the "unique-id" as an id for the links and use that id when posting.
Link
Foo
ASDF

A: Check Ajaxify Jquery plugin using the new the Forms submit feature its very easy to use and clean


text:
Q: Lambda Missing authentication token I'm trying to create a simple lambda function to show a QRCode when the link is accessed. I would like it to be public so anyone can access it.
This is the code for the controller:
[Route("QRCode")]
[ApiController]
public class QRCodeController : ControllerBase
{

    [HttpGet]
    public IActionResult GetQRCode()
    {
        //return Ok();
        //byte[] imgData = null;
        //return File(imgData, "image/png");
        QRCodeGenerator qrGenerator = new QRCodeGenerator();
        QRCodeData qrCodeData = qrGenerator.CreateQrCode("hello", QRCodeGenerator.ECCLevel.Q);
        QRCode qrCode = new QRCode(qrCodeData);
        Bitmap qrCodeImageBitMap = qrCode.GetGraphic(20);
        byte[] imgData;
        using (var stream = new MemoryStream())
        {
            qrCodeImageBitMap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            imgData = stream.ToArray();
        }
        return File(imgData, "image/png");
    }

}

I published to AWS Lambda and the it can be seen in the Lambda Functions. However, when I try to access it, I get the error: "{"message":"Missing Authentication Token"}". This is strange as I don't think I am using any authentication.

What should I change to make it public? This is where I got the link:

A: This error is mostly related to requesting a non-existent URL. Double check what URL are you trying to call.
Sorry for not commenting, just don't have the rep yet :)
Best regards!
EDIT: so it came out that there was no policy attached to the Lambda => it couldn't write to CloudWatch.
Once the permissions were in place, the logs showed that a library which is present in .NET was missing in .NET Core


text:
Q: error call to member function set_value is ambigious (in xcode using pugixml library) i am using pugixml in visual c++ express 2010. this code works. however when i use it in xcode. it gives me an error that 'call to member function ''set_value'' is ambigious'.
can any body help in solving it or why it is giving me error in xcode.
for (size_t k = 0; k < num; ++k) {

    for (size_t v = 0; v < height; ++v) {

        if(width==2){
            pugi::xml_node weightNode = weightsNode.append_child("Test_Output");
            weightNode.append_attribute("No").set_value(k);
            weightNode.append_attribute("index1").set_value(v);
            weightNode.append_attribute("index2").set_value(v);  //as 1x2 case first value position is (0x0)
            weightNode.append_attribute("value").set_value(networks[k][6][0].at<double>(v,v));
            weightNode.append_attribute("index1").set_value(v);
            weightNode.append_attribute("index2").set_value(v+1);
            weightNode.append_attribute("value").set_value(networks[k][6][0].at<double>(v,v+1));
        }else{
            for (size_t u = 0; u < width; ++u) {
                pugi::xml_node weightNode = weightsNode.append_child("Output");
                weightNode.append_attribute("No").set_value(k);
                weightNode.append_attribute("index1").set_value(v);
                weightNode.append_attribute("index2").set_value(u);
                weightNode.append_attribute("value").set_value(networks[k][6][0].at<double>(v,u));
                weightNode.append_attribute("index1").set_value(v);
                weightNode.append_attribute("index2").set_value(u);
                weightNode.append_attribute("value").set_value(networks[k][6][0].at<double>(v,u));
            }
        }
    }
}

can any body pinpoint why it is giving error in xcode. however it works properly in visual c++.
thanks

A: According to the documentation, there are overloads of set_value for several types:
bool set_value(const char_t* rhs);
bool set_value(int rhs);
bool set_value(unsigned int rhs);
bool set_value(double rhs);
bool set_value(bool rhs);

but not for size_t, unless it happens to be an alias for unsigned int.
You'll need to either change the type of k and v to unsigned int, or cast when calling set_value. If you need support for very large values which aren't representable by unsigned int, then you'll need a better library.


text:
Q: how to get the object inside an object? I am trying to use thread can anyone tell me what is wrong in the following code. I am getting a NullPointerException in main.
 public class threadtest implements Runnable {

   Thread t;

   public threadtest(String name) {
     Thread t = new Thread(name);
   }

   public void run() {
     for(int i = 0; i <= 10; i++) {
       try {
         Thread.sleep(1000);
       }
       catch(Exception e) {
         System.out.println(e);
       }
     }
   }

  public static void main(String args[]) {
   threadtest ob = new threadtest("satheesh");
   ob.t.start();
  }
}

A: In your constructor you declare a local variable called t which uses the same name as your field t. Simply replace Thread t with this.t or simple t there:
public threadtest(String name) {
  this.t=new Thread(name);
}

BTW1, it's highly recommended to start class names with capital letters, i.e. ThreadTest in your case would be a better name.
BTW2, a decent IDE would spot this mistake for you and drew your attention to this.

A: Field Thread t is never used, threadtest itself is a Runnable.
Remove t, and call new Thead(threadtest).start();
or java.util.concurrent.Executors.newSingleThreadExecutor().submit(threadtest);

A: You must pass "this" to the constructor of your thread, if you want that your own runnable gets executed.

A: hey there! actually, Grzegorz Oledzki pretty much has the right answer, however, there is one more thing that was overlooked-
in your constructor, you still need to pass this as a parameter to Thread. because right now, you implemented runnable, but are merely passing the string name to the Thread constructor. that won't do anything.
public threadtest(String name) {
     t = new Thread(this, name);
}


text:
Q: Defining custom Schema methods in mongoose to return a single property? I have two schemas and from each, I want to return a single property.
Here is the schema for a single document or file.
// @ts-check
import { Schema, model } from "mongoose";

const docSchema = new Schema({
  name: { type: String, required: true },
  approved: { type: Boolean, default: false },
  docType: { type: String, required: true },
  size: { type: Number, required: true },
  bucket: { type: Schema.Types.ObjectId, ref: "Bucket" }
});

docSchema.methods.getSize = function(cb) {
  // Return the size of document
};

const Doc = model("Document", docSchema);

export default Doc;

And this is the schema for a bucket of documents
// @ts-check
import { Mongoose, Schema, model } from "mongoose";

const bucketSchema = new Schema({
  name: { type: String, required: true, index: true, unique: true },
  projectId: { type: String, required: true, index: true },
  contractorId: { type: String, required: true, index: true },
  Docs: [{ type: Schema.Types.ObjectId, ref: "Document" }]
});

bucketSchema.methods.getSize = function(cb) {
  // return the size of all documents that belong to a single bucket
  // How do I traverse over the Docs array and use Doc.getSize()???
};

const Bucket = model("Bucket", bucketSchema);

export default Bucket;

Is there a way to do this? I don't want to have to query the database each time I need to get the size of the bucket and then traverse over the results and add the size of each document. I want to make it simple so that basically I call Bucket.getSize() and it returns me the size of the bucket so I can restrict the users from uploading files when they've exceeded a certain limit.
Any help would be appreciated.


text:
Q: How do I select records into a single row? I've tried writing my sql query to select multiple records on to one row but it isn't working the way I expected it to
Currently my table looks something like this

person id
fruit

1
apple

1
orange

1
banana

2
apple

2
orange

3
apple

I've tried using CASE and GROUP BY but it just gave extra records and didn't display the way I wanted it to and is displaying like this
SELECT DISTINCT
F.MEMBER
,F.GIVEN_NAMES
,F.SURNAME
--VALUES NEEDED
,CASE WHEN F.VALUE_NEEDED = 'Postal Address' THEN 'Yes' ELSE '' END POSTAL_ADDRESS
,CASE WHEN F.VALUE_NEEDED = 'Birthday' THEN 'Yes' ELSE '' END BIRTHDAY
,CASE WHEN F.VALUE_NEEDED = 'Email Address' THEN 'Yes' ELSE '' END EMAIL_ADDRESS
,CASE WHEN F.VALUE_NEEDED = 'First Name' THEN 'Yes' ELSE '' END FIRST_NAME
,CASE WHEN F.VALUE_NEEDED = 'Surname' THEN 'Yes' ELSE '' END SURNAME
,CASE WHEN F.VALUE_NEEDED = 'Title and Gender' THEN 'Yes' ELSE '' END 'TITLE|GENDER'
,CASE WHEN F.VALUE_NEEDED = 'Mobile' THEN 'Yes' ELSE '' END MOBILE
,CASE WHEN F.VALUE_NEEDED = 'Beneficiary' THEN 'Yes' ELSE '' END BENEFICIARY
FROM #FINAL F
GROUP BY F.MEMBER,F.GIVEN_NAMES
,F.SURNAME,VALUE_NEEDED
ORDER BY F.MEMBER

person id
apple
orange
banana

1
yes

1

yes

1

yes

How do I write the query so it looks more like this?

person id
apple
orange
banana

1
yes
yes
yes

2
yes
yes

3
yes

A: You are almost there, just needed to add the max and group by to aggregate it . This used to be a typical interview question back then.
Some thing like this if I understood correctly
with t as
(
  select 1 as person_id, 'apple' fruit
  union
  select 1 ,'orange'
  union
  select 1 ,'banana'
  union
  select 2 ,'apple'
  union
  select 2 ,'orange'
  union
  select 3 ,'apple'
)
, b as
(
  select
    person_id,
    case when fruit= 'apple' then 'yes' else null end 'apple',
    case when fruit= 'orange' then 'yes' else null end 'orange',
    case when fruit= 'banana' then 'yes' else null end 'banana'
  from t
)
select
  person_id,
  max(apple) apple,
  max(orange) orange,
  max(banana) banana
from b
group by 1;

person_id
apple
orange
banana

1
yes
yes
yes

2
yes
yes
NULL

3
yes
NULL
NULL

A: You have tagged the tool that you are using (SQL Server Management Studio) which can be used with different DBMS. As Microsoft's SQL Server is the most typical used in this tool, I assume your are using that.
First let's look at your table. It seems a bit weird. It seems to be a kind of key-value table (aka EAV). Each row tells us for an attribute whether it is needed for a person. Now how to identify a person in the table? Is the column member a unique person ID? Probably not, because then, what would be given_names and surname be for in that table, that can change with every entry. Why would the same person with the ID 1234 be called John Smith when the value_needed is 'Birthday', but be called 'Anne Miller' when value_needed is 'Mobile'? That wouldn't make much sense. So maybe member is just a flag, whether a person is a member or not, and a person is uniquely identified by their given_names and surname. But then again, why would the same person John Smith be a member when value_needed is 'Birthday', but not a member when value_needed is 'Mobile'? So something is amiss here. It seems your table is not normalized. Better have one person table and one table for the attributes.
That being said, GROUP BY ___ means "I want one result row per ___". You group by the person and their value_needed. But you don't want one result row per person and value_needed. You want one resut row per person. Hence, group by person.
Then you SELECT DISTINCT .... This means you want to remove duplicate rows. But look at the rows you are selecting. There are no duplicates. If you use GROUP BY, you can be 99.99% sure you don't need DISTINCT. (There do exist rare situations where you voluntarily group by columns, don't select all of them and then apply DISTINCT, but these are so rare that you probably won't ever use them at all.)
Now to the task: You want to get from rows to columns. This is called pivot and can be achieved with the PIVOT keyword, but it is more common to use conditional aggregation. "Conditional aggregation" means that you aggregate your data (per person) and then apply a condition. In standard SQL:
SELECT MIN('YES') FILTER (WHERE f.value_needed = 'Postal Address')

You can use MIN or MAX here, and it is only required for syntax reasons (the FILTER clause must refer to some aggregation function.
In SQL Server there is no FILTER clause, so you use a CASE expression instead:
SELECT MIN(CASE WHEN f.value_needed = 'Postal Address' THEN 'YES' END)

If you want the empty string '' instead of NULL, apply COALESCE:
SELECT COALESCE(MIN(CASE WHEN f.value_needed = 'Postal Address' THEN 'YES' END), '')

Columns aliases containing special characters like | require quoting. But not single quotes, as these denote string literals. In standard SQL use double quotes, in SQL Server use brackets. But better, just avoid them alltogether, by avoiding special characters in names.
The complete query:
SELECT
  person_id,
  MIN(CASE WHEN value_needed = 'Postal Address'   THEN 'yes' end) AS postal_address,
  MIN(CASE WHEN value_needed = 'Birthday'         THEN 'Yes' end) AS birthday,
  MIN(CASE WHEN value_needed = 'Email'            THEN 'Yes' END) AS email_address,
  MIN(CASE WHEN value_needed = 'First Name'       THEN 'Yes' END) AS first_name,
  MIN(CASE WHEN value_needed = 'Surname'          THEN 'Yes' END) AS surname,
  MIN(CASE WHEN value_needed = 'Title and Gender' THEN 'Yes' END) AS title_gender,
  MIN(CASE WHEN value_needed = 'Mobile'           THEN 'Yes' END) AS mobile,
  MIN(CASE WHEN value_needed = 'Beneficiary'      THEN 'Yes' END) AS beneficiary
FROM #FINAL
GROUP BY person_id
ORDER BY person_id;


text:
Q: Atom: Unstaged Changes Pop Up I'm using the Atom IDE, and an "Unstaged Changes" tab pops up each time I switch to an other tab (see image below).
I know what unstaged changes are, I just don't know how to keep the window from popping up all the time. I've turned off all the packages that contain the word "git", but that didn't solve the isse. Any help would be appreciated!
Atom Unstaged Changes Tab

A: I uninstalled Atom, and reinstalled it. That solved the problem. I was hoping to not have to uninstall, but it was really making me crazy to work with the constant pop-ups.
Thanks for all the comments! It seems like it wasn't a problem with the .git file in the project folder (since that wouldn't be effected by reinstalling Atom)


text:
Q: Testing on iOS 3.1 simulator iOS project. Base SDK 4.2, deployment target 3.0. A customer is complaining about an issue on iOS 3.1 (he has an old device).
I tried installing Xcode 3.2.3 - the oldest there is for download. It does not offer iOS 3.1 as a test target. Does anyone know how can I enable older versions of iOS on the simulator?
The box also has Xcode 4 (in a different folder). Could it be the case that they're sharing the iOS simulator, and the backwards-incompatible one from Xcode 4 is getting in the way?

A: There is no substitute for testing on a real device.
I've had a problem with my iPod touch (3rd gen, ios 5.0) crashing in one app. Every day. The dev won't buy, beg, borrow or steal a real iPod touch to test it on so he can fix it. As a user this is extremely frustrating.
EDIT:
The final versions of Xcode with the iPhone SDK, as it was called then, are not available from Apple's download page, but the direct links still work.
The direct links can be found at:
http://chris-fletcher.com/2010/08/28/howto-install-iphone-sdk-2-0-3-1-for-xcode-3-2/

A: If you use the latest Xcode, you can install device debugging support via the Downloads->Components section, a la: http://cl.ly/3U1V1G3W2p2E1G29342e

A: http://iphonesdkdev.blogspot.com/2010/04/old-versions-of-iphone-sdk.html
Some of the links are dead though. Apple is removing those old files little by little. Get them while supplies last.


text:
Q: Export Values from MATLAB workspace to CSV or XLS I would like to be able to export the Value from each Name in the Workspace using MATLAB.
I have some questions, which then sets the variables in the workspace. I have tried xlswrite but I have been unsuccessful in being able to export the file. I don't think that it would export just the value, which I would like it to do.
% Construct a questdlg with three options
choiceprepq = 'Which animal do you like?';
choiceprep = questdlg('Which animal do you like?', 'Which animal do you like?', 'Dog', 'Cat','Fish');
% Handle response
switch choiceprep
case 'Dog'
    disp([choiceprep ' Dog Selected.'])
case 'Cat'
    disp([choiceprep ' Cat Selected.'])
case 'Fish'
    disp([choiceprep ' Fish Selected.'])
end

alldata= whos('global');
filename='Test.xls';
xlswrite(filename,alldata)

Is there any way to export the question and the value which the user selects from the question boxes as an Excel file? Not the name of the variable, choiceprep, but its value.
An example in this case would be:

A: First of all, unless you actually declare choiceprepq and choiceprep as global variables, using whos('global') won't give you those two. It's not necessary here anyways, because you already know the variables you want.
Also, you're using questdlgwrong, you need to specify your default answer, so it should be like this:
% syntax :  button = questdlg('qstring','title', default)
choiceprepq = 'Which animal do you like?';
choiceprep = questdlg(choiceprepq, choiceprepq, 'Dog', 'Cat', 'Fish', 'Dog');

When you do xlswrite, it actually only writes the values held by the variables. In your case, you can easily store the question and answer into an xls file by this:
filename = 'Test.xls';
xlswrite(filename, {choiceprepq, choiceprep})

The curly braces turn the two variables into a 1x2 cell array whose values can be easily written into xls file by xlswrite.
xlswrite does not seem to work properly on Mac OS. Here's a MATLAB file exchange submission that's supposed to help : http://www.mathworks.com/matlabcentral/fileexchange/38591-xlwrite--generate-xls-x--files-without-excel-on-mac-linux-win


text:
Q: ConnectionResetError: [WinError 10054] When using Selenium Chrome Hello i have a simple problem that has suddenly developed on my code, until yesterday it was working correctly, this means it opened a web page and entered login details (is a test for a bigger app), however now whenever it tries to connect to the login page i get a timeout error. I have updated Selenium and Chrome Web Driver to the latest and it is still failing to connect, this is my code:
#importing libraries, selenium is the base of the script, time to add pauses when appropiate or necessary and select and request will stay until i determine that they are not necessary for the final script.
from selenium import webdriver
from selenium.webdriver.support.ui import Select
import time
import requests
#defining browser to use the webdriver with chrome, and navigating to Makor.
browser = webdriver.Chrome()
browser.get('http://mrmprod/Login.aspx')

And this is the complete error code:

Traceback (most recent call last):
        File "C:\Users\AMSUser\AppData\Local\Programs\Python\Python35-32\Scripts\Input
  test.py", line 7, in
          browser = webdriver.Chrome()
        File "C:\Users\AMSUser\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\chrome\webdriver.py",
  line 69, in init
          desired_capabilities=desired_capabilities)
        File "C:\Users\AMSUser\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py",
  line 92, in init
          self.start_session(desired_capabilities, browser_profile)
        File "C:\Users\AMSUser\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py",
  line 179, in start_session
          response = self.execute(Command.NEW_SESSION, capabilities)
        File "C:\Users\AMSUser\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py",
  line 234, in execute
          response = self.command_executor.execute(driver_command, params)
        File "C:\Users\AMSUser\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 407, in execute
          return self._request(command_info[0], url, body=data)
        File "C:\Users\AMSUser\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 439, in _request
          resp = self._conn.getresponse()
        File "C:\Users\AMSUser\AppData\Local\Programs\Python\Python35-32\lib\http\client.py",
  line 1197, in getresponse
          response.begin()
        File "C:\Users\AMSUser\AppData\Local\Programs\Python\Python35-32\lib\http\client.py",
  line 297, in begin
          version, status, reason = self._read_status()
        File "C:\Users\AMSUser\AppData\Local\Programs\Python\Python35-32\lib\http\client.py",
  line 258, in _read_status
          line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
        File "C:\Users\AMSUser\AppData\Local\Programs\Python\Python35-32\lib\socket.py",
  line 575, in readinto
          return self._sock.recv_into(b)
      ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

I asked the network administrator and he has told me that there hasn't being any change on the network settings since i originally got the code working.

A: If you have reviewed the aforementioned then do the following steps:
You have to include inside the parenthesis the chromedriver path.
Check the code below:
CODE SAMPLE FOR WINDOWS OS
browser = webdriver.Chrome('C:\\User\\YOUR_USERS_NAME\\YOUR_PATH\\chromedriver.exe')

CODE SAMPLE FOR LINUX OS
browser = webdriver.Chrome('usr\\bin\\YOUR_PATH\\chromedriver')


text:
Q: How to calculate the Summation?? Can we get the formula in terms of N and k for this summation series?
$$
A=\sum_{t=0}^N\sum_{s=0}^t\sum_{r=0}^sk^rk^{s-r}k^{t-s}
$$

A: $$A=\sum_{t=0}^{N}\sum_{s=0}^{t}\sum_{r=0}^{s}k^t=\sum_{t=0}^N\sum_{s=0}^t (s+1)k^t = \sum_{t=0}^N \frac{(t+2)(t+1)}{2}k^t \tag{1}$$
is a partial sum for the Taylor series of $\frac{1}{(1-k)^3}$ in a neighbourhood of $k=0$.
By multiplying the RHS of $(1)$ by $(1-k)^3$ we get:

$$ A = \frac{1}{(1-k)^3}\left(1-\binom{N+3}{2}k^{N+1}+(N+3)(N+1)k^{N+2}-\binom{N+2}{2}k^{N+3}\right).\tag{2}$$

A: Another way of determining the last sum is to note that if
$$S_N(k)=\frac12 \sum_{t=0}^N k^{t+2}=\frac{k^2-k^{N+3}}{2(1-k)} \tag 1$$
then upon taking two derivatives reveals that
$$S_N''(k)=\sum_{t=0}^N \frac{(t+2)(t+1)}{2}k^{t}=A \tag 2$$
Thus, taking the second derivative of the right-hand side of $(1)$, we find that
$$S_N''(k)= \frac12 \left( 2\frac{k^2-k^{N+3}}{(1-k)^3} +2\frac{2k-(N+3)k^{N+2}}{(1-k)^2} +\frac{2-(N+3)(N+2)k^{N+1}}{1-k}    \right)$$


text: Q: Cant login to the laptop (windows 10 ) with domain users at our company, we have several laptops, that for no apparent reason stopped to allow all the users who are not admins in AD to log in. When you try to log in to one of those laptops it goes to a loading screen and just never enters the user profile. Can anyone tell me what I should look for to resolve this issue? thank you


text:
Q: Seq number for CouchDB document Is there a way to know which database sequence number ( seqnum ) a document belongs to in Couchdb ? Like how we determine a commit hash for files in git ?
I am looking for some kind of a _field which is already present or can be determined.
Please help. Thanks !

A: You can use the changes feed to connect a seqnum to a specific document if you know the seqnum ahead of time.
GET /database/_changes?since=<seqnum - 1>&limit=1

It will return you just a single result, and it will have the changed document's ID, as well as whatever changes were made during that write operation.


text:
Q: How to capture div content and display within a modal box? On the user clicking an image on the html page, the below uses jquery to capture that image and then display it within a modal pop up box.
I'd now also like to capture the contents of a div to pass to this modal box.
I've tried adding the below  $(this).width(100).height(100).appendTo('#badgeselect');, but this does'nt appear to work, what have I missed?
(I have added the .go class to the wrapper div)
               $( ".wrapper" ).on('click', 'wrapper');
               $(this).width(100).height(100).appendTo('#badgeselect_b');

Existing code
$(document).ready(function() {
    $('.go').css('cursor', 'pointer');
    $('.go').on('click', 'img', function(e) {
        $(this).width(100).height(100).appendTo('#badgeselect');
        $('#modal').reveal({
            animation: 'fade',
            animationspeed: 600,
            closeonbackgroundclick: true,
            dismissmodalclass: 'close'
        });
        return false;
    });
});

A: Sample tutorial to capturing text from one div and show it another div Sample

Hellooo World !

A: http://jsfiddle.net/m2AJs/1/ : WORKING FIDDLE FOR EXAMPLE

To capture the content as you say you can use following methods :
1. .text() : http://api.jquery.com/text/
This will get you textual content of the div.
Use this if you need only text.
ex : $("#modalDivId").text($("#divID").text());

2. .html() : http://api.jquery.com/html/
This will get you the div as is, i.e. with any formatting, tags, or elements in it.
Use this if you need elements such as , ,  as well.
ex : $("#modalDivId").html($("#divID").html());


text:
Q: XML generation using Nokogiri involving nested tags and namespace Using gem Nokogiri I'm trying to generate XML like:
<?xml version='1.0'?>
  <env:Envelope xmln:env = "http://abc.ca">
    <env:Header>
      <mm7:TransactionID xmlns:mm7="http://def.ca"> Some Text Here </mm7:TransactionID>
    </env:Header>
  </env:Envelope>

The code I have is:
env_ns = {
  "xmlns:env" => "http://abc.ca"
}

mm7_ns = {
  "xmlns:mm7" => "http://def.ca"
}

env_header = Nokogiri::XML::Builder.new do |xml|
  xml['mm7'].TransactionID(mm7_ns) do
    "Some Text Here"
  end
end

builder = Nokogiri::XML::Builder.new { |xml|
  xml['env'].Envelope(env_ns) do
    xml.Header do
      env_header
    end
  end
}

puts env_header.to_xml
puts "----------------------"

puts builder.to_xml

However, the output is not as desired because the value "Some Text Here" did not go inside the mm7:TranactionID tag. The mm7 tag did not go inside the header tag. Also, the header tag did not go inside the envelope tag.
<?xml version="1.0"?>
  <mm7:TransactionID xmlns:mm7="http://def.ca"/>
-----------------------------------------------------------
<?xml version="1.0"?>
  <env:Envelope xmlns:env="http://abc.ca">
   <env:Header/>
  </env:Envelope>

Thanks.

A: You only need 1 builder:
env_ns = {
  "xmlns:env" => "http://abc.ca"
}

mm7_ns = {
  "xmlns:mm7" => "http://def.ca"
}

builder = Nokogiri::XML::Builder.new do |xml|
  xml['env'].Envelope(env_ns) do
    xml.Header do
      xml['mm7'].TransactionID(mm7_ns, "Some Text Here")
    end
  end
end

puts builder.to_xml

# will render the following:
# <?xml version="1.0"?>
# <env:Envelope xmlns:env="http://abc.ca">
#   <env:Header>
#     <mm7:TransactionID xmlns:mm7="http://def.ca">Some Text Here</mm7:TransactionID>
#   </env:Header>
# </env:Envelope>


text:
Q: C++ select function breaks prematurely Okay, first off: Sorry if this has been asked before, but I couldn't figure out the correct keywords if it had been.
Situation: I have a small Network server, which runs in it's own Thread. The 'Run'-Method iterates over a collection of active Sockets (Both UDP and TCP), checks for Activity and does it's thing. All of this is achieved via select.
It is possible, that, while 'stuck' in select a new server is added. For this purpose, I have incorporated a 'Breaker socket', which is checked alongside the others. It gets closed when a new socket is added, so the new socket will also be monitored for traffic. (fd_set gets regenerated each time select got broken)
Code is like this (abbreviated):
fd_set fds;
SOCKET mSock = Breaker;

FD_ZERO(&fds);
//Aquire Mutex
if(Breaker == INVALID_SOCKET)
    mSock = Breaker = socket(AF_INET, SOCK_STREAM, 0);
FD_SET(Breaker, &fds);
//Iterate over active sockets and add them to fds.
//Release Mutex

if(select(mSock + 1, &fds, NULL, NULL, NULL) > 0) {
    //AquireMutex
    //Iterate over active sockets, check for activity and act accordingly.
    if(Breaker != INVALID_SOCKET && FD_ISSET(Breaker, &fds)
        //Close Breaker and set it to INVALID_SOCKET
    //Release Mutex
}

Now the actual problem: select is broken continuously, no matter whether I close Breaker or not. It constantly reports 'activity' on the socket.
Breaker is a simple socket, not bound or connected.
If I change the type of Breaker to 'DGRAM', it doesn't break select at all, even if closed.
Language is C++, Platform is a Linux-derivate, INVALID_SOCKET is defined as -1 and SOCKET is a typedef to int. (Code is supposed to work with WinSock too)
Thank you for your help.
Edit:
I've tried reading from the Buffer. Calling recv on the Breaker socket returned with -1, setting errno to 107 (Transport endpoint not connected), which is not surprising, seeing how it really isn't connected.
Edit:
Since my intention apparently is unclear, I'll describe it again.
It is possible, that a new server socket is added to the queue at any given point in time. However this socket will not be monitored for traffic, unless select is broken (and fd_set is subsequently refilled with the new socket) at least once. Any traffic arriving on the new socket is thereby discarded.
I am aware, that I could be using timeouts, but I was hoping there'd be a different solution.

A: This is expected. If there's nothing to wait for, select cannot wait. If the socket is closed, there's nothing to wait for. If the socket isn't connected, there's nothing to wait for. If you want select to wait, you have to give it something to wait for. And when it tells you that there's nothing to wait for, you shouldn't ask it to wait again -- that makes no sense. You have to handle whatever select is telling you before you call it again or the same thing will just keep happening.

A: Instead of using a socket to signal an event you could use a pipe (man 2 pipe).
I'd rather revise your architecture if possible.
PS: I swear I haven't looked on the question proposed by Michael Burr in a comment.


text:
Q: How to parse XML with multiple attribute values within a single tag to DataFrame? <?xml version="2.0" encoding="UTF-8" ?><timestamp="20220113">
<defintions>
    <defintion id="1" old_id="0">Lang</defintion>
    <defintion id="7" old_id="1">Eng</defintion>

How can I parse an XML file that looks like this? Here, I have multiple values within a single tag. I want to extract values such as "ID", and "OLD_ID" in a list or dataframe format.

A: You could use BeautifulSoup and xml parser to get your goal, simply select the elements needed and iterate ResultSet to extract attribute values via .get().
with open('filename.xml', 'r') as f:
    file = f.read()
    soup = BeautifulSoup(file, 'xml')

Example
from bs4 import BeautifulSoup
import pandas as pd

xml = '''<?xml version="2.0" encoding="UTF-8" ?><timestamp="20220113">
<defintions>
    <defintion id="1" old_id="0">Lang</defintion>
    <defintion id="7" old_id="1">Eng</defintion>
'''
soup = BeautifulSoup(xml,'xml')

pd.DataFrame(
    [
        (e.get('id'),e.get('old_id'))
        for e in soup.select('defintion')
    ],
    columns = ['id','old_id']
)

Output

id
old_id

0
1
0

1
7
1

A: Using python Beautiful Soup, you could parse the .xml file to a Beatuful soup object and then use .findAll('defintions').
Then loop through the tags you find and get the desired values
object.findAll('defintions')

for defintion in defintions:
    old_id = defintions['old_id']
    id = defintions['id']

references:
https://www.crummy.com/software/BeautifulSoup/bs4/doc/
https://linuxhint.com/parse_xml_python_beautifulsoup/

A: If you have a valid XML like (timestamp tag can't have a value like an attribute):
<?xml version='1.0' encoding='utf-8'?>
<root timestamp='20220113'>
<defintions>
    <defintion id="1" old_id="0">Lang</defintion>
    <defintion id="7" old_id="1">Eng</defintion>
</defintions>
</root>

Than you can use pandas:
import pandas as pd

df = pd.read_xml('x89.xml', xpath='.//defintion')
print(df.to_string(index=False))

Output:
 id  old_id defintion
  1       0      Lang
  7       1       Eng


text:
Q: How to add a context indicator to a flipview I created a simple Windows 8 app with a single page and a flipview. My goal is to slide through a set of images. Microsoft suggests to use a context indicator for image galleries with larger amount of images (I have 25 photos).
So for starters: I hope that flipview is the correct tool to my needs?
And how can I add a context indicator to an existing flipview? So far I added the flipview to the xaml file:
<FlipView x:Name="flipView"  Grid.Row="1" VerticalAlignment="Top" Background="Black"/>

Also I added some images in C#:
ImageBrush brush1 = new ImageBrush();
brush1.ImageSource = new BitmapImage(new Uri("ms-appx:///Assets/gallery/IMG_0001.jpg"));

FlipViewItem flipvw1 = new FlipViewItem();
flipvw1.Background = brush1;

flipView.Items.Add(flipvw1);

etc...

A: Check this blog post that describes how to implement one:
http://blogs.u2u.be/diederik/post/2012/08/24/A-CXAML-FlipView-Context-Indicator-for-Windows-8.aspx
Also Callisto includes the implementation that you can just grab from NuGet:
https://github.com/timheuer/callisto/blob/master/src/Callisto/Controls/FlipViewIndicator/FlipViewIndicator.cs


text:
Q: Why asp:UpdatePanel updates hiddenfield value only on second click on button I have problem while updating hiddenfield on button click. When I click on button,
it does not update hiedenfield for first time, only if I click button second time
then I am getting correct value. I searched on web for this and I could not find solution for this. Does anyone know why it is happening and is it default behaviour or if someone can provide me some other usefull approach to solve this problem.
.aspx file:
<asp:ScriptManager ID="scriptManager" runat="server">
</asp:ScriptManager>
<asp:RadioButtonList ID="radioQuestion" runat="server">
    <asp:ListItem Text="first" Value="first"></asp:ListItem>
    <asp:ListItem Text="second" Value="second"></asp:ListItem>
</asp:RadioButtonList>
<asp:UpdatePanel ID="updateResult" runat="server" >
    <ContentTemplate>
        <asp:HiddenField ID="hiddenResult" runat="server" />
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="btnCheck" EventName="Click" />
    </Triggers>
</asp:UpdatePanel>
<asp:Button ID="btnCheck" runat="server" OnClick="btnCheck_Click" Text="Check"
    CssClass="check"  />

Javascript code:
  <script type="text/javascript">
    $(document).ready(function () {
        $('.check').click(function () {
            alert($('#hiddenResult').val());
        });
    });
</script>

.cs file:
 protected void btnCheck_Click(object sender, EventArgs e)
{
    switch (radioQuestion.SelectedValue)
    {
        case "first":
            hiddenResult.Value = "YES";
            break;
        case "second":
            hiddenResult.Value = "NO";
            break;
    }
}

A: What will be helpful for this case is a callback mechanism that is invoked everytime an AJAX request ends . Fortunately, there is one available and it can be registered using:
   Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler).

Later, the EndRequestHandler can be implemented for executing any javascript code on request completion. The argument sender can be used to handle specific requests. The following javascript should serve the purpose:
$(document).ready(function () {
   Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
});
function EndRequestHandler(sender, args) {
   var senderId = sender._activeElement.id;
    if (senderId=="btnCheck") {
        alert($('#<%=hiddenResult.ClientID%>').val());
    }
}

Update: Just realised that activeElement gets you the element on the form currently in focus, which for this case is not necessarily a good poperty to check for. Below is the updated javascript that takes a better approach by using _postBackSettings:
function EndRequestHandler(sender, args) {
   var senderId = sender._postBackSettings.sourceElement.id;
    if (senderId=="btnCheck") {
        alert($('#<%=hiddenResult.ClientID%>').val());
    }
}

A: I dont know what you are trying to do. Still you can buy this
1) Trigger is not required for updatepanel with id=updateResult as UpdateMode is not set and default is always true.
2) You are changing and checking values of <asp:HiddenFiled> on with same control.
So what glitches here, your client side code calls prior to server it means alert($('#hiddenResult').val()); is called before setting  <asp:HiddenFiled> value at code-behind. Once client code calls by returning true value (True by default in any/your case), request sent to server and your btnCheck_Click executes and changes hidden field value with latest one. Next time so on.. You will always get older value with above logic.

Approach you can use

As I said client side code calls prior to server, So move your server code to client side like
   $('.check').click(function () {
        // Get Hidden field
        var hidden = $('[id$=hiddenResult]');

        //Your logic
        if ($('[id$=radioQuestion] input:radio')[0].checked) {
            $(hidden).val('Yes');
        }
        else if ($('[id$=radioQuestion] input:radio')[1].checked) {
            $(hidden).val('No');
        }

        alert($(hidden).val());
  }

Don't forget to add jquery file for reference at header of your page.
Hope This will help

A: Everyone who tried to answer my question helped me a lot. That's why thank you all, but I also have to say that Saurabh answer lead me to find correct solution. I didn't know much about AJAX until now. Back to answer; actually Saurabh was close to find it, only few corrections was necessary to achieve that. Anyway I am posting my working code bellow(only part of Javascript):
  $(document).ready(function () {
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
    });

    function EndRequestHandler(sender, args) {
        if (document.getElementById('btnCheck')) {
            alert($('#<%=hiddenResult.ClientID%>').val());
        }
    }


text:
Q: CQS with dispatcher casting issues I am trying to build a microservice that pulls commands and queries off of a queue. My service watches a specific queue and pulls a message off that could be any type command for that domain. That message is pulled off and passed to the dispatcher. My problem is that in trying to make everything as generic as possible, my message is being passed into the dispatcher as an object, but the dispatcher needs a concrete IQuery class. I can cast it to IQuery because I know that it is that type, but when I try to resolve the dependencies in the dispatcher based on the type, it fails because the concrete type is not known. I will try to keep the code samples small and to the point:
Main Service
    private static async Task HandleMessageReceived(MessageReceivedEventArgs args) {
        await queryDispatcher.Dispatch((IQuery)args.Message.Payload);
    }

Query Dispatcher
public class QueryDispatcher : IQueryDispatcher {
    #region attributes
    private readonly IComponentContext _context;
    #endregion

    #region ctor
    public QueryDispatcher(IComponentContext context) {
        _context = context;
    }
    #endregion

    #region methods
    public async Task<IEvent> Dispatch<T>(T query) where T : IQuery{
        if (query == null) {
            return new ArgumentNullEvent(nameof(query));
        }

        var validator = _context.Resolve<IValidator<T>>();
        var handler = _context.Resolve<IQueryHandler<T>>();

        List<ValidationResult> errors = await validator.Validate(query);

        if(errors.Count == 0) {
            return await handler.Handle(query);
        } else {
            return new ValidationFailedEvent(query.Id, errors);
        }
    }
    #endregion
}

Queue Message
public class QueueMessage {
    public Guid OperationId { get; set; }
    public object Payload { get; set; }
}

Concrete IQuery Impl
public class GetSite : BaseQuery, IQuery {
    public Guid SiteGuid { get; set; }
}

A: You could build the type using MakeGenericType:
var validator = _context.Resolve(typeof(IValidator<>)
                        .MakeGenericType(new[] { query.GetType() }));
var handler = _context.Resolve(typeof(IQueryHandler<>)
                      .MakeGenericType(new[] { query.GetType() }));


text:
Q: netcdf (.nc) file only has -999 values? I'm trying to analyze rainfall data from https://imdpune.gov.in/Clim_Pred_LRF_New/Grided_Data_Download.html, specifically the 'Gridded Rainfall (0.25 x 0.25) NetCDF' Files.
I used netCDF4 to load the data but I get this peculiar result:
from netCDF4 import Dataset
import numpy as np

path = '2013.nc'
f = Dataset(path ,'r')
rain = np.array(f.variables['RAINFALL'][:,:,:])

print(rain[0][0])

output:
[-999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999.
 -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999.
 -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999.
 -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999.
 -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999.
 -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999.
 -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999.
 -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999.
 -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999.
 -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999.
 -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999. -999.
 -999. -999. -999.]

NOTE: There isn't a problem with this specific file, as I get the same result with the data for every year. You can try it out yourself.
Am I loading the data in python wrong is there something up with the data that I downloaded?
The latitude and longitude variables don't give me this problem though

A: from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt

# file import
path = Path('../../Downloads/')
file = 'Clim_Pred_LRF_New_RF25_IMD0p252013.nc'
f = Dataset(path / file, 'r')

# select variable "Rainfall"
rain = np.array(f.variables['RAINFALL'][:,:,:])
# assign NaN value
rain[rain==-999.] = np.nan

# plot dataset for selected date (2013-01-18)
plt.pcolormesh(rain[17])
plt.colorbar()

The data looks fine.
But check out the shape of rain:
print(rain.shape)
(365, 129, 135)
# --> (days, latitude, longitude).

With rain[0][0] you're selecting the first time step (Jan-01) and the first latitude (6.5), which will return a 1D array with NaN values only because all pixels are outside of India. Selecting the second and third dimension with 0 will always return arrays with -999 exclusively. You can try for example rain[17][100]!
print(rain[17][100]
array([        nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,  1.2962954 ,  0.99620295,  2.705826  ,
        9.772656  , 11.187045  ,  0.        ,  3.0871496 ,  5.298688  ,
       18.108587  , 34.280876  , 35.034836  , 41.41929   , 38.952507  ,
       63.49905   , 92.398125  , 92.92495   , 80.57031   , 63.660515  ,
       45.413662  ,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan,
               nan,         nan,         nan,         nan,         nan],
      dtype=float32)


text:
Q: How to make the image fit the whole screen, including the upper part I'm having some trouble styling my app, I want to make the background image to fit the whole screen including the part where the wifi icon and the battery percent. I looked up the older answers but it seems that the android:scaleType isn't there for the autocompletion so I guess it may have been dropped. Can anyone help me? And by this I mean to make the image height to be as big as the actual screen.
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:background="@drawable/books_background"
tools:context=".MainActivity">
</androidx.constraintlayout.widget.ConstraintLayout>

A: Use this code before  setContentViewin onCreate:
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN)


text:
Q: i'm trying to make two different table manytoone mapping in single column for one entity class i'm new to hibernate two manytoone mapping column make to single column
my entity class
      @ManyToOne
      @JoinColumn(name="assignedto_id", referencedColumnName="id", insertable=false, updatable=false)
      private User assignedto;

      @ManyToOne
      @JoinColumn(name="assignedto_id", referencedColumnName="id", insertable=false, updatable=false)
      private LDAPUser assignedto1;

mysql table column
  KEY `FKs437l1xgobeh3iucqmifj356i` (`assignedto_id`),
  CONSTRAINT `FKs437l1xgobeh3iucqmifj356i` FOREIGN KEY (`assignedto_id`) REFERENCES `tbl_master_user` (`ID`)

i want mysql table column like this
 KEY `FKs437l1xgobeh3iucqmifj356i` (`assignedto_id`),
 CONSTRAINT `FKs437l1xgobeh3iucqmifj356i` FOREIGN KEY (`assignedto_id`) REFERENCES `tbl_master_user` (`ID`)

 KEY `FKs437l1xgobeh3iucqmifj356i` (`assignedto_id`),
 CONSTRAINT `FKs437l1xgobeh3iucqmifj356i` FOREIGN KEY (`assignedto_id`) REFERENCES `tbl_ldap_master` (`ID`)

please help me thank you in advance

A: I think what you are looking for is explained in the Hibernate ORM section about @Any annotation:
@Any(metaColumn = @Column(name = "userType"))
@AnyMetaDef(name = "PropertyMetaDef", metaType = "string", idType = "long",
            metaValues = {
                    @MetaValue(value = "User", targetEntity = User.class),
                    @MetaValue(value = "LDAP", targetEntity = LDAPUser.class)
            }
    )
@JoinColumn(name="assignedto_id", referencedColumnName="id", insertable=false, updatable=false)
private Object assignedTo

But it won't create any foreign keys.
I don't even think is possible to create two foreign keys on the same column for different tables (does it even make sense?).
Alternatively, if the two classes could extend from a common super class, you could use Inheritance mapping to achieve something similar.
For example:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public static class UserEntity {

    @Id
    private Long id;

    ...
}

@Entity
public class User extends UserEntity {
...
}

@Entity
public class LDAPUser extends UserEntity {
...
}

and then
      @ManyToOne
      @JoinColumn(name="assignedto_id", referencedColumnName="id", insertable=false, updatable=false)
      private UserEntity assignedto;

This will create three tables though. The table UserEntity will have a foreign key on the assignedto_id column. User id and LDAPUser id will have a constraint each on UserEntity id. Basically, getting close to what you asked originally.


text:
Q: Laravel API resource whenLoaded not working properly with another values I'm working with API resources but I wanted to add some extra logic.
I have this Resource:
return [
    'id' => $this->id,
    'name' => $this->name,
    'contacts' => $this->whenLoaded('contacts'),
    'phone' => $this->whenLoaded('contacts',
        $this->contacts->where('type', '=', 'phone')->first()
            ? $this->contacts->where('type', '=', 'phone')->first()->value
            : null),
];

contacts is a relationship 'one-to-many' where there a multiple ways to contact (phone, email, etc).
Then I wanted to add the attribute 'phone' where it will return the phone contact.
This code works fine, the problem is the attribute phone is always loaded even when the 'contacts' relation is not loaded, this is so bad for the performance because is doing the N+1 problem when I don't need the phone attribute.
Am I using bad the whenLoaded method? The logic is very simply, when the contacts relation is loaded get the phone attribute else don't do it.

A: Your second argument is executed as it gets sent to the function. So the solution is to pass a callable.
You have to structure it like this:
return [
    'id' => $this->id,
    'name' => $this->name,
    'contacts' => $this->whenLoaded('contacts'),
    'phone' => $this->whenLoaded('contacts', function() {
        return object_get($this->contacts->where('type', 'phone')->first(), 'value');
    })
];

I've added some simplification using object_get() as well.


text:
Q: MODX Revo, Path Issue with friendly URLS (only in IE) my MODX installation have serval contexts, each context go to an other domain. Friendly URLS is on.
Everything works fine in Mozilla, Chrome and Safari.
Now we find out that the site do not Work in IE (version 11).I discovered that firendly urls creates the alias path twice.
The Base-Tag is in any template:
<base href="[[!++site_url]]" />

Example url in firefox/mozilla/safari: hostname/section/page.
Example url in IE: hostname/section/section/page.
Do anybody have an idea how can I fix this problem?
I know. IE11 is outdated since Edge comes out. But there a many user that still uses it.

A: Okay, the solution is that pages that hold childs should NOT be marked as "container".


text:
Q: Help with 200k record limit for SOQL query (query selectivity error) We are experiencing an issue around an insert and update for Opportunity Line Items. When creating/updating the OLI, a class is called to creates/updates records on a custom object. The error message is received because a query is run on the custom object and the custom object has over 200k records.
The code was created by a consulting firm and we don't have any devs to help us fix this. Was wondering if this is a quick fix that we could handle with our very limited knowledge of APEX or would we require someone to come in?
Here is the error message:
execution of AfterInsert caused by: System.QueryException: Non-selective query against large object type (more than 200000 rows). Consider an indexed filter or contact salesforce.com about custom indexing. Even if a field is indexed a filter might still not be selective when: 1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times) Class.AutoScheduling.CreateSchedules: line 206, column 1 Trigger.OpportunityLineItemTrigger: line 46, column 1
Here is the part of class containing the SOQL query.
        String theQuery = SOQL_SCHEDULE_QUERY_PT1;
    for (AutoScheduler_Mapping__c s : theCustomSettingMapping.values()) {
        //v1.1 - Check to make sure the field isn't contained in the mandatory fields
        // so taht we prevent duplicate field errors
        if (!theOppScheduleSet.contains(s.Opportunity_Line_Item_Schedule_Field__c.toLowerCase())) {
            theQuery += ', ' + s.Opportunity_Line_Item_Schedule_Field__c;
        }
    }

Thanks.


text:
Q: How to change data type of stl containers in API without breaking existing application? I've a library based c++ where many API has stl container as parameter. And stl container's are int type. Like
f1(std::vector<int> items)
f2(std::map<int, int> mp)

Now int type needed to be changed into long long int (64 bit integer). Like
f1(std::vector<long long int> items)
f2(std::map<long long int, int> mp)

Lots of application has already been developed based on that library. If I changed API signature from int to long long int that will break those applications. And as there are many API I don't want to overload every API.
Is there a way to support long long int in those API without breaking existing applications and without using function overloading?
Is it possible to create a wrapper class which will implicitly convert itself to std::vector or std::vector based on function calling?

A: The thing is, that if you don't want existing applications to break, you cannot require them to change their code. If you need the 64-bit integers in your API internally, you can just cast the elements (or copy the input vectors), but since the passed parameters are most likely 32-bit integer, the additional information that a long long can store aren't there anyway. If you want to pass effectively 64-bit of data, the client code has to change.
EDIT: If newer implementations should be able to use long long, then I suggest overloading to be your best option. Casting to vector<int> will lose information  and changing the signature of the only method will break current clients. When someone calls the old variant you can cast the single elements to long long. If you want to store the whole vector, just copy it.
I also suggest to pass the vector by (const) reference, you can avoid an unnessecary copy of possible large data and it will not break clients, since the calling syntax stays the same.


text:
Q: Auto install dependencies when installing rpm package I'm new on Centos and i would like to know how to install an rpm package with all it dependencies.
Example : deepin-screenshot
When i try to install it with :
rpm -Uvh deepin-screenshot-4.0.10.4-4.fc29.x86_64.rpm

i have a dependency error :
attention : deepin-screenshot-4.0.10.4-4.fc29.x86_64.rpm: Entête V3 RSA/SHA256 Signature, clé ID 429476b4: NOKEY
erreur : Dépendances requises:
    libQt5Core.so.5(Qt_5.11)(64bit) est nécessaire pour deepin-screenshot-4.0.10.4-4.fc29.x86_64
    libdtkcore.so.2()(64bit) est nécessaire pour deepin-screenshot-4.0.10.4-4.fc29.x86_64
    libdtkwidget.so.2()(64bit) est nécessaire pour deepin-screenshot-4.0.10.4-4.fc29.x86_64
    libdtkwm.so.2()(64bit) est nécessaire pour deepin-screenshot-4.0.10.4-4.fc29.x86_64

A: You need to use the yum install rpm_name.
sudo yum install deepin-screenshot-4.0.10.4-4.fc29.x86_64.rpm
The rpm command does not download the dependencies from the internet, yum does.
Moreover, Uvh parameter in your command stands for uninstall, verbose, hash.
So, you are trying to uninstall the RPM with your mentioned command instead of installing it.

A: You cannot install a Fedora 29 package (the fc29 suffix) on CentOS. You need to find a CentOS version of the RPM you're installing, or rebuild it from source.
After that, you could use yum to handle dependency traching.


text:
Q: What is the first non zero digit in 50 factorial (50!)? What is the first non zero digit in 50 factorial (50!)?
Any Help or hint will be appreciated.

A: Since $50_{\text{ten}}=200_{\text{five}}$, $\sigma_5(50)=2$. Thus, the number of factors of $5$ in $50!$ is $\frac{50-2}{5-1}=12$.
Since $50_{\text{ten}}=110010_{\text{two}}$, $\sigma_2(50)=3$. Thus, the number of factors of $2$ in $50!$ is $\frac{50-3}{2-1}=47$.
Thus, $\frac{50!}{10^{12}}$ has $35$ factors of $2$.
Little Fermat says that $2^4\equiv1\pmod{5}$, so $2\cdot2^4\equiv2\pmod{10}$, therefore $2^{35}\equiv2\cdot2^{34}\equiv2\cdot2^2\equiv8\pmod{10}$.

Every integer is uniquely representable as $m\cdot2^j\cdot5^k$ where $(m,10)=1$.
Let's compute the product $\bmod{\,10}$ of all of the numbers $m$ so that $(m,10)=1$ and $m\cdot2^j\cdot5^k\le50$, grouped by $2^j\cdot5^k$:
$\overbrace{(1\cdot3\cdot7\cdot9)^5}^{1}\overbrace{(1\cdot3\cdot7\cdot9)^2(1\cdot3)}^{2}\overbrace{(1\cdot3\cdot7\cdot9)^1(1)}^{4}\overbrace{(1\cdot3)^{\vphantom{1}}}^{8}\overbrace{(1\cdot3)^{\vphantom{1}}}^{16}\overbrace{(1)^{\vphantom{1}}}^{32}\\
\overbrace{(1\cdot3\cdot7\cdot9)^1}^{5}\overbrace{(1\cdot3)^{\vphantom{1}}}^{10}\overbrace{(1)^{\vphantom{1}}}^{20}\overbrace{(1)^{\vphantom{1}}}^{40}\\
\overbrace{(1)^{\vphantom{1}}}^{25}\overbrace{(1)^{\vphantom{1}}}^{50}\\
\equiv(1\cdot3\cdot7\cdot9)^9(1\cdot3)^4\equiv9\pmod{10}$

Thus, $\frac{50!}{10^{12}}\equiv8\cdot9\equiv2\pmod{10}$.

A: First, the exponent of $2$ in $50!$ is $47$, and the exponent of $5$ in $50!$ is $12$, so we're looking for $\frac{50!}{10^{12}}$ mod$ 10$.

Since $\frac{50!}{10^{12}}$ is even (in fact, divisible by $2^{35}$), it suffices to compute it mod $5$:
$\frac{50!}{5^{12}}$ $\equiv$ ($4!$. $1$. $4!$. $2$. $4!$. $3$. $4!$. $4$. $4!$. $1$.($4!$. $1$. $4!$. $2$. $4!$. $3$. $4!$. $4$. $4!$). $2$
=$4!^{10}$.$4!^2$.2!
$\equiv$$(-1)^{10}$.$(-1)^2$.2
$\equiv$ $2$ mod $5$
$\frac{50}{10^{12}}$ $\equiv$ $2$.$2^{-12}$ $\equiv$ $2$ . $(2^4)^{-3}$ $\equiv$ $2$ mod $5$

So, $\frac{50!}{5^{12}}$ $\equiv$ $2$ (mod $10$ )

A: The obvious method is to compute $50!$ and look at its digits (there's not that many of them).  Here it is:

30414093201713378043612608166064768844377641568960512000000000000

This is fairly straightforward to do on a computer (as long as you're alert for numerical overflow).  This method also has the benefits of (a) giving you all the other digits too, which helps you cross-check that the answer is correct, (b) being less likely to incur human error, and (c) will be more scaleable than human-operated methods.
In Wolfram|Alpha, we can input 50! to obtain:

I personally prefer to use GAP.  In GAP, we input Factorial(50); to obtain:
gap> Factorial(50);
30414093201713378043612608166064768844377641568960512000000000000

Or if we're feeling industrious, we might whip up some code to compute the last non-zero digit of $n!$ for all $n \in \{1,2,\ldots,100\}$.
for n in [1..100] do
  N:=Factorial(n);
  str:=DigitsNumber(N,10);
  i:=Size(str);
  while(str[i]='0') do
    i:=i-1;
  od;
  Print(n," ",Int([str[i]]),"\n");
od;

We can put these numbers into Sloane's On-Line Encyclopedia of Integer Sequences, and discover it's sequence A008904.  Here we can learn all sorts of things about these numbers, along with code for SAGE, Python, Mathematica and PARI (much more efficient than mine above).


text:
Q: Get parent fragment from child when using Navigation Component I need to transfer data from one fragment to another. Now the recommended way to do this is to use a shared ViewModel. To get the same instance available in both fragments, common owner is needed. As it can be their common Activity. But with this approach (In the case of Single Activity), the ViewModel instance will live throughout the entire application. In the classic use of fragments, you can specify ViewModelProvider (this) in the parent fragment, and ViewModelProvider (getParentFramgent ()) in the child. Thus, the scope of ViewModel is limited to the life of the parent fragment. The problem is that when using Navigation Component, getParentFramgent () will return NavHostFragment, not the parent fragment. What do I need to do?
Code samples:
Somewhere in navigation_graph.xml:
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/nav"
        app:startDestination="@id/mainMenuFragment">

    <fragment
        android:id="@+id/mainMenuFragment"
        android:name="com.mypackage.mainmenu.MainMenuFragment"
        android:label="MainMenu"
        tools:layout="@layout/fragment_main_menu">

        <action
            android:id="@+id/start_game_fragment"
            app:destination="@id/gameNav" />

    </fragment>

    <navigation
        android:id="@+id/gameNav"
        app:startDestination="@id/gameFragment">

        <fragment
            android:id="@+id/gameFragment"
            android:name="com.mypackage.game.GameFragment"
            android:label="@string/app_name"
            tools:layout="@layout/fragment_game"/>
    </navigation>

</navigation>

Somewhere in MainMenuFragment:
    override fun startGame(gameSession: GameSession) {
            //This approach doesn't work
            ViewModelProvider(this)[GameSessionViewModel::class.java].setGameSession(
                gameSession
            )
            findNavController().navigate(R.id.start_game_fragment)
    }

GameFragment:
    override fun onActivityCreated(savedInstanceState: Bundle?) {
            super.onActivityCreated(savedInstanceState)
            gameSessionViewModel =
                ViewModelProvider(requireParentFragment())[GameSessionViewModel::class.java].apply {
                    val session = gameSession.value
                    )
                }
    }

EDIT:
I can use NavHostFragment(returned from getParentFragment()) as a common for all fragments, but then, as in the case of Activity, ViewModel.onCleared() will not be called when the real parent fragment finishes.

A: There's really no way to do this.
Here is a code snippet from androidx.navigation.fragment.FragmentNavigator:
public NavDestination navigate(@NonNull Destination destination, @Nullable Bundle args,
                    @Nullable NavOptions navOptions, @Nullable Navigator.Extras navigatorExtras) {
    // ...
    final FragmentTransaction ft = mFragmentManager.beginTransaction();
    // ...
    ft.replace(mContainerId, frag);
    ft.setPrimaryNavigationFragment(frag);
    // ...
}

Under the hood, the FragmentManager is used, which calls replace(). Therefore, the child fragment is not added, but is replaced with a new one, so it will not be in getParentFramgent().

A: I faced the same problem and after researching and experimenting, I found the solution.
You simply have to call this while scoping your ViewModel which will resolve to your fragment where you have created the navigation host fragment.
ViewModelProvider(getParentFragment().getParentFragment())

or more appropriately
ViewModelProvider(requireParentFragment().requireParentFragment())

(to avoid NPE)
This is because child fragment's parent is NavHostFragment and NavHostFragment's parent is ParentFragment.
I tested this and it's working fine for me

A: for those of you who are bothered with this problem, here is the answer that worked for me:
suppose that you go from fragment A to fragment B, and you want to use a shared ViewModel for fragment A and B, and in this case, A is a fragment and B is a dialogFragment.
you can initialize ViewModel in fragment A:
ViewModelProvider(this).get(AviewModel::class.java)

and in order to use it on fragment B, initialize the ViewModel in fragment B like this:
ViewModelProvider(requireParentFragment().childFragmentManager.fragments[0]).get(AviewModel::class.java)

TL;DR:
requireParentFragment() returns NavHostFragment which hosts all the navigation of the current navigation.
requireParentFragment().childFragmentManager returns FragmentManagerImpl which seems to be the container for all fragments.
requireParentFragment().childFragmentManager.fragments returns a mutable list of fragments that are in the stack, so you can iterate through the list to see the fragments that are living in stack.


text:
Q: Kill all task started by object : Objective C I have class. In which I am running some background task (using performselectorInBackground), when these function complete in the end I am adding a subview. But in some case I am releasing and setting nil the object of class before completing the background task.
Event then these background task was not killed and update my UI with adding subview.
How I kill the all the task started by the object.

A: performSelectorInBackground is a set and forget method. You can't cancel them. However you have two choices. You can move over to dispatch_* type commands. Or you can use a boolean in your background loop to check if it should cancel itself. Then just set that bool to YES when you need to cancel it and on the next loop you can return or something along those lines.


text:
Q: Localizations: converting english text to Chinese text
Possible Duplicate:
How to have a translation service in android app

I am having one text view with some text like " This is a simple statement "
I am having one button view. if i click this button then the text available in text view should change to Chinese language.
How to do this?

A: I would recommend the Google Translate API, but turns out they're turning it off this December due to abuse.

A: Hire a person (who preferably speaks both English and Chinese reasonably) to translate the text and save it in a document.  You can then load this document into the view at the click of the button.
Alternatively, you can query translate.google.com for potentially hilarious results.


text:
Q: Mapping a virtual serial port to a remote serial port I'm trying to start a multiplayer match on an old game (runs on Dosbox), which uses serial communication.
So what I need to do is define virtual comports on both computers running the game, and somehow connect those comports (on the same network)
Which application should I use to do that?
Thanks
Nitay

A: You can use a free software that creates a virtual serial port. You can use com2tcp:

A: It seems Dosbox has got it covered!
Everything is here:
http://www.dosbox.com/wiki/Connectivity
The game supported both IPX networking & modem, in addition to direct serial


text:
Q: Evaluate CSS calc function in JS I am trying to figure out a way to execute the CSS calc function directly in my js file in order to compare two elements height.
So let's say i have two elements that I get using jQuery, and all I want to do is something around those simple lines :
if (element1.height > element2.height) then ...

Element2 is nested within Element1, who has an overflow:scroll.
Problem is, my element1 has all attributes clientHeight, scrollHeight,etc equals to 0 and when i go in the element1.style.height the result is : "calc(100% - 64px)". Please do note that the result of this is never equal to 0px since my element1 height when i inspect it is around 500px (of course depends of the screen size). And my element2 height is obtained in px using element2.scrollHeight (more reliable in my case).
So in the end I'm trying to compare two expressions that would like this : calc(100% - 64px) > 452 .. And of course this doesn't work.
Is there any way I could execute the calc() function within my js file to get the equivalent height in px in order to compare my two elements ? Or can I have access to the data anywhere else ?
My end goal is to know whether the element2's height is bigger than element1's. So any other implementation that height calculation is welcome as well.

A: You can get the computed style using Window.getComputedStyle(). Check out the compatibility table.
Then, grab the width and remove the "px" from the result, and parse it to an integer:

let myElement = document.getElementById('child');
let width = parseInt(window.getComputedStyle(myElement).width.slice(0, -2), 10);
console.log(width);
#parent {
  background: red;
  height: 100px;
  width: 80%;
}

#child {
  background: green;
  height: 60px;
  width: calc(100% - 64px);
}


text:
Q: cant scan wifi results Iam trying to scan WiFi and get the results, but the problem is when i using "WifiManager.getScanResult()"it showing only null value
Code
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@ReactMethod
public void loadWifiList(Callback successCallback, Callback errorCallback) {
    try {
        Log.e(TAG, "----Attempt try----");

        List<ScanResult> results = wifi.getScanResults();
        JSONArray wifiArray = new JSONArray();
        Log.e(TAG, "-----results:---- " + results);
        for (ScanResult result : results) {
            Log.e(TAG, "SSID : " + result.SSID);
            JSONObject wifiObject = new JSONObject();
            if (!result.SSID.equals("")) {
                try {
                    wifiObject.put("SSID", result.SSID);
                    wifiObject.put("BSSID", result.BSSID);
                    wifiObject.put("capabilities", result.capabilities);
                    wifiObject.put("frequency", result.frequency);
                    wifiObject.put("level", result.level);
                    wifiObject.put("timestamp", result.timestamp);
                    //Other fields not added
                    //wifiObject.put("operatorFriendlyName", result.operatorFriendlyName);
                    //wifiObject.put("venueName", result.venueName);
                    //wifiObject.put("centerFreq0", result.centerFreq0);
                    //wifiObject.put("centerFreq1", result.centerFreq1);
                    //wifiObject.put("channelWidth", result.channelWidth);
                } catch (Exceptional e) {
                    errorCallback.invoke(e.getMessage());
                }
                wifiArray.put(wifiObject);
            }
        }
        successCallback.invoke(wifiArray.toString());
    } catch (IllegalViewOperationException e) {
        errorCallback.invoke(e.getMessage());
    }
}

react Code
detectedWifiNetwork(){
            wifi.loadWifiList((wifiStringList) => {
            var wifiArray = JSON.parse(wifiStringList);
            alert("WifiList:"+wifiArray)
            },
            (error) => {
            alert(error)
            }
            );
            }

Anyone Please give me solution for the problem.thanks in advance


text:
Q: Should enum never be used in an API? I am using a C library provided to me already compiled.  I have limited information on the compiler, version, options, etc., used when compiling the library.  The library interface uses enum both in structures that are passed and directly as passed parameters.
The question is: how can I assure or establish that when I compile code to use the provided library, that my compiler will use the same size for those enums?  If it does not, the structures won't line up, and the parameter passing may be messed up, e.g. long vs. int.
My concern stems from the C99 standard, which states that the enum type:

shall be compatible with char, a signed integer type, or an unsigned
  integer type. The choice of type is implementation-defined, but shall
  be capable of representing the values of all the members of the
  enumeration.

As far as I can tell, so long as the largest value fits, the compiler can pick any type it darn well pleases, effectively on a whim, potentially varying not only between compilers, but different versions of the same compiler and/or compiler options.  It could pick 1, 2, 4, or 8-byte representations, resulting in potential incompatibilities in both structures and parameter passing.  (It could also pick signed or unsigned, but I don't see a mechanism for that being a problem in this context.)
Am I missing something here?  If I am not missing something, does this mean that enum should never be used in an API?
Update:
Yes, I was missing something.  While the language specification doesn't help here, as noted by @Barmar the Application Binary Interface (ABI) does.  Or if it doesn't, then the ABI is deficient.  The ABI for my system indeed specifies that an enum must be a signed four-byte integer.  If a compiler does not obey that, then it is a bug.  Given a complete ABI and compliant compilers, enum can be used safely in an API.

A: From the question:
The ABI for my system indeed specifies that an enum must be a signed four-byte integer. If a compiler does not obey that, then it is a bug.
I'm surprised about that. I suspect in reality you're compiler will select a 64-bit (8 byte) size for your enum if you define an enumerated constant with a value larger that 2^32.
On my platforms (MinGW gcc 4.6.2 targeting x86 and gcc 4,.4 on Linux targeting x86_64), the following code says that I get both 4 and 8 byte enums:
#include <stdio.h>

enum { a } foo;
enum { b = 0x123456789 } bar;

int main(void) {
    printf("%lu\n", sizeof(foo));
    printf("%lu", sizeof(bar));
    return 0;
}

I compiled with -Wall -std=c99 switches.
I guess you could say that this is a compiler bug. But the alternatives of removing support for enumerated constants larger than 2^32 or always using 8-byte enums both seem undesirable.
Given that these common versions of GCC don't provide a fixed size enum, I think the only safe action in general is to not use enums in APIs.
Further notes for GCC
Compiling with "-pedantic" causes the following warnings to be generated:
main.c:4:8: warning: integer constant is too large for 'long' type [-Wlong-long]
main.c:4:12: warning: ISO C restricts enumerator values to range of 'int' [-pedantic]

The behavior can be tailored via the --short-enums and --no-short-enums switches.
Results with Visual Studio
Compiling the above code with VS 2008 x86 causes the following warnings:
warning C4341: 'b' : signed value is out of range for enum constant
warning C4309: 'initializing' : truncation of constant value

And with VS 2013 x86 and x64, just:
warning C4309: 'initializing' : truncation of constant value

A: APIs that use enum are depending on the assumption that the compiler will be consistent, i.e. given the same enum declaration, it will always choose the same underlying type.
While the language standard doesn't specifically require this, it would be quite perverse for a compiler to do anything else.
Furthermore, all compilers for a particular OS need to be consistent with the OS's ABI. Otherwise, you would have far more problems, such as the library using 64-bit int while the caller uses 32-bit int. Ideally, the ABI should constrain the representation of enums, to ensure compatibility.
More generally, the language specification only ensures compatibility between programs compiled with the same implementation. The ABI ensures compatibility between programs compiled with different implementations.


text:
Q: How to vertical-align to x-height? I have a line of text and a small image, which I am trying to align vertically within the line. My goal is to align the vertical center of the image with the x-height (or half of the height of a capital letter) from the baseline of the text. I can't figure out any way to do this. The closest thing that I know of is:
vertical-align: middle;

This behavior as it is stated in the CSS 2.1 spec:

Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent

If there were a way to remove the world "half" from that definition, I'd have what I want. How do I accomplish this?

A: The problem is, text sits on the text baseline while the image descends below that. And different browsers handle that differently.
My favorite solution is to display the image as a background-image, with its background-position set to left center ... you can season to taste.

A: Don't know if it's the "best" answer, but I would always set the "line-height" of my text to match the height of what I'm trying to center it in.

A: Here is the vertical align center.
http://www.templatespoint.com/blog/2010/10/div-vertical-align-middle/
or use image as background image
background:url(bg_image.jpg) no-repeat left center;