text:
Q: Linking or scrolling to Specific scetion in PHP when using dynamic div id In HTML we can create A single page site with smooth scrolling, and highlighted navigation links depending on which section is currently being viewed.To do the above in HTMl we
 link to this point (e.g. from the top of the page), we link using the hash character (#) and the name of the destination anchor:
Go To Contact Form
The same I am Trying to Implement in PHp but I am facing Issues.

                <?php
        function readCSV($fileName) {
          $rows = array();
          $rows = file($fileName);
          return $rows;
    }

    ?>

      Available Positions:

     <?php
     $rows=readCSV('joinUs.csv');
      $max = sizeof($rows);
              for ($x=1; $x<$max; $x++) {
          echo "
 $rows[$x] |
";

    }

     ?>

<div class="position" id="<?php print_r(readCSV('joinUs.csv')[1]);?>">
 Job Descreption here

The Anchor Id seen while inspecting is Sr. Product Engineer and $rows[$x] is Sr. Product Engineer and both are same still Its not scrolling(from top of site on clicking the Click).
When I am hardcoding to Sr. Product Engineer it Its Working. It not working only in case of dynamic div id.While Inspecting in browser I am able to see correct div ID.
How to fix the above issue.
please let me know if any other clarification is required.
Attached is the ScreenShot

I was Requested in comment to post html source code also:
  Available Positions:

 Sr. Product Engineer
 |

 Quality Assurance Engineer
 |

 Frontend Javascript Engineer
 |

 Business Development Manager
 |

Sr. Product Engineer

      This is what we have in mind for you, the Role:

        You will be part of the tech team and will be working closely with founders
        and design team on the core product. You will be working to build new features,
        fix bugs and refactor things as necessary.

Responsible for the tech architecture

Take ownership of things

Write simple/readable code which is testable, extendable, robust and highly scalable

Help getting new joinees upto speed with the product

Suggest new features, priorities tasks and see to their completion

Please help as in above source code you can see PHP generates the same ID in html.When I am hardcoding the id It working but without hardcoding its not working.

A: Use valid IDs without dots or spaces or any other special characters.
Sr. Product Engineer

Sr. Product Engineer

To generate that dynamically with PHP:
<?php
$str = readCSV('joinUs.csv')[1];
$id = preg_replace('/[^A-Za-z0-9]/', '', $str); // Remove all characters except A-Z, a-z, 0-9
echo '' . $str . '';
echo '
' . $str . '
';
?>

A: Inside the loop, just name the id's as
position_0, position_1, position_2

and then anchor them using
#position_0, #position_1, #position_2


text:
Q: JUnit AssertionError: Expecting code to raise a throwable I am trying to write a test for a method that throws custom exception. It fails with Assertion error. What could be done to properly catch the exception and pass the test?
Service method:
@Service
public class CustomServiceImpl implements CustomService {
    @Autowired
    UserUtil userUtil;
    public ResultDTO getResultDto (String type, Long id) throws CustomException {
        User user = userUtil.getCurrentUser();
        if (user == null) {
            throw new CustomException("User does not exist");
        }
    }
}

Test method:
@MockBean
CustomServiceImpl  customServiceImpl ;

@Test
public void test01_getResultDto() {
    UserUtil userUtil = Mockito.mock(UserUtil.class);
    Mockito.when(userUtil.getCurrentUser()).thenReturn(null);
    Assertions.assertThatThrownBy(() -> customServiceImpl.getResultDto (Mockito.anyString(), Mockito.anyLong()))
        .isInstanceOf(CustomException .class)
        .hasMessage("User does not exist");
}

This test fails with the following error:
java.lang.AssertionError: Expecting code to raise a throwable.
    at com.ps.service.CustomServiceImplTest.test01_getResultDto(CustomServiceImplTest.java:62)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

--------------------------- EDIT ------------------------
Changed the code Test to include the following
@Mock
UserUtil userUtil;
@InjectMocks
CustomServiceImpl cutomServiceImpl;

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
}

@Test
public void test01_getResultDto() {
    when(userUtil.getCurrentUser()).thenReturn(null);
    assertThatThrownBy(() -> customServiceImpl.getResultDto ("type", 1L))
        .isInstanceOf(CustomException .class)
        .hasMessage("User does not exist");
}

Seems to be working.
Thanks to the advice in comments.

A: I have made suitable changes to my original code and the following set up works well.
@Mock
UserUtil userUtil;
@InjectMocks
CustomServiceImpl cutomServiceImpl;

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
}

@Test
public void test01_getResultDto() {
    when(userUtil.getCurrentUser()).thenReturn(null);
    assertThatThrownBy(() -> customServiceImpl.getResultDto ("type", 1L))
        .isInstanceOf(CustomException .class)
        .hasMessage("User does not exist");
}

A: Another way you can do it is :
@MockBean
CustomServiceImpl  customServiceImpl ;
@Rule
public ExpectedException exceptionRule = ExpectedException.none();

@Test
public void test01_getResultDto() {
    exceptionRule.expect(CustomException.class);
    UserUtil userUtil = Mockito.mock(UserUtil.class);
    Mockito.when(userUtil.getCurrentUser()).thenReturn(null);
    customServiceImpl.getResultDto ("type", 1L);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Thread-Safe ArrayList merge: will this work?   private static final ExecutorService ES = Executors.newWorkStealingPool();

  public Future<List<String>> isThisSafe() {
    List<String> a = new ArrayList<>();
    a.add("a");
    List<String> b = new ArrayList<>();
    b.add("b");

    return ES.submit(() -> {
      a.addAll(b);
      return a;
    });
  }

I'll say that thread X is the one that calls isThisSafe(). Thread Y runs the Callable submitted to the ExecutorService.
Right now, I think this works.
✓ The two ArrayLists are never modified by X after being published to Y
✓ ArrayList 'a' is modified by thread Y, but X does not hold a reference to 'a'.. the returned reference to 'a' would be considered 'new' and so X will pull this from MM.
But is there a problem with my second point? Maybe I misunderstand the memory model.

A: The thread X safely publishes the object a to thread Y and does not do any modification until Y succeeds. So the object a is safely published from thread X to thread Y.
Moreover, All actions in a thread happen-before any other thread successfully returns from a Future.get() on that thread. Upon returning from Future.get() thread X can see all the changes made by thread Y to the object a.
So according to our thread safety analysis, we can conclude that this code is thread safe.


text:
Q: Get selectedItem in ItemsPanelTemplate I have the following code which posts buttons in rows and columns.
<ItemsControl ItemsSource="{Binding MyCollection}">
<!-- ItemsPanelTemplate -->
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <UniformGrid Columns="2" />
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>

<!-- ItemTemplate -->
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Button Content="{Binding }" />
    </DataTemplate>
</ItemsControl.ItemTemplate>

Here is my collection which populates the user controls
private Collection<TemplateView> _myCollection;
public Collection<TemplateView> MyCollection
{
    get { return _myCollection; }
    set { _myCollection = value; }
}

How do I know which particular button is pressed? (row/column would suffice).
Many thanks in advance :)


text:
Q: metastable example of verilog I'm learning metastable and using 2-FF sychronizer .
And I.m trying to figure out it meaning.
but it seem to almost example is about click button and cause it so we need 2-FF sychronizer to solve it.
Is there any other example code of verilog that I can try to test on my own computer?
I think it will more understandable and compare 1-FF and 2-FF by result.
thanks all.

A: Metastability is the result of analog behavior. You cannot simulate metastability problems with a digital event driven simulator. You can only verify that the solution doesn't cause other functional issues. CDC/RDC tools can help statically (i.e. without dynamic simulation) catch design flaws where metastability might arise and make sure they have been properly corrected


text:
Q: VBA - IF ElseIf with .Visible = True/False I was hoping I could get some help on a VBA issue I ran into, but first I would like to say that I am in no way an expert of VBA, or anywhere close to that... But, I am eager to learn!
I am working with reports within MS Access 2010 and using VBA, I am hiding 1 page footer and showing another based on the page number. The problem I am runnning into is that I need to make the footer visble and invsible twice in report. I tried to use an IF ELSEIF, but it does not seem to be working. Does this code look correct? Or am I doing something wrong?
If Me.Page <= 2 Then
    Me.PageFooter1.Visible = True
    Me.PageFooter2.Visible = False
ElseIf Me.Page >= 9 Then
    Me.PageFooter1.Visible = True
    Me.PageFooter2.Visible = False
Else
    Me.PageFooter1.Visible = False
    Me.PageFooter2.Visible = True
End If

Thanks for any help in advance!

A: Well, the first two conditions are doing the same thing:
If Me.Page <= 2 Then
    Me.PageFooter1.Visible = True
    Me.PageFooter2.Visible = False
ElseIf Me.Page >= 9 Then
    Me.PageFooter1.Visible = True
    Me.PageFooter2.Visible = False

Whether the page is smaller than or equal to 2, or page is greater than or equal to 9, then:
Me.PageFooter1.Visible = True
Me.PageFooter2.Visible = False

Otherwise (so, if page is greater than 2 but less than 9):
Me.PageFooter1.Visible = False
Me.PageFooter2.Visible = True

That would be reworded as such:
 If Me.Page <= 2 Or Me.Page >= 9 Then
     Me.PageFooter1.Visible = True
     Me.PageFooter2.Visible = False
 Else
     Me.PageFooter1.Visible = False
     Me.PageFooter2.Visible = True
 End If

But then that still looks weird. Looks like you have 2 "footer styles" going on here. How about introducing that concept?
 Dim showFooterStyle1 As Boolean
 showFooterStyle1 = (Me.Page <= 2 Or Me.Page >= 9)

 Me.PageFooter1.Visible = showFooterStyle1
 Me.PageFooter2.Visible = Not showFooterStyle1

Now, whether or not that's what you're trying to accomplish is pretty unclear from the question you're asking. But at least it should be easier to see where the problem is.


text:
Q: Background chromed image We like to get a background on our responsive site that gives the shiny effect of chromed plating.
The real chrome effect is not possible with css. I think I need a picture instead of only css code. But how can I get the right height + width on pc screen + mobile (responsive). And what will me the size (WxH) to include in the css?
How do we do this in css without downgrading the site speed.
We only found images that do not fit our needs.
Thanks in advance.

A: You can see next examples:
Example 1
Example 2
In booth variants you need to use linear-gradient property.

A: You can use gradient property of CSS3 to make a chromed color effect using white, gray and black shades.
.yourclass{
    background: linear-gradient(angle, color1, color2);
}

Here's the link below to know more about this property.
http://www.w3schools.com/css/css3_gradients.asp


text:
Q: How to get last and next date from a date number in php? I want to find entries in a month range based on date of a month
like if a user registered on 20th of a month, the script should get entries in a range from last 20th to next 20th of the month.
I.e if the script is running on any day before 20th of April the range should be March 20 - April 20, and if its running on 20th April or after then the range should be April 20 - May 20.
I looked up relative formats but it only lists functions for day names and weeks etc.
Is there any way the relative date format works like last n to next n. where n= 1 to 31.
Can anyone help? Thanks
Based on comment from Cully, here is an implementation (it still feels too messy, maybe there is an easier way to do it). It may explain the question a bit more.
function getFromDate($myDate, $nDate)
{
    // sub 1 day till date is $nDate
    while(true)
    {
        if($myDate->format('d')==$nDate)
            break;
        $myDate->sub(new DateInterval('P1D'));
    }
    return $myDate;
}

function getToDate($myDate, $nDate)
{
    // add 1 day till date is $nDate
    while(true)
    {
        $myDate->add(new DateInterval('P1D'));
        if($myDate->format('d')==$nDate)
            break;
    }
    return $myDate;
}

$timestamp = 1602107066; // An example user registration date, 7 October 2021
$nDate = gmdate("d", $timestamp);

$fromDate = getFromDate(new DateTime('now'), $nDate);
$toDate = getToDate(new DateTime('now'), $nDate);

echo $fromDate->format('d M y')."\r\n"; // 7 May 2021 (run on May 22 2021)
echo $toDate->format('d M y'); // 7 June 2021 (run on May 22 2021)

A: Do you mean something like this? It might not be exactly what you want, but can you use it to create what you want?
<?php

$numberOfDaysIWant = 20;
// March 20th, 2021, but you can use any date you want
$startDate = new DateTimeImmutable('2021-03-20');
$myPastDates = [];
$myFutureDates = [];

$currentDate = $startDate;
for($i = 0; $i < $numberOfDaysIWant; $i++) {
  $currentDate = $currentDate->sub('P1D');
  $myPastDates []= $currentDate;
}

$currentDate = $startDate;
for($i = 0; $i < $numberOfDaysIWant; $i++) {
  $currentDate = $currentDate->add('P1D');
  $myFutureDates []= $currentDate;
}

var_dump($myPastDates, $myFutureDates);

It's unclear from your question, but it sounds like maybe you want to get the $numberOfDaysIWant value based on the date of the selected month. If so, you could use this to get it:
<?php

$startDate = new DateTimeImmutable('2021-03-20');
$numberOfDaysIWant = (int) $startDate->format('j'); // "j" gives you the day of the month, without leading zeroes


text:
Q: Properties file could not be found by getResourceAsStream(). Check the CLASSPATH or class loader This is from an open source project where there is nearly no support. Compilation of the project went well. But I cannot test or install because of a particular property file cannot be found. I have search up and down the internet and not able to find any solutions. The organization of the director is a little bit unconventional.
some directories.
core/src/main/java/org/mskcc/cbio/portal/util/Config.java.
String props = "portal.properties";
InputStream in = this.getClass().getClassLoader().getResourceAsStream(props);
...

more directoires.
src/main/resources/portal.properties.
This last src directory has only one subdirectory main,
and the main directory has only one resources subdirectory.
The file that could not be found is located here.
I am using java 1.7.  Maven 3.0.5
The command I used is mvn install
I must be missing one simple configuration somewhere.
There got to be some who can resolve this easily.

A: src/main/resources is, by default, the path of Aplication/Library resources in Maven. But, you can optionally force this in the pom.xml.
1) Add in the pom.xml
<resource>
   <directory>src/main/resources</directory>
   <filtering>true</filtering>
</resource>

2) run maven -> mvn clean install
3) Search for portal.properties at the build generated at "target" folder. Assert that portal.properties is in the root of the artifact classpath  (root of .jar, .ear or /classes in .war).


text:
Q: PhantomJS Showing exit code 0 even after network error I am using PhantomJS for printing pdf from my web page and then storing the resultant pdf to S3 if the pdf is generated successfully.
My problem is PhantomJS is returning exit code 0 i.e. success even after a network error occur and the resultant pdf is not which I want.
So I want to know is there any way to abort PhantomJS when error occur with an exit code .
Currently the error in which this happening is NETWORK Error : 101
But even though PhantomJS do not abort and return with exit code 0

A: The only time that PhantomJS exits on its own is when it encounters a Syntax Error of your script (PhantomJS 2.0.0 has a bug and simply freezes and doesn't print anything at this point).
For everything else you need to call phantom.exit() to exit. phantom.exit() takes an optional argument which is the exit code. So when you encounter an error for example by checking the success argument of the page.open() callback or when onResourceError or onResourceTimeout events are triggered, you can exit PhantomJS with your own intended exit code such as
phantom.exit(1);


text:
Q: Jquery show on hover hide on click I have an element I am trying to have show on hover and stay shown. Then hides when anywhere is clicked or the button previously hovered is clicked. I have code that works, BUT it switches the hover effect if the button is clicked.
Button hover = div shown
div shown and anywhere outside clicked = div hidden
div shown and button clicked = div hides on hover and shows after mouse moves off button
I'd like to have the div hide when the button is clicked and stay hidden after the mouse is no longer hovering. NOT reappear after the mouse moves off the button.

    Button

Subscribe your email

A: try this:-
 $(document).ready(function() {
   $('.email-div').hide();
     $('.showemail').hover(function() {
              if(!$(this).hasClass('hoverd'))
              {
                  $(this).addClass('hoverd')
                    $('.email-div').show();
              }
     },function(){
     $(this).removeClass('hoverd')
     });
 });
 $(document).on("click", function () {
   $(".email-div").hide();
  });

Demo

A: Try using mouseenter instead of hover
JSFiddle : https://jsfiddle.net/toLt4tfg/1/
    $(document).ready(function() {
        $('.email-div').hide();
            $('.showemail').mouseenter(function() {

                    $('.email-div').show();
            });
    });
    $(document).on("click", function () {
            $(".email-div").hide();
    });


text:
Q: Random range of float in Objective C? for an in I'm doing this:
int randomRange(int min, int max) {
    int range = max - min;
    if (range == 0) return min;

    return (arc4random() % range) + min;
 }

but how can I do this with a float?

A: +(float) randFloatBetween:(float)low and:(float)high
{
    float diff = high - low;
    return (((float) rand() / RAND_MAX) * diff) + low;
}


text:
Q: How to remove a file in S3 Bucket with knox? I need to remove a file in S3 Bucket with Knox library.
I found some examples that explain how to upload a file but I was not able to find any examples that explain how to remove a file.
Can you provide me with an example code?
Thanks.

A: Here is a sample code. More reference you can refer KNOX
client.del('/test/Readme.md').on('response', function(res){
  console.log(res.statusCode);
  console.log(res.headers);
}).end();


text:
Q: How can I get an image button's dimensions to make sense in android? First of all, can I just say, I find laying out android UI's to be a frustrating experience? I used to think the XML layouts were simple and clean and awesome but every time I try to make anything with it I spend hours trying to do the simplest things!
In this particular instance I'm trying to make a simple horizontal bar that contains an image button of fixed size on the right and to the left of it I want an ImageView that takes up the rest of the available width.  I see similar constructs all the time in the UI: the search box that appears at the top of the screen when searching, the text area and send button for composing text/googletalk messages, etc.
I've tried both a horizontal linear layout and a relative layout, and I can't get the button to look right in either one. My latest attempt has the following layout code:

It looks like this:

Using the hiearchyviewer indicates that both the imageview and the button have the same height (45px).  And it shows the view dimensions and positions to be exactly what I'm looking for.  Same height (differing widths of course since the ImageView is much wider). And they butt right up next to each other, centered in the Relative Layout.  However the button as drawn on screen is obviously not taking up the full ImageButton view.  I'm thinking it's something weird about the android system 9patch drawable used for the ImageButton background. But what do I know? I can't get it to look right no matter what I try.

A: How did you set up your RelativeLayout? Try to set it up like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent" android:layout_height="wrap_content">
    <ImageButton android:layout_width="wrap_content" android:src="@drawable/icon" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:id="@+id/imgButton"></ImageButton>
    <ImageView android:id="@+id/imageView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:src="@drawable/red_button" android:scaleType="fitXY" android:layout_alignBottom="@+id/imgButton" android:layout_alignTop="@+id/imgButton" android:layout_toLeftOf="@+id/imgButton"></ImageView>
</RelativeLayout>

Hope this helps.

A: If dimensions are exactly how you are looking for , then in ImageButton and ImageView , use android:scaleType="fitXY" and check.
For simple case , I might use linearlayout with horizontal orientation with two buttons in it with proper weights.


text:
Q: Spring MVC & Velocity : Template structure I'd like to achieve this kind of template functionality:

*

*Have a template defining header, footer, and common parts of complete (x)html webpage

*When returning String from @Controller it will define the view included to specific part of template

Like this:
@Controller
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
    return "home_view";
}

views/home_view.vm

Content title

Content text

views/template.vm

        <title></title>

        #include({context variable which contains "home_view"} + ".vm");

If anybody knows CakePHP, this is similar to its template system
How can I do this?

A: Final solution based on @Nathan Bubna suggestion.
Project is based on Spring MVC template, with Maven controlled resources.
Spring version 3.1.1.RELEASE
/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>mainServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mainServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>

/WEB-INF/spring/servlet/servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <annotation-driven />

    <resources mapping="/resources/**" location="/resources/" />
    <resources location="/resources/favicon.ico" mapping="/favicon.ico"/>
    <resources location="/resources/favicon.ico" mapping="/favicon.png"/>

    <beans:bean id="velocityConfig"
        class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
        <beans:property name="resourceLoaderPath" value="/WEB-INF/views/" />
    </beans:bean>

    <beans:bean id="viewResolver"
        class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
        <beans:property name="cache" value="true" />
        <beans:property name="prefix" value="" />
        <beans:property name="layoutUrl" value="layout.vm"></beans:property>
        <beans:property name="suffix" value=".vm" />
    </beans:bean>

    <context:component-scan base-package="com.mypackage.subpackage" />

</beans:beans>

important pom.xml lines
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity</artifactId>
    <version>1.7</version>
</dependency>
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-tools</artifactId>
    <version>2.0</version>
</dependency>

A: I think Spring has support for a VelocityLayoutView. Or, i thought they did.


text:
Q: Using MongoDB in Atlas, cant connect to replicas Been following this tutorial to set up a MERN stack database(see part iii).
I have created a New Project on Atlas using AWS as my cloud provider and Sandbox as my plan type. I have added myself as an admin user and entered in the correct IP address in the corresponding fields in Atlas. Ive tried to connect to the database using this URI connection string mongodb+srv://<username>:<password>@cluster0-echb9.mongodb.net/test?retryWrites=true&w=majority in my Mac terminal.
***Left username and password out for obvious reasons but in terminal I typed out all the information.
When I try to connect I get an error that says: Error picture
Also, both my mongoDb shell and server are the same version so I know thats not the issue. Any help? If you need more info, please let me know. New here.


text:
Q: Show variable image in Go templates I'm using a template in a Go web application which should show an image depending on which country the visitor is from.
For the images I use the FileServer
http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("images"))))

In the template the variable country is passed so the application knows which flag to show.

However, for some reason the string I pass adds %0a which causes the src of the img to be wrong.

The expected output should be

The following code is used to grab the country string
resp3, err := http.Get("https://ipinfo.io/country")
if err != nil {
    fmt.Println(err)
}
bytes3, _ := ioutil.ReadAll(resp3.Body)
country := string(bytes3)

Could anyone help me resolve this issue?

A:
the string I pass adds %0a which causes the src of the img to be
  wrong.

The expected output should be

Trim the newline (0x0A or "\n"). For example,
package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    resp3, err := http.Get("https://ipinfo.io/country")
    if err != nil {
        fmt.Println(err)
    }
    bytes3, err := ioutil.ReadAll(resp3.Body)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Printf("%q\n", bytes3)
    country := string(bytes.TrimRight(bytes3, "\n"))
    fmt.Printf("%q\n", country)
}

Output:
"US\n"
"US"


text:
Q: VlcControl.TakeSnapshot produces a file but is empty My VlcControl in winforms does not take snapshots when invoked. The file is created, but when I open the file, it cannot be opened and the bytes is 0. I don't get any errors. Please see my code below:
private void CaptureImage(string fileName)
        {
            try
            {
                var outputFile = $@"{imageDirectory}/{fileName}.jpg";
                vlcControl1.TakeSnapshot(new FileInfo(outputFile), 400, 400);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

        }

This are the files created:

I can stream without any problems.

A: I would try to take a snapshot on another thread or try to take a snapshot without specifying the size of the snapshot.
ThreadPool.QueueUserWorkItem(_ => vlcControl1.TakeSnapshot(new FileInfo(outputFile), 400, 400));


text:
Q: How do I access a Rest endpoint on a scratch org? I've set up a connected app and a rest endpoint on a scratch org but can't access it through either the workbench, Postman or client code. I get the following error in each case:

404 Not Found

response body:
{
        "errorCode": "NOT_FOUND",
        "message": "Could not find a match for URL"
}

For the code and postman approaches, I'm getting back a sessionId. It's the subsequent call to ../services/apexrest/MyEndpoint that's failing.
The URL I'm using is the autogenerated scratch org URL
https://xxxxxxx-xxx-XXXX-dev-ed.cs42.my.salesforce.com/services/apexrest/MyEndpoint
I tried using https://test.salesforce.com/services/apexrest/MyEndpoint but get a different error:

400 Bad request

Is there something different about Rest endpoints on scratch orgs I need to be aware of?


text:
Q: how to configure cluster address in weblogic I am configuring cluster which group of managed server in console. I have 2 managed server:
Managed_server_name   listen_address  listen_port  ip_address

m1                       slc001.us.xxx.com    7001     10.1.1.1
m2                       slc002.us.xxx.com    7002     10.1.1.2

So I created a cluster and added the two managed server to this cluster, the cluster message mode is unicast, now how do I configure cluster address? I have three options, which is correct one?

*

*slc001.us.xxx.com:7001,slc002.us.xxx.com:7002

*10.1.1.1:7001,10.1.1.2:7002

*10.1.1.1,10.1.1.2

A: Both options 1 and 2 will work. Ideally I would use hostnames in case the IP ever changes. As an example of one of our clusters we use:
portal1:11602, portal2:11602

You must have the ssl port in there if you're using ssl, otherwise use the regular unsecure port.


text:
Q: How to get analytics report to my web through api in laravel with google analytics 4 property I created a CMS website and I create google analytics account for get the hits and other data from my website, I am not used the universal analytics , I used the google analytics 4 property , but how to get the analytics data to my website through API in Laravel?

A: Have a look at the documentation for the google analytics data api.  There is a php client library for it you can use.
require 'vendor/autoload.php';

use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;

$client = new BetaAnalyticsDataClient();

$response = $client->runReport([
    'property' => 'properties/[YOUR_PROPERTY_ID]'
]);

foreach ($response->getRows() as $row) {
    foreach ($row->getDimensionValues() as $dimensionValue) {
        print 'Dimension Value: ' . $dimensionValue->getValue() . PHP_EOL;
    }
}

A few things to note.

*

*use a service account this will give you access to your personal account.

*Remember this api is in beta and it can change.

*Data is returned as json you will need to format it yourself.


text:
Q: Import Root Certificate of Google/iTunes into WebSphere Application Server - Liberty Profile 8.5.5.1 I am trying to Configuring WebSphere Application Server - Liberty Profile 8.5.5.1 to support applications in public app stores and   following this link : [http://www-01.ibm.com/support/knowledgecenter/SSZH4A_6.2.0/com.ibm.worklight.installconfig.doc/appcenter/t_ac_applinks_google.html][1]
Its saying that I have to import Root Certificate of Google play into the WebSphere trust store. This is the part I got stuck since I don't know how to open liberty profile console.

A: Liberty profile does not have console yet. Whole configuration is held in server.xml file.
In that file you will find reference to the keystore, like this:
<feature>ssl-1.0</feature>
<keyStore id="defaultKeyStore" password="password" />

If default settings are used you should have key.jks file in the serverName\resources\security\key.jks
Then you need to add cert there using some tool e.g. keytool, or ikeyman (if you have full WAS at hand). Example for keytool:
keytool -importcert -alias certAlias -file certificate.crt -keystore key.jks


text:
Q: How to show tests from another repository in GitLab CI So I have my project with it's unit tests and they show nicely as green or red circles when I do a merge request after I've configured the CI system in GitLab.
But now I also have some integration tests, which reside in a separate repository (why you ask? because I have multiple micro-services that need to be tested together, and each has it's own repository).
When I do a merge request on this integration tests' repository, they show nicely, but what I need it for those tests to show on the merge requests of the other repositories.
I did manage to trigger them from the micro-services' repositories with a URL/command that GitLab CI gives me, something like this: curl -X POST -F token=... -F ref=master https://gitlab.com/api/v4/projects/.../trigger/pipeline
But in the micro-services' repositories, it always shows as a green circle, meaning it successfully started the integration tests, but  I don't know how to display the tests results (or at least if they broke or not).
Could anyone point me to the right documentation, if there is one, or just explain to me how to do it and if it's even possible?
The best solution I could think of was to create my integration tests as a library, then I'd import and use that library on all the other projects, but I'd definitely rather avoid this, since it would force me to write the integration tests in the same programming language as the projects (assuming they are the same) or make some hack to run it on the other languages.
Thank you.

A: What you could do is expand on what you're currently doing using a Python/Bash script;
From the main project, using said script:

*

*Trigger the micro-service pipeline (and capture the pipeline ID)

*Poll the status of the pipeline, using the captured ID (which can be running, pending, failed, canceled or skipped)

*Raise an exception / error if it has failed...

This should do what you require, but would mean that you would be using a runner just to be constantly sending a curl request to the GitLab instance (and that this runner can't pick up another job, depending on how you have setup the runner's limit and concurrent settings).

Example run_pipeline.py:
import gitlab
import time, timeit
import sys

from datetime import timedelta

gl = gitlab.Gitlab("https://your_gitlab_instance.com/",
                    private_token="you_private_token")

project = gl.projects.get('your_project')
create_pipeline = project.pipelines.create({'ref': 'master'})

# Set default
status = "pending"
start_time = timeit.default_timer()

while (status == "running" or status == "pending"):
    pipeline = project.pipelines.get(create_pipeline.id)

    status = pipeline.status

    elapsed_time = timeit.default_timer() - start_time
    formated_time = str(timedelta(seconds=elapsed_time))
    sys.stderr.write("Still running pipeline... ({})\n".format(formated_time))

    if status == "success":
        sys.stderr.write("\nPipeline success\n")
        break
    elif status == "failed":
        raise Exception
    elif status == "canceled":
        raise Exception

    time.sleep(10)

And then call this python script as a stage in your gitlab-ci.yml.


text:
Q: HTML/CSS Two Columns/One Row Second Row Wrapping If Browser Width Is Too Small I am creating a web page that shows a series of rows. Each row has two columns. The first column consists of an image and the second column has two rows (it might have more later but for now I only have two).
Here is a quick sketch of what I am after:

Here is my HTML markup:

icon

Name: Some Name

Description: Some description blah blah blah.

As you can see the root div (extensions) contains all the rows. To create the first column (icon) I put a div directly below the root div. Next, I create another div which is the parent for the rows (name and desc).
Here is my CSS:
.extensions {
    font-family: sans-serif;
    font-size: 95%;
}
.extensions .row  {
    margin: 5px;
    border: 1px solid red;
}
.extensions .row .icon {
    display: inline-block;
    border: 1px solid green;
}
.extensions .row .details {
    display: inline-block;
}
 .extensions .row .details .name {
    border: 1px solid orange;
}
.extensions .row .details .desc {
    border: 1px solid purple;
}

(Note the borders are for debugging only.)
Everything looks fine when my browser is wide enough as shown below:

However, if I make the browser width smaller eventually the second column gets wrapped below the image column:

I have tried various ways to prevent this from happening to no avail.
Can anyone tell me how to stop the second column from wrapping? Do I need to create another div to put both the image column and the details column all inside one div?
Thank you.

A: FIDDLE0
FIDDLE1
                Specify width in percentage. It will solve your problem.
.extensions
{
 font-family: sans-serif;
 font-size: 95%;
 width: 100%;
}
.extensions .row
{
 margin: 5px;
 border: 1px solid red;
 width: 100%;
}
.extensions .row .icon
{
 display: inline-block;
 border: 1px solid green;
 width: 10%;
}
.extensions .row .details
{
 display: inline-block;
 width: 50%;
}
.extensions .row .details .name
{
  border: 1px solid orange;
  width: 70%;
}
.extensions .row .details .desc {
 border: 1px solid purple;
 width:70%
 }


text:
Q: Gridview with multiple tables? Using C# and ASP.NET, I need my gridview to draw columns from multiple tables. How do I do this? I currently have
`SelectCommand="SELECT [SubId], [CustName], [CustCity] FROM [Customer]">
    </asp:SqlDataSource>`

as my select statement, but I need to select from two more tables. What is the syntax?
apologies for being unclear before.

A: If you don't need to update the SqlDataSource, you can simply put JOINS into your query.
For example:-
Select CustFld1, CustFld2, OrdFld1, OrdFld2 from Cust inner join Ord on CustPKeyFld=OrdCustFKeyField
If you do need to update the SqlDataSource, you need to use sub-queries to return the data that would otherwise be returned in the join
For example:-
Select CustFld1, CustFld2, (Select OrdFld1 from Ord where OrdCustFkeyFld=CustPKeyFld) as OrdFld1, (Select OrdFld2 from Ord where OrdCustFKeyFld=CustPKeyFld) as OrdFld2 from Cust

A: Your SelectCommand should be the same statement that you would execute if you were running the query on the database directly. So, in your case, you would want something like:
SELECT [SubId], [CustName], [BroName], [Entity]
FROM [Customer]
JOIN [Broker] ON <join condition>
JOIN [Submission] ON <join condition>


text:
Q: What is meant by a signal being asynchronous? Both definitions from Wikipedia:

In computer science, asynchronous I/O, or non-blocking I/O is a form
  of input/output processing that permits other processing to continue
  before the transmission has finished.
Signals are a limited form of inter-process communication used in
  Unix, Unix-like, and other POSIX-compliant operating systems. A signal
  is an asynchronous notification sent to a process or to a specific
  thread within the same process in order to notify it of an event that
  occurred.

I can not really understand what is meant by:

A signal is an asynchronous notification sent to a process

Does this mean, just like I/O, a signal is sent to a process and the process which sends the signal does not wait for the return value of the the process receiving the signal, and keeps going?
If a signal were to be synchronous, then would the sending process wait for the return value?

A: It seems to me that the statement you highlight from the Wikipedia article is too general to be helpful in figuring out what is happening "under the hood."  In regard to implementation of callbacks, for example, take a look at this part of the Open Group specification:

pointer to a function
Catch signal.
On delivery of the signal, the receiving process is to execute the
  signal-catching function at the specified address. After returning
  from the signal-catching function, the receiving process shall resume
  execution at the point at which it was interrupted.

A: It looks as if "asynchronous" could be left out in

A signal is an asynchronous notification sent to a process or to a specific thread within the same process in order to notify it of an event that occurred.

Whether the sending process continues or waits is not known to the signal recipient. Neither is it of importance to the receiver (except maybe in protocols where it is "agreed" that the sender waits or continues, possibly dictating constraints on the response time by the receiver).
Another view could be:

*

*An asynchronous event could mean that more of the same or different events can be received from the sender before the first event has been processed by the receiver.

*A synchronous event could mean that no events of the same type will be recieved from the sender until the previous synchronous event of the type has been processed by the receiver. (It may be though that other types of synchronous or asynchronous events can be received from the sender.)
It seems that the statement of [a]synchronousness of an event is only of relevance to what the receiver can expect from the sender, but I suspect that the Wikipedia definiton refers to the sender blocking/continuing its processing, which is not of importance to the receiver.
How would this translate to multiple senders sending the same type of synchronous event to a single receiver?

A: A signal is asynchronous because a thread may receive a signal at any point in execution. This contrasts with the synchronicity of all other things in the code: one statement follow another, after a function call you expect a value, this instruction follows the one before, etc... you get the idea. A signal handler may start executing at any moment (normally interrupting the current flow execution until it finishes).
The problem is that the paragraph does not refer to the same asynchronous term: it refer instead to non-blocking calls that may execute "in the background", allowing the current thread to do other tasks while it waits for the response to be received (notice how this reception is asynchronous in the same way signals are).


text:
Q: Finding Max in SqLite using SQLitePCL-WP8.1 I'm very new to integrating SQlite to Universal Apps. I have got the db up and running. But now I'm trying to find the Max of a Column. Its not returning the expected value. The Db is populated with data
var db = App.conn;
using (var statement = db.Prepare("SELECT MAX(Priority) as Priority FROM FOLDER; "))
{
    statement.Step();
    var result = (int)statement["Priority"];
}

The exception says wrong casting but Priority is of Integer type.
EDIT

An exception of type 'System.InvalidCastException' occurred in JusWrite Trial.WindowsPhone.exe but was not handled in user code
  Additional information: Specified cast is not valid.

A: int is an alias for Int32 not Int64 hence int != Int64. You can only cast a boxed struct to same type or its Nullable variant. In this case it happens to be long/Int64 or Nullable aka long?.
To fix this, you either need a cast to long before casting to int or simply use Convert.ToInt32
var result = (int)(long)statement["Priority"];

or
var result = Convert.ToInt32(statement["Priority"]);

Further reading Representation and Identity


text:
Q: Status Code: 500 Malformed UTF-8 characters, possibly incorrectly encoded Laravel I get that error everytime I try to create a post request in Postman with a controller, I think that it is this Model that is causing the problem. What can I do to fix the error? I think that the json_decode is causing the problem. please help me. thank you
<?php

namespace App;

use Illuminate\Database\Eloquent\SoftDeletes;

class Group extends BaseModel
{
    use SoftDeletes;

    /**
     * The connection name for the model.
     *
     * @var string
     */
    protected $connection = 'mysql-core';

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'uuid',
        'organization_id',
        'name',
        'description',
        'allowed_members',
    ];

    public function setAllowedMembersAttribute($value)
    {
        if (empty($value)) {
            $value = [];
        }

        $this->attributes['allowed_members'] = json_encode($value, JSON_HEX_QUOT | JSON_HEX_TAG);
    }

    public function getAllowedMembersAttribute($value)
    {
        if ($value === null) {
            return [];
        }

        return json_decode($value);
    }
}


text:
Q: jQuery - for .each call function which contains method .on I need to use for ".each" element jquery method ".on" , but something I do wrongly..can anybody help?
get the ID's from SVG and put them into an Array:
    var svgZi10 = document.getElementById("svg"); //get the main SVG container
    var svgElementZi10 = svgZi10.contentDocument; //get the inner DOM from SVG

var lock    = []; //new Array
lock[0] = svgElementZi10.getElementById("lock-door-open-right-contour"); //get the inner element by id
lock[1] =  svgElementZi10.getElementById("lock-door-open-left-contour"); //get the inner element by id
lock[2] = svgElementZi10.getElementById("lock-door-closed-right-contour"); //get the inner element by id
lock[3] = svgElementZi10.getElementById("lock-door-closed-left-contour"); //get the inner element by id

manipulation with the object's from the Array (doesn't works):
 $.each(lock, function(i,element) {
        $(element).on("mousedown",function(){tab12[0].click() })
    });

when is each object separetly (works):
 var lock1 = svgElementZi10.getElementById("lock-door-open-right-contour"); //get the inner element by id
 var lock2 = svgElementZi10.getElementById("lock-door-open-left-contour"); //get the inner element by id
lock1.addEventListener("mousedown",function(){tab7[0].click()});
lock2.addEventListener("mousedown",function(){tab7[0].click()});

A: You should be calling .on() on the current element, not the array:
$.each(lock, function(i,element) {
    $(element).on("mousedown",function(){tab12[0].click() })
});

If lock is an array of DOM elements, you don't need .each. When you give jQuery() an array of elements, it will create a jQuery object that wraps them. So you can just write:
$(lock).on("mousedown", function() {
    tab12[0].click();
});

When you use a binding function on a jQuery collection, it binds all the elements in the collection.


text:
Q: C# MS ClearScript Add dynamic host objects I have a collection which I am exposing to a clearscript engine, at the moment I have to specify that the Value property is a static type int so that scripting basic arithmetic as plus or minus will work:
Here's my collection and the class it makes use of that I expose to the script engine:
public class LogicBlockIOCollection : ConcurrentDictionary<string, LogicBlockIO> { }

public class LogicBlockIO
{
    public string Name;
    public dynamic Value;
}

I am adding host objects to my clearscript egine using the following method:
public void AddBlock(LogicBlockIOCollection Entries)
{
    foreach (var Entry in Entries)
    {
        this[LastBlockID].Engine.Script[Entry.Key] = Entry.Value.Value;
    }
}

When I program the LogicBlockIO.Value property as dynamic and run the following script I receive these results:
C = A + B;
C = 1 + 2;
C = 12;  //Not 3 as expected

When I program the LogicBlockIO.Value property as integer, and I try to run the same simple script i get the results I expect:
   C = 3;

Does someone have a suggestion how it is possible to make use of a single property that may be of different types to achieve what I require?


text:
Q: Unity WebGL Build Particle System Error On Safari So I have a small web game that I made recently, and decided to try it out in Safari. Every other browser works (Chrome, Firefox, Edge), but a few seconds (seemingly random) after an on screen particle system starts playing, the whole game crashes. Obviously disabling particles isn't an option. Any ideas?
An error occurred running the Unity content on this page. See your browser JavaScript console for more info. The error was:
RuntimeError: Out of bounds memory access (evaluating 'asm[name].apply(null, arguments)')
<?>.wasm-function[OptimizedPolynomialCurve::Evaluate(math::_float4 const&) const]@[wasm code]
<?>.wasm-function[Evaluate(MinMaxCurve const&, math::_float4 const&, math::_float4 const&)]@[wasm code]
<?>.wasm-function[ParticleSystem::UpdateModulesPreSimulationIncremental(ParticleSystemUpdateData const&, ParticleSystemParticles&, unsigned long, unsigned long, math::_float4 const&, bool)]@[wasm code]
<?>.wasm-function[ParticleSystem::Update1b(ParticleSystemUpdateData&, int)]@[wasm code]
<?>.wasm-function[ParticleSystem::UpdateFunction(ParticleSystemUpdateData*)]@[wasm code]
<?>.wasm-function[ParticleSystem::BeginUpdateAll()]@[wasm code]
<?>.wasm-function[ParticleSystem::InitializeClass()::PreLateUpdateParticleSystemBeginUpdateAllRegistrator::Forward()]@[wasm code]
<?>.wasm-function[ExecutePlayerLoop(NativePlayerLoopSystem*)]@[wasm code]
<?>.wasm-function[ExecutePlayerLoop(NativePlayerLoopSystem*)]@[wasm code]
<?>.wasm-function[MainLoop()]@[wasm code]
<?>.wasm-function[dynCall_v]@[wasm code]
wasm-stub@[wasm code]
81288@[native code]
@http://localhost:55812/Build/dev.framework.js:1043:25
browserIterationFunc@http://localhost:55812/Build/dev.framework.js:8963:17
callUserCallback@http://localhost:55812/Build/dev.framework.js:7153:7
runIter@http://localhost:55812/Build/dev.framework.js:7214:20
Browser_mainLoop_runner@http://localhost:55812/Build/dev.framework.js:7128:27


text:
Q: Put values into memory? I am new at xcode and I just built my first app. Basically its a bunch of labels that gets values from a database. The other day my internet wasn't working and didn't realize it and I went to run my app and had empty labels. What I am looking to do is if the variable data is nil then get the values from previously. I think I saw something in tutorials about putting values into memory. Is what I am asking possible? Here is a bit of my code:
NSURL *url = [NSURL URLWithString:@"http://myserver.com/GetData.php"];
        NSData *data = [NSData dataWithContentsOfURL:url options:0 error:nil];

A: Yes, what you're trying to do is called "caching". Here's a tutorial on how it can be done for images.
And if I were to modify your code, I'd write out the data from your server into a file somewhere in "~/Library/Caches" and if the server ends up not responding on a subsequent launch, I'd load the previous data from that cache file.

A: In your .h file
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    NSData * data;
}
@end

And in your .m file
- (void)viewDidLoad
{
    [super viewDidLoad];

   NSURL *url = [NSURL URLWithString:@"http://myserver.com/GetData.php"];
   data = [NSData dataWithContentsOfURL:url options:0 error:nil];
  [self saveToUserDefaults];
    }

You can Store it in either DB or in NSUserDefaults for saving data in userDefault Use this code
- (void)saveToUserDefaults
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:data forKey:@"data"];
    [defaults synchronize];
    NSLog(@"Dilip Data saved");
}

And when You want that data back use this code.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *data = [defaults dataForKey:@"data"];
NSLog(@"Dilip Data : %@",data);

A: Yes, this is possible. You need to store this data to your local. XCode is just a development tool so it will not store the data for you. You have to store your data to some file in document directory. May be using SQLite database or a .plist file or NSUserDefaults.
For SQLIte there are few tutorials:
http://www.raywenderlich.com/902/sqlite-101-for-iphone-developers-creating-and-scripting
http://www.tutorialspoint.com/ios/ios_sqlite_database.htm
you can find more by googleing.
For using .plist
http://www.theappcodeblog.com/2011/07/18/iphone-development-tutorial-create-a-plist-programmatically-after-user-action/
For NSUserDefaults
[[NSUserDefaults standardUserDefaults] setObject:yourData forKey:@"data"];
[[NSUserDefaults standardUserDefaults] synchronize];

No matter which way you go make sure you delete old values once you receive the new values. If you don't get new values due to any reason you can either try to recorrect by your own or can fetch values from the local store.
I generally prefer .plist for temporary use. As you don't need to use the data for long time. Also NSUserDefaults is the ios level store and I prefer not to use it on large scale but this is my preference. You can go for either of one.
Hope this helps :)


text:
Q: Is there a matplotlib.pyplot function to draw two columns plot? I'm experimenting with data visualization.
I've got the following dataframe:
one = {'year' : [2010,2011,2012,2010],
      'value' : [10,10,20,30],
      'model' : ['one', 'one', 'one', 'two']}
df = pd.DataFrame(one)
df

I'd like to plot a line showing the increasing value of model one.
I've tried this:
df.set_index('model').loc['one'].plot()

But it doesn't show the appropriate plot which is df.set_index('model').loc['one'] versus df['year']
Any help?

A: IIUC:
try:
df.pivot('model','year','value').plot()

OR
#import seaborn as sns
sns.relplot(kind='line',x='model',y='value',data=df,hue='year')

output:


text:
Q: How do I create a playfab leaderboard and send player stats to it using to their playfab ID? I am not sure how to create a Playfab leaderboard and add scores to a user, based on their Playfab ID retrieved from the details they've entered in my 2 player login system. Both players enter their details (email, password) separately.
My 2 player login system for the game is fully functional and I have worked out how to retrieve their unique Playfab IDs. I have stored both playfab IDs as strings I don't know how to use them to update a specific player's stats.


text:
Q: Weak Equivalence of Pullbacks This is a modification of the question I previously asked here.
Consider the category of pointed topological spaces $C$. Suppose objects $a,b,c,d,e,f,g,h \in C$. Suppose we have two pullback squares where all the morphisms are serre fibrations $$\begin{array}& &a&\to &b\\
&\downarrow & &\downarrow \\
&c &\to &d\end{array}$$
$$\begin{array}& &e&\to &f\\
&\downarrow & &\downarrow \\
&g &\to &h\end{array}$$
and maps $f_{ae}:a \to e,f_{bf}:b \to f, f_{cg}:c \to g,f_{dh}:d \to h$ satisfying the obvious commutativity conditions. Then I want to show that if  $f_{bf}, f_{cg},f_{dh}$ are weak homotopy equivalence then so is $f_{ae}$.


text:
Q: Is there a way to expand a summation of product of two functions? I have been experimenting with summations were you multiply to functions, e.g.
$\sum_{i=0}^n f(n)g(n)$ where $f(x)=x^2$ and $g(x)=-\frac{x^2}{\log{x}}$. While trying out different functions for $f(x)$ and $g(x)$, I stumbled upon this. $$\sum_{i=1}^n ((-1)^i\left|i+x-\frac{n}{2}\right|+\frac{1}{2})$$
I simplified it until here $$(\sum_{i=1}^n(-1)^i\left|i+x-\frac{n}{2}\right|\bigr)+\frac{n}{2}$$
I think I can simplify it more by making it so that in $\sum_{i=1}^nf(x)g(x), f(x)=(-1)^i$ and $g(x)=\left|i+x-\frac{n}{2}\right|$ and then expanding the summation, but I don't know how.

Is there a formula that expands out or simplifies $\sum_{i=1}^n f(x)g(x)$?


text:
Q: Python exclusive loop I want to loop through a list and separate the current element from others.
Like this :
for e in the_list:
    function_call(e, <the_list but e>)

Is there an elegant way to do that ?

A: You could use enumerate and slice the list:
for index, elem in enumerate(the_list):
    function_call(elem, the_list[:index] + the_list[index + 1:])

A: A nice solution that reads (reasonably) well and doesn't need messing around with indices.
>>> from itertools import combinations
>>> data = [1, 2, 3, 4]
>>> for item, rest in zip(data,
                          reversed(list(combinations(data, len(data)-1)))):
...     print(item, rest)
...
1 (2, 3, 4)
2 (1, 3, 4)
3 (1, 2, 4)
4 (1, 2, 3)


text:
Q: Adding a timeout to a render function in ReactJS I have been exploring animations with the ReactCSSTransitionGroup props transitionAppear and transitionEnter.
These animate the entry of the notes onscreen but the initial load of the list renders all the items at once.
Is there a way to add a delay to the rendering of each item on initial load so that they do not appear at once?
You can see the full code here
var NotesList = React.createClass({
  render: function(){
    var notes = this.props.notes.map(function(note, index){
      return (

                {note}

);
    })
    return (

        <ReactCSSTransitionGroup transitionName="fade" transitionAppear={true} transitionAppearTimeout={500} transitionEnterTimeout={500} transitionLeaveTimeout={300}>
            {notes}
         </ReactCSSTransitionGroup>

    )
  }
});

A: Since you're looping over the items to render them, you can use the index to assign a growing transition-delay to each item (demo):
var NotesList = React.createClass({
  firstTime: true, // is this the 1st render
  render: function(){
    var delay = this.firstTime ? 500 : 0 // delay 500 for first time, 0 for all others
    var notes = this.props.notes.map(function(note, index){
      // add the transition-delay using the index to increment it
      return (<li className="list-group-item" key={index} style={{ transitionDelay: `${index * delay}ms` }}>
                {note}

);
    })

    this.firstTime = false // turn of first time

    return (

        <ReactCSSTransitionGroup transitionName="fade" transitionAppear={true} transitionAppearTimeout={500} transitionEnterTimeout={500} transitionLeaveTimeout={300}>
            {notes}
         </ReactCSSTransitionGroup>

    )
  }
});


text:
Q: Javascript for changing form border color doesnt work? Trying to animate the border color of a form but doesn't seem to be running.I want the border color to change automatically without any user interaction once the page loads.
window.onload(function colormagic() {
  //alert("OK1")
  var blueborder = document.getElementById("form1")
  var colorarray = new array()
  colorarray[0] =  "blue"
  colorarray[1] = "green"
  colorarray[2] = "yellow"
  colorarray[3] =  "blue"
  colorarray[4] =  "green"
  colorarray[5] = "yellow"
  //alert("OK2")
  for (i = 0; i < elements.length; i++) {
    blueborder.style.borderColor=colorarray[i];
    //alert("OK3")
  }
})

So i tried adding alert to debug it. And I am only getting the first alert statement.

A: Not sure what you're trying to accomplish with this and it doesn't seem very friendly but maybe this is close to what you're looking for. Of course you can set the timeout interval to your liking.
var form = document.getElementById('form1');

function colormagic() {
    var colorarray = ['blue', 'green', 'yellow'];
    var len = colorarray.length;
    var index = (Math.floor(Math.random() * len) + 1) - 1;

    form.style.borderColor = colorarray[index];

    setTimeout(colormagic, 100);
}

window.onload = colormagic;

Few improvements:

*

*There's no point of querying the DOM every time you loop so the first line is taken out of the loop

*style.borderColor isn't a function

*You needn't create an array with new Array() and assign individual indecies when you can just do var arr = [colors, go, in, like, this];

A: Try like this, this works
Fiddle demo
window.onload = function colormagic() {
            var blueborder = document.getElementById("form1");
            var colorarray = new Array();
            colorarray[0] =  "blue"
            colorarray[1] = "green"
            colorarray[2] = "yellow"
            colorarray[3] =  "blue"
            colorarray[4] =  "green"
            colorarray[5] = "yellow"

            for (i = 0; i < colorarray.length; i++) {
                blueborder.style.borderColor = colorarray[i];
            }
}


text:
Q: Numerical Methods for nth order ODEs I know that any nth order ODE can be made into a system of n first order ODEs. I'm also aware that Euler's method is a primitive way of getting numerical solutions to first order ODEs.
My question is, can we use Euler's method to "solve" nth order ODE, perhaps by conversion into a system of equations? If so, it would be very enlightening to me if someone could outline how to carry out the procedure as I can't see how it would be done.
Thanks

A: I'll let more experienced people answer more thoroughly if necessary, but essentially Euler's method can just be done on the system of first order ODEs by considering it as a single variable first order ODE but in $\mathbb{R}^n$, a vector ODE if you will, and adapted from there.


text:
Q: How does the multiple background images overlay each other ?Do they really overlay each other in order as they are defined? here is the code as one image is png without any background and one is with background so i want to know how the images overlay each other? How will i know which images will going to overlay and which will lay underneath?will the first background will be only visible if i have it as an JPEG image?

<!DOCTYPE html>

Multiple Backgrounds

The following div element has two background images:

Lorem Ipsum Dolor

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

A:
The background images are drawn on stacking context layers on top of
  each other. The first layer specified is drawn as if it is closest to
  the user.

More information


text:
Q: Use a custom cursor for "pointer" Is it possible to, using only CSS, change the cursor of "pointer" to a custom one?
So that if I reference it like in:
button {
  cursor: pointer;
}

html {
  cursor: url("/static/images/paw-cursor.svg"), pointer;
}

pointer will reference my custom cursor. Otherwise it will use the browser's default cursor.

A: Yes it is possible. Use:
cursor: url(/static/images/paw-cursor.svg), auto;

https://css-tricks.com/almanac/properties/c/cursor/
JSFiddle: http://jsfiddle.net/1majnh04/


text:
Q: batch list all .xls files in folder I have following batch files to list all the excel files in my folder:
for /r %%i In (*.xls) DO echo %%i

However, this will also include all excel files in subfolders of my current folder. How can I prevent that? I only want the files in the folder itself, not the subfolder.

A: Pff, silly question, silly answer: just remove the /r


text:
Q: linter pylint is not installed vscode I know there are multiple version of this question on SO, I've tried the solutions posted on those threads and they don't seem to help :(
I have VS Code installed in an Ubuntu VM. I can't seem to get the python linter to work. i.e. I get a message saying
Linter pylint is not installed

I am pretty sure pylint is installed on the VM because when I run which pylint I have a valied output.
Here are the outputs for which python and which pylint respectively
/usr/bin/python
/home/rakshak/.local/bin/pylint

And I have the following in my User settings and workspace settings in VS Code
// Place your settings in this file to overwrite the default settings
{
       "python.linting.pylintEnabled": true,
       "python.linting.pylintPath": "/home/rakshak/.local/bin/pylint",
       "python.pythonPath": "/usr/bin/python"
}

A: So, turns out this was just a permissions issue!
When I got the pylint not installed message, I was presented with a button to "Install pylint" this runs

sudo pip install pylint

This changed the owner of my .local/lib/ to root and made it inaccessible to vscode.
Output of ls -ld ~/.local/lib/ was

drwx------ 3 root root 4096 Sep 24 10:49 /home/userName/.local/lib/

Runing chown with my group and user fixed this issue.

sudo chown -R group:user ~/.local

now the output of ls -ld ~/.local/lib/ reads

drwx------ 3 userGroup userName 4096 Sep 24 10:49
  /home/rakshak/.local/lib/

A: Have you checked with which python version you have installed pylint?
If you have used python 3.6 then the setting has to be like this:
"python.pythonPath": "/usr/bin/python3.6"


text:
Q: How do I runtime-safeguard my assert from string to type literal? I am coding a crude abstract syntax tree based on user input. In my AST type, I want to have type literals for valid operators. How do I convert the user input (strings) to string type literals in a safe manner? Consider the snippet below.
type operator = '==' | '!=';

function isOperator(raw: string): raw is operator {
    return ['==', '!='].indexOf(raw) !== -1
}

const parseOperator = (raw: string) => {
    if (isOperator(raw)) {
        return raw
    } else {
        throw new Error('Invalid input')
    }
}

const indata: string[] = ['!=', '!=', '==','a']
const data: operator[] = indata.map(parseOperator)

In the code, I have duplicated the valid operators (once in the type definition, and later in the parsing logic). That seems to be a bad way to structure code, since updating the operator type means I have to update hard coded arrays in other places.
What is the idiosyncratic typescript way to do this assertion?
ps. I realize this question: Ways to get string literal type of array values without enum overhead is realated. The answerthere seems kind-of-hackish to me though. If that is the best poossible solution - please explain why it is a good coding style.


text:
Q: How do I programmatically change the style of a Material Component Text Button in Android? I have a material text button <Button android:id="@+id/button" style="@style/Widget.MaterialComponents.Button.TextButton"/> that I'd like to change the colour of at runtime. So I set the text colour using button.setTextColor(Color.rgb(10, 10, 10)). Unfortunately, this doesn't change the background drawable, so when I click on the button it's ripple colour is unchanged. I'm guessing I need to change the background with something like attackButton.background = getDrawable(R.drawable.ripple), but I'm not sure how to populate the ripple.xml. Does this method make sense for changing the button text colour and ripple? If so, how should I write the ripple.xml?

A: To change the colors in the MaterialButton you can use:

*

*button.setBackgroundTintList to change the background tint. You should use a selector.

*button.setRippleColor to change the ripple color. Also in this case you should use a selector (see below)

*button.setTextColor to change the color of the text. Also in this case you should use a selector.

It is the default selector used in the ripple color:
<selector xmlns:android="http://schemas.android.com/apk/res/android">

  <item android:alpha="@dimen/mtrl_low_ripple_pressed_alpha" android:color="?attr/colorPrimary" android:state_pressed="true"/>
  <item android:alpha="@dimen/mtrl_low_ripple_focused_alpha" android:color="?attr/colorPrimary" android:state_focused="true" android:state_hovered="true"/>
  <item android:alpha="@dimen/mtrl_low_ripple_focused_alpha" android:color="?attr/colorPrimary" android:state_focused="true"/>
  <item android:alpha="@dimen/mtrl_low_ripple_hovered_alpha" android:color="?attr/colorPrimary" android:state_hovered="true"/>
  <item android:alpha="@dimen/mtrl_low_ripple_default_alpha" android:color="?attr/colorPrimary"/>

</selector>

A: Have you tried a RippleDrawable?  Then just Button.setBackground() to different resource or even a selector xml.  If a ripple with selector won't be enough for you, setting the ripple mask itself can be done
myRipple.xml
<ripple android:color="#ffff0000">
   <item android:id="@android:id/myRippleMask"
         android:drawable="@android:color/white" />
</ripple>

programmatically:
LayerDrawable myRipple = ContextCompat.getDrawable(context, drawable.myRipple.xml);
myRipple.setDrawableByLayerId(R.id.myRippleMask,Color.rgb(10, 10, 10));

with each mask being a different color

A: One line of code programmatic no resource file methods for textcolor, backgroundcolor, and ripplecolor:
 MaterialButton myMaterialButton = new MaterialButton(this);
 myMaterialButton.setTextColor(Color.RED);
 myMaterialButton.setBackgroundColor(Color.GRAY);
 myMaterialButton.setRippleColor(ColorStateList.valueOf(Color.RED));


text:
Q: Looping through multiple variables in Java I am trying to figure out how to loop through and check if the conditions are met for the player to be in any of the variables (TEST1, TEST2, etc), using the isIn methods that I created. However, I am stuck on how I would do this without manually creating a bunch of if else statements.
    public class Boundary {

    int minX, minY, highX, highY;

    public Boundary(int minX, int highX, int minY, int highY) {
        this.minX = minX;
        this.minY = minY;
        this.highX = highX;
        this.highY = highY;
    }

    public int getMinimumX() {
        return minX;
    }

    public int getMinimumY() {
        return minY;
    }

    public int getMaximumX() {
        return highX;
    }

    public int getMaximumY() {
        return highY;
    }

    //current x, y - placeholder variables
    public int x, y;

    public boolean isIn(Boundary[] boundaries) {
        for (Boundary b : boundaries) {
            if (x >= b.minX && x <= b.highX && y >= b.minY && y <= b.highY) {
                return true;
            }
        }
        return false;
    }

    public boolean isIn(Boundary boundaries) {
        return x >= boundaries.minX && x <= boundaries.highX && y >= boundaries.minY && y <= boundaries.highY;
    }

    //low x, high x, low y, high y
    private final Boundary TEST1 = new Boundary(2368, 2392, 9479, 9498);
    private final Boundary TEST2 = new Boundary(2328, 3492, 5279, 1498);
    private final Boundary[] TEST3 = new Boundary[] {
        new Boundary(2817, 2917, 3192, 3204), new Boundary(2817, 2961, 3131, 3191)
    };
    private final Boundary[] TEST4 = new Boundary[] {
        new Boundary(1817, 6917, 5192, 3204), new Boundary(5817, 3961, 6131, 4191)
    };
    private final Boundary TEST5 = new Boundary(8328, 9492, 7279, 6498);
    private final Boundary TEST6 = new Boundary(1328, 2492, 3279, 4498);
}

Currently only way I can figure out how to do this is:
public void isInAny() {
    if (isIn(TEST1)) {
        System.out.println("in test1");
    } else if (isIn(TEST2)) {
        System.out.println("in test2");
    } else if (isIn(TEST3)) {
        System.out.println("in test3");
    } else if (isIn(TEST4)) {
        System.out.println("in test4");
    } else if (isIn(TEST5)) {
        System.out.println("in test5");
    } else if (isIn(TEST6)) {
        System.out.println("in test6");
    }
    System.out.println("not in any tests");
}

Is there any easier way I can loop through this without making a bunch of if else statements? Any help is appreciated.
Thank you!

A: You can get the fields and loop through them:
Field[] fields = Boundary.getFields();
for (Field f : fields){
    if ((f instanceof Boundary)||((f.getType().isArray())&&(f[0] instanceof Boundary))){
        if (isIn(f)){
            System.out.println("in " + f.getName());
        }
    }
}

A: Actually you can use Java reflection and by the name of the field you can retrieve field value but I don't see the sense to use it here. if you want something more beautiful you can try something like this. But I recommend to leave it as is
int minX, minY, highX, highY;
List<Boundaries> boundaries = new LinkedList<>();

{
    boundaries.add(new Boundaries(() -> System.out.println("test1"), new Boundary(2368, 2392, 9479, 9498)));
    boundaries.add(new Boundaries(() -> System.out.println("test2"), new Boundary(2328, 3492, 5279, 1498)));
}

public Boundary(int minX, int highX, int minY, int highY) {
    this.minX = minX;
    this.minY = minY;
    this.highX = highX;
    this.highY = highY;
}

public int getMinimumX() {
    return minX;
}

public int getMinimumY() {
    return minY;
}

public int getMaximumX() {
    return highX;
}

public int getMaximumY() {
    return highY;
}

//current x, y - placeholder variables
public int x, y;

public boolean isIn(Boundary[] boundaries) {
    for (Boundary b : boundaries) {
        if (x >= b.minX && x <= b.highX && y >= b.minY && y <= b.highY) {
            return true;
        }
    }
    return false;
}

public void isInAny() {
    for (Boundaries boundary : boundaries) {
        isIn(boundary.boundaries) {
            boundary.action.test();
        }
    }
}

interface Action {
    void test();
}

static class Boundaries {
    Boundary[] boundaries;
    Action action;

    public Boundaries(Action action, Boundary... boundary) {
        this.boundaries = boundary;
        this.action = action;
    }

}


text:
Q: Prove that isomorphisms are symmetric
Prove that isomorphisms are symmetric

Now if $(G, *)$ and $(H, \circ)$ are two groups. A map $\gamma : G \to H$ such that $\gamma (x * y) = \gamma(x) \circ \gamma(y)$ for all $x, y \in G$ is a homomorphism, and a bijective homomorphism is an isomorphism, and we notationally put $G \cong H$ if a isomorphism exists between $G$ and $H$.
I need to prove that $G \cong H \implies H \cong G$.
Now we know that $\gamma : G \to H$ is an isomorphism, and it seems like $\gamma^{-1} : H \to G$ should be an isomorphism as well. Proving that $\gamma^{-1}$ is bijective is trivial, however proving that it is an homomorphism doesn't seem to be as easy, since $\gamma^{-1}(\gamma(x * y)) = \gamma^{-1}(\gamma(x) \circ \gamma(y)) \implies (x * y) = \gamma^{-1}(\gamma(x) \circ \gamma(y))$ and since we have no idea how $\circ$ affects $\gamma^{-1}$ we can't deduce anything further. (please correct me if I'm wrong)
However I found a proof online, that I'm not so sure about

In the proof above how do we know that $$s_1 \circ s_2 = \phi^{-1}(t_1) \circ \phi^{-1}(t_2) \ \ \ \ \ \ \ \ (1)$$ and how do we know that the $t_1$ and $t_2$ in $(1)$ above is the same as $t_1$ and $t_2$ in equality $(2)$ below? $$\phi^{-1}(t_1 * t_2) = s_1 \circ s_2 \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ (2)$$

A: What we would like to show, based on what we know already, is that for any $h_1,h_2 \in H$, that:
$\gamma^{-1}(h_1 \circ h_2) = \gamma^{-1}(h_1) \ast \gamma^{-1}(h_2)$.
Now, since $\gamma$ is bijective, we know there exists unique $g_1,g_2 \in G$ with:
$\gamma(g_1) = h_1, \gamma(g_2) = h_2$.
So:
$\gamma^{-1}(h_1 \circ h_2) = \gamma^{-1}(\gamma(g_1) \circ \gamma(g_2))$
and since $\gamma$ is a homomorphism, $\gamma(g_1) \circ \gamma(g_2) = \gamma(g_1\ast g_2)$, thus:
$\gamma^{-1}(h_1 \circ h_2) = \gamma^{-1}(\gamma(g_1) \circ \gamma(g_2)) = \gamma^{-1}(\gamma(g_1\ast g_2)) = g_1 \ast g_2.$
Now, from $\gamma(g_1) = h_1, \gamma(g_2) = h_2$, applying $\gamma^{-1}$ to both these equations gives:
$g_1 = \gamma^{-1}(\gamma(g_1)) = \gamma^{-1}(h_1)$, and:
$g_2 = \gamma^{-1}(\gamma(g_2)) = \gamma^{-1}(h_2).$
So, finally, we have: $\gamma^{-1}(h_1 \circ h_2) = g_1 \ast g_2 = \gamma^{-1}(h_1) \ast \gamma^{-1}(h_2)$, which is what we sought to prove.

A: Those are good questions. I think you have to ask them in part because the proof you're quoting is too condensed for a beginning student of abstract algebra
and should use more words. Here's what's going on in the last three lines.
For any $s \in S$,
 $$
\phi^{-1}(\phi(s)) = s .
$$
That's just the meaning of "inverse function". We can call $\phi(s)$ by the name $t$ if we like. Then that equation becomes
$$
\phi^{-1}(t) = s .
$$
That explains (1) and (2) in your question: you're just using different names for $s_1$ and $s_2$.
I'd write the argument this way.
Given $t_1$ and $t_2$ in $T$ I need to prove
$$
\phi^{-1}(t_1 \circ t_2)
=
\phi^{-1}(t_1) \circ \phi^{-1}(t_2) .
$$
Since $\phi$ is a bijection, the two sides of that equation will be equal if they have equal values when I apply $\phi$. Then for the left member:
$$
\phi(\phi^{-1}(t_1 \circ t_2)) =  t_1 \circ t_2 \quad (\text{meaning of } \phi^{-1})
$$
and on the right:
$$
\begin{align}
\phi(\phi^{-1}(t_1) \circ \phi^{-1}(t_2))
& =
\phi(\phi^{-1}(t_1)) \circ \phi(\phi^{-1}(t_2)))  \quad (\phi \text{ is a morphism})\\
& =  t_1 \circ t_2 \quad (\text{meaning of } \phi^{-1})
\end{align}.
$$
Done.

A: I can't see the image but I'll try to guess the proof enouncement. Let guess $\phi:H\rightarrow G$ is an isomorphism and let prove $\phi^{-1}$ is also. Its easy to see that $\phi^{-1}$ is bijective. As we know $\phi$ is bijective, given $t_1,t_2\in G$ take $s_i=\phi^{-1}(t_i)$, so $t_i=\phi(s_i)$, which results in $(1)$. We know that $\phi(s_1\circ s_2 )=t_1*t_2$ as $\phi$ is homomorphism, so taking $\phi^{-1}$ we get $(2)$. Joining $(1)$ and $(2)$ proves that $\phi^{-1}$ is homomorphism


text:
Q: Perform action on the hour, every hour, with ReactiveCocoa Trying to follow the best practices of ReactiveCocoa to update my UI on the hour, every hour. This is what I've got:
NSDateComponents *components = [[[NSCalendar sharedCalendar] calendar] components:NSMinuteCalendarUnit fromDate:[NSDate date]];
// Generalization, I know (not every hour has 60 minutes, but bear with me).
NSInteger minutesToNextHour = 60 - components.minute;

RACSubject *updateEventSignal = [RACSubject subject];
[updateEventSignal subscribeNext:^(NSDate *now) {
    // Update some UI
}];

[[[RACSignal interval:(60 * minutesToNextHour)] take:1] subscribeNext:^(id x) {
    [updateEventSignal sendNext:x];
    [[RACSignal interval:3600] subscribeNext:^(id x) {
        [updateEventSignal sendNext:x];
    }];
}];

This has some obvious flaws: manual subscription and sending, and it just "feels wrong." Any ideas on how to make this more "reactive"?

A: Sounds like you need something like +interval:startingIn:.
With that thought, you could make your own version of +interval:startingIn: by slightly tweaking the implementation of +interval:.
+ (RACSignal *)interval:(NSTimeInterval)interval startingIn:(NSTimeInterval)delay {
  return [[RACSignal createSignal:^(id<RACSubscriber> subscriber) {

    int64_t intervalInNanoSecs = (int64_t)(interval * NSEC_PER_SEC);
    int64_t delayInNanoSecs = (int64_t)(delay * NSEC_PER_SEC);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));
    dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, delayInNanoSecs), (uint64_t)intervalInNanoSecs, (uint64_t)0);
    dispatch_source_set_event_handler(timer, ^{
      [subscriber sendNext:[NSDate date]];
    });
    dispatch_resume(timer);

    return [RACDisposable disposableWithBlock:^{
      dispatch_source_cancel(timer);
      dispatch_release(timer);
    }];
  }] setNameWithFormat:@"+interval: %f startingIn: %f", (double)interval, (double)delay];
}

With this in place, your code could be refactored to:
NSDateComponents *components = [[[NSCalendar sharedCalendar] calendar] components:NSMinuteCalendarUnit fromDate:[NSDate date]];
// Generalization, I know (not every hour has 60 minutes, but bear with me).
NSInteger minutesToNextHour = 60 - components.minute;

RACSubject *updateEventSignal = [[RACSignal interval:3600 startingIn:(minutesToNextHour * 60)];
[updateEventSignal subscribeNext:^(NSDate *now) {
    // Update some UI
}];

A: You can do this using completely vanilla operators. It's just a matter of chaining the two intervals together while still passing through both of their values, which is exactly what -concat: does.
I would rewrite the subject as follows:
RACSignal *updateEventSignal = [[[RACSignal
    interval:(60 * minutesToNextHour)]
    take:1]
    concat:[RACSignal interval:3600]];

This may not give you super ultra exact precision (because there might be a minuscule hiccup between the two signals), but it should be Good Enough™ for any UI work.


text:
Q: How to access value of a key by index in an array in jQuery? Take the example below, it's part of a json response. I want to access the "TestUser4" value of the fourth "ID". How can I achieve this with jQuery?
"UIDs": [
    {
      "ID": "TestUser1",
      "Type": "Ext"
    },
    {
      "ID": " TestUser2",
      "Type": "Int"
    },
    {
      "ID": "TestUser3",
      "Type": "Ext"
    },
    {
      "ID": "TestUser4",
      "Type": "Sys"
    }
  ]

My code is something similar to the following:
jQuery.ajax({
    type: "GET",
    dataType: "json",
    success: function( data ) {
        console.log( "ID: " + data.UIDs.ID[ 3 ].value );
    }
});

A: You have an array called UIDs, holding 4 unnamed objects having the attributes "ID" and "Type". To access this in javascript:
console.log("ID: " + data.UIDs[3].ID );

A: You are pretty close.. What you want to do is access ID at the third index of your UIDs array like so :
data.UIDs[3].ID
Example Use :
jQuery.ajax({
    type: "GET",
    dataType: "json",
    success: function( data ) {

        console.log( "ID: " + data.UIDs[3].ID);
    }
});

Hope this helps..


text:
Q: Python-Data from different files (of different lengths) involved in calculations I am trying to figure out how to make my code read through each line in the Members.dat table, read the ras and decs in it, look for an ra and dec match (not exact, but within a certain range since they are from two different surveys) in the other table (Aligned...), and if it finds one to do the calculations using the appropriate redshift and rbandmag for the ra and dec match.
If it doesnt find a match, the 'Aligned...' file doesn't have data for every ra and dec in the Members.dat file, then just go to the next ra and dec pair in Members.dat and search for that one.
Right now the code reads though the Members.dat table and will return all the redshifts and rbandmags, but then for the second print statement it only uses the very last pair it reads for all the calculations with the data from the other file (Aligned....).
@mdurant
!/usr/bin/python
import csv
import numpy as np
if name == "main":
fout = open('newfile.txt', 'w')
group, rab, decb, Redshift, a, b, c, d, e = np.loadtxt('Members.dat', unpack=True)
matched_id, fuv_mag, fuv_flux, nuv_mag, nuv_flux, e_bv, g, raa, deca = np.loadtxt('Aligned FULL MEMBERS WITH DATA', unpack=True)
dist = np.subtract.outer(rab,raa)**2*np.cos(decb)**2 + np.subtract.outer(decb-deca)**2
match_bool = dist.min(axis=0)
best_match = dist.argmin(axis=0)

a = fuv_mag
b = nuv_mag
v = c*Redshift
MFuv = a-5*(np.log(10*v/70))
MNuv = b-5*(np.log(10*v/70))
Ls=3.846*10**26
LFuv=(Ls)*(np.e**((MFuv-4.47)/-2.5))
LNuv=(Ls)*(np.e**((MNuv-4.47)/-2.5))
X = MNuv-Rbandmag
MFuv = a-5*(np.log(10*v/70))
MNuv = b-5*(np.log(10*v/70))
Ls=3.846*10**26
LFuv=(Ls)*(np.e**((MFuv-4.47)/-2.5))
LNuv=(Ls)*(np.e**((MNuv-4.47)/-2.5))
X = MNuv-Rbandmag
print >> fout, '{:.2e},'.format(float(LFuv)), '{:.2e},'.format(float(LNuv)), '%f, %f, %f, %f, %f, %f, %f, %f' % (Fuvmag, Nuvmag, MFuv, MNuv, g, X,Redshift, Rbandmag)

fout.close()

So there are two objectives:

*

*Find a match within a certain range

*Do calculations for only the ras and decs with matches and only with the corresponding data.

My code:
#!/usr/bin/python

import csv
import numpy as np

if __name__ == "__main__":

    fout = open('LGroupall', 'w')

    for line in open('Members.dat'):
        if not line.startswith('#'):
            cols = line.split()
            Redshift = float(cols[3])
            Rbandmag = float(cols[4])
            c = 2.9979*10**5
            v = c*Redshift
            print >> fout,'%f, %f' % (Redshift, Rbandmag)
    for line2 in open('Aligned FULL MEMBERS WITH DATA'):
            if not line2.startswith('#'):
                cols2 = line2.split()
                Fuvmag = float(cols2[1])
                Nuvmag = float(cols2[3])
                g = float(cols2[6])
                a = Fuvmag
                b = Nuvmag
                MFuv = a-5*(np.log(10*v/70))
                MNuv = b-5*(np.log(10*v/70))
                Ls=3.846*10**26
                LFuv=(Ls)*(np.e**((MFuv-4.47)/-2.5))
                LNuv=(Ls)*(np.e**((MNuv-4.47)/-2.5))
                X = MNuv-Rbandmag
                print >> fout, '{:.2e},'.format(float(LFuv)), '{:.2e},'.format(float(LNuv)), '%f, %f, %f, %f, %f, %f, %f, %f' % (Fuvmag, Nuvmag, MFuv, MNuv, g, X, Redshift, Rbandmag)

    fout.close()

Members.dat sample:
# Group rab decb Redshift a b c d e
2293 215.197952 4.370193 0.02667 -18.116 0.739 0 0.950 1.71
2293 215.186829 4.257247 0.02722 -18.379 0.660 0 0.950 1.59
2293 215.390656 4.447858 0.02743 -17.853 0.523 0 0.943 1.95
2293 215.540527 4.521144 0.02672 -19.289 0.925 0 0.943 1.87
2293 215.647522 4.547533 0.02639 -18.097 0.715 0 0.943 1.76
2293 215.861160 4.533366 0.02646 -17.987 0.330 0 0.943 1.73
2293 215.711914 4.665845 0.02584 -18.848 0.574 0 0.943 1.56
2293 216.152466 4.559171 0.02598 -20.265 0.666 0 0.987 1.64
2293 216.167786 4.570475 0.02643 -18.496 0.513 0 0.987 1.66
2293 216.474045 4.642701 0.02615 -20.271 0.770 0 0.987 1.61
2293 216.262772 4.364132 0.02686 -18.347 0.491 0 0.987 1.97
2296 220.980103 4.096979 0.02549 -17.933 0.611 0 0.974 2.79
2296 220.881287 4.309001 0.02549 -17.989 0.373 0 0.974 3.08
2296  221.061447   4.218551  0.02557  -20.525  0.939  0  0.974    2.93
2320  216.793182   4.757412  0.02698  -18.566  0.564  0  0.987    1.69
2320  216.884888   4.821614  0.02685  -20.531  0.849  0  0.987    1.68
2320  216.873398   4.779740  0.02753  -20.111  0.699  0  0.987    1.76
2320  216.691772   4.575934  0.02806  -19.103  0.833  0  0.987    1.92

Aligned.... sample:
#matched_id fuv_mag fuv_flux nuv_mag nuv_flux e_bv g raa deca
6383546990167328408     22.11728    5.165242    20.81406    17.15441    0.02696899  2293    215.197952  4.370193
2429377676145856182 22.33954    4.209049    20.93236    15.38349    0.02696899  2293    215.197952  4.370193
2429377676144817309 21.39752    10.02288    -999        -999        0.02578526  2293    215.186829  4.257247
6383546999829960446 22.0422     5.535058    -999        -999        0.02578526  2293    215.186829  4.257247
6383546990167328949 19.40973    62.53322    19.39661    63.29321    0.02752976  2293    215.390656  4.447858
2429377676145857353 19.61978    51.53339    19.34272    66.51405    0.02752976  2293    215.390656  4.447858
6383546990165232142 -999        -999        19.93376    38.59196    0.03139252  2293    215.540527  4.521144
2429377676145858738 20.62856    20.35057    19.28588    70.089      0.03139252  2293    215.540527  4.521144
2429553598006301900 20.53106    22.2628     20.17618    30.86948    0.02996568  2293    215.647522  4.547533
6383546989093587265 20.6668     19.64633    20.26241    28.51261    0.02996568  2293    215.647522  4.547533
6383546989093587234 18.51288    142.8394    18.3558     165.0736    0.03155341  2293    215.86116   4.533366
2429553598006303442 18.64594    126.3644    18.3048     173.0134    0.02757647  2293    215.711914  4.665845
6383546989093587956 18.84079    105.6055    18.36372    163.875     0.02757647  2293    215.711914  4.665845
2429553598006302429 17.40474    396.3743    17.00334    573.674     0.03030299  2293    216.152466  4.559171
6383546989093587283 17.45678    377.825     17.03622    556.5612    0.03030299  2293    216.152466  4.559171
6383546989093587400 19.14371    79.89501    18.63046    128.1783    0.03030299  2293    216.167786  4.570475
2429553598006302434 19.07138    85.39802    18.62435    128.9025    0.03030299  2293    216.167786  4.570475
6383546989093587315 18.24552    182.7237    17.59955    331.2669    0.03227024  2293    216.474045  4.642701
2429518413634214656 18.04468    219.8524    17.5183     357.0097    0.03227024  2293    216.474045  4.642701
6383546988019847429 18.03906    220.9926    17.47195    372.5806    0.03227024  2293    216.474045  4.642701
2429553598006303494 18.05234    218.3062    17.59173    333.6613    0.03227024  2293    216.474045  4.642701
2937827037201564330 18.11119    206.7875    17.5436     348.7877    0.03227024  2293    216.474045  4.642701
6383546989093586253 19.34859    66.15564    18.8084     108.8025    0.03201414  2293    216.262772  4.364132
2429553598006299849 19.16085    78.64319    18.7739     112.315     0.03201414  2293    216.262772  4.364132
6383546994462298969 19.61141    51.93227    19.43124    61.30603    0.03103101  2296    220.980103  4.096979
2429905441727194814 19.99832    36.36427    19.34747    66.22339    0.03103101  2296    220.980103  4.096979
6383546983724877047 18.67604    122.9098    18.44853    151.5609    0.03023296  2296    220.881287  4.309001
2430010994843455574 18.65218    125.6409    18.40909    157.1673    0.03023296  2296    220.881287  4.309001
2937827037201564850 19.31565    68.19363    18.83648    106.0248    0.03118853  2320    216.793182  4.757412
2937827037199466565 -999        -999        19.97776    37.05916    0.02839247  2320    216.691772  4.575934
6383546988019846679 21.08108    13.41437    20.09341    33.31459    0.02839247  2320    216.691772  4.575934
2429518413634213555 20.98475    14.65897    20.00091    36.27739    0.02839247  2320    216.691772  4.575934
6383546988019848025 22.73846    2.914851    20.76309    17.97894    0.03277461  2320    217.289642  4.769514

LGroupall sample:
0.037170, -18.947000
0.030550, -19.078000
0.030620, -17.943000
0.030760, -20.465000
0.029680, -19.325000
0.029900, -18.618000
0.030040, -19.208000
0.030470, -19.630000
0.030550, -18.344000
0.030420, -18.616000
0.030700, -19.695000
0.030610, -21.650000
0.030460, -18.813000
5.63e+29, 9.48e+29, 22.117280, 20.814060, -13.750652, -15.053872, 2293.000000, 3.759128, 0.030460, -18.813000
5.15e+29, 9.04e+29, 22.339540, 20.932360, -13.528392, -14.935572, 2293.000000, 3.877428, 0.030460, -18.813000
7.50e+29, 1.37e+207, 21.397520, -999.000000, -14.470412, -1034.867932, 2293.000000, -1016.054932, 0.030460, -18.813000
5.80e+29, 1.37e+207, 22.042200, -999.000000, -13.825732, -1034.867932, 2293.000000, -1016.054932, 0.030460, -18.813000
1.66e+30, 1.67e+30, 19.409730, 19.396610, -16.458202, -16.471322, 2293.000000, 2.341678, 0.030460, -18.813000
1.53e+30, 1.71e+30, 19.619780, 19.342720, -16.248152, -16.525212, 2293.000000, 2.287788, 0.030460, -18.813000
1.37e+207, 1.35e+30, -999.000000, 19.933760, -1034.867932, -15.934172, 2293.000000, 2.878828, 0.030460, -18.813000
1.02e+30, 1.75e+30, 20.628560, 19.285880, -15.239372, -16.582052, 2293.000000, 2.230948, 0.030460, -18.813000
1.06e+30, 1.22e+30, 20.531060, 20.176180, -15.336872, -15.691752, 2293.000000, 3.121248, 0.030460, -18.813000
1.01e+30, 1.18e+30, 20.666800, 20.262410, -15.201132, -15.605522, 2293.000000, 3.207478, 0.030460, -18.813000
2.38e+30, 2.53e+30, 18.512880, 18.355800, -17.355052, -17.512132, 2293.000000, 1.300868, 0.030460, -18.813000
2.26e+30, 2.59e+30, 18.645940, 18.304800, -17.221992, -17.563132, 2293.000000, 1.249868, 0.030460, -18.813000
2.09e+30, 2.53e+30, 18.840790, 18.363720, -17.027142, -17.504212, 2293.000000, 1.308788, 0.030460, -18.813000
3.71e+30, 4.35e+30, 17.404740, 17.003340, -18.463192, -18.864592, 2293.000000, -0.051592, 0.030460, -18.813000
3.63e+30, 4.29e+30, 17.456780, 17.036220, -18.411152, -18.831712, 2293.000000, -0.018712, 0.030460, -18.813000

A: I think this can be done with some clever use of numpy.loadtxt and recarrays (see numpy reference for these as well as the documentation on array indexing)
import numpy as np

colnames = tuple('Group rab decb Redshift a b c d e'.split())
coltypes = tuple(['i4'] + ['f4']*(len(colnames)-1))
Members = np.loadtxt('Members.dat', dtype={'formats':coltypes, 'names':colnames})

colnames = tuple('matched_id fuv_mag fuv_flux nuv_mag nuv_flux e_bv g raa deca'.split())
coltypes = tuple(['i4'] + ['f4']*5 + ['i4'] + ['f4']*2)
Aligned = np.loadtxt('Aligned.dat', dtype={'formats':coltypes, 'names':colnames})

Members['Group'] == Aligned['g']

for Group in set(Members['Group']):             # [1]

    # get indexes in Members and Aligned for    # [2]
    # this group index
    Midx = (Group == Members['Group'])
    Aidx = (Group == Aligned['g'])

    raa = Aligned['raa'][Aidx]                  # [3]
    deca = Aligned['deca'][Aidx]
    rab = Members['rab'][Midx]                  # [4]
    decb = Members['decb'][Midx]

    # print out the first two element of the data
    # for each group ID
    print 'Group:',Group
    print '    raa = ',raa[:2],'...'
    print '    rab = ',rab[:2],'...'
    print '    deca = ',deca[:2],'...'
    print '    decb = ',decb[:2],'...'

    # do some math with the values:
    print raa * rab

Notes:
[1] Looping over all unique Group values
[2] Midx is the "index mask" of this group for the Members data
    and Aidx is the mask of this group for the Aligned data
[3] at this point raa is an array of all the raa values for this
    particular Group
[4] similarly, rab is an array of all the rab values for this Group
I prefer to use column types this way to force index columns to integer types so that masks are more robust. With this, you can go ahead and do the math you want on the group-level. See the output of the last line of the script above.

A: I recommend that you not loop through your files as you are doing. Although this will work, it makes the code hard to read and correct, and can lead to the sort of problem you are having. Instead, you can load the whole file into arrays, and then work on these:
group, rab, decb, Redshift, a, b, c, d, e = np.loadtxt('Members.dat', unpack=True)
matched_id, fuv_mag, fuv_flux, nuv_mag, nuv_flux, e_bv, g, raa, deca = np.loadtxt('Aligned FULL MEMBERS WITH DATA', unpack=True)

and then you have a match when (rab-raa)**2*cos(decb)**2 + (decb-deca)**2 < limit**2 (I am assuming your units here, please check).
You can either loop through one coordinate set:
for i in range(len(rab)):
   dist = (rab[i]-raa)**2*cos(decb[i])**2 + (decb[i]-deca)**2)
   if dist.min()<limit**2:
       print raa[dist.argmin()],deca[dist.argmin()]

or form a (big) matrix of distances
dist = np.subtract.outer(rab,raa)**2*cos(decb[:,None])**2 + np.subtract.outer(decb,deca)**2
match_bool = dist.min(axis=0)
best_match = dist.argmin(axis=0)