Q: ImageView show different output on different resolution device I have a ImageView which is 450px*450px，it show perfectly on Note 3(1080*1920), but when I run the app on other smaller resolution device, the ImageView shown larger, and some other contents doesn't fit in the screen. Any solution to solve this kind of problem? is it about the unit(px, dp)?

A: The reason is every devices has different screen dimensions, so either you have to re-size the ImageView based on the screen size or simply use different size Images for your ImageView which will be used automatically based on the screen dimension. To do so, check this,
A. Getting the screen dimension programmatically and settings the appropriate size into the ImageView,
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);

float density  = getResources().getDisplayMetrics().density;
float dpHeight = outMetrics.heightPixels / density;
float dpWidth  = outMetrics.widthPixels / density;

B. Adding different image sizes for different screens,
res/drawable-mdpi/my_icon.png        // bitmap for medium density
res/drawable-hdpi/my_icon.png        // bitmap for high density
res/drawable-xhdpi/my_icon.png       // bitmap for extra high density

The following code in the Manifest supports all dpis.
<supports-screens android:smallScreens="true"
          android:normalScreens="true"
          android:largeScreens="true"
          android:xlargeScreens="true"
          android:anyDensity="true" />

A: Your Screen Resolution Represents that you are Setting the ImagevIew height and width for xxhdpi resolution device and the Second thing use dp for density pixel it cover the screen according to resolution use 150dpX150dp for ImageView use the following link for px to dp conversion http://pixplicity.com/dp-px-converter/


Q: Maximize frobenius norm of qudaratic form I am facing the following optimization problem:
$$
\max \|R^T A R\|_F \\
s.t.  R^T R = I
$$
That is, maximize the frobenius norm of the qudaratic form $R^T A R$ where $R$ is a orthonormal matrix.
$A \in \mathbb{R}^{n\times n}$ is a real symmetric matrix. $R\in \mathbb{R}^{n\times m}$ where $m < n$.

*

*The objective can be transformed to $tr(R^T A R R^T A R)$.

*If the frobenius norm is replaced by the trace operator ($\max tr(R^T A R)$), then the problem can be solved with eigen-decomposition. But I don't know how to solve the frobenius norm case.

Any ideas or comments will be appreciated. Thanks!


Q: Mockito: creating a parameter matcher for a class Given a method definition as follows:
MyClass.myMethod(SecondClass secondClass);

and a mock of MyClass:
MyClass myClass = mock(MyClass.class);

how would you match the method parameter when defining the expecation?
when(myClass.myMethod(???)).thenReturn(null);

Thanks

A: when(myClass.myMethod(Mockito.any(SecondClass.class))).thenReturn(null);

A: You can use
Mockito.any(SecondClass.class)

or
(SecondClass)any()

A: Actually the best way to do it is
doReturn(object).when(myClass).myMethod(???);

in ??? you have some possibilities.

*

*You can pass a given object and then you wait for an especific one

*Or you can pass Mockito.any(Clazz.class) and then you will accept any object of that kind


Q: Can a process send keystrokes or read text to/from a tty that is running su/sudo? I need some information regarding the possible attack vector on *nix platforms of running su/sudo.
Can an malicious process wait for the user to run su or sudo and then exploit that root access somehow? Or is this already protected somehow?
For example, if /dev/tty2 has impersonated root with su:
# inject text
echo Adding malicious text to a root tty, like Enter Password: > /dev/tty2
# read keystrokes
cat /dev/tty2
# not sure how to write keystrokes or if it is possible

Maybe this is absolutely documented, or protected, if so, please link me the docs.

PS: Please don't shut me down as if I am requesting help to do an exploit. I am not. The question is about the risks of using su/sudo versus logging as root in the context of a discussion about whether should Windows have a sudo command or not. I need to get my facts straight.

A: Yes, a process can inject input into a tty via the TIOCSTI ioctl. At least on Linux, that's subject to some restrictions: the user should be root (CAP_SYS_ADMIN) or inject into its controlling tty.
That's still quite dangerous, and TIOCSTI was gutted in systems like OpenBSD, but its threat model was usually backwards than that from your question: the root was supposed to use su (or something else) to run a command as an ordinary user, and that command was able to insert keys into the controlling tty it was sharing with its privileged caller. See examples here and here.
Of course, that could also be exploited via a biff(1) or some other program running in the same tty su root was started from, but that's doesn't look that interesting: if an attacker was able to get grip of an account able to su or sudo, there are probably simpler an nicer ways to escalate it.


Q: git show logs exclude some user or committer I don't know how to do this
I try these already:

git log -p --author="user" --not Sites/Web/Templates

git log -p --author="!user" Sites/Web/Templates

still show log of that user. Help, please.


Q: How Ix in the give fig. is Zero in 2nd Step?
How the ix in the second step is zero

A: When short-circuiting A and B the voltage across the 6 ohm resistor will be 0 and hence the current Ix will be zero.
This is one of the steps to get the Thevenin equivalent circuit (to get Rth in particular).


Q: libtorch c++ doesn't release tensor memory I'm having an issue when using libTorch C++.
I load a module
torch::jit::script::Module net = torch::jit::load(universal_path);

As this takes some time to load, I store it to use it later on different images that I want to process :
    net.to(device);
    net.eval();

    torch::Tensor out_tensor = net.forward({ input_tensor.to(device) }).toTensor().to(cpy);

The problem is that the forward function allocates a lot of memory (between 2 to 8MB) but it's not released when out_tensor is going out of scope.
The only way to release the memory is to delete the module as well, but this is not efficient.
Am I missing something?
I'm using libtorch 1.5.1, a bit old, is there known leaks with this version?
Thanks


Q: Rails fuzzy searching on title and description I have a simple rails 3 application that lists restaurants as a training exercise. I want to be able to search name and description using one textfield on the restaurant index page.
Given the query pizza. The matches should be

*

*name: Tony's, description: ... is a pizzeria that has been around since the 1950's ...

*name: Domino's Pizza, description: ...

*name: The Hall, description: ... pizzas, pastas and steaks ...

Because:

*

*the word pizza is a fuzzy match to " pizz eri a " using similar logic as TextMate's Cmd-T. (the spaces in the word pizzeria are only used to get the mini-Markdown to work)

*pizza is a lowercase match to Pizza

*pizza is a substring of pizzas (should work with ends-with begins-with and includes)

How would I go about doing this in rails 3? Do I use thinking_sphinx, tire, sunspot-rails or just a custom query for my application.

A: The only tricky one is pizza/pizzeria and it's an issue called stemming.
Both sphinx and solr/sunspot support stemming but I imagine you will need to teach them both that pizza is a stem of pizzeria.

A: One way to remove false positives is to run a user defined function (UDF) to compute the edit distance between a candidate answer and the original string, and ignore those answers whose edit distance is too large.

A: I found a very simple solution that serves my needs.
"%#{"pizza".scan(/./).join("%")}%"

This creates a string that looks like this
"%p%i%z%z%a%"

Then I use it in a LIKE query and I get the expected results. Now all that remains is to solve the non-trivial problem of determining the order of relevance :)
UPDATE:
Found a quick and dirty way of determining order of relevance base on the assumption that a shorter string will most likely be a closer match than a longer one.
ORDER BY length(sequence) ASC


Q: WP_Query Sorting Posts by month ... timeline effect Hoping someone can take a look at my code and help me out. Right now I am trying to show my blog in a timeline style approach. My current query is generating the posts how I would like them to but I am not getting the HTML structure properly. Right now I have a
 that contains a
 with post info. I would like the
 to generate a unique
 for each post within that month instead of each time generating a new
 for the post. So for example... if July 2014 has 3 blog posts I want the structure to be:

Right now it generates as:

Here is my template:

        <?php
            $counter = 0;
            $ref_month = '';
            $monthly = new WP_Query(array(
                'posts_per_page' => -1
            ));

            if( $monthly->have_posts() ) : while( $monthly->have_posts() ) : $monthly->the_post();

            if( get_the_date('mY') != $ref_month ) {
                if( $ref_month );
        ?>

<?php echo get_the_date('M Y'); ?>

        <?php
            $ref_month = get_the_date('mY');
            $counter = 0;
            } if ($counter++ < 5) {
        ?>

        <div class="timeline <?php echo strtolower(get_the_time('F-Y')); ?>">

                                <?php if (has_post_thumbnail()) { ?>

                                    <?php the_post_thumbnail( 'full' ); ?>

                                <?php } else { ?>

                                <?php } ?>

<a href="<?php the_permalink();?>"><?php the_title();?>

                                    By <?php the_author(); ?> | <?php the_time(get_option('date_format'));?>

<?php echo excerpt(25); ?>

                                    <a href="<?php the_permalink();?>" class="more"><?php echo __('Read More >')?>
                                     <?php comments_number('0','1 comment','% comments')?>

                            <?php } else { ?>

                            <?php } ?>

        <?php endwhile; endif; ?>

<?php next_posts_link(__(' ')); ?>

<?php previous_posts_link(__(' ')) ?>

        <?php wp_reset_query(); ?>

Any help is appreciated, thank you!


Q: Barcode scanner with RS232 interface not working with USB adapter I used RS232 interface of barcode scanner (Datalogic QD2100), for my project but a problem arises. The manual given with this barcode scanner has certain barcodes for mode setting (scan mode-flashing, scan mode-always ON etc), restoring default settings, select interface. The output of the barcode scanner is a female RS232 and so i used a male RS232-usb converter cable to connect it to my laptop. I installed the driver which came with RS232-usb converter cable and also installed the software which was sent to me regarding barcode scanner. I have set the com port to COM1 and opened word. My cursor was placed in the word and when i do scan any barcode it doesn't show up on word. I used RS232 interface selection (using the barcode provided in the manual) first time and as i did not get any data in my word i used usb interface selection and that too didn't work. I have used barcode scanner with an old pc which has RS232 male pin and it does work. So my question is how can i possibly get my barcode scanner to work with my laptop which does not have any RS232 port.

A: The problem is not RS232. On the contrary: RS232 ís FUN. It always WORKS! And you never run into version problems of drivers and so on because every operating system has standard RS232 support. See all the industries today where it is still in use because of the reliability. The issue here is USB: your RS232 to USB converter converter only converts data to a serial port. If you look in your hardware list of Windows, you will see that your converter simulates a serial port. A serial port is NOT a keyboard! So the data will never appear in applications (like Word) that only listen to keyboard devices! However, for barcode scanners there exist SPECIAL converters that convert RS232 to USB and behave like a keyboard. They have a double function: emulate a USB keyboard AND translate character codes from RS232 to USB because USB does not use standard ANSI.

A: RS232 is no fun.  We use several barcode scanners like yours but had to upgrade to the newer USB style to get it to work.  If that's not an option, there are some Express or PCI adapters that you could install in your computer that work.  Again, not all of them work for us, you might have to try a couple.
We have had the best luck with a laptop that has a PCMCIA slot using this PCMCIA adapter and then you'll need a short ethernet to RS232: Amazon PCMCIA Adapter
If it's a desktop you might need something like this: Amazon PCI Card

A: If you must use an RS232 to USB converter, be sure it uses the FTDI chipset.  That's the gold standard for RS232 to USB and I've had troubles when using something cheap in the past.  Here are some choices: www.amazon.com
Also, maybe something like the following is what you need to convert the serial communication into keyboard input: serial2keyboard.  This is a free utility to convert a serial signal to a keyboard event.
Good luck!


Q: how to get the value from button on click I am having some buttons which are created dynamically based on the number of phone numbers present.Suppose I have 3 names in DB so there will be three buttons.So when I click on the 1st button then it should give the value of first button,if 2nd is clicked then 2nd button value should display.This is simple jsfiddle which describes about my requirement.I thought of assigning the each button a different id which should be the phone number.In the jsfiddle when i am clicking on a particular button then alert pops but it does not give any value.
i did like this
$('.btn').click(function(){
var number1 = $('#s2').val();
alert(number1);
});

A: You have to use event delegation using jQuery's on() method. From its documentation:

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

In your case, you'll need to delegate the .btn click event to an ancestor which exists prior to that element being dynamically added to the page:
$('body').on('click', '.btn', function() {
    var number1 = $('#s2').val();
    alert(number1);
});

The closer you get to the .btn element, the better, so unless your document's body is the nearest non-dynamic ancestor then you'll want to change this to something a bit closer.

Edit: Further question in comments:

can I get the ID of each button

To get the id of each button, simply use this.id:
$('body').on('click', '.btn', function() {
    var id = this.id;
    alert(id);
});

Edit 2: Further question in comments

So as I said,ID are numbers.So if i click button1 then it will print s1 in the inputfield.Can you please tell me how to do?

As your input has an id of "number", you can simply use jQuery's .val() method to set the value of the input to the id of the clicked button:
$('body').on('click', '.btn', function(){
    $('#number').val(this.id);
});

Working JSFiddle demo.

A: $(document).on('click', '.btn', function(){
   alert($(this).val());
});

Should work. The "on" is a way of working with dynamically placed elements.

A: Put value attribute in button input
  <button type="button" class="btn" value="test2" >test</button>
  <button type="button" class="btn" value="test1" id="s1">test</button>
  <button type="button" class="btn" value="test" id="s2">test</button>

And then use script
 $('.btn').on('click', function() {
       var number = $('#s2').val();//get value

 });

A: If you want to get the id of the clicked button you should use attr:
$('.btn').click(function(){
   var number1 = $('#s2').attr('id');
   alert(number1);
});


Q: Error in my trigger I am working on a project using SqlSiteMapProvider.  I have two tables Articles and SiteMap
Articles table:
CREATE TABLE [dbuser].[Articles](
 [ArticleId] [uniqueidentifier] NOT NULL,
 [Title] [nvarchar](500) NULL,
 [Description] [ntext] NULL,
 [CategoryId] [int] NULL,
 [pubDate] [datetime] NULL,
 [Author] [nvarchar](255) NULL,
 [Hit] [int] NULL,
 [Auth] [bit] NULL
)...

And SiteMap Table:
CREATE TABLE [dbuser].[SiteMap](
 [ID] [int] IDENTITY(0,1) NOT NULL,
 [Title] [nvarchar](50) NULL,
 [Description] [nvarchar](512) NULL,
 [Url] [nvarchar](512) NULL,
 [Roles] [nvarchar](512) NULL,
 [Parent] [int] NULL,
 CONSTRAINT [PK_SiteMap] PRIMARY KEY CLUSTERED
(...

When I insert an Article my asp.net page also inserts that articles url and such information into SiteMap table. What I am trying to do is when I delete an Article from my Articles table (from asp.net page) the related row from SiteMap table with a trigger.
My asp.net page inserts the Article info into Sitmap table in this format:
Dim SMUrl As String = "~/c.aspx?g=" & ddlCategoryId.SelectedValue & "&k=" & BaslikNo.ToString

I mean there is no one column exactly matchin in two tables.
My Trigger is as follows:
USE [MyDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET NOCOUNT ON
GO
SET ROWCOUNT 1
GO
ALTER TRIGGER [dbuser].[trig_SiteMaptenSil] ON [dbuser].[Articles]
AFTER DELETE
AS
BEGIN
DECLARE  @AID UNIQUEIDENTIFIER, @ttl NVARCHAR,@CID INT
SELECT @AID=ArticleId, @ttl = Title, @CID=CategoryId  FROM DELETED
IF EXISTS(SELECT * FROM dbuser.SiteMap WHERE Url = N'~/c.aspx?g=' + CONVERT(nvarchar(5), @CID) + N'&k=' + CONVERT(nvarchar(36), @AID))
BEGIN
 DELETE FROM dbuser.SiteMap WHERE Url = N'~/c.aspx?g=' + CONVERT(nvarchar(5), @CID) + N'&k=' + CONVERT(nvarchar(36), @AID)
END
END
GO

I am using SSMSE 2008 and my remote db server's version is 8.0
The Error I get is:
No rows were deleted.
A problem occurred attempting to delete row 1.
Error Source: Microsoft.VisualStudio.DataTools.
Error Message: The row value(s) updated or deleted either do not make the row unique or they alter multiple rows(2 rows).
Correct the errors and attempt to delete the row again or press ESC to cancel the change(s).
May you help me how to get this working? I have searched for this for about a few days.. Couldn't find a solution for my case...
Thanks in advance

A: To deal with the original issue and cope with deletions of multiple rows your trigger could be rewritten as follows.
ALTER TRIGGER [dbuser].[trig_SiteMaptenSil] ON [dbuser].[Articles]
AFTER DELETE
AS
BEGIN
 SET NOCOUNT ON

DELETE
FROM   s
FROM   dbuser.SiteMap     AS s
       INNER JOIN Deleted AS d
       ON     s.Url = N'~/c.aspx?g=' + CONVERT(nvarchar(5), d.CategoryId) + N'&k='
                                     + CONVERT(nvarchar(36), d.ArticleId)

END


Q: Get jsondata value in javascript JSON
   var jsondata={"id": "10", "skills": "english", "post": "devloper", "emp_name": "jaydeep","timestemp":"10:45"}

I am trying to get each element key and value:
javascript
..
}).done(function(data){
    console(data['post']);
});

Expected Output :
emp_name = jaydeep
post = devloper
I am getting undefined in console. WHY? I tried data.post, i tried loop but no success..

A: I think you'll need to decode the JSON first.
}).done(function(data){
    data = JSON.parse(data);
    console(data['post']);
});

A: You can use basic JS too to attain this.

// property is an optional parameter.
function disp(obj, property) {
  var prop;
  if (property) {
    obj[property] && (console.log(obj[property]));
  } else {
    for (prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        console.log(prop + " = " + obj[prop])
      }
    }
  }
}
var jsondata = {
  "id": "10",
  "skills": "english",
  "post": "devloper",
  "emp_name": "jaydeep",
  "timestemp": "10:45"
}
//disp(jsondata, "post");
disp(jsondata);


Q: trying to run jiunt test cases spring boot application I tried to run junit test cases with spring boot application. But there is bean creating issue due to not finding setProxyTargetClass on PersistenceExceptionTranslationPostProcessor package.
An attempt was made to call the method org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setProxyTargetClass(Z)V but it does not exist.
Below is my stack trace.
Description:
An attempt was made to call the method org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setProxyTargetClass(Z)V but it does not exist. Its class, org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor, is available from the following locations:

 jar:file:/C:/Users/r2um2k/.m2/repository/org/springframework/spring-dao/2.0.8/spring-dao-2.0.8.jar!/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessor.class
    jar:file:/C:/Users/r2um2k/.m2/repository/org/springframework/spring-tx/5.1.4.RELEASE/spring-tx-5.1.4.RELEASE.jar!/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessor.class

It was loaded from the following location:
file:/C:/Users/r2um2k/.m2/repository/org/springframework/spring-dao/2.0.8/spring-dao-2.0.8.jar

Action:
Correct the classpath of your application so that it contains a single, compatible version of org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor

2020-07-30 12:49:55.741 ERROR 17624 --- [           main] o.s.test.context.TestContextManager      : Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@73afe2b7] to prepare test instance [com.fanniemae.acquisitions.cdds.datafeed.task.UcdpCompDataFeedTaskHelperTest@5b251fb9]

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) [spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) [spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) [spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) [spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) [spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) [spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365) [surefire-junit4-2.22.1.jar:2.22.1]
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:273) [surefire-junit4-2.22.1.jar:2.22.1]
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238) [surefire-junit4-2.22.1.jar:2.22.1]
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:159) [surefire-junit4-2.22.1.jar:2.22.1]
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:384) [surefire-booter-2.22.1.jar:2.22.1]
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:345) [surefire-booter-2.22.1.jar:2.22.1]
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:126) [surefire-booter-2.22.1.jar:2.22.1]
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:418) [surefire-booter-2.22.1.jar:2.22.1]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistenceExceptionTranslationPostProcessor' defined in class path resource [org/springframework/boot/autoconfigure/dao/PersistenceExceptionTranslationAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor]: Factory method 'persistenceExceptionTranslationPostProcessor' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setProxyTargetClass(Z)V
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:607) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:228) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:707) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:531) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:127) ~[spring-boot-test-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) ~[spring-test-5.1.4.RELEASE.jar:5.1.4.RELEASE]
    at org.springframework.test.con

Here is my POM file.
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
    http://maven.apache.org/maven-v4_0_0.xsd">

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.fanniemae.acquisitions.cdds</groupId>
    <artifactId>ucdp-company-datafeed</artifactId>
    <packaging>jar</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>ucdp-company-datafeed</name>
    <properties>
        <java.version>1.8</java.version>
        <ucdp-ram-common.version>0.0.1-SNAPSHOT</ucdp-ram-common.version>
        <common.version>0.0.1-SNAPSHOT</common.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>

            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-ibatis -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-ibatis</artifactId>
            <version>2.0.8</version>
        </dependency>

        <dependency>
            <groupId>com.oracle.ojdbc</groupId>
            <artifactId>ojdbc8</artifactId>
            <version>19.3.0.0</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.11.3</version>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <!-- <version>1.6</version> -->
        </dependency>

        <dependency>
            <groupId>org.pojava</groupId>
            <artifactId>pojava</artifactId>
            <version>2.8.0</version>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <!-- <version>42.2.11</version> -->
        </dependency>

        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>addressing</artifactId>
            <version>1.3</version>
            <type>mar</type>
            <exclusions>
                <exclusion>
                    <groupId>xalan</groupId>
                    <artifactId>xalan</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>

            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.fanniemae.acquisitions.cdds.internal.dependentjar</groupId>
            <artifactId>rahas</artifactId>
            <version>1.3</version>
            <type>mar</type>
        </dependency>

        <!-- <dependency>
            <groupId>com.oracle.weblogic</groupId>
            <artifactId>wlthint3client</artifactId>
            <version>12.2</version>
            <scope>test</scope>
        </dependency> -->

    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jaxb2-maven-plugin</artifactId>
        </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.3.2</version>

            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.10</version>

            </plugin>
        </plugins>
    </build>
</project>

Any help will be appreciated.

A: Remove the dependency to spring-ibatis - this is for Spring v 2 and you are using version 5! Look at the release date, this is from 2008.
mybatis-spring is enough for spring integration of mybats (see here)


Q: Finding pairs in a list I'm trying to look for pairs of elements in a list, assuming that they are the only pair in the list, and there are no more than 3 identical consecutive elements.
I have a function that takes in a list, and returns the index of the first element of the pair, if there is any. If not, then it returns -1
searchForPairs xs = searchHelp xs ((genericLength xs) - 1)
    where searchHelp xs n
        | searchHelp xs 0 = -1              -- no pairs found
        | (xs !! n) == (xs !! (n - 1)) = n
        | otherwise = searchHelp xs n-1

For some reason, it is returning the error:
Couldn't match expected type `Bool' with actual type `Int'
In the expression: n
In an equation for `searchHelp':
    searchHelp xs n
      | searchHelp xs 0 = - 1
      | (xs !! n) == (xs !! (n - 1)) = n
      | otherwise = searchHelp xs n - 1
In an equation for `searchForPairs':
    searchForPairs xs
      = searchHelp xs ((genericLength xs) - 1)
      where
          searchHelp xs n
            | searchHelp xs 0 = - 1
            | (xs !! n) == (xs !! (n - 1)) = n
            | otherwise = searchHelp xs n - 1

It seems like it should work. Any ideas why it is not?

A: You have two problems. The first is in this line:
        | otherwise = searchHelp xs n-1

The compiler interperets this as (searchHelp xs n) - 1, not searchHelp xs (n-1), as you intended. The second problem is in you use of guards:
        | searchHelp xs 0 = -1              -- no pairs found

Since searchHelp xs 0 is not a boolean expression (you wanted to use it as a pattern), the compiler rejected it. I can see two easy solutions:
searchForPairs xs = searchHelp xs ((genericLength xs) - 1)
    where searchHelp xs n
        | n == 0 = -1              -- no pairs found
        | (xs !! n) == (xs !! (n - 1)) = n
        | otherwise = searchHelp xs (n-1)

and
searchForPairs xs = searchHelp xs ((genericLength xs) - 1)
    where
      searchHelp xs 0 = -1         -- no pairs found
      searchHelp xs n
        | (xs !! n) == (xs !! (n - 1)) = n
        | otherwise = searchHelp xs (n-1)

Now, unfortunately, although this works, it is terribly inefficient. This is because of your use of !!. In Haskell, lists are linked lists, and so xs !! n will take n steps, instead of 1. This means that the time your function takes is quadratic in the length of the list. To rectify this, you want to loop along the list forward, using pattern matching:
searchForPairs xs = searchHelp xs 0 where
    searchHelp (x1 : x2 : xs) pos
        | x1 == x2 = pos
        | otherwise = searchHelp (x2 : xs) (pos + 1)
    searchHelp _ _ = -1

A: @gereeter already explained your errors, I would just like to point out that you should not return -1 in case the answer is not found. Instead, you should return Nothing if there is no answer and Just pos if the answer is pos. This protects you from many kinds of errors.

A: I couldn't quite grok what you want to do, but from the code, it looks like you're trying to find two consecutive elements in a list that are equal.  Instead of using !! to index the list, you can use pattern matching to extract the first two elements of the list, check if they are equal, and continue searching the remainder (including the second element) if they are not.  If the list doesn't have at least two elements, you return Nothing
searchForPairs xs = go 0 xs where
  go i (x1:xs@(x2:_)) | x1 == x2 = Just i
                      | otherwise = go (i+1) xs
  go _ _ = Nothing

A: For what it's worth, here is a somewhat idiomatic (and point-free) implementation of what you are trying to do:
searchPairs :: Eq a => [a] -> Maybe Int
searchPairs = interpret . span (uncurry (/=)) . (zip <*> tail)
    where
    interpret (flag, res) = if null flag then Nothing else Just $ length res

Explanation: zip <*> tail creates a list of pairs of successive elements (using the reader Applicative type class). uncurry (/=) tests if such a pair is made of identical elements. Finally, interpret translates the result in a value of Maybe Int type.


Q: C# Event causing Session Variable Error ASP.NET 5 MVC 6 So I basically have an event that fired off when my connected cash receiver takes in money, and I'm using a session variable to store the index of the bill inserted, and I get an error that says:
My session variables work everywhere else correctly except here. Any idea why this is happening? Everywhere I look online it tells me to set up my session correctly which it is if my other ones work fine. This event is fired when on a view page with no other methods running. Any help is appreciated. If the information is too vague I apologize, I will provide more information if you need it to help me solve this problem. Thank you.
Edit: Stack

This is the event being fired where the SetString is causing the error.
 void validator_OnCredit(object sender, CreditArgs e)
    {
        Console.WriteLine("Credited bill#: {0}", e.Index);

        switch (e.Index)
        {
            case 1:
                HttpContext.Session.SetString("Test", "1");
                break;
            default:
                HttpContext.Session.SetString("Test", e.Index.ToString());
                break;
        }

        Thread.Sleep(500);
    }

A: 3) Updated Answer
Session Namespace Reference for beta(s) or RC1
Microsoft.AspNet.Session

Session Namespace Reference from CORE 1.0
Microsoft.AspNetCore.Session

2) Updated Answer - If accessing a session outside the controller then you need to inject the session into it as follows
public class TestClass
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private ISession _session => _httpContextAccessor.HttpContext.Session;

    public TestClass(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public void SetString()
    {
        _session.SetString("Test", "Ben Rules!");
    }

    public string GetString()
    {
        return _session.GetString("Test");
    }
}

1) Initial Answer - Incorrect for current scenario... but if session isn't working this is a good place to start
From the error message I assume you are using .NET Core?
If so then the middleware is added sequentially so you need to ensure that your code intitialises Session Management first before it uses MVC
public void ConfigureServices(IServiceCollection services)
{
   // ...
   services.AddSession();
   // ...
}

public void Configure(IApplicationBuilder app)
{
    app.UseSession();
    app.UseMvc();
    // ...
}


Q: Paging and sorting with BCS - Is it really possible? I'm trying to add paging on an external list and so far it does not work 100%. The best references I could find (that actually... kinda... work) are these:
Paging and sorting with BCS
Paging and sorting in sharepoint BCS
I've done like in the posts (I have a .Net Assembly Type Lob System instead of WCF) and all works if I set constant values for the filters in the view. But if I use name placeholders (like {dvt_sortdir}) I get errors that the value {dvt_sortdir} can't be converted to System.Int32.
<View ...>
  <Method Name="GetEmployeesPaged">
     <Filter Name="FilterRowNum" Value="{dvt_firstrow}"/>
     <Filter Name="FilterPageCount" Value="30"/>
     <Filter Name="FilterSortColumn" Value="{dvt_sortfield}"/>
     <Filter Name="FilterSortDir" Value="{dvt_sortdir}"/>
  </Method>
  ...
</View>

In the second post I noticed it's {$dvt_sortdir} but again it does not work (recreating the list is still no joy).
I've tried all sorts of combinations in SP Designer but nothing works, just plain number. But I don't need constant numbers, I need values at runtime.
I've read a lot and tried a lot and I'm starting to doubt that paging is possible on an external list. So is it possible or not? What's missing from those posts to make it work?

A: Struggled with this quite a bit myself. You need to check the parameter types of your finder methods. Check both the code as well as the model file. Those should match and be of the right type (depends on the parameter; firstrow and pagecount should be integers).
As far as I know, you cannot use filter parameters which don't exist in your entity. So you need to abuse fields in your entity for filtering. Those fields have to be of the correct type. So if your entity has an integer column, you could use that as pagenumber parameter; make sure you properly comment your code because you'll lose track of things when you don't.
As for sorting, I didn't get that working at all. My solution performs sorting, but only on the items retrieved from BCS (which are paginated). So first it's retrieving items from my BCS connector, which only returns like 30 records, and THEN it sorts those records. Kind of useless. Perhaps you could get there with dvt_sortfield and dvt_sortdir, but that would require two more (string?) parameters in your finder method (and thus entity).
I found this link pretty usefull: http://lightningtools.com/blog/archive/2010/06/25/sharepoint-2010-external-list-paging-ndash-server-side.aspx


Q: Order dropdown by existing data SQL I have a list of records from a MySQL database. When a record is clicked it takes you to a page where you can update these records. I'm using a HTML form to display the data dynamically.
For example, if a game was released in 2007 I'd have a dropdown box with all the different years that it could be changed to.
My current SQL for the year dropdown is as follows;
SELECT DISTINCT gameYear FROM games ORDER BY gameYear

This displays the years in order. Is there a way to have them displayed in correct order (IE 2001, 2002, 2003 and so on) but have the existing year selected to begin with?
An example, a game with a year of 2007.
When I click the record and go to edit the game, I want the dropdown box to display the current value (2007) automatically. Then, when I select the dropdown I want the years to still be in order.

A: You can sort it this way:
select DISTINCT gameYear from game order by
  case
     when gameYear = 2007 then 0
     else gameYear
  end;

A: You probably fill the dropdown by looping over your SQL result set and output HTML <option> elements. You need to check inside this loop if the current loop value is equal to the year of your game. If it is add the selected HTML attribute.

A: SelectedYear  is Your  current Selected Year
SELECT '$SelectedYear' as gameYear
UNION
SELECT * FROM
  (SELECT gameYear from game
  WHERE gameYear <> $SelectedYear
  ORDER BY gameYear)


Q: About Equallogic Dell storages controller replacement ? Active /Passive Regarding Dell Equallogic storage arrays, is it possible to replace the active controller module despite the fact that it's processing volume I/O? If not, what should I do before replacing it?

A: You move no LUN.
The way it work is the passive will activate and the active become passive. The IP is the same, so the gear connect to the new active, the problem you can face is a bad failover in case of a bad configuration, thus your hypervisor can lost access to the SAN temporaly. Its the problem you can face.
To switch to the passive controller manually the easiest way is to unplug the rj45 from the active controller, the passive (still plugged) will take the load from there.
Its actually a good test before putting a equalogic into production.
To move LUN its not when the active/passive controler do balance. Its when you have a failover equalogic SAN configuration. When the active SAN fail, the passive SAN automaticly take the load, but when the failed SAN is ready to rebecome online you need to redirect to a new iscsi target to retarget the correct active SAN. As you can see its not your case.

A: Before replacing the active controller, you should perform a "restart" from Group Manager. The process this starts makes an attempt at a non-disruptive failover, and provides a quicker handoff of iSCSI sessions than simply removing the active controller would. Whether or not this causes an outage for you would depend on whether your host configuration follows Dell's best practices (e.g. iSCSI login timeout of 60 seconds).


Q: Read txt file line by line into char array C I know this question has been asked a few times, but never in a way that helps me figure out my problem. Essentially, I am reading four text files, all single words separated by a new line, and wanting to store these in a char array. I first count the number of lines in the file and then create a new char array, but for the life of me, I cannot figure out how to get it to read correctly. The last two lines are just to test if it has read the entire file correctly and they always come back a NULL and the question mark symbol.
I want each line to be at the next index in the char array.
Any help would be awesome! Thank you ahead of time.
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

void countAnagrams(char* fileName);

void main ()
{
    char *fileNames[] = {"AnagramA.txt","AnagramB.txt","AnagramC.txt","AnagramD.txt"};

    countAnagrams(fileNames[0]);
    countAnagrams(fileNames[1]);
    countAnagrams(fileNames[2]);
    countAnagrams(fileNames[3]);
}

void countAnagrams(char* fileName)
{
    int anagramCount = 0;
    int ch, lines = 0;

    //Count number of lines in file
    FILE *myfile = fopen(fileName, "r");
    do
    {
        ch = fgetc(myfile);
        if(ch == '\n')
            lines++;
    }while(ch != EOF);

    char contents[lines];
    int i = 0;
    for(i=1;i<lines;i++)
    {
        fscanf(myfile,"%s",contents[i]);
    }
    fclose(myfile);

    printf("%.12s\n",fileName);
    printf("number of lines: %d\n", lines);

    printf("first thing: %s\n", contents[0]);
    printf("last thing: %s\n", contents[lines-1]);
}

A: Here's a slight modification of your code that might help you.
The main points:

*

*You can use getline() instead of fscanf(). fscanf() can be used to read line-by-line, but it needs an explicit check for the end of line condition. getline() does this automatically.

*As kaylum pointed out, it's necessary to rewind() the file pointer back to the beginning of the file after counting the number of lines.
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

void countAnagrams(char* fileName);

void main ()
{
    char *fileNames[] = {"AnagramA.txt","AnagramB.txt","AnagramC.txt","AnagramD.txt"};

    countAnagrams(fileNames[0]);
    countAnagrams(fileNames[1]);
    countAnagrams(fileNames[2]);
    countAnagrams(fileNames[3]);
}

void countAnagrams(char* fileName)
{
    int anagramCount = 0;
    int ch, lines = 0;

    //Count number of lines in file
    FILE *myfile = fopen(fileName, "r");
    do
    {
        ch = fgetc(myfile);
        if (ch == '\n')
            lines++;
    } while (ch != EOF);

    rewind(myfile);

    char *contents[lines];
    int i = 0;
    size_t len = 0;
    for(i = 0; i < lines; i++)
    {
        contents[i] = NULL;
        len = 0;
        getline(&contents[i], &len, myfile);
    }
    fclose(myfile);

    printf("%.12s\n",fileName);
    printf("number of lines: %d\n", lines);

    printf("first thing: %s\n", contents[0]);
    printf("last thing: %s\n", contents[lines-1]);
}

A: I think that the problem is char contents[lines] and then fscanf(myfile,"%s",contents[i]) and the printf-s after. contents[i] is char type, and you want to read an array of chars into one char. contents needs to be declared as char* contents[lines] to be able to read a char array into contents[i].


Q: radio button in datagrid taking different group name? I have a datagrid whose autogenerated column property is true. Each cell of the grid is bound with a radio button. But radio buttons in different rows are taking different groupname where as all of them are to be in same group. Can anyone resolve this? TIA.
int j = 0;
foreach(DataGridItem dgItem in dgPhoto.Items) {
    for (int i = 4; i < dgItem.Cells.Count; i++) {
        RadioButton rad = new RadioButton();
        rad.ID = "Photo_" + j.ToString() + i.ToString();
        rad.Text = priceTxt;
        rad.Attributes.Add("name", "priceGrp");
        dgItem.Cells[i].Controls.Clear();
        dgItem.Cells[i].Controls.Add(rad);
    }
    j++;
}

A: Try Setting the GroupName Property in your code:
Use:
rad.GroupName = "priceGrp"


Q: Oracle-update multiple row value where the the id column equals specific values I am new in oracle and I want to update multiple row value where the column id = 1 , 2.
I tried this :
update Tester
set employee_phone_number = ( 0789456123,0789456321)
where employee_id in (1,2);

but it gives me "missing right parenthesis"
any help please and thanks in advance.

A: Another approach:
merge into
  tester
using (
  select 1 id,'0123456785' employee_phone_number from dual union all
  select 2 id,'0123456786' employee_phone_number from dual) new_values
on (
  tester.id = new_values.id)
when matched then update
  set employee_phone_number = new_values.employee_phone_number;

More words, but allows the values to be specified in only one place and extends to allow inserts where the id does not already exist.
http://sqlfiddle.com/#!4/8fc86/3

A: Try this instead:
update Tester
set employee_phone_number = CASE WHEN employee_id = 1 THEN 0789456123
                                 WHEN employee_id = 2 THEN 0789456321
                            END
where employee_id in (1,2);


Q: Distribution of the degree of a node in a random graph in the unit circle My question is about the degree distribution  of a special random graph. Suppose $n$ points are uniformly and independently chosen in a unit circle. Join two points iff they are within a distance of $r$, where $0<r<1$ is some fixed parameter. This generates a random graph on the unit circle. If $X$ is the r.v. corresponding to the degree of a node ,what is $P(X\mid \text{radial distance is } d)$?
Here is a rough idea: given a node at some distance  from the center, the number of nodes within a vicinity of $r$ can be $0,1,2,3,....n-1$. So the number of nodes within a distance of $r$ of a particular node  is a binomial r.v. with the parameter $p$ where $p$ is the area common to the unit circle and the  circle of radius $r$ with centre at the particular node (whose degree distribution we are looking for). Will this approach work or do we need to try something else? What happens to degree distributio when $n$ goes to infinity?


Q: Good implementations of MVC in PHP I've done some development in RoR and I'm now trying to make something in PHP.
I think the MVC architecture is an ideal frame for my current project (users, application data, purchases, etc.)
Is there implementation of MVC on the web that is recommended or does PHP just not work in the same way as Rails and every MVC in PHP must be hand made?
My google fu is weak and I couldn't really find anything conclusive.

A: These four are MVC frameworks:

*

*CakePHP

*Symfony

*CodeIgniter

*Kohana
I prefer CodeIgniter and Kohana, because they're pretty focused and not bloated at all, and because they both, besides being MVC, are also big on the convention over configuration principle, meaning you don't have to go around maintaining XML/YAML/etc config files of your classes, URL routes, etc.
In particular I like Kohana because it has this nifty file system-based configuration hierarchy (they call it "Cascading Filesystem") which basically means you have even less configuration nonsense to maintain, because based on where you put your app's files (classes, config files, etc), the framework will know which parts of the system will be overridden. So I'd recommend you give Kohana a test run. Beware though, it's relatively new and the documentation is kind of weak, so if your google fu is indeed weak as you say, then you might be better off going straight for CodeIgniter, which has been around for longer and thus has more docs. But I'd still keep an eye on the Kohana project.
Symfony is... too bloated for my taste (i.e. having to run scripts in order to "generate views" and whatnot), but I've seen some large successful projects running on it.

A: Rails is an MVC framework, for PHP you could use CodeIgniter or CakePHP both of those use the MVC design pattern. CodeIgniter is the bomb.

A: You can find more discussion about PHP frameworks here: http://www.quora.com/Whats-the-best-MVC-framework-for-PHP
I haven't looked into other frameworks, I have found Codeigniter to satisfy most of my requirements from an MVC framework.

A: Sure, Theres Codeignitor and Frostbite Framework.. Both are good, and easy to find via google. Here is a whole list of php frameworks: http://matrix.include-once.org/framework/simple

A: Everyone else pretty much nailed it. The only reason I'm adding on to this question is because you use Ruby on Rails, and as such, CakePHP is going to be the most similar framework for you.
I use CodeIgniter because it's very well-documented and lightweight (with very little magic), but that's just my personal preference. Cake will be most like what you're used to.

A: I think laravel is best for you. Remember, frameworks are for SSBs Small scale businesses. For large scale businesses you write your own framework with all planning, execution phases etc.


Q: Enable TLS in bitnami Redis Pod - Certificate issue I am trying to enable TLS in my redis cluster.
Followed this article to create self signed certificate.
https://blog.devolutions.net/2020/07/tutorial-how-to-generate-secure-self-signed-server-and-client-certificates-with-openssl/
After generation of certificates followed the steps as given by bitnami documentation as below:-
https://docs.bitnami.com/kubernetes/infrastructure/redis/administration/enable-tls/
deployed using below
tls.enabled="true"
tls.certificatesSecret="certificates-tls-secret"
tls.certFilename="server.crt"
tls.certKeyFilename="server.key"
tls.certCAFilename="ca.crt"

But after this not able to start redis pod, getting below error
Error accepting a client connection: error:14094418:SSL routines:ssl3_read_bytes:tlsv1 alert unknown ca
I am guessing some issue with certificate chain but cannot figure out what. Can someone point me in right direction?


Q: looping and sentinel values I am trying to find average of inputted numbers by a user. The loop is supposed to repeat itself until the user inputs -9999 (sentinel value) this is what i have so far and it works in idle but the program doesnt end an give me the average when i type -9999. I am new to python and could use a little guidance thank you.
import random

numbers = [int(input("Please, enter number {}(-9999 to end")

if input("-9999"):

# will display prompt like "Please, enter number 1:"
print ("numbers entered:", numbers) # this will print the entered number

positives = [num for num in numbers if num > 0]
negatives = [num for num in numbers if num < 0]

# loop ends here

print ("Average negative number is :", sum(negatives)*1.0/len(negatives))
print ("Average positive number is :", sum(positives)*1.0/len(positives))
print ("Average of all numbers is:",sum(numbers)/len(numbers))

A: ns = []
while not ns or ns[-1] != -9999:
    ns.append(int(input("Please, enter number {}(-9999 to end"))))

A: ns = list(iter(lambda:int(input("Enter Number:")),-9999))

is a cool way to do it
iter can take a sentinal value to wait for as a second argument, if you use a function for the first argument
as an aside with your positive and negatives .... it seems it will ignore zeros (which may be intentional)...

A: This code will loop while you add numbers to your list and stop when you enter -9999. It will then throw the -9999 away so you can get on with your averaging. It's not compact, but it works and it's simple.
numbers = []

while True:
    numbers.append(input("Enter a number: "))   #append user input to 'numbers'
    if numbers[-1] == -9999:     #check to see if the last number entered was -9999
        numbers = numbers[:-1]   #if it was, modify numbers to exclude it
        break                    # and break the loop


Q: ASP dropdown list selected value I have a page with "date" field as drop down list and submit button. When I click on submit the selected value is displayed in grid view in other page.
Now in the grid view I have a field like "edit", when I click on that it is navigated to first page with that date value. The problem is that this time "date which is passed from grid view " is not shown selected value in drop down list.
<asp:TemplateField HeaderText="DOB" SortExpression="dob">
            <ItemTemplate>
                   <asp:Label ID="lbldob" runat="server" Text='<%# Bind("dob") %>'>
                   </asp:Label>
            </ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Edit">
            <ItemTemplate>
                     <asp:LinkButton ID="hypeno" CommandName="cmdBind" runat="server" Text='<%# Eval("id") %>' CommandArgument='<%# Bind("id") %>'>
                     </asp:LinkButton>
           </ItemTemplate>
</asp:TemplateField>

Code:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "cmdBind")
        {
            string id = e.CommandArgument.ToString();
            LinkButton lb = (LinkButton)e.CommandSource;

            Response.Redirect("/practice/registation.aspx?id=" + id +"&type=edit");
        }

    }

      string type = Request.QueryString["type"].ToString();
       if (type == "edit")
       {                 connection con = new connection();
                     DataSet ds;
                     ds = con.select("select dob from registration where id='"+Request.QueryString["id"].ToString()+"'");

      drddate.SelectedItem.Text= ds.Tables[0].Rows[0][0].ToString();
        }

A: Post your code, but sounds to me like you have to set the selected value in your dropdown in the grids onrowdatabound event - but I'm not entirely sure based on the vagueness of your question.


Q: How can I add an external JS file to my laravel controller file I'm new to Laravel and I wrote a piece of code to extract data from a database and display it in a tabular form using the Ajax.
Now I want to add 'onclick' function to the result. I've tried importing the external JS file but can't seem to get it right.
I would also appreciate an alternative approach. Here's my code
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class courseController extends Controller
{
 /**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('auth');
}

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    return view('course_registration');
}
public function search(Request $request)
{
    if($request->ajax())
    {
        $output="";

       $student=DB::table('dataentries')->where('ID_number','LIKE','%'.$request->search.'%')
                                        ->orWhere('name','LIKE','%'.$request->search.'%')->get();

        if($student)
        {
            foreach($student as $key => $student){
                $output.='
'.
                        ''.$student->ID_number.'	'.
                        ''.$student->name.'	'.
                        '
';

            }
            return Response($output);
        }
        else
        {

        }
    }
}

}


Q: Trim bar like the GarageBand and iMovie ones I'm creating a Mac app which needs a trim bar like the GarageBand and iMovie ones. I need a library to get the audio waves to draw them on a NSView. Anyone knows a good library for that?
I think he was referring to the track editor (cut/copy/paste/move).

A: There's a cool blog post on how to draw Waveforms by the author of the Capo audio editing software:
http://supermegaultragroovy.com/2009/10/06/drawing-waveforms/
I wrote Cocoa (Mac) code based on that, and it's not too hard. You can find that code here:
https://github.com/uliwitness/UKSoundWaveformView
Though it's far from a finished, shippable editor, it's under a permissive license (zlib) and could easily be used as a basis for a full editor.

A: Maibe this helps: Drawing waveform with AVAssetReader
and if the issue is to draw, then this may help: Parametric acceleration curves in Core Animation

A: This framework might help you out.  From the examples it looks like its pretty easy to use and works well.  It provides components to open an audio file, play it and draw the waveform.   You might need to implement the cut/copy/paste features on your own.


Q: External Hard Drive only recognized on USB3 Linux I have a 2 TB WD Elements hard drive. It was lost during a file transfer on Mac. It is not recognized on Mac or Windows, either USB2 or 3. It is not shown on device manager on Windows. The same happen on USB2 on Linux but surprisingly It works perfectly on USB3 on Linux. So far I have done a lot of tests:

*

*Tested on different systems and Operating Systems. Even tested it on two different Linux system and on both the hard worked only on USB3.

*Tested with different cables. Same results.

*Read and Wright works perfectly on USB3 in Linux. Smart test is OK.

*I have Formated the hard drive after I made a backup of my files. Again the hard only works on USB3 Linux. So I Formatted it in different file systems. NTFS, FAT and even ext4. Same results and no success.

*After plugging hard drive I can hear the disk cycling.

*Nothing in lsusb and dmesg on Linux when I connect my hard drive on USB2 in Linux.

*I suspected that because a USB3 port can transfer more power than USB2, maybe the problem is power. After plugging the hard in USB3, sudo lsusb -v |grep 'Bus\|MaxPower' for my hard drive gives me 224mA. I concluded that the problem is not power because my USB2 port gives 500mA for my IPod Classic so it can support 224mA.

Any help would be appreciated.

A: It is worth noting that MaxPower isn't always accurate. The hardware can report back to software any number it pleases, and still skimp on the actual power to run more economically.
To be honest, I wouldn't rule out a power issue, but it's easy to test: Connect your drive via a USB hub with external power. This way you know for sure that the drive gets all the power it needs, regardless of your computers ability. I did this once to connect a power-hungry drive to a USB port that simply wasn't able to deliver enough juice, even tho the USB3 standard dictated that it should be able to.

A: Instead of formatting the drive try writing zeros to it in order to clear any and all possible data and partitions that could prevent it from being recognized. You can do that with WD Data Lifeguard Diagnostic.
Trying a powered USB hub is also a very good idea.
Check if the drive is showing up in the BIOS and then see if it is anywhere to be found in Device Manager.


Q: Thread safety of the plus operator for Strings, optimizations included This post says that a += b is the equivalent of
a = new StringBuilder()
    .append(a)
    .append(b)
    .toString();

Let's say I have this code:
public class MultiThreadingClass extends SomeThirdPartyClassThatExtendsObject{
    public void beginmt(String st) throws IOException {
        //st is a thread number
        st = new File("c:\\somepath").getCanonicalPath()+"\\"+st;
        System.out.println(st);
    }
}

Assume that beginmt runs multiple times simultaneously (with thread numbers 1 to 15500) on a single instance of MultiThreading class. Could there be instances such that it could print the following i.e. some thread numbers are lost and some numbers are doubled?
c:\somepath\2
c:\somepath\1
c:\somepath\1
c:\somepath\4
c:\somepath\5
c:\somepath\6
c:\somepath\7
c:\somepath\8
c:\somepath\8
c:\somepath\10
...

Edit:
Will it be safe to say that the + operator won't get into some unsafe publication issue? I'm thinking the StringBuilder could be optimized into something that resembles an instance variable in which case it could be unsafely published.
Edit 2:
As far as the JLS, the abovementioned post, and a similar class file for the above code are checked, the StringBuilders to be used seem to have to get contained within different stackframes. However, I'd still like to check whether some form of aggressive optimization could cause the StringBuilders to be replaced by a centralized StringBuilder in some way. This sounds possible as it sounds logical for optimizers to optimize when it predicts that an object is just implemented in a non-constant way when in fact such object could be constant.
Found stringopts.cpp but haven't found the time yet to fully check it. I'm hopefully looking for answers involving details of this source file.
Edit 3:
I'm still looking for answers that include code on aggressive inlining for mutable objects.

A: Could there be instances such that it could print the following i.e. some thread numbers are lost and some numbers are doubled?
st is a method local variable, also st doesn't escape the method's scope so it is thread-safe. So, multithreading will have no effect on st . The messages can be printed out of order depending on which thread runs the method at what time.

A: As you don't share any field between your threads, the order of printing can differ, but any problem concerning thread safety (race conditions) shouldn't appear.

A: No, there is no state that's being shared between different threads so the situation you described can not happen.
If instead st was a member variable of that class, instead of being passed as an argument, and was incremented - that's a different story.
How it works now is that st will be put on the execution stack, each thread has it's own execution stack and they don't share stuff from there. Therefore each thread has it's own value of st. When it's a member variable of a class it's in memory (single value) and all threads would try to use it (the same one).
@Edit: well I guess it is possible if you call the method several times with the same value :-))

A: The Java Language Specification states

The result of string concatenation is a reference to a String object
  that is the concatenation of the two operand strings. The characters
  of the left-hand operand precede the characters of the right-hand
  operand in the newly created string.

So, although a compiler is free to optimize how the concatenation happens, it must do so while following that rule, "a" + "b" becomes "ab". In an unthread-safe, shared StringBuilder, implementation that would potentially not be the case. That implementation would therefore not be correct and could not be considered Java.

A: Each thread will always have individual StringBuilder instances.
Thread-safety is no issue when threads don't share instances.
So, the following simple method ...
public class MyThreadSafeClass
{
  public String myMethod(String field1, String field2, String field3)
  {
     return field1 + field2 + field3;
  }
}

... will be compiled to use a local StringBuilder.
public class MyThreadSafeClass
{
  public String myMethod(String field1, String field2, String field3)
  {
     return new StringBuilder(field1).append(field2).append(field3).toString();
  }
}

Each time the method is entered, a new StringBuilder instance is created.
This instance is only used withing the scope of this thread.
You are correct however that StringBuilders are not always thread-safe. (see below)
If multiple threads start calling the saveEvent method, they may be using the builder simultaneously.
public class History
{
  // thread-safety issues !!!!
  // In fact, here you should use a StringBuffer or some locking.
  private StringBuilder historyBuilder = new StringBuilder();

  public void saveEvent(String event)
  {
     historyBuilder.append(event).append('\n');
  }

  public String getHistoryString()
  {
     return historyBuilder.toString();
  }
}

But compiler optimizations will not create these kind of constructions. The StringBuilder is always created and used only within one and the same thread.
We could try to make things more complex (static fields, multiple classloaders, ...) but always again, each StringBuilder instance is created and used by only 1 thread.
EDIT:
Perhaps useful to know: This optimization happens during the generation of the byte-code. There are other optimizations later on during JIT compilation, but this optimization is not one of them.  However the JIT compiler does have an important impact in the final performance.

A: I have to partially disagree. This sentence is incomplete / missleading:
"If instead st was a member variable of that class, instead of being passed as an argument, and was incremented - that's a different story."
What matters in the original example is that the expression on the right is a rvalue. If it were not, the outcome would have been different. I will explain a bit.
So yes, Strings are immutable, and beginmt() receives a final reference to a String and this means a final reference to an immutable heap memory area. JVM will make a copy of this final reference and whatever you do inside the beginmt(), it is done on this copy, and this copy, immediately after the string is modified (st = ...), will point to another memory area. Now the point is that this final heap memory area has no pointer to it, because it is created inside the method and it seems that nothing points to it. Well, almost! The JVM may intern the string and if another thread points to the same value as the interned value it could be possible that they would actually share the same heap address. Now having a race condition exactly here is very hard to detect, so I will make a synthetic example to illustrate what could happen in case the expression on the right is a lvalue (induced by JVM's String intern-al):
public class AnExample {
    private static final int N = 20000;
private static class Foo {
    static HashMap<String, Foo> foos = new
            HashMap<String, Foo>(N);

    static synchronized Foo createInstance(String i) {
        if (foos.containsKey(i))
            return foos.get(i);
        foos.put(i, new Foo(i));
        return foos.get(i);
    }

    String i;

    private Foo(String i) {
        this.i = i;
    }

    Foo inc() {
        synchronized(Foo.class){
            i += "1";
            return createInstance(i);
        }
    }

    @Override public String toString() {
        return i;
    }
}

private static class Bar {
    public void bar(Foo st) {
        st = st.inc();
        System.out.println(st);
    }
}

public static void main(String... args) {
    final Bar cucu = new Bar();
    for (int i = 0; i < N; i++) {
        final Foo st = Foo.createInstance(i + "");
        new Thread(new Runnable(){
            @Override public void run() {
                cucu.bar(st);
            }
        }).start();
    }

    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

}
This will produce about 40% duplicates (I have less than 10100 unique values). Note that in the bar() method st = some_expression(st)
In my example I intentionally produce a lvalue just to show what might happen in case the JVM will intern the expression and it happens to have a reference to that (which is sent back in another thread to the same method).
The conclusion is that your code is not correct because "st is not a member variable of that class" and "st becomes a local, copied reference", etc - but because the expression on the right is a rvalue.


Q: Heat Equation: Polynomial Inital, Neumann Boundary Consider the heat equation solution $h(x,t)$ where $x \in [0,1]$ and $t \geq 0$ with initial condition $h(x,t=0)=f(x)$ and Neumann boundary $\frac{d}{dx} h(x=0,t)=0$ and $\frac{d}{dx} h(x=1,t)=0$. Suppose $f(x)=x^n$ where $n \in \mathbb{N}$. Obviously, the solution $h$ can be expressed as an infinite Cosine series. However, I was wondering if for this particular choice of $f$, whether $h(x,t)$ has a closed form solution? If yes, then, great, what is the expression? :)
If not, then here is the next question: is there a good approximation for $\hat{h}(x,t) \approx h(x,t)$ such that $\hat{h}(x,t)$ is a polynomial of degree at most $n$ with respect to variable $x$ (does not necessarily need to be polynomial in $t$)?
Thanks,
Golabi

A: I assume the constant in your heat equation is $1$, so it's
$$\dfrac{\partial h}{\partial t} = \dfrac{\partial^2 h}{\partial x^2}$$
If I'm not mistaken, your solution can be written as an integral of a
Jacobi theta function:
$$h(x,t) = \int_0^1 s^n \vartheta_3\left(\dfrac{\pi (x-s)}{2}, e^{-\pi^2 t}\right)\; ds $$
although that probably won't help you much.  It's basically equivalent to your cosine series.
For large $t$, there's not much point in approximating the solution using polynomials:
 the first few terms of your cosine series will give you a very good approximation, because $\exp(-n^2 \pi^2 t)$ goes to $0$ very rapidly unless
$n$ is small.


Q: Cannot get text of a span attribute using BeautifulSoup I am trying to get from the following
ΚΩΔ. 473768

the value of data-nodeid
I did the following
price_nodes = soup.find('span', attrs={'id': 'SkuNumber'})
datanode = price_nodes.select_one('span[data-nodeid]')

But I get "None"
How can I fix this? thank you

A: If price_nodes is correctly fill
i.e. price_nodes =
ΚΩΔ. 473768

You just have to do this:
datanode = price_nodes.get('data-nodeid')

Full code should be:
from bs4 import BeautifulSoup as soup

html = '
ΚΩΔ. 473768
'
page = soup(html, 'html.parser')
price_nodes = page.find('span', {'id': 'SkuNumber'})
datanode = price_nodes.get('data-nodeid')

A: from bs4 import BeautifulSoup

html = 'ΚΩΔ. 473768
'
soup = BeautifulSoup(html)

price_nodes = soup.find('span', attrs={'id': 'SkuNumber'})
print(price_nodes['data-nodeid'])


Q: Sharepoint 2013 REST API - Shared Documents / Author Info In one Call? We are in the process of integrating from Sharepoint 2007 to Sharepoint 2013.  We have a java based application using Sharepoint 2007 SOAP based webservices.
In Sharepoint 2013 we are using the REST API.  And I am not seeing an obvious way to make a single call to get a list of documents for Shared Documents and have it include the Author's name.
I am calling to this REST endpoint:
https://www.acme.org/sites/PortalTest/_api/Web/GetFolderByServerRelativeUrl('/sites/PortalTest/Shared%20Documents')/Files?$select=*
I do get an Author property back, but it points to another REST end point (partial JSON response):
            "Author":{
           "__deferred":{
              "uri":"https://www.acme.org/sites/PortalTest/_api/Web/GetFileByServerRelativeUrl('/sites/PortalTest/Shared%20Documents/Test.docx')/Author"
           }

Now I could make separate calls to get the Author information, but I'd rather not do it that way.
Is there anyway to make one call to get the documents in a Shared Documents folder that will include the author's name using the Sharepoint 2013 REST API?
EDIT TO ADD:
I found the answer.  Adding the "expand" parameter will flush out deferred properties:
https://www.acme.org/sites/PortalTest/_api/Web/GetFolderByServerRelativeUrl('/sites/PortalTest/Shared%20Documents')/Files?$expand=Author

A: Try this query
?$select=Author/Id,Author/Name,Author/Title,Editor/Id,Editor/Name,Editor/Title,*&$expand=Author,Editor

A: I was myself looking for an answer to this problem today. But whenever I attempted to add the query parameters to the URL straightaway I got an error:

A potentially dangerous Request.Path value was detected from the
client (?)

So those of you that are also bothered by the above error message, you might want to try the following:
Endpoint (taking from the question):
https://www.acme.org/sites/PortalTest/_api/Web/GetFolderByServerRelativeUrl(@a1)/Files
Query parameters (declare them separately):
@a1: "/sites/PortalTest/Shared%20Documents"
$expand:"Properties,Author,CheckedOutByUser,ModifiedBy" (Depending on which ones you need. The entire list is available here)

Note:
I am invoking the endpoints from my Java middleware and for that I'm using Client, WebTarget and Invocation.Builder from the javax.ws.rs.client namespace.
Client client; // Construct your client here with your token, secret and other attributes

WebTarget target = client.target("https://www.acme.org/sites/PortalTest/_api/Web")
.path("/GetFolderByServerRelativeUrl(@a1)/Files")
.queryParam("@a1", "%27%2Fsites%2Fdms%5Fo2%2FShared%20Documents%27") // encoded!
.queryParam("$expand", "Properties,Author,CheckedOutByUser,ModifiedBy");

Builder request = target.request();

//...


Q: using local notification data coming from web service I am new to IOS and wants to used Local Notification feature of iOS.
my problem is i do not know if i can go with local notification. in my case data will come from web service... it is like..no specific date. default time interval is 60 Sec. after 60 sec app has to call webservice which will return notification data..and after some validation i need to push to user.
and if user click on view details it will launch appand get data via webservice.
Is using localnotification will serve my purpose? or i have to go with other approach?
Please help.
Thanks in advanced.

A: I think this 60 second thing is you polling the server every 60 seconds to fetch new data, then if there is new data post a local notification?
This is kinda possible with iOS7 but not exactly every 60 seconds, sometimes not at all, But in general it is strongly frowned upon. Instead the webserver should send push notifications when new data is available, It saves the user battery life.
On iOS7 there are silent push notifications (just don't include the alert) that can ask the client to do the validation you mentioned, and If the user needs a notification you can create a Local Notification to alert the user in a change
You should give this documentation a long look, it isn't trivial work for a new iOS programmer:
https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Introduction.html
And here is a relevant Apple documentation quote "Local and push notifications serve different design needs. A local notification is local to an application on an iPhone, iPad, or iPod touch. Push notifications—also known as remote notifications—arrive from outside a device. They originate on a remote server—the application’s provider—and are pushed to applications on devices (via the Apple Push Notification service) when there are messages to see or data to download."

A: If you are trying to achieve this functionality to happen automatically/polling (i.e without user interaction like, clicking on the view details button)- the answer is a big NO at least not till iOS6.x
Your application cannot run for infinite length in background at-not till ios6.x. You may have to consider using APNS service to achieve this.
Otherwise, your approach on scheduling a local notification for ever 60 sec - The user clicks in the view option - the application comes up - You make a web-service call - Get the data - Validate the received data - Uploading to the server, looks fine to happen.
Will it not be annoying to the user getting notification for ever 60 sec & operating on the app to do whatever you intended to do? - Just curious.


Q: Create SVG components with scoped CSS I am creating React components that will render out various SVGs:
const Close = ({
  fill, width, height, float,
}) => (
  <svg width={ `${width}px` } height={ `${height}px` } viewBox="0 0 14.48 14.48" style={ { float: `${float}`, cursor: 'pointer' } }>
    <title>x</title>
    <g id="Layer_2" data-name="Layer 2">
      <g id="Background">
        <line style={ { fill: 'none', stroke: `${fill}`, strokeMiterlimit: 10 } } x1="14.13" y1="0.35" x2="0.35" y2="14.13" />
        <line style={ { fill: 'none', stroke: `${fill}`, strokeMiterlimit: 10 } } x1="14.13" y1="14.13" x2="0.35" y2="0.35" />
      </g>
    </g>
  </svg>
);

It's very convenient to be able to supply various attributed to this component to control dimensions, colour, etc...
What I don't have a good solution for, however, is handling the styles in a DRY manner. Note the line elements have the same value for style. I presently have them written inline because if I added an embedded stylesheet, then I would get class name collisions with other SVGs I render elsewhere on the page (our SVG software uses the same classes over and over).
<style scoped> has been removed from the spec: https://github.com/whatwg/html/issues/552
Shadow DOM is not yet supported by Edge: https://caniuse.com/#feat=shadowdomv1
Is there any other alternative for scoping styles?

A: To combine the best of both worlds, you could create an external styles file, as you would for CSS, but with exported style objects. You could then import it into any file that needs it.
As example, main file:
import React, { Component } from 'react';
import { render } from 'react-dom';
import * as Styles from './svgstyles';

class App extends Component {
  render() {
    return (
      <div>
        <svg width="100" height="200" viewBox="0 0 100 200">
          <rect x="0" y="0" width="10" height="10" style={Styles.style1} />
          <rect x="15" y="0" width="10" height="10" style={Styles.style2} />
          <rect x="30" y="0" width="10" height="10" style={Styles.style3} />
          <rect x="45" y="0" width="10" height="10" style={Styles.style4} />
          <rect x="0" y="15" width="10" height="10" style={Styles.style4} />
          <rect x="15" y="15" width="10" height="10" style={Styles.style3} />
          <rect x="30" y="15" width="10" height="10" style={Styles.style2} />
          <rect x="45" y="15" width="10" height="10" style={Styles.style1} />
        </svg>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

And an external styles file:
export const style1 = {
  stroke: 'red',
  strokeWidth: "1",
  fill: "blue",
}

export const style2 = {
  stroke: 'red',
  strokeWidth: "1",
  fill: "green",
}

export const style3 = {
  stroke: 'red',
  strokeWidth: "1",
  fill: "yellow",
}

export const style4 = {
  ...style3,
  fill: "pink",
}

Live example here

A: If you just want to DRY up the code, you could create one style-object and reuse it:
const Close = ({
                 fill, width, height, float,
               }) => {
  const style = { fill: 'none', stroke: `${fill}`, strokeMiterlimit: 10 }
  return (
    <svg width={ `${width}px` } height={ `${height}px` } viewBox="0 0 14.48 14.48" style={ { float: `${float}`, cursor: 'pointer' } }>
      <title>x</title>
      <g id="Layer_2" data-name="Layer 2">
        <g id="Background">
          <line style={ style } x1="14.13" y1="0.35" x2="0.35" y2="14.13" />
          <line style={ style } x1="14.13" y1="14.13" x2="0.35" y2="0.35" />
        </g>
      </g>
    </svg>
  );
}

This would also result in a small performance improvement since fewer objects would be created in each render cycle.

A: Actually, if I was in your place, Surely I use fonts instead of SVGs, but for your exact question, I prefer to use constant variables inside of my arrow function, just like below:
import React from 'react';

const Close = ({ fill, width, height, float }) => {
  const constStyle = { fill: 'none', stroke: `${fill}`, strokeMiterlimit: 10 };

  return (
    <svg
      width={`${width}px`}
      height={`${height}px`}
      viewBox="0 0 14.48 14.48"
      style={{ float: `${float}`, cursor: 'pointer' }}
    >
      <title>x</title>
      <g id="Layer_2" data-name="Layer 2">
        <g id="Background">
          <line style={constStyle} x1="14.13" y1="0.35" x2="0.35" y2="14.13" />
          <line style={constStyle} x1="14.13" y1="14.13" x2="0.35" y2="0.35" />
        </g>
      </g>
    </svg>
  );
};

export default Close;

Even, I make the line dimension variables as props, but I don't know what is your case exactly.
Hope this answer helps you.


Q: TFDMemTable lost/clearing data after filtering I have created a FDMemTable with following structure:
Cds_NaMenu := TFDMemTable.Create(nil);
Cds_NaMenu.FieldDefs.Add('ID', ftInteger);
Cds_NaMenu.FieldDefs.Add('MN_TELA_CODIGO', ftInteger);
Cds_NaMenu.FieldDefs.Add('MN_MENU_PESQUISA', ftString, 500);
Cds_NaMenu.FieldDefs.Add('DISPONIBILIDADE', ftInteger);
Cds_NaMenu.IndexDefs.Add('Ordem', 'MN_TELA_CODIGO', []);
Cds_NaMenu.CreateDataSet;
Cds_NaMenu.LogChanges := False;
Cds_NaMenu.IndexName := 'Ordem';

I put data in TFDMemTable like this:
Cds_NaMenu.Append;
Cds_NaMenu.FieldByName('DISPONIBILIDADE').AsInteger := 1;
Cds_NaMenu.Post;

Well... The problem ocurrs when a set filtered property to True and back to False. The RecordCount property goes to 0; None data has found in, even I use saveToFile procedure. Aparently the data was losted.
_recCount := Cds_NaMenu.RecordCount; // Result = 867;
Cds_NaMenu.Filter := 'DISPONIBILIDADE=1 AND MN_MENU_PESQUISA like ' + QuotedStr('%' + sTexto + '%');
Cds_NaMenu.Filtered := True;
_recCount := Cds_NaMenu.RecordCount; // Result = 0;
Cds_NaMenu.Filtered := False;
Cds_NaMenu.Filter := '';
_recCount := Cds_NaMenu.RecordCount; // Result = 0;

PS: With ClientDataSet, this code works perfectly

A: If you're working with a pure memory table, there should not be any problem to query record count by the RecordCount property. Maybe you expect having NULL and empty value records included in a filtered view when having filter Value LIKE '%%', but it's not so. When having dataset like this:
ID | Value
1  | NULL
2  | ''
3  | 'Some text'

And applying filter like this:
var
  S: string;
begin
  S := '';
  FDMemTable.Filtered := False;
  FDMemTable.Filter := 'Value LIKE ' + QuotedStr('%' + S + '%');
  FDMemTable.Filtered := True;
  { ← FDMemTable.RecordCount should be 1 here for the above dataset }
end;

The empty and NULL value records should not be included in the view. Here is a short proof:
var
  S: string;
  MemTable: TFDMemTable;
begin
  MemTable := TFDMemTable.Create(nil);
  try
    MemTable.FieldDefs.Add('ID', ftInteger);
    MemTable.FieldDefs.Add('Value', ftString, 500);
    MemTable.IndexDefs.Add('PK_ID', 'ID', [ixPrimary]);
    MemTable.CreateDataSet;

    MemTable.AppendRecord([1, NULL]);
    MemTable.AppendRecord([2, '']);
    MemTable.AppendRecord([3, 'Some text']);

    S := '';
    MemTable.Filtered := False;
    MemTable.Filter := 'Value LIKE ' + QuotedStr('%' + S + '%');

    ShowMessage(Format('Total count: %d', [MemTable.RecordCount])); { ← should be 3 }
    MemTable.Filtered := True;
    ShowMessage(Format('Filtered count: %d', [MemTable.RecordCount])); { ← should be 1 }
    MemTable.Filtered := False;
    ShowMessage(Format('Total count: %d', [MemTable.RecordCount])); { ← should be 3 }
  finally
    MemTable.Free;
  end;
end;

A: I think this is just a minor FD quirk.  The code below works as expected, with Cds_NaMenu declared as a TFDMemTable (though it would have been nice if you could have dropped the Cds_ to avoid confusion).
The key difference, I think, is the call to .Locate after the filter is cleared.  The reason I put it there is because it causes the dataset to scroll and, I imagine, to recalculate its RecordCount as a result.  Probably any other operation which causes a scroll would have the same effect, even MoveBy(0) - try it.
procedure TForm1.FormCreate(Sender: TObject);
var
  _recCount : Integer;
  ID : Integer;
  sTexto : String;
begin
  sTexto := 'xxx';  // added

  Cds_NaMenu.FieldDefs.Add('ID', ftInteger);
  Cds_NaMenu.FieldDefs.Add('MN_TELA_CODIGO', ftInteger);
  Cds_NaMenu.FieldDefs.Add('MN_MENU_PESQUISA', ftString, 500);
  Cds_NaMenu.FieldDefs.Add('DISPONIBILIDADE', ftInteger);
  Cds_NaMenu.IndexDefs.Add('Ordem', 'MN_TELA_CODIGO', []);
  Cds_NaMenu.CreateDataSet;
  Cds_NaMenu.LogChanges := False;
  Cds_NaMenu.IndexName := 'Ordem';

  Cds_NaMenu.Append;
  Cds_NaMenu.FieldByName('ID').AsInteger := 666;  // added
  Cds_NaMenu.FieldByName('DISPONIBILIDADE').AsInteger := 1;
  Cds_NaMenu.Post;

  _recCount := Cds_NaMenu.RecordCount; // Result = 1

  ID := Cds_NaMenu.FieldByName('ID').AsInteger;  // added

  Cds_NaMenu.Filter := 'DISPONIBILIDADE=1 AND MN_MENU_PESQUISA like ' + QuotedStr('%' + sTexto + '%');
  Cds_NaMenu.Filtered := True;
  _recCount := Cds_NaMenu.RecordCount; // Result = 0;
  Cds_NaMenu.Filtered := False;
  Cds_NaMenu.Filter := '';

  // Now force the dataset to scroll
  if Cds_NaMenu.Locate('ID', ID, []) then;  // added
  _recCount := Cds_NaMenu.RecordCount; // Result = 1;
  Caption := IntToStr(_recCount);  // added
end;


Q: Conditional probability of scoring more than $8$ questions correctly given at least $6$ is correct.
Question: In a multiple choice test, there are 20 questions, and each question has four choices. Jane is clueless and answers by purely guessing. She is equally likely to pick any of the possible choices, and each such choice is independent of the other ones. If it is known that Jane guessed correctly strictly more than six questions correctly, what is the chance that she scored strictly more than eight questions correctly?

I have attempted it and my work is shown below for this practice problem. However, I got it wrong and I am not sure why is the answer correct. Could anyone please tell me what I did wrong and how should I solve it?
My answer:
$$P(X > 8| X> 6) = \frac{P(X > 8)}{P(X>6)}=\frac{\sum_{i=9}^{20}\binom{20}{i}(0.75)^{20-i}(0.25)^i}{\sum_{i=7}^{20}\binom{20}{i}(0.75)^{20-i}(0.25)^i}$$
But answer provided was:
$$\frac{\sum_{i=7}^{20}\binom{20}{i}3^{20-i}}{\sum_{i=9}^{20}\binom{20}{i}3^{20-i}}$$

A: The "actual answer" can't be correct, since the numerator is greater than the denominator.
Probability can't exceed $1$.


Q: Select every paragraph element that is not the first child of its parent What is the correct CSS selector, if I want to select every
 that is not the first element of its parent?
Like this snippet below, just reverse! (so 'second', 'third', 'fourth' are red, 'first' is normal)

p:first-of-type {
  background: red;
}

The first paragraph.

The second paragraph.

The third paragraph.

The fourth paragraph.

A: You can use the :not negation pseudo-class. Note that when combining pseudo-classes, you must put the second pseudo-class inside of brackets as :not(:first-of-type):

p:not(:first-of-type) {
  background: red;
}

The first paragraph.

The second paragraph.

The third paragraph.

The fourth paragraph.

Note that if you're specifically looking to select every element other than the first child of an element, you can use :not(:first-child). Note that the selector goes on the child element in this case though, not the parent:

.parent p:not(:first-child) {
  background: red;
}

The first paragraph.

The second paragraph.

The third paragraph.

The fourth paragraph.

A: Very simply:

p+p {
  background: red;
}

The first paragraph.

The second paragraph.

The third paragraph.

The fourth paragraph.

The next-sibling combinator (+) targets an element that is immediately preceded by another element.
So in this case, only p elements following another p are selected. This excludes the first p.
You may also be interested in the subsequent-sibling combinator (~), which is similar to the above, except the first element does not need to immediately precede the second.

A:

.text p:not(:first-child) {
  background: green;
}

The first paragraph.

The second paragraph.

The third paragraph.

The fourth paragraph.


Q: Internet Explorer 8 adds line breaks after link_to With the following code, IE 8 adds line breaks after the link_to. Its in a
 tag, so there should not be a line break. Even adding a CSS class to the link_to with display: inline does not help.

After registering, at any time you can click on the "My Profile" links and buttons found throughout the site, or simply click <%= link_to "here", user_path(current_user) %>.

Here is the HTML that is generated:

After registering, at any time you can click on the "My Profile" links and buttons found throughout the site, or simply click here.


Q: Error fetching data from api and display it I want to make a get request from my restApi and then display the data in a listView but for some reason it is not working.
The error I'm getting:

The getter 'length' was called on null.
Receiver: null
Tried calling: length

Api call (apiBaseHelper.dart)
 Future<List<Post>> getAllPosts() async {
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key) ?? 0;

final getPublishedPostUrl = "http://192.168.1.7:5000/post/all";
final response = await http.get(getPublishedPostUrl, headers: {
  'Accept': 'application/json',
  'Authorization': 'Bearer $value'
});
if (response.statusCode == 200) {
  List jsonResponse = json.decode(response.body);
  return jsonResponse.map((posts) => new Post.fromJson(posts)).toList();
} else {
  throw "something ";
}

}
PostListView
class PostListView extends StatelessWidget {
  final List<Post> posts;
  PostListView({Key key, this.posts}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: ListView.builder(
      itemCount: posts.length,
      itemBuilder: (context, index) {
        return Column(
          children: <Widget>[
            Container(
              constraints: BoxConstraints.expand(
                height:
                    Theme.of(context).textTheme.display1.fontSize * 1.1 + 200.0,
              ),
              color: Colors.white10,
              alignment: Alignment.center,
              child: Card(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    ListTile(
                      contentPadding: EdgeInsets.all(10.0),
                      title: new Text(posts[index].title),
                      leading: new Image.network(
                        posts[index].picture,
                        fit: BoxFit.cover,
                        height: 40.0,
                        width: 40.0,
                      ),
                      subtitle: Text(posts[index].category),
                    ),
                  ],
                ),
              ),
            ),
          ],
        );
      },
    ));
  }
}

homePage.dart
class HomePage extends StatefulWidget {
final ApiBaseHelper apiBaseHelper = ApiBaseHelper();

  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {
  Future<List<Post>> futurePost;
  @override
  void initState() {
    super.initState();
    futurePost = ApiBaseHelper().getAllPosts();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      backgroundColor: Colors.teal,
      body: new Padding(
        padding: EdgeInsets.fromLTRB(1.0, 10.0, 1.0, 10.0),
        child: FutureBuilder<List<Post>>(
          future: ApiBaseHelper().getAllPosts(),
          builder: (context, AsyncSnapshot<List<Post>> snapshot) {
            if (snapshot.hasError) {
              print(snapshot.error);
            }
            return snapshot.hasData
                ? PostListView()
                : Center(child: CircularProgressIndicator());
          },
        ),
      ),
    );
  }
}

I have been working on it for like 2 days and I don't know where the problem exactly
I'm sorry if it's too much code. thank you in advance

A: This code section here ,
  return snapshot.hasData
                ? PostListView()
                : Center(child: CircularProgressIndicator());

Add PostListView(posts:snapshot.data)
Tell me if it works.