text:
Q: Prove that a harmonic homology preserves the conic I came across a question in the book by Judith N. Cederberg and I'm learning about projective geometry.
One of the question was "Show that a harmonic homology whose centre and axis are pole and polar with respect to a point conic $\mathscr C$ keeps $\mathscr C$ invariant." A harmonic homology just means that the cross ratio is $-1$.
I am unsure on how I can even start the proof. I took on some simple examples. For example. I let the center be $Z(0,0,1)$ and axis be $z(0,0,1)$. I am able to find that the matrix is a symmetric diagonal matrix.
Anyone has any hints on how I can show that it keeps the conic $\mathscr C$ invariant?

A: I don't have the book, but there is probably a statement and proof of the following: A conic in the projective plane has the following property: If $P$ is a point not on $C$, and if a variable line through $P$ meets $C$ at points $A$ and $B$, then the variable harmonic conjugate of $P$ with respect to $A$ and $B$ traces out a line. The point $P$ is called the pole of that line of harmonic conjugates, and this line is called the polar line of $P$ with respect to the conic. (paraphrased from https://en.wikipedia.org/wiki/Projective_harmonic_conjugate#Projective_conics)
In other words, given a point P not on the conic, draw a line that intersects the conic at $A$ and $B$, and the polar at $P'$.  The cross ratio $[AB;PP']=-1$, and $P'$ and $P$ are harmonic conjugates with respect to $A,B$.  This defines the polar line of $P$.  And it is also true that $A$ and $B$ are harmonic conjugates with respect to $P,P'$.
But this is the definition of the given harmonic homology.  It maps every point $A$ of the conic into a point $B$ of the conic.  Thus it maps the conic to itself. (I would quibble with the use of the word 'invariant' to describe this, but I assume this is what the author meant.)


text:
Q: Azure Site-To-Site VPN with Oracle OCI I am trying to connect to Oracle cloud infrastructure from Azure using azure S2S VPN and it's not getting connected.
I have already created policy-based route that's supports IKEv1 because oracle OCI only supports IKEv1. Please find here the parameters from oracle side:

What could be the problem ?

A:
The above is the configuration of Azure VPN gateway. On checking, it seems like PFS needs to be disabled on your end as Azure Policy based gateway doesn't support.
If that doesn't fix the issue, please post the IKE/IPSEC logs to further troubleshoot.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to read unformatted contents of the numeric cells using NPOI? I want to read an unformatted contents of the numeric cells (e.g. 0.05 instead of 5% and 123456 instead of 123,456.000).
I thought the easiest way to do it would be to change the format of the cell:
ICell cell = ...;
string s = cell.SetCellType(<ICell.CELL_TYPE_STRING-doesn't compile>).ToString();

but I do not know how to set string/numeric format.
All examples I have googled are either from POI or HSSF universes, they won't do for me (I am reading Excel 2007 spreadsheet using NPOI)

A: This worked for me:
string formatProofCellReading(ICell cell)
{
    if (cell == null)
    {
        return "";
    }
    if (cell.CellType == CellType.NUMERIC)
    {
        double d = cell.NumericCellValue;
        return (d.ToString());
    }
    return cell.ToString();
}


text:
Q: Android testing: Waited for the root of the view hierarchy to have window focus In Android Ui testing, I want to click on a spinner item in a dialog, but it pop up with this error:
va.lang.RuntimeException: Waited for the root of the view hierarchy to have window focus and not be requesting layout for over 10 seconds. If you specified a non default root matcher, it may be picking a root that never takes focus. Otherwise, something is seriously wrong. Selected Root:
Root{application-window-token=android.view.ViewRootImpl$W@2dac97c7, window-token=android.view.ViewRootImpl$W@2dac97c7, has-window-focus=false, layout-params-type=1, layout-params-string=WM.LayoutParams{(0,0)(fillxfill) sim=#10 ty=1 fl=#81810100 pfl=0x8 wanim=0x1030461 surfaceInsets=Rect(0, 0 - 0, 0) mwfl=0x0}, decor-view-string=MultiPhoneDecorView{id=-1, visibility=VISIBLE, width=1600, height=2560, has-focus=true, has-focusable=true, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}}
. All Roots:
Root{application-window-token=android.view.ViewRootImpl$W@3c913e1, window-token=android.view.ViewRootImpl$W@21b23506, has-window-focus=true, layout-params-type=1002, layout-params-string=WM.LayoutParams{(310,600)(722x480) gr=#10000033 sim=#1 ty=1002 fl=#1860200 fmt=-3 wanim=0x10302db surfaceInsets=Rect(0, 0 - 0, 0) mwfl=0x0}, decor-view-string=PopupViewContainer{id=-1, visibility=VISIBLE, width=722, height=480, has-focus=true, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}}
Root{application-window-token=android.view.ViewRootImpl$W@3c913e1, window-token=android.view.ViewRootImpl$W@3c913e1, has-window-focus=false, layout-params-type=2, layout-params-string=WM.LayoutParams{(0,0)(wrapxwrap) gr=#11 sim=#20 ty=2 fl=#1800002 pfl=0x8 fmt=-3 wanim=0x1030462 surfaceInsets=Rect(0, 0 - 0, 0) mwfl=0x10}, decor-view-string=DecorView{id=-1, visibility=VISIBLE, width=1136, height=1058, has-focus=true, has-focusable=true, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}}
Root{application-window-token=android.view.ViewRootImpl$W@2dac97c7, window-token=android.view.ViewRootImpl$W@2dac97c7, has-window-focus=false, layout-params-type=1, layout-params-string=WM.LayoutParams{(0,0)(fillxfill) sim=#10 ty=1 fl=#81810100 pfl=0x8 wanim=0x1030461 surfaceInsets=Rect(0, 0 - 0, 0) mwfl=0x0}, decor-view-string=MultiPhoneDecorView{id=-1, visibility=VISIBLE, width=1600, height=2560, has-focus=true, has-focusable=true, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}}
at android.support.test.espresso.base.RootViewPicker.get(RootViewPicker.java:99)
at android.support.test.espresso.ViewInteractionModule.provideRootView(ViewInteractionModule.java:69)
at android.support.test.espresso.ViewInteractionModule_ProvideRootViewFactory.get(ViewInteractionModule_ProvideRootViewFactory.java:23)
at android.support.test.espresso.ViewInteractionModule_ProvideRootViewFactory.get(ViewInteractionModule_ProvideRootViewFactory.java:9)
at android.support.test.espresso.base.ViewFinderImpl.getView(ViewFinderImpl.java:68)
at android.support.test.espresso.ViewInteraction$1.run(ViewInteraction.java:120)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6117)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

I have tried
onData(allOf(is(instanceOf(String.class)),containsString("A4"))).inRoot(isPlatformPopup()).perform(click());

and
onView(withText(containsString("A4"))).inRoot(isFocusable()).check(matches(isDisplayed()));

and
onView(withText(containsString("A4"))).inRoot(withDecorView(not(getActivity().getWindow().getDecorView()))).check(matches(isDisplayed()));

but none of them works...
Can anyone tell me how to get the ralavant root please?

A: I had similar issue when a dialog popup contains spinner items (dropdown list), my click couldn't perform on any of the spinner items and got the same error.
I found a solution by using onData() method with RootMatchers:
onData(anything()).inRoot(RootMatchers.isPlatformPopup()).atPosition(1).perform(click());

Note that, the index value in atPosition() is the item's index value from the spinner list.

A: This error can happen when a system dialog is displayed — like "Power Off" or "Unfortunately, Launcher has stopped" (a background app crashed) — and you try to run an Espresso unit test whilst that dialog is visible.

Image credit: Android 4.0 emulator always has a crashing Launcher?
You can workaround it in code by dismissing the system dialog before running the test:
// Use the 'testing' Context
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));

// Alternative: Use the Activity for the Context
MyActivity activityUnderTest = activityTestRule.getActivity();
activityUnderTest.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));

Or send the broadcast on the command line using adb:
adb shell am broadcast -a android.intent.action.CLOSE_SYSTEM_DIALOGS

Another cause of the error is when a background app is frozen (ANR) or is running slowly, and a system dialog appears saying "Launcher isn't responding. Do you want to close it? [Wait] [OK]":

Image credit: https://engineering.linkedin.com/blog/2016/08/introducing-and-open-sourcing-test-butler--reliable-android-test
If you try to run an Espresso test while this dialog is visible, the tests will all fail and show the "Waited for the root..." error. There's no easy way to close this dialog programmatically. Espresso cannot click these buttons, for the reasons described here:  Dismiss Alert Dialog in Android Espresso Test . However, one way is to use UI Automator to press the "Wait" button in the dialog, just before a test starts:
app/build.gradle
dependencies {
    ...
    androidTestImplementation "androidx.test.uiautomator:uiautomator:2.2.0"
}

ActivityUiTest.kt
companion object {
    @JvmStatic
    @BeforeClass
    fun dismissANRSystemDialog() {
        val device = UiDevice.getInstance(getInstrumentation())
        // If running the device in English Locale
        var waitButton = device.findObject(UiSelector().textContains("wait"))
        if (waitButton.exists()) {
            waitButton.click()
        }
        // If running the device in Japanese Locale
        waitButton = device.findObject(UiSelector().textContains("待機"))
        if (waitButton.exists()) {
            waitButton.click()
        }
    }
}

ActivityUiTest.java
@BeforeClass
public static void dismissANRSystemDialog() throws UiObjectNotFoundException {
    UiDevice device = UiDevice.getInstance(getInstrumentation());
    // If the device is running in English Locale
    UiObject waitButton = device.findObject(new UiSelector().textContains("wait"));
    if (waitButton.exists()) {
        waitButton.click();
    }
    // If the device is running in Japanese Locale
    waitButton = device.findObject(new UiSelector().textContains("待機"));
    if (waitButton.exists()) {
        waitButton.click();
    }
}

Alternatively, you could use adb on the command line to send screen taps or key strokes to dismiss it. For example:
# On a 320x480 screen, click at screen location [x=233,y=293] to tap an "OK" dialog button.
# Just in case there is a "Launcher isn't responding" system dialog.
adb shell input tap 233 293

or
# Send keystroke Arrow Right
sleep 3; adb shell input keyevent 22
# Send keystroke Arrow Right again
sleep 3; adb shell input keyevent 22
# Send keystroke Enter to press a button on the dialog
sleep 3; adb shell input keyevent 66

More info:

*

*https://groups.google.com/forum/#!topic/android-test-kit-discuss/yIEwus_hjeY

*How to dismiss system dialog in Android?

*Android adb shell am broadcast: Bad component name

*How to use ADB to send touch events to device using sendevent command?

A: I had the same error, when I used a Spinner inside a DialogFragment.
This is the only code that was working for me:
onView(withText(containsString("A4"))).inRoot(isPlatformPopup()).check(matches(isDisplayed()));

A: Just in case if it happens to anyone's Travis build (with exact the same log).  Please check this.
Had exact the same problem, and solved by creating avd with lower target version (19).
What I've tried and didn't work:

*

*Adding a unlockScreen() @Before method to UI test.

*Adding / Removing adb shell input keyevent 82 &.

*Removing different emulator command options -no-skin or -no-audio or -no-window.  Now I have -no-window there which is fine.
Finally, changing
from
echo no | android create avd --force -n test -t android-24 --abi armeabi-v7a

to
echo no | android create avd --force -n test -t android-19 --abi armeabi-v7a

perfectly solve the issue.

A: For me, when testing my custom AlertDialog, using the .inRoot(isDialog()) method instead of .inRoot(isPlatformPopup()) worked.
onView(withText(containsString("A4"))).inRoot(isDialog()).check(matches(isDisplayed()));

A: I encountered this issue periodically when running Espresso tests on emulators in CI.  Because the checks fail if a single test fails, the answer at https://stackoverflow.com/a/54203607/4520965 was insufficient for my use case.  That answer handles dismissing the ANR Dialogue in the subsequent test class, but the test class where the ANR initially appeared would still fail.  To get around this I added the following to my base ui test class that all my Espresso tests inherited from:
    //Running count of the number of Android Not Responding dialogues to prevent endless dismissal.
    private var AnrCount = 0
    //`RootViewWithoutFocusException` class is private, need to match the message (instead of using type matching).
    private val rootViewWithoutFocusExceptionMsg = java.lang.String.format(
            Locale.ROOT,
            "Waited for the root of the view hierarchy to have "
                    + "window focus and not request layout for 10 seconds. If you specified a non "
                    + "default root matcher, it may be picking a root that never takes focus. "
                    + "Root:")

    @Before
    fun setUpHandler() {
        Espresso.setFailureHandler { error, viewMatcher ->

            if (error.message!!.contains(rootViewWithoutFocusExceptionMsg) && AnrCount < 3) {
                AnrCount++
                handleAnrDialogue()
            } else { // chain all failures down to the default espresso handler
                DefaultFailureHandler(context).handle(error, viewMatcher)
            }
        }
    }

    private fun handleAnrDialogue() {
        val device = UiDevice.getInstance(getInstrumentation())
        // If running the device in English Locale
        val waitButton = device.findObject(UiSelector().textContains("wait"))
        if (waitButton.exists()) waitButton.click()
    }

A: just update the build tools in the travis.yml:

*

*In this file .travis.yml: you should have this before_install: - echo yes | android update sdk --all --filter build-tools-26.0.1 --no-ui --force

*as wel this in .travis.yml:

script: echo no | android create avd --force -n test -t android-22
--abi armeabi-v7a emulator -avd test -no-audio -no-window &
android-wait-for-emulator
adb shell settings put global window_animation_scale 0 &
adb shell settings put global transition_animation_scale 0 &
adb shell settings put global animator_duration_scale 0 &
adb shell input keyevent 82 &

A: Maybe the problem is newly up to date, but with the new Android version.
AndroidX Test: 1.3.0
Espresso: 3.3.0
Android OS: Android 11 (API 30)
See https://github.com/android/android-test/issues/751


text:
Q: Using a bash script to apply another script to every file in a directory like a matrix Let's say in my directory I have five files.
Files: 1,2,3,4, & 5
I have a script that will do a mathematical process to compare two files and I want to use this script on every file in the directory, example below.
compare file 1 to 2,3,4, & 5
compare file 2 to 3,4, & 5
compare file 3 to 4 & 5
compare file 4 to 5
The files follow this name scheme filename_V0001.txt
How can a write a simple bash script to do this?

A: script_v1.sh:
#!/bin/bash
compare="/path/to/my/compare_tool"

for i in {1..5}; do
    for j in $(seq $((i+1)) 5); do
        echo "Comparing $i and $j"
        compare filename_V000$i.txt filename_V000$j.txt > result_$i_$j.txt
    done
done

result_v1:
$ > bash script_v1.sh
Comparing 1 and 2
Comparing 1 and 3
Comparing 1 and 4
Comparing 1 and 5
Comparing 2 and 3
Comparing 2 and 4
Comparing 2 and 5
Comparing 3 and 4
Comparing 3 and 5
Comparing 4 and 5
$ >

script_v2.sh:
#!/bin/bash
compare="/path/to/my/compare_tool"

for i in {1..100}; do
    for j in $(seq $((i+1)) 100); do
        fi="Filename_V$(printf "%04d" $i).txt"
        fj="Filename_V$(printf "%04d" $j).txt"
        if [[ -f "$fi" && -f "$fj" ]]; then
            echo "Comparing $fi and $fj"
            compare "$fi" "$fj" > result_$i_$j.txt
        fi
    done
done

result_v2:
$ > bash script_v2.sh
Comparing Filename_V0001.txt and Filename_V0002.txt
...
Comparing Filename_V0001.txt and Filename_V0100.txt
Comparing Filename_V0002.txt and Filename_V0003.txt
...
Comparing Filename_V0002.txt and Filename_V0100.txt
Comparing Filename_V0003.txt and Filename_V0004.txt
...
Comparing Filename_V0099.txt and Filename_V0100.txt
$ >

ASSUMPTIONS:

*

*the scripts are called from the path the files reside in

A: for a in *
do
  start=0
  for b in *
  do
    if [ "$start" = 1 ]
    then
      echo "Comparing $a with $b ..."
      diff "$a" "$b"
    elif [ "$a" = "$b" ]
    then
      start=1
    fi
  done
done

Any name scheme for the files can of course be given in the glob pattern, e. g. for a in filename_V*.txt.

A: One fairly general way of doing it:
#!/bin/sh
for comp1; do
  shift
  for comp2; do
    echo "Comparing '$comp1' with '$comp2'"
    do_compare "$comp1" "$comp2"
  done
done

Then you can call that script with the list of files to compare:
do_all_compares Filename_V*.txt

for x is equivalent to for x in "$@". The list is computed when the for statement is executed, so the shift which happens at the start of the loop will only affect the list for the inner comparisons.


text:
Q: Applying overflow:hidden to .mat-tab-body-content Applying overflow:hidden to .mat-tab-body-content.
I have provided overflow-x:hidden in css but also it is not getting

A: If you mean hiding Overflow in css, the answer is :
 .mat-tab-body-content {
    overflow: hidden;
}

Or:
 .mat-tab-body-content {
    overflow-x: hidden;
    overflow-y: hidden;
}


text:
Q: Is it possible to access a variable, using a string which holds that variables name in JAVA? In Java,
If I had a String already declared and it holds the name of a variable. Can I use that String to access that variable?
For Example
int sample=10;
String test = "sample";

Here,is it possible use the string test to access integer variable sample.
If yes, then how.

A: Reflection
One of the strongest aspects of Java is the robust reflection API provided by the standard libraries.

Reflection allows you examine and modify the structures and behaviour of classes, methods, and attributes at runtime.

Reflection is, in my opinion, single handedly responsive for the robust Java ecosystem of platforms, frameworks, and JVM languages available today.
Caution
While reflection is powerful and is definitely a part of Java widespread success I caution against using it in many circumstances.
For the most part reflection
 is used in software used by other software (frameworks, platforms, languages, etc).  Generally when I see someone ask about reflection (especially if they do not call it by name) they are thinking about the problem wrong.
I would definitely like to hear your use case so we can possibly suggest a different way of looking at it.
Sample Code
Below is some psuedo code that illustrates one way to accomplish what you are trying to do. I call it psuedo code because I have not compiled it, and it could likely be optimized.
Before adding it to your project I would like to reiterate that you should post your specific problem so we can analyze it and possibly help you think about it differently.
final String ATTR = "test";
Class<?> clazz = Class.forName("your.fully.qualified.class.name");
Field[] fields = clazz.getFields();

for ( Field field : fields ) {
    String name = field.getName();

    if ( name == ATTR ) {
       Object value = field.get(name);
   }
}


text:
Q: Optional parts of regex pattern in vba I am trying to build regex pattern for the text like that
numb contra: 1.29151306 number mafo: 66662308
numb contra 1.30789668number mafo 60.046483
numb contra/ 1.29154056 number mafo: 666692638
numb contra     137459625
mafo: 666692638
mafo: 666692638 numb contra/ 1.29154056

Here's the pattern I could build
contra?.\s+?(\d+\.?\d+)(.+mafo.?\s+(\d+\.?\d+))?

It works fine for all the lines except the last one. How can I implement all the possibilities to include the last line too?
Please have a look at this link
https://regex101.com/r/pSThAU/1
All is OK as for contra but not as for mafo

A: I think the key here is to make your regexp do less and your vba do more.  What I think I see here is either the word 'mafo' or 'contra' and a number following.  Don't know what order or whether each is present or how many times.  So you can scan each of your strings for ALL occurrences with a regexp like this:
(?:^|[^A-Z])(?:(mafo)|(contra))[^A-Z]\s*(\d*\.?\d+)

Then process it with some VBA code like this that I created in Excel:
Sub BreakItUp()
Dim rg As RegExp, scanned As MatchCollection, eachMatch As Match, i As Long, col As Long

Set rg = New RegExp
rg.Pattern = "(?:^|[^A-Z])(?:(mafo)|(contra))[^A-Z]\s*(\d*\.?\d+)"
rg.IgnoreCase = True
rg.Global = True
i = 1
Do While (Not IsEmpty(ActiveSheet.Cells(i, 1).Value))
    Set scanned = rg.Execute(ActiveSheet.Cells(i, 1).Value)
    col = 2
    For Each eachMatch In scanned
        ActiveSheet.Cells(i, col).Value = eachMatch.SubMatches(0) & eachMatch.SubMatches(1)
        ActiveSheet.Cells(i, col + 1).Value2 = "'" & eachMatch.SubMatches(2)
        col = col + 2
    Next eachMatch
    i = i + 1
Loop
End Sub

That MatchCollection object will get one item for each Match that occurs and the subMatches array contains each capturing group.  You should be able write your own logic within this processing loop to interpret what was extracted.  When I ran it on your data it created all the fields in blue:

Notice I added a line to your data that had two contra entries and one mafo and it found all the occurrences.  You should be able to modify this to interpret the meanings.


text:
Q: Spring LazyInitializationException when using "redirect" in controller I started creating an application with Spring-Roo 1.3.1 and Spring-Security 3.1.7
I'm using Spring OpenEntityManagerInViewFilter to be able to do lazy loading of my domain objects.
<filter>
    <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

This is working fine so far. However, I encountered the following issue when doing a redirect from a controller:
@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(@Valid Service service, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
    if (bindingResult.hasErrors()) {
        populateEditForm(uiModel, service);
        return "services/update";
    }
    uiModel.asMap().clear();
    serviceRepository.save(service);
    return "redirect:/services/" + encodeUrlPathSegment(service.getId().toString(), httpServletRequest);
}

This redirect return "redirect:/services/" + encodeUrlPathSegment(service.getId().toString(), httpServletRequest); is failing with an LazyInitializationException. It fails during execution of the filter chain after the commit is done and redirect took place. The URL redirected to is working when access directly.
When using return "forward:/services/" + encodeUrlPathSegment(service.getId().toString(), httpServletRequest); the page loaded just fine.
I really do not know why the hibernate session is not available when using "redirect". Another strange thing is, when activating DEBUG logging for org.springframework.security.web is is also working fine.
e.g. log4j.logger.org.springframework.security.web=DEBUG
I already searched the internet for some hints but generally lazy loading is working fine in my app, it's just in that circumstance and currently I do not fully understand why.
Any comments/hints are welcome.
Thanks
Stefan

A: Try to change controller like this:
@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(@Valid Service service, BindingResult bindingResult,
           Model uiModel, HttpServletRequest httpServletRequest) {
      if (bindingResult.hasErrors()) {
          populateEditForm(uiModel, service);
          return "services/update";
      }
      uiModel.asMap().clear();
      Service attached = serviceRepository.save(service);
      return "redirect:/services/" +
           encodeUrlPathSegment(attached.getId().toString(),
           httpServletRequest);
}

The instance service is create by Spring binder to map request values to the object but it is not attached to entityManager (no db session). When you call save you get an attached (instance managed by entityManager) instance so, if you try to get any lazy property from this instance it knows how do it.
You can found more information about JPA objects live cycle here.
Good luck!


text:
Q: Add tags to existing text How to add new tags to text that is already present inside some element. Is there a better way than copying the text into new element and then deleting from old?
In the example below, text Hello World! is already present inside a div. The goal is to add h1 around the text.

Hello World!

  <button onclick="myFunction()">Click Here</button>

A: This question is likely going to get multiple opinions.
Mine is that you are doing it just fine using the DOM API. However, if you understand the performance and security implications of .innerHTML, you could do this:

Hello World!

  <button onclick="myFunction()">Click Here</button>


text:
Q: Iphone Internet Connection Verification - Reachability I read there were many problem with the Reachability sample app that apple provided, but now with their new 2.2 implementation it's suppose to work fine.
So I just want an advice before I integrate it into my app instead of my current implementation.
Basically I'm asking 2 question:

*

*Will this code work ? I need to know if internet is available through 3G or WIFI. (If there is a WIFI with no internet, of course I need it to return false)

2.I'm planning to deploy my app on ios 3.0 and above, do I need to perform any adjustments so it won't crash on ios below 4.0 (cause Reachability 2.2 said to be working on ios 4) ?
Thanks alot!!
+ (BOOL) isInternetReachable
{
    NetworkStatus status = [[Util sharedReachability] currentReachabilityStatus];

    return (status != NotReachable);
}

+ (Reachability*) sharedReachability
{
    if (reachability == nil)
    {
        reachability = [[Reachability reachabilityForInternetConnection] retain];
        [reachability startNotifier];
    }
    return reachability;
}

A: Yes this code is gonna work. It is right.


text:
Q: Rspec undefined method `belong_to' I am using RSpec 3.10 and trying to test a belongs_to relationship
RSpec.describe MyClasss, type: :model do
  it { is_expected.to belong_to(:another_class) }
end

NoMethodError:
  undefined method `belong_to' for #<RSpec::ExampleGroups::MyClasss

Do I need a special configuration in order to use belong_to matcher?

A: You should have the shoulda-matchers gem installed
https://github.com/thoughtbot/shoulda-matchers

A: In my case, I set up my test incorrectly.  Here's what I had:
describe MyModel do

and here's what worked:
RSpec.describe MyModel, type: :model do

A: If you're working on a Rails app, simply place this at the bottom of spec/rails_helper.rb (or in a support file if you so choose):

Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :rspec
    with.library :rails
  end
end


text:
Q: Android - DatabaseUtils.sqlEscapeString() does not work I want to insert "women's cloth" in the database, so I use
String name = DatabaseUtils.sqlEscapeString("women's cloth");

but it gives out put like
"'Women''s Clothing'"

and while inserting app crashes and gives
E/SQLiteLog: (1) near ",": syntax error

--------- beginning of crash -----------------
07-12 12:42:19.628 22387-22521/com.i4ustores E/AndroidRuntime: FATAL EXCEPTION: Thread-8634
android.database.sqlite.SQLiteException: near ",": syntax error (code 1):

A: From your simple code, I guess you create SQL statement manually.
Try using String.format:
String query = String.format("SELECT * FROM %s WHERE %s = ?",
                      TABLE_NAME, SEARCH_KEY);

Read more at: Local Databases with SQLiteOpenHelper
Or try using PreparedStatement like below:
PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES
                                     SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00)
pstmt.setInt(2, 110592)

Please be aware that the parameterIndex (i.e 1 and 2 in above code) start from 1.


text:
Q: codeigniter pagination in multiple table joins displying error Invalid argument supplied for foreach() I have a problem with pagination.when I click on the next but it brings the above error, but when I click on the previous link it works normally. here is my code for the controller:
public function categoryfour()

{

$config = array();

    $config["base_url"] = base_url() . "bulletins/categoryfour";

    $total_row = $this->news_model->record_count_category_four();

    $config["total_rows"] = $total_row;

    $config["per_page"] = 2;

    $config["uri_segment"] = 3;

    $config['use_page_numbers'] = TRUE;

    $config['num_links'] = $total_row;

    $config['cur_tag_open'] = ' ';

    $config['cur_tag_close'] = '';

    $config['next_link'] = 'Next';

    $config['prev_link'] = 'Previous';

    $this->pagination->initialize($config);
    $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
    $data["posts"] =$this->news_model->get_news_cat_four($config["per_page"], $page);

    $str_links = $this->pagination->create_links();

    $data["pages"] = explode(' ',$str_links );

    $this->load->view('category_one',$data);
}

here is the code for the model:
function get_news_cat_four($limit, $start)
{

    $this->db->select('news.id as newsId,news_category.id as catId,users.id as userId,news.*,news_category.*,users.*,comments.*, COUNT(comments.post_id) as num_comments');

    $this->db->join('users' , 'users.id = news.user_id');

    $this->db->join('news_category' , 'news_category.cat_id = news.news_id');

    $this->db->join('comments' , 'comments.post_id = news.id');

    $this->db->group_by('comments.post_id');

    $this->db->order_by('news.date_added','desc');

    $this->db->where('news.news_id',4);

    $this->db->limit($limit, $start);

    $query = $this->db->get("news");

    if ($query->num_rows() > 0) {
        foreach ($query->result() as $row) {
            $data[] = $row;
        }
        return $data;
    }
    return false;}

and finally the view:

            <?php if(count($posts)) {

              foreach($posts as $n){ ?>

<a href="<?php echo base_url('bulletins/view/'.$n->newsId)?>"><?php echo $n->title;?>

                      <?php echo date( 'F jS, Y g:i a' , strtotime($n->date_added))?>/

               <?php echo $n->num_comments;?>/

                   <?php echo $n->username?>

<a href="<?php echo base_url();?>bulletins/view/<?php echo $n->newsId?>"><img src="<?php echo base_url('assets/images/'.$n->image)?>"
                 style="width:800px;height:500px" />

<?php echo  substr(strip_tags($n->content), 0, 200).'...';?>

                            <a href="<?php echo base_url()?>bulletins/view/<?php echo $n->newsId?>">Read More...
                            <?php }}?>

             <?php foreach ($pages as $link) {

              echo "
". $link."
";

               }
              ?>


text:
Q: Are there useful applications of SVD that use only the smallest singular values? In a number of singular value decomposition (SVD) applications, for example Latent Semantic Indexing, only the biggest singular values are used to make searches and calculate distances.
Are there useful applications that drop the biggest singular values and use only the smallest ones?

A: *

*Slow feature analysis (SFA) uses the smalles Eigenvalues of the covariance matrix of temporal differences to find the slowest features in a time series,

*Minor component analysis (MCA) uses the smallest components in a probabilistic setting--here, not directions of variations are found but constraints,

*Extreme component analysis (XCA) is a combination of probabilistic PCA and MCA,

*In Canonical Correlation Analysis (where you analyse the correlation btw two different data sets), the smaller components of the correlation matrix correspond to so called "private" spaces. These represent the subspaces of each variable which do not correlate linearly with each other.

A: It acts like a highpass filter in a slightly different space.
There is lots of linear data, and in many cases you are looking for that linear relationship, so a low-pass (high-blocking) filter lets you retain the important part.
For non-linear data, usually stuff that you have applied the simple methods without success to, the high-pass means that you throw away the unimportant (linear) part.
This makes me wonder about computational photography and edging.  Thanks..

A: Total Least Squares regression (aka Orthogonal Distance regression) uses the singular vector corresponding to the smallest singular value of the augmented predictor/criterion matrix.
When there is only one dependent variable (i.e., when $k = 1$), both equation 12.3-5 in my Golub & Van Loan (first edition), and the final equation and Octave code in the "Algebraic point of view" section of the Standard account, use only the singular vector corresponding to the smallest singular value to get the vector of regression coefficients.

A: Yes, there are. I'm currently working with a professor on a research project where we try to predict very short-term stock market changes based on real-time tweets from Twitter. Unfortunately, the majority of what people say on Twitter about the companies we are tracking is useless rambling. In other words, the largest singular values are useless.
Our plan is to use the biggest singular values to flag vast amounts of garbage tweets so that we can delete them. The remaining tweets and their text content (the small singular values) are candidates for a variable selection process.
We are trying find the needles in a haystack, and dropping the largest singular values is like setting the hay on fire.

A: It's a bit of a stretch, but consider the portfolio optimization problem: minimize $w^{\top} \Sigma w$ subject to $w^{\top} w \ge 1$. You can think of this as the minimum variance portfolio with an $\ell_2$ constraint. After applying Lagrange Multiplier method, you find that $w$ should be the eigenvector associated with the smallest eigenvalue of $\Sigma$. Since $\Sigma$ is typically the sample covariance $(1/N) \sum_{1\le i\le N} X_i X_i^{\top}$, where the $X_i$ have been centered, you can view this problem as an SVD computation where the singular vector associated with the smallest singular value is of importance. Like I said, it's a bit of a stretch.

A: There is an interesting LSA related paper which concludes that discarding (a lot of) first SVD features can improve results on semantic tests like TOEFL - "Extracting Semantic Represenations from Word Cooccurrence Statistics: Stop-lists, Stemming and SVD" (Bullinaria and Levy, 2012)

A: I'm not aware of any.  The smallest singular values correspond to modes that don't contribute much to the reconstruction of the original matrix, or to use the PCA interpretation, don't describe much of the variance in the data.  Typically,  the modes with smaller singular values are just noise.  This doesn't rule out the possibility that some meaning could be found in them, but I think it would be highly dependent on the data which make up the original matrix and — honestly — pretty unlikely.


text:
Q: Pay As You Go subcriptiona cancellation in Azure I just created a azure account. When I see my subcription it shows two

*

*3 Months Free Trial

*Pay-As-You-Go

I want only the trial thing at the moment. So I cancelled Pay-As-You-Go. (It's status is currently Disabled)
So I just want to know that will I be charged for this. Or should I remove this by contacting suppor center to be safe.
Thanks

A: If you do not deploy anything to your Pay-As-You-Go subscription then you should not get billed for it.  Since it is disabled then you shouldn't be able to deploy anything to it, or use it anyway, so you should be safe.  You may get billed for anything that was used by that subscription prior to it being disabled (if you used it for something).
I believe you can call support and request they remove the subscription completely if you like.  I had an old beta subscription linked to my ID that was disabled and contacting support is what got it removed.


text:
Q: Cant compile for x64 even after installing Visual C++ 2008 Express and Windows SDK I have Visual C++ 2008 Express Edition installed. From here I have installed the MICROSOFT WINDOWS SOFTWARE DEVELOPMENT KIT FOR WINDOWS 7 and .NET FRAMEWORK 4 for x64 bit compile.
Now I can see the option of x64 through IDE in configuration menu. But whenever I try to build with this Debug|x64 selected, all I get is:
========== Build: 0 succeeded or up-to-date, 0 failed, 1 skipped ==========

It never gets build and always fails.
     I also don't have amd64\vcvarsamd64.bat folder inside C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin
Even when trying to build from cmd through msbuild "[PROJECT_PATH].sln" /t:Clean,Build /p:Configuration=Debug;Platform=x64 I get this:
Microsoft (R) Build Engine Version 3.5.30729.5420
[Microsoft .NET Framework, Version 2.0.50727.5420]
Copyright (C) Microsoft Corporation 2007. All rights reserved.

Build started 11/4/2016 11:55:00 AM.
Project "[PROJECT_PATH].sln" on node 0 (Clean;Build target(s)).
  Building solution configuration "Debug|x64".
vcbuild.exe : error VCBLD0004: Project '[PROJECT_PATH].vcproj' does not contain a configuration called 'Debug|x64'.
vcbuild.exe : error VCBLD0004: Project '[PROJECT_PATH].vcproj' does not contain a configuration called 'Debug|x64'.
vcbuild.exe : error VCBLD0004: Project '[PROJECT_PATH].vcproj' does not contain a configuration called 'Debug|x64'.
Done Building Project "[PROJECT_PATH].sln" (Clean;Build target(s)) -- FAILED.

Build FAILED.

Seems like tools aren't installed but I have installed Windows SDK after selecting the compile tools, then why it isn't?
Any idea what went wrong?

A: The Windows SDK does not include any C++ compiler, and VC++ 2008 Express edition is 32 bit only. You need to install a 64 bit compiler (more recent versions of VC++ Express are available in 64 bit flavor).


text:
Q: Rails 3.2 link_to a File in Safari I have an area on my site where a user can upload files to the server.  The files are not restricted to the type of file.  Everything works in Firefox etc, but safari tries to open the file in a new window resulting in gibberish for filetypes it does not understand.  I can "save linked file" and everything works fine. However for usability I want the file to download automatically when the link is clicked.  I used carrierwave to upload the files.
Here is what My link looks like
<%= link_to document.name,"#{document.file}"%>

A: @Stefan answered this in the comments.
in Gemfile:
gem 'mime-types'

in the uploader file generated by carrierwave:
require 'carrierwave/processing/mime_types'

class MyUploader < CarrierWave::Uploader::Base
  include CarrierWave::MimeTypes

  process :set_content_type
end


text:
Q: How to increase value of a text variable in a file file1.text contains below data.
VARIABLE=00
RATE=14
PRICE=100

I need to increment value by 1 only for below whenever I want.
VARIABLE=00  file name: file1.txt
output should be incremented by 1 every time.
output will be like below
VARIABLE=01
in next run VARIABLE=02 and so on....

A: Could you please try following, written and tested with shown samples in GNU awk.
awk 'BEGIN{FS=OFS="="} /^VARIABLE/{$NF=sprintf("%02d",$NF+1)} 1' Input_file > temp && mv temp Input_file

Explanation: Adding detailed explanation for above.
awk '                             ##Starting awk program from here.
BEGIN{                            ##Starting BEGIN section of this program from here.
  FS=OFS="="                      ##Setting FS and OFS as = here.
}
/^VARIABLE/{                      ##Checking condition if line starts from VARIABLE then do following.
  $NF=sprintf("%02d",$NF+1)       ##Adding 1 last field and saing it to last field with 2 digits value.
}
1                                 ##1 will print the current line.
' Input_file > temp && mv temp Input_file                      ##Mentioning Input_file name here.

A: You can do it quite simply as a one-liner in Perl:
perl -i -pe '/^VARIABLE=/ && s/(\d+)/$&+1/e' file

In case you are unfamiliar with Perl, that says...

Run Perl and modify file in-place. if you come to any lines containing VARIABLE=, substitute the digits on that line with an expression calculated as "whatever the number was +1"

Note that Perl is a standard part of macOS - i.e. automatically included with all versions.


text:
Q: Task List and Back Stack with Android O Picture in Picture mode Has anyone got any experience or advice on managing back stack and tasks in PiP mode for android O?
Entering PiP mode seems to detach the activity from the current task stack. And exiting doesn't restore it.
Chrome seems to handle the back stack correctly when using PiP in that you enter pip mode, can navigate around other apps, restore pip to full screen and press back to end up back in the web page. You also don't see Chrome in the task list whilst it's in PiP mode. Is there something I'm missing or is Chrome doing something special or possibly only using a single activity for a Tab and full screen video?
Basically I want restore the entire app and it's back stack at the point we entered PiP when coming back from PiP.

A: Unfortunately, none of the Google apps (YouTube, Duo, Chrome) have this issue because they tend to use only a single Activity, and so when entering or leaving PiP there is no task issue in the recents menu because there is only ever a single task with a single Activity in it. This is why you do not see any entry in the recents menu for these apps when they are in PiP mode; it is being hidden by the APIs.
If you use multiple Activities in your app, then you will run into this issue. This is especially common given that most apps out there will use a new Activity in the task that launched their application to house their video playback.
The best solution I have found is to make your video player Activity be in its own task (set a unique task affinity) and hide it from the recents menu. This results in expected behaviour when entering and exiting PiP as well as allowing the user to navigate throughout the rest of your app (via the other tasks) without interfering with the PiP task. Unfortunately, this means that users will not be able to re-enter your video player from the recents; if the users uses the home or recents buttons, the video player task will end up being destroyed and your player Activity will be finished.
    <activity
            android:name=".YourVideoPlayerActivity"
            android:resizeableActivity="true"
            android:configChanges="keyboardHidden|screenSize|smallestScreenSize|screenLayout|orientation"
            android:supportsPictureInPicture="true"
            android:launchMode="singleTask"
            android:taskAffinity=".YourVideoPlayerActivityTask"
            android:excludeFromRecents="true"
            android:noHistory="true"
            android:autoRemoveFromRecents="true" />


text:
Q: How to change video url for MPMoviePlayerViewController? I am developing for iOS 6 using Xcode 4.6.1 (Target is iPad)
I am trying to change the video URL when the user swipes the screen.
This is my ViewController.m file:
#import "ViewController.h"

@interface experiencesViewController () {
    MPMoviePlayerViewController *playerViewController;
    MPMoviePlayerController *player;
}

@end

...

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    NSString *url = [[NSBundle mainBundle] pathForResource:"video" ofType:@"mp4"];

    playerViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];

    player = [playerViewController moviePlayer];
    [player setMovieSourceType:MPMovieSourceTypeFile];
    player.fullscreen = YES;

    [player play];

    ...

}

...

Now, I want to change the video on a swipe event. I tried doing this:
- (IBAction)didSwipeLeft:(UITapGestureRecognizer *)recognizer {
    NSLog(@"Left");

    player.movieSourceType = MPMovieSourceTypeFile;
    player.contentURL = [NSURL URLWithString:@"video2.mp4"];

    [player prepareToPlay];
    [player play];
}

However, this doesn't work. The video stops playing and nothing happens after that. Any help would be highly appreciated.
Thanks :)

A: remove the [player play] because the video is not yet ready to play.


text:
Q: Adding parity to binary in other words Hamming code I have a binary number of 01000001
I would like to add 4 parity numbers to that binary code.
I have an array of 8 bits unsigned char arr[8];
each index has digit of the bit
ex:
arr[0] = 0
Using hammingcode so it should be 12 digits with the parity (8 + 4parity)
p[0] = sequence[10] + sequence[8] + sequence[6] + sequence[4] + sequence[2]

What i'm getting is 1110 and it should be 1001 for parity

A: I don't know what language you're using but it seems to use 0-based array indexing.
However, you are indexing arr from arr[1] to arr[8].


text:
Q: Crossing a bridge? Let's say you have to get to the other side of the river by using a hanging bridge or the like. Could you say:

You have to cross this bridge before you get to the other side

Is this correct?

A: Your sentence sounds like it's expressing a pre-requisite (something one is required to do in advance) for getting to the other side rather than explaining the means by which one gets to the other side. Compare:
"You have to take off your shoes before you enter my home."
"You have to walk up my front steps to enter my home."
"You have to walk up my front steps in order to enter my home."
So the sentence you're looking for is "You have to cross this bridge to get to the other side" or "You have to cross this bridge in order to get to the other side."


text:
Q: Why is it that i am still not able to create a new directory in sdcard after capturing an image for my app? public class EditUploads extends Activity implements OnClickListener {

    ImageView ivEditUploads, imgSave;
    EditText etxtPrice, etxtDescription;
    Spinner sCategories;

    PhotoDbAdapter ourHelper;
    Long pRowId = null;

    private String description, category, price, imagepath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_edit_uploads);

        findViewById();

        if (getIntent().hasExtra("byteArray")) {

            Bitmap b = BitmapFactory.decodeByteArray(getIntent()
                    .getByteArrayExtra("byteArray"), 0, getIntent()
                    .getByteArrayExtra("byteArray").length);
            ivEditUploads.setImageBitmap(b);

        }

        addItemsOnSCategories();
        addListenerOnSpinnerItemSelection();

        String _path = Environment.getExternalStorageDirectory() + "/Myfolder/"
                + System.currentTimeMillis() + ".jpg";
    }

    private void findViewById() {
        ivEditUploads = (ImageView) findViewById(R.id.ivEditUploads);
        imgSave = (ImageView) findViewById(R.id.imgSave);
        sCategories = (Spinner) findViewById(R.id.sCategories);
        etxtDescription = (EditText) findViewById(R.id.etxtDescription);
        etxtPrice = (EditText) findViewById(R.id.etxtPrice);

        imgSave.setOnClickListener(this);
    }

    public void addItemsOnSCategories() {

        sCategories = (Spinner) findViewById(R.id.sCategories);
        List<String> list = new ArrayList<String>();
        list.add("His");
        list.add("Hers");
        list.add("Kid's");
        list.add("Everything Else");

        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, list);
        dataAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sCategories.setAdapter(dataAdapter);
    }

    public void addListenerOnSpinnerItemSelection() {
        sCategories
                .setOnItemSelectedListener(new CustomOnItemSelectedListener());

    }

    @Override
    public void onClick(View v) {

        Bitmap sourceBitmap = ((BitmapDrawable) ivEditUploads.getDrawable())
                .getBitmap();

        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/Neatpicks");
        myDir.mkdirs();

        sendBroadcast(new Intent(
                Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://" + Environment.getExternalStorageDirectory())));

        Random generator = new Random();
        int n = 10000;
        n = generator.nextInt(n);
        String fname = "Image-" + n + ".jpg";
        File file = new File(myDir, fname);

        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, fname);
        Uri mCapturedImageURI = getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null,
                null);
        int column_index_data = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String capturedImageFilePath = cursor.getString(column_index_data);

        File mediaStorageDir = new File(Environment
                .getExternalStorageDirectory().getPath(), "Neatpicks");
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("Neatpicks", "failed to create directory");
                return;
            }
        }

        description = etxtDescription.getText().toString();
        category = sCategories.getOnItemSelectedListener().toString();
        price = etxtPrice.getText().toString();
        imagepath = capturedImageFilePath;

        PhotoDbAdapter saveUploads = new PhotoDbAdapter(EditUploads.this);
        saveUploads.open();

        if (pRowId == null) {

            long saveUpId = saveUploads.createEntry(description, category,
                    price, imagepath);
            saveUploads.close();

            if (saveUpId > 0) {
                pRowId = saveUpId;

                Intent uploads = new Intent(getApplicationContext(),
                        Mobile.class);

                startActivity(uploads);

            }

        }
    }

}

i had tried to use the mkdir methods however, i was still not able to see the images in a newly created folder...i am hoping someone would help point out my mistakes and guide me along cause i am fairly new to android programming. Thanks in advance!

A: Your app probably needs to request the WRITE_EXTERNAL_STORAGE permissions as described here, but you might also want to check your folder path.
In future you should report any exceptions or logcat entries you see and more detail in general about HOW the operation fails. Also try other things such as creating folders in your private data space using Environment. getDataDirectory()

A: You need to provide the permission to AndroidManifest.xml for STORAGE permissions.
Go to AndroidManifest.xml-> permission tab -> click add -> uses permission
Name:android.permission.WRITE_EXTERNAL_STORAGE and android.permission.READ_EXTERNAL_STORAGE if necessary.


text:
Q: Angular - ngFor over collection of objects that have an array property I have a class like this:
export class TableColumn {
  columnName: string;
  isToFilter: boolean;
  isToSort: boolean;
  isLink: boolean;
  linkUrl: string;
  columnData: any[];

constructor(
    columnName: string,
    isToFilter: boolean,
    isToSort: boolean,
    isLink: boolean,
    linkUrl: string,
    columnData: any[]) {
    this.columnName = columnName;
    this.isToFilter = isToFilter;
    this.isToSort = isToSort;
    this.isLink = isLink;
    this.linkUrl = linkUrl;
    this.columnData = columnData;
  }
}

You can see there is an array property here - columnData. My problem is when I use *ngFor directive to iterate over array of instances of this class like this:
 ngFor="let column of tableColumns"

the directive iterate not only through content of tableColumns but through content of columnData property in every instance as well.
I would like to know how to not iterate through content of property columnData.

A: You're saying you have an array of the TableColumn objects, and you want to loop over those, and then inside each of them also loop over the columnData array?
First, just so you know, you can write your class object like this to simplify things.  It compiles down to the exact same JavaScript. Look at this page to see what I mean.
export class TableColumn {
    constructor(
        public columnName: string,
        public isToFilter: boolean,
        public isToSort: boolean,
        public isLink: boolean,
        public linkUrl: string,
        public columnData: any[]
    ) { }
}

With some sample data like this in our controller:
public tableColumnList = [
  new TableColumn('one', true, true, true, 'google.com', [1,2,3]),
  new TableColumn('two', true, true, true, 'google.com', [4,5,6, 7, 8]),
  new TableColumn('three', true, true, true, 'google.com', [9, 10, 11])
];

You can just use nested *ngFor directives, like this.

{{tc.name}}

      {{data}}


text:
Q: Finding Network Analyst tools in ArcGIS Pro? I am trying to run some network analysis within 3D buildings to study handicap accessibility, best routes, emergency evacuation routes, etc. In ArcMap 10.3 there is a simple and easy to use toolbar that allows you to run the network analysis "on the fly" (directly to the map) and it is very quick to reset the start and end paths, restrictions, barriers, etc. With ArcGIS Pro so far I am able to run the network analysis, but it is very slow and requires individual inputs and outputs to be ran one at a time. With a large amount of starting and destination nodes this can be very tedious.
I was wondering if there is any way to get ArcGIS Pro to run the network analyst similar to the ArcMap 10.3 toolbar, or if there were any other options that can be used within ArcGIS Pro.

A: I do not have a Network Analyst license for testing but I can see a button for it on the ANALYSIS tab of the ribbon:

If this does not lead to the options that you seek, then I think you should consider posting an ArcGIS Idea.


text:
Q: nginx, gunicorn and django timing out I'm so confused!
I set everything up, my site was working for two days, and then suddenly today it stops working.
The only thing I changed was yesterday I was trying to serve PHP files so I installed PHP and uwsgi. It was late and I didn't realize what I was doing. It was from this website: http://uwsgi-docs.readthedocs.org/en/latest/PHP.html
# Add ppa with libphp5-embed package
sudo add-apt-repository ppa:l-mierzwa/lucid-php5
# Update to use package from ppa
sudo apt-get update
# Install needed dependencies
sudo apt-get install php5-dev libphp5-embed libonig-dev libqdbm-dev
# Compile uWSGI PHP plugin
python uwsgiconfig --plugin plugins/php

But didn't change any settings. Even after doing that, everything was still fine. However the next day, my site just doesn't load.
I tried a few things which didn't work. In my settings:
ALLOWED_HOSTS = ['*']

In my gunicorn.sh, I set TIMEOUT=60. However, when I try to access my site (lewischi.com), nothing even happens. But when I go to http://127.0.0.1:8000, I do see workers doing stuff and get a 404 error.
Using the URLconf defined in django_project.urls,
Django tried these URL patterns, in this order:

I'm not sure what's going on! nginx-error log isn't very helpful but the access log seems more useful.
From my nginx-access.log (it works, then stops working):
50.156.86.221 - - [25/Sep/2015:00:25:43 -0700] "GET /codeWindow.html
HTTP/1.1" 200 2081 "http://lewischi.com/" "Mozilla/5.0 (Windows NT 6.1; WOW64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36"
50.156.86.221 - - [25/Sep/2015:00:25:58 -0700] "GET /test.jpg HTTP/1.1"
404 208 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36"
192.168.2.6 - - [25/Sep/2015:16:42:19 -0700] "GET / HTTP/1.1" 200 9596 "-" "-"
192.168.2.6 - - [25/Sep/2015:17:24:44 -0700] "GET / HTTP/1.1" 200 9596 "-" "-"
192.168.2.6 - - [25/Sep/2015:23:28:51 -0700] "GET / HTTP/1.1" 200 9596 "-" "-"
192.168.2.6 - - [25/Sep/2015:23:29:02 -0700] "GET / HTTP/1.1" 200 9596 "-" "-"

From my supervisor log file:
supervisor: couldn't exec /home/lewischi/projects/active/django_project/gunicorn.sh: ENOEXEC
supervisor: child process was not spawned

ANY HELP would be greatly appreciated!!!! I feel like I should just uninstall uwsgi. I don't want to break anything so I'm asking for advice before I go messing things up.

I'm pretty new to this so I may be overlooking something obvious. My gunicorn debug mode output:
    "Starting "djangotut" as lewischi"
[2015-09-26 17:50:28 +0000] [2316] [DEBUG] Current configuration:
  proxy_protocol: False
  worker_connections: 1000
  statsd_host: None
  max_requests_jitter: 0
  post_fork: <function post_fork at 0x7faf049ec848>
  pythonpath: None
  enable_stdio_inheritance: False
  worker_class: sync
  ssl_version: 3
  suppress_ragged_eofs: True
  syslog: False
  syslog_facility: user
  when_ready: <function when_ready at 0x7faf049ec578>
  pre_fork: <function pre_fork at 0x7faf049ec6e0>
  cert_reqs: 0
  preload_app: False
  keepalive: 2
  accesslog: None
  group: 1000
  graceful_timeout: 30
  do_handshake_on_connect: False
  spew: False
  workers: 3
  proc_name: "djangotut"
  sendfile: True
  pidfile: None
  umask: 0
  on_reload: <function on_reload at 0x7faf049ec410>
  pre_exec: <function pre_exec at 0x7faf049ecde8>
  worker_tmp_dir: None
  post_worker_init: <function post_worker_init at 0x7faf049ec9b0>
  limit_request_fields: 100
  on_exit: <function on_exit at 0x7faf049f2500>
  config: None
  secure_scheme_headers: {'X-FORWARDED-PROTOCOL': 'ssl', 'X-FORWARDED-PROTO': 'https', 'X-FORWARDED-SSL': 'on'}
  proxy_allow_ips: ['127.0.0.1']
  pre_request: <function pre_request at 0x7faf049ecf50>
  post_request: <function post_request at 0x7faf049f20c8>
  user: 1000
  forwarded_allow_ips: ['127.0.0.1']
  worker_int: <function worker_int at 0x7faf049ecb18>
  threads: 1
  max_requests: 1
  limit_request_line: 4094
  access_log_format: %(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"
  certfile: None
  worker_exit: <function worker_exit at 0x7faf049f2230>
  chdir: /home/lewischi/projects/active/django_project
  paste: None
  default_proc_name: django_project.wsgi:application
  errorlog: -
  loglevel: DEBUG
  logconfig: None
  syslog_addr: udp://localhost:514
  syslog_prefix: None
  daemon: False
  ciphers: TLSv1
  on_starting: <function on_starting at 0x7faf049ec2a8>
  worker_abort: <function worker_abort at 0x7faf049ecc80>
  bind: ['0.0.0.0:8000']
  raw_env: []
  reload: False
  check_config: False
  limit_request_field_size: 8190
  nworkers_changed: <function nworkers_changed at 0x7faf049f2398>
  timeout: 60
  ca_certs: None
  django_settings: None
  tmp_upload_dir: None
  keyfile: None
  backlog: 2048
  logger_class: gunicorn.glogging.Logger
  statsd_prefix:
[2015-09-26 17:50:28 +0000] [2316] [INFO] Starting gunicorn 19.3.0
[2015-09-26 17:50:28 +0000] [2316] [DEBUG] Arbiter booted
[2015-09-26 17:50:28 +0000] [2316] [INFO] Listening at: http://0.0.0.0:8000 (2316)
[2015-09-26 17:50:28 +0000] [2316] [INFO] Using worker: sync
[2015-09-26 17:50:28 +0000] [2327] [INFO] Booting worker with pid: 2327
[2015-09-26 17:50:28 +0000] [2328] [INFO] Booting worker with pid: 2328
[2015-09-26 17:50:28 +0000] [2329] [INFO] Booting worker with pid: 2329
[2015-09-26 17:50:29 +0000] [2316] [DEBUG] 3 workers
[2015-09-26 17:50:30 +0000] [2316] [DEBUG] 3 workers

A: The problem is not with supervisord itself, few things to consider when dealing with Nginx, Gunicorn and Django in general:

*

*Make sure the user running the app process(minimum 1 user non root not including users created by default for e.g: Nginx, Postgresql. Changes with the stack) has the right permissions and ownership to achieve it's goals.

*When adding another app to your stack, you should first check the port it runs on by default, and change it to prevent port conflicts, keep in mind the difference between internal and external ports since you use Nginx as a proxy to Gunicorn(this is what causes most timeouts, happened to me several times at late night work), you can use Nginx as a proxy server and create many apps with different unique internal port for each app.

With the error log you provided for supervisor, it seems you're running your gunicorn.sh either with a user that doesn't have enough permissions or ownership, or executing with a wrong command.
Please provide the supervisor config file relevant to your app.
Update: seems his ip address changed.

A: Ah never mind. Thanks for your time.
It turned out that my ip address somehow changed which should not have happened.... Rookie mistake.


text:
Q: SQLite saving date 12/31/69? The dates in my sqlite in android is saving 12/31/69 instead of the actual date. I have this in my db adapter:
    + KEY_DATE + " DATETIME DEFAULT CURRENT_TIMESTAMP

In my activity i have
        Date date = new Date(cursor.getLong(cursor.getColumnIndex(mDbHelper.KEY_DATE)));
        mDateFormat = DateFormat.getDateInstance(DateFormat.SHORT);

When I do a Log.d("Debug", mDateFormat.format(date)) it outputs 12/31/69 what am I doing wrong?

A: mDateFormat is just a date format - you haven't used the value of date from the previous line anywhere. You want something like:
Log.d("Debug", mDateFormat.format(date));

Now that may still give the wrong value - but we can move on to that. It would really help if you'd show more of what's in your adapter than the partial statement you've got there. We haven't got nearly enough context.
EDIT: You're calling getLong, but you've got a default value of CURRENT_TIMESTAMP, which looks like it'll come out as text:

If the default value of a column is CURRENT_TIME, CURRENT_DATE or CURRENT_TIMESTAMP, then the value used in the new row is a text representation of the current UTC date and/or time. For CURRENT_TIME, the format of the value is "HH:MM:SS". For CURRENT_DATE, "YYYY-MM-DD". The format for CURRENT_TIMESTAMP is "YYYY-MM-DD HH:MM:SS".

It's unclear to me what you'd expect to happen when you fetch that value as a long... according to the documentation, the result is implementation-specific - I suspect it's returning 0, giving you a date of the Unix epoch, which would make sense with your output if you're in a time zone west of Greenwich.

A: Wild guess:

*

*you are in a timezone which is GMT minus something (edit: confirmed);

*the long you return is a number of seconds, which means you must multiply by 1000.

The Date constructor takes a number of milliseconds since epoch, not seconds.
Try and replace your first line with:
Date date = new Date(cursor.getLong(cursor.getColumnIndex(mDbHelper.KEY_DATE)) * 1000);


text:
Q: bootstrap nav-collapse wont show icon when collapsed

abc.def

1234

Mail Us

Live Chat

     Remote

Our Approach

Services

About Us

in this bootstrap navbar will collapse but the glyphicon wont showup when minimised..  Any Ideas or Suggestions..?

A: Your items were a little out of order, and you were missing the <a class="btn btn-navbar"... parts.

        abc.def

Mail Us

Live Chat

Remote

Our Approach

Services

About Us

and don't forget the collapsable plugin...


text:
Q: Is it possible to share some controllers, views and images across multiple website projects in visual studio 2013 I can create websites that use shared C# libraries.  I like this approach because it allows me to change the c# libraries and easily deploy the the changes to my customer's websites.
But now I'm finding that it would be very useful to have some controllers, views and images that I can share across multiple websites. In this way, as before, I can make changes and quickly and easily deploy them to all my clients.
Could someone please tell me if this is possible?

A: Any controller (implementing System.Web.Controller) that resides in an assembly in your bin folder will be considered, you do not need to do anything for this.
For Views you could use RazorGenerator: https://www.nuget.org/packages/RazorGenerator.Mvc/


text:
Q: LaTeX Error: Command \etalchar already defined Has anyone ever come across the following error, and how would I solve it? Quick googling did not seem to help, and I guess that the issue may not be with \etalchar (I don't define it ever), but some conflicting packages.
LaTeX Error: Command \etalchar already defined.
               Or name \end... illegal, see p.192 of the manual.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...

l.1 \newcommand{\etalchar}[1]{$^{#1}$}

?

A: A search of this site, http://tex.stackexchange.com/search?q=%5Cetalchar+ reveals that the command \etalchar exists already for use in bibliography applications. It is defined, for example, in the alphadin.bst file (https://github.com/youkan/abschlussarbeit-latex/blob/master/alphadin.bst)
If the OP was not himself defining the command explicitly, it could mean that there is a package conflict, in which two separate packages are both trying to define the macro \etalchar.
However, based on the comment from the OP, it appears that a redundant call was accidentally made to the bibliography, which had the effect of trying to execute the same set of code twice, containing the \etalchar definition.  Thus, an error was thrown, as a result of the redundancy.
Relevant part of alphadin.bst code:
FUNCTION {begin.bib}
{ et.al.char.used
    { "\newcommand{\etalchar}[1]{$^{#1}$}" write$ newline$ }
    'skip$
  if$
  preamble$ empty$
    'skip$
    { preamble$ write$ newline$ }
  if$
  "\begin{thebibliography}{"  longest.label  * "}" * write$ newline$
  newline$
  "% this bibliography is generated by alphadin.bst [8.2] from 2005-12-21"
  write$ newline$
  newline$
  "\providecommand{\url}[1]{\texttt{#1}}"
  write$ newline$
  "\expandafter\ifx\csname urlstyle\endcsname\relax"
  write$ newline$
  "  \providecommand{\doi}[1]{doi: #1}\else"
  write$ newline$
  "  \providecommand{\doi}{doi: \begingroup \urlstyle{rm}\Url}\fi"
  write$ newline$
}


text:
Q: How can I bind already existing socket in Python 2.7 on Linux? How can I sending packets through socket which I already created in my browser? I don't want to create new socket in Python, only bind socket as I mentioned earlier.

A: You cannot overtake an existing TCP connection from within another process without cooperation of the original process. With cooperation there are at least on UNIX like systems ways to transfer open file descriptors between processes. But to get this cooperation you would need to make changes to the browser.
But, your problem sounds like an XY problem. You should better ask about the original issue leading to this question.


text:
Q: Check that click isn't on grid elements I have a grid, there are: stackpanel, button and ~50% empty space.
I need to handle click only if it is not on button,stackpanel, only on empty space of grid.
How I can do this?

A: Here is example based on default template, with Grid named LayoutRoot.
private void LayoutRoot_Tap(object sender, GestureEventArgs e)
{
    if (e.OriginalSource == LayoutRoot)
        MessageBox.Show("You clicked on LayoutRoot!");
    else
        MessageBox.Show("You clicked on somewhere else!");
}

XAML
<Grid x:Name="LayoutRoot" ... Tap="LayoutRoot_Tap">


text:
Q: Passing parameters, pointer and adress problem I have some problem with passing parameters to function. Example:
#include <iostream>
using namespace std;

struct VShop
{
    bool index;
    char *fName;
    char *edName;
    char *genre1;
    char *genre2;
    double rating;
    double price;
};

void AddtoDB (VShop *Film, char *name, char *ed, char *genre1, char *genre2, double rating, double price, int *size, int *element);

int main()
{
    int size = 0, element = 0;
    VShop *Film = new VShop[size];

    AddtoDB(Film, "The Shawshank Redemption", "Frank Darabont", "Crime", "Drama", 9.2, 20, &size, &element);

    cout<<size; // ERROR!

    return 0;
}

void AddtoDB (VShop *Film, char *name, char *ed, char *genre1, char *genre2, double rating, double price, int *size, int *element)
{
    *size++;
    Film[*element].fName = name;
    Film[*element].edName = ed;
    Film[*element].genre1 = genre1;
    Film[*element].genre2 = genre2;
    Film[*element].rating = rating;
    Film[*element].price = price;
    *element=(*element+1);
}

Im getting error every time i wanna get size or element. What does it happen? Thanks.

A: There are several errors with your code. Firstly:
VShop *Film = new VShop[size];

size is 0 and which may fail and will not work when you try to access it.
Secondly:
*size++;

++ has higher precedence than * so it evaluates to:
*(size++);

while increments size and then dereferences the old value of size. You probably wanted:
(*size)++;

which increments the value of the int pointed to by size.

A: You have a big problem with memory here. Look:
You created array with zero size:
VShop *Film = new VShop[size];

Then you try to grow up size variable but did not change array size:
*size++; //must be (*size)++;

Array still has zero length, but you are trying to change some data of first(zero) element:
Film[*element].fName = name;

You must resize array before inserting new element in it like that:

*

*create new array with proper size;

*copy all data from old array to new;

*delete old array;

*replace pointer to old array with new one.

Another variant is using std::vector.
Anyway, read some books about memory management in c++, and c++ at all.

A:
Because ++ has greater precedence than *, this expression is
  equivalent to *(size++). Therefore, what it does is to increase the value
  of size (so it now points to the next element), but because ++ is used as
  postfix the whole expression is evaluated as the value pointed by the
  original reference (the address the pointer pointed to before being
  increased).

Try using just;
(*size)++;

This will cause the expression to be evaluated as the value pointed by size increased by one.


text:
Q: Not seeing any output when using a different classloader So here's my issue:
I have some code that is being called when a certain event happens on a DocuShare server.  I listen for the event in my own eventlistener.  So far so good, this works without issue.
This listener will call other code that is developed separately and resides in its own jar file.
Currently we have the overhead of always having to shut down the entire system to deploy a new version of one of those jars so it can be used.
So now I am trying to create a system that copies that jarfile (not on the classpath) to another temp location (so no jarlock), loads the jarfile in its own different classloader and executes it.  This way I can simply overwrite the original jarfile when a new version is developed.  The code will then see if there was a modification to the jarfile and do the same steps if that's the case.
I have done this successfully in a simpler setup (a servlet being called) so I know the approach of 'hot deploying' the jars works.
However, in this case, the code works fine up until I start using the separate classloader.
I can find the jarfile and check for differences and load the jarfile accordingly but when I try to access the class I don't get any output in System.out or System.err anymore.  The code in the jar is not being executed properly but I can't see why.
Extra info: the code is being executed in its own Thread
Overview of whats happening:

*

*DocuShare sends an event

*My listener picks up the event

*The listener (implements java.util.concurrent.Executor) starts a new Thread (Runnable impl)

*The Runnable impl creates a new classloader and then checks if there is a new version of the jar file inside a folder, if so it will copy it to another dir, if not it uses the existing version, load it on the classpath of the new classloader and execute it

*Fromt the moment I load a class with the new ClassLoader I don't see any line printed in the System.out/System.err.

code example (in the Runnable.run() method):
URLClassLoader hotCL = new URLClassLoader(((URLClassLoader) systemCL).getURLs()); //new URLclassloader with URLs from system CL

//the following approach for putting the class on the classpath comes from another SO question from somebody else
Method m = cl.getClass().getDeclaredMethod("addURL", new Class[]{URL.class});
m.setAccessible(true);
m.invoke(cl, jar.toURI().toURL());
String cp = System.getProperty("java.class.path");
if (cp != null) {
    cp += File.pathSeparatorChar + jar.getCanonicalPath();
} else {
    cp = jar.toURI().getPath();
}

Logger.log(">>>>>>>> instantiating impl");  //this is printed in the System.out
Class<?> clsService = hotCL.loadClass(strService);  //strService is the class inside the separate jar
Object instance = clsService.newInstance();

Logger.log(">>>>>>>>>>>> class: " + clsService.getClass().toString()); //this is not printed in the System.out, neither is any log-statement after this or any error
//after this a method of the class instance is called but the code doesn't do anything.  Possibly an error but there's no error/stacktrace

Is there something I'm missing about ClassLoaders?  I just don't get why I don't see any error or code being executed.

A: Your classloader is probably hanging when it tries to load JDK classes that are referenced from your dynamic classes, because it needs a parent classloader capable of loading JDK classes. You can borrow a functional parent from the current context, i.e.:
new URLClassLoader(urls, this.getClass().getClassLoader())

Check out this thread if you run into problems after reloading classes that have already been instantiated.


text:
Q: Changing the dtype of a row in a dataframe A new dataframe is returned when the .describe() method is called on a dataframe.  In my project, the values in the "counts" row display as floats, with many zeros, which is ugly.  A count should be an int, since it is literally a count of the number of values.
I'd like the counts row to display as ints, but I can't find a way to change the dtype of a specific row.
Any suggestions would be greatly appreciated!  Thanks.
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(5,3))
df_stats = df.describe()

A: Use astype(object)
df_stats.astype(object)

              0          1         2
count         5          5         5
mean   0.551652   0.577811  0.494294
std    0.229048   0.312622   0.28331
min    0.185523  0.0350725  0.136097
25%    0.542329   0.651676  0.275079
50%    0.544838   0.652151  0.538186
75%    0.706685   0.713614   0.74606
max    0.778883   0.836541   0.77605

A: That simple:
df_stats.iloc[0].astype(int)

Or:
df_stats.loc['count'].astype(int)


text:
Q: html/javascript automaticly getting link from submit button (maybe automating with python?) I have a website where I have to click a submit button on a form. This gives me a link. I know the link is made up with the paramter that is passed through a hidden value. I was wondering if I could make a python script or something else that would go to the website and click some buttons returning the link that the submit button generates, if so how could I pass the extra parameter that influences the creation of the link?
thanks in advance.

A: If it is python you're looking for then give the Mechanize library a shot. If you are just extracting small but unique elements of the HTML document then you may as well use regex's with python. To work with the HTML document more pragmatically then BeautifulSoup may be more beneficial, which you can combine with mechanize/python.
It's more straightforward than it may initially seem.

A: Take a look at this documentation of the urlib2 package.  Below is the code you would use, but the documentation explains (very well) what is happening.
Excerpt:
import urllib
import urllib2

url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = {'name' : 'Michael Foord',
          'location' : 'Northampton',
          'language' : 'Python' }

data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()

You would need to use an HTML parser like BeautifulSoup to obtain the parameter name and value that is being posted when you click the button.
Edit:
Yes, you could use mechanize for this as well.  You would do something like this (untested):
from mechanize import Browser

br = Browser()
br.open("http://www.example.com/")  # this would be your website
br.select_form(name="order")        # change this to the name of your form
response = br.submit()              # submits the form, just like if you clicked the submit button
print response.geturl()             # prints the URL you are looking for

You'll need to make this specific to your website/form, but something along these lines should do the trick.
Check out the examples/documentation for the ClientForm object if you find you need more control.

A: Once you have downloaded your html data with mechanize as other users said, then you could use Beautifulsoup like this:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html_data)
hidden_tag = soup.find('input',name='hiddenId',type='hidden')
hidden_value = hiddenId['value']

then you could forge a POST with urllib2 like this:
import urllib
import urllib2
url = 'http://yoursite.com'
values = {'yourhiddenname' : hidden_value}
request = urllib2.Request(url, urllib.urlencode(values))
response = urllib2.urlopen(request)
result = response.read()


text:
Q: How to get the closing price of apple stock for the last Friday for each month? I want to get closing price of apple stock for the last Friday for each month. How can i do it ?  Thx
import pandas as pd
import numpy as np
import yfinance as yf
apple=yf.Ticker("AAPL")
apple=apple.history(period="5y")

A: Here's a way of doing it:
import pandas as pd
import numpy as np
import yfinance as yf

apple=yf.Ticker("AAPL")
apple=apple.history(period="5y")

apple['weekday'] = apple.index.weekday
apple['month_year'] = apple.index.to_period('M')
apple['date'] = apple.index

friday_groupy = apple[apple['weekday'] == 4].groupby(['month_year'])
apple.loc[friday_groupy['date'].idxmax()]

A: An example solution:
import pandas as pd
import yfinance as yf
import calendar

# create dataframe
df = yf.Ticker("AAPL")
df = df.history(period="5y")

df.head()

# define helper function for retrieving last fridays for a given year
def last_fridays(year):
    result = []
    for month in range(1, 13):
        last_friday = max(week[calendar.FRIDAY] for week in calendar.monthcalendar(year, month))
        result.append('{:4d}-{:02d}-{:02d}'.format(year, month, last_friday))
    return result

last_fridays = [frd for y in pd.DatetimeIndex(df.index).year for frd in last_fridays(y)]

# filter dataframe
df.loc[df.index.strftime('%Y-%m-%d').isin(last_fridays)]


text:
Q: Behavioral discrepancy in Tkinter listbox, arrow keys vs. mouse click My environment is Python 2.7, running on Windows 7.
I'm trying get a Tkinter Listbox to trigger a callback in response to the user changing the 'active' item (i.e. the item with focus).  I'm using a binding to the <<ListboxSelect>> event to make this happen, and it's working -- sort of.
The callback itself is supposed to check what the new active item is, and carry out some processing accordingly.  This logic operates the way I expect when I change the active item via the up/down arrow keys.  But when I point & click on a new item instead, the code mistakenly identifies the prior active item as the current one.
Here's a stripped-down code sample that illustrates the behavior I'm getting:
import Tkinter as tk

#Root window
root = tk.Tk()

#Callback to show focus change
def updateDisplay(*args):
    focusIndex = str(lb.index(tk.ACTIVE))
    ctrlFI.set('Focus is at index '+focusIndex)

#Control variables
ctrlLB = tk.StringVar()
ctrlFI = tk.StringVar()

#Widgets
lb  = tk.Listbox(root,
                 width=20, height=10,
                 relief=tk.FLAT,highlightthickness=0,
                 selectmode=tk.EXTENDED,
                 activestyle='dotbox',
                 listvariable=ctrlLB)
lbl = tk.Label(root,
               justify=tk.LEFT, anchor=tk.W,
               textvariable=ctrlFI)
lb.grid(row=0,column=0,sticky=tk.NW,padx=(5,0),pady=5)
lbl.grid(row=1,column=0,columnspan=2,sticky=tk.NW,padx=5,pady=5)

#Listbox binding to trigger callback
lb.bind('<<ListboxSelect>>',updateDisplay)

#Initializations to prep GUI
ctrlLB.set('Index0-entry Index1-entry Index2-entry Index3-entry Index4-entry')
ctrlFI.set('Ready')

#Begin app
tk.mainloop()

Here are the results when you use the arrow keys:

But here's what you get when you click with the mouse:

The information 'lags' one behind, showing the prior selection instead.  (If you click the same item a second time, it 'catches up.')
So my questions are:

*

*What is causing the discrepancy?

*How do I fix it so the mouse click gives the right result?

A: The active item is not necessarily the same as the selected item. When you press the mouse down it changes the selected value but it does not change the active item. The active item only changes once you release the mouse button.
You should be able to see this by clicking and holding the mouse button over an item that is not currently selected. When you do, you'll see something like this:

In the above image, the active item is the one surrounded by a dotted outline. The selected item is in blue. When your code displays the 'focus', it's displaying the active element rather than the selected element.
If you want the selected item, you need to use curselection to get the index of the selected item. It returns a tuple, so in extended mode you need to get the first element that is returned (eg: lb.curselection()[0]). Be sure to handle the case where curselection returns an empty string.


text:
Q: Previous attribute of backbone.js isn't persistent I'm trying to use the example mentioned for using the previous api in Backbone's Model. I've pasted the example below
var bill = new Backbone.Model({
  name: "Bill Smith"
});

bill.bind("change:name", function(model, name) {
  alert("Changed name from " + bill.previous("name") + " to " + name);
});

bill.set({name : "Bill Jones"});

The previous value in the alert is Bill Smith which is correct. But if I try to access this in firebug by calling
bill.previous("name");

it is Bill Jones and not Bill Smith. Why is it so? What am I missing ?

A: Well, if you look at Backbone's source, you'll see that the _previousAttributes attribute in Backbone.Model is reset to a copy of the current attributes after the 'change' events have been fired (in the change method: this._previousAttributes = _.clone(this.attributes);).
I think I've seen issues on Github about this behavior before; it's unexpected to a lot of people.
Edit: found it; a quote from the author in https://github.com/documentcloud/backbone/pull/373 :

I'm afraid that the current behavior is how things are supposed to work. Previous attributes are only available during the course of a "change" event. Without this, the entire notion of hasChanged() makes no sense.
If you're looking for more robust undo-like functionality, I'd recommend keeping a true list of previous versions of the model.


text:
Q: from import adds another execution of functions Created a python 'library' module which contains functions that I use a lot. Importing this module into a script which does a test using
from 'library name' import *

However whenever I import the test script using
from 'script name' import *

All the function calls in the test script execute twice.
I'm pretty sure this is an import issue, but I don't know enough about python to fix it.
Example:
Library.py
doSomething()
    print "Library"

Test.py
from Library import *
doSomething()

This will output:
  "Library"
  "Library"

A: You need to add the following at the button of your module to eliminate running your module as a script
if __name__ == '__main__':
    execution code here

This will tell Python what code to run when you are executing your module as a script. Otherwise, it will just load the module namespace
Python's main docs

'main' is the name of the scope in which top-level code executes. A module's name is set equal to 'main' when read from standard input, a script, or from an interactive prompt.
A module can discover whether or not it is running in the main scope by checking its own name, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported.

A: It was an issue related to python's logging function. logger.getLogger(name)


text:
Q: Errors while creating SAS hash join with complex comparisons from sql I am trying to write a SAS hash join from a proc sql.
The proc sql is like this:
    proc sql;
        create table output_table as
        select a.*
                , b.var1
                , b.var2
                , b.var3
                , b.var4
        from big_table as a
             , LIB.small_table as b
        where a.keyval1     ge  b.key1
            and a.keyval1   lt  b.key2
            and a.keyval2   ge  b.key3
            and a.keyval2   lt  b.key4
    ;
    quit;

So, when keyval1 in table a is greater or equal key1 in table b AND lower than key2 in table b,
AND keyval2 in table a is greater or equal key3 in table b AND lower than key4 in table b,
THAT is what I want to join on.
This makes it very complicated for me to write a hash join. I have no experience in this.
Sofar, I made this, but it is wrong:
    data output_table;
        drop rc;
        if _N_ = 1 then do;
        dcl hash cpohash(dataset: 'LIB.smalltable');
        cpohash.definekey('key1', 'key2', 'key3', 'key4');
        cpohash.definedata('var1', 'var2', 'var3', 'var4');
        cpohash.definedone();
        end;
        set big_table;

        rc=cpohash.find();
        do while (rc=0);
            if  key1 <=  keyval1   <  key2
                and   key3   <=    keyval2   <=   key4 then output;
        rc = cpohash.find_next();
        end;

    run;

I can't find any information on how to create a complex hash join like this. SQL isn't good enough as one of the tables is exceptionally large (even after dividing it into 20 pieces).
Please, can you help me get the correct code or point out a website which explains such complex SAS hash joins?

A: A hash join is not the right solution here, unfortunately, at least not the way you have it written.  A hash join requires an exact match; basically what's happening behind the scenes is the "key" is hashed (converted into a single string using a formula, similar to MD5 or SHA algorithms) and then SAS looks up the hash of the find-key in the stored table.  Because the hashing process makes totally different results for similar but not identical keys, you can't do any sort of math here - you have to look up specific values.  So in your case you are looking up the 4 keys, but they aren't actually exact matches in table A.
Depending on the actual numbers behind your data, though, it's possible there could be a solution that works.
If, for example, key1 and key2 aren't too far apart, and key3 and key4 aren't too far apart, then what you could possibly do is create a table C, that has all of the possible exact matches from A.
data c;
  set b;
  do keyval1 = key1 to key2;
    do keyval2 = key3 to key4;
       output;
    end;
  end;
run;

Something like that.  This is possibly really big, so please think about this before doing it.  But if it's not too big, then you now have a table C that contains all of the values you're looking for.  Then, you can do a straightforward hash table lookup.  You also could just do the SQL code, most likely, as there's a good chance SQL would choose a hash join anyway on the back end.
The other thing I would do, if this is not feasible, is look at indexes on table A that might make the query more feasible.  There are things you might be able to do to help SQL along, like if there are a bunch of rows in A that are before/less than any table B row, you could filter those out, or similarly rows that are after/greater than any table B row.


text:
Q: Wrong byte is written to file I am writing a few bytes to a newly created file in Visual Basic.
The following code is executed:
compressedFileStream.WriteByte(&H00)
compressedFileStream.WriteByte(&H00)
compressedFileStream.WriteByte(&H00)
compressedFileStream.WriteByte(&H00)
compressedFileStream.WriteByte(&H00)
compressedFileStream.WriteByte(&HD5)
compressedFileStream.WriteByte(&H55)
compressedFileStream.WriteByte(&H6E)
compressedFileStream.WriteByte(&H49)

Unfortunately the output is not what I wrote. Using Notepad++ I see this result:

Creation of compressedFileStream:
Using compressedFileStream As FileStream = File.Create(ArchivePath & ".zip")

The D0 and B5 are wrong. After those two bytes that magically appeared it will continue with the correct bytes (55, 6E and 49). Did anyone actually experience this or does anyone know what can cause this?

A: I tried your code and it works as expected.  Is there any other process that takes place after the WriteByte statements are executed?
Or, perhaps Notepad++ is playing tricks on you.


text:
Q: Preview image before upload with Carrierwave I have a form where user can create new pictures. I've successfully done it with Carrierwave. I was wondering is it possible to preview selected image in browser before upload? I've found some try outs with javascript but didn't work for me.
This is the code for image upload with CARRIERWAVE:
<%= form_for @photo, :html => {:multipart => true} do |f| %>

  <%= f.file_field :image %>

    <%= f.label :name %>

    <%= f.text_field :name %>

    <%= f.label :description %>

    <%= f.text_area :description %>

    <%= f.submit "Save Photo" %>

<% end %>

My goal is to have one small thumbnail of image so user can see it before upload. I am guessing I can't use Rails here because it could be only for server side...
Any ideas? :)

A: If you are using bootstrap 3 there is an awesome extension for it here
http://jasny.github.io/bootstrap/javascript/#fileinput

A: I've found a lot of success in using Transloadit: https://transloadit.com/ and handing that off to Carrierwave on the success call. There is also a transloadit gem that makes things even easier: https://github.com/transloadit/rails-sdk. Using this method will give you a preview, modal, loading bar, and a bunch of other options you can turn on or off for a great user experience. It has the same options for resizing or cropping that carrierwave does, or you can hand it off to carrierwave to do it for you. Your jquery callback to your controller might look something like:
updateAttachment: function(fileName, attachmentType) {
      var self = this;
  $.ajax({
    type: "PUT",
    url: <your update url>,
    data: {
      attachment: {
        file: fileName
      }
    },
    success: function() {
      location = self.windowLocation();
    },
    error: function() {
      self.showError("Error uploading file.");
      location = self.windowLocation();
    }
  });
}


text:
Q: Kendo Grid Export To Excel With Border Currently kendo grid can easily export it's data to excel but doesn't show border among the columns at all. How can I format the excel worksheets so that the data will be in full border? Are there any setting related to worksheet customization in order to achieved that? Thanks
You can view some examples by kendo in the link below:
http://demos.telerik.com/kendo-ui/grid/excel-export#

A: You can edit a few things about the data rendering such as right to left allignement but you can't customize the style of the worksheet.
From the kendo grid documentation about customization of the Excel exported from the kendo grid and it's limitations:
Limitations
Column Templates
The Grid does not use column templates during the Excel export—it exports only the data. The reason for this behavior is that a column template might contain arbitrary HTML which cannot be converted to Excel column values. For more information on how to use a column template that does not contain HTML, refer to this column template example.


text:
Q: How to apply damage to entities without instant damage effect? I want to be able to give an entity damage for a command I'm making, but instant damage effect is way too much, how do I apply other amounts of damage with command blocks?

A: 1.16+
Note: This data pack is in beta, and is in the works.  If you have any bugs please let me know, and I'll add it to the known bugs list.  Also, this is not tested in any version other then 1.16.4
I created a data pack that allows you to set health and  deal damage to a player(for mobs use data modify instead).  First off, you can get the data pack here.  After installing it, make sure it says in chat that it was installed.
How To Use
Dealing Damage
To damage a player, set that player's damage scoreboard to how much damage you want to apply(negatives heal players), then run the function editor:deal_damage as the player you want to damage and you are done.
Setting Health
To set the health of a player, set that player's sethealth scoreboard to what health you want that player to have, then run the function editor:set_health as the player you want to edit health and you are done.
Remember: 1 heart is 2 HP, and a half a heart is 1 HP, default max health is 20 HP(10 hearts)
The Commands
To damage players:
scoreboard players set <selector> damage <value>
execute as <selector> run function editor:deal_damage

To set player health:
scoreboard players set <selector> sethealth <value>
execute as <selector> run function editor:set_health

How It Works
What the data pack does is set the max health of the player to what health you want to set, and gives the player the instant health effect so it will update the player health, setting the player's health to max, then it sets the max health to be what it originally was.
Known Bugs

*

*A bug that shows the player as dead, even though they are not. (Its a Minecraft bug)

Incompatibilities
All Incompatibilities are being worked on to be compatible

*

*An existing helmet/item in the helmet slot with the max health attribute

Finding Bugs/Issues
Bugs
If you find any bugs, please report it.  Also add how you found the bug, so I can recreate it, and fix it, videos/screenshots of bugs are preferred.
Issues
If you have any performance issues while running the data pack, please report it.  Also add what performance issues you are getting, low tps, low fps, etc.  Videos/screenshots and computer specs do help!
Where to report
To report bugs/issues, use either comments on this answer, or the issues page on the GitHub download link.
Terms of Use
If you use this in a data pack to publish, I would like for you to put the GitHub link to the data pack somewhere for others who may want it, Thanks.  You are welcome to edit the data pack to whatever you want, just don't break it! :)