Q:

Php upload image to remote server with cURL

I would like to use cURL in php to upload an image to a remote image server. I have this piece of code, it's on the webserver:
<form enctype="multipart/form-data" encoding="multipart/form-data" method="post" action="webform.php">
<input name="somevar" type=hidden value='.$somevar.'>
<input name="uploadfile" type="file" value="choose">
<input type="submit" value="Upload">
</form>

and:
if (isset($_FILES['uploadfile']) ) {

 $filename  = $_FILES['uploadfile']['tmp_name'];
 $handle    = fopen($filename, "r");
 $data      = fread($handle, filesize($filename));
 $POST_DATA = array(
   'somevar' => $somevar,
   'uploadfile' => $data
 );
 $curl = curl_init();
 curl_setopt($curl, CURLOPT_URL, 'http://1.1.1.1/receiver.php');
 curl_setopt($curl, CURLOPT_TIMEOUT, 30);
 curl_setopt($curl, CURLOPT_POST, 1);
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($curl, CURLOPT_POSTFIELDS, $POST_DATA);
 $response = curl_exec($curl);
 curl_close ($curl);
 echo $response;

}

On the image server I've got an image upload handling php file, which worked very well on localhost, but I would like to use it on the remote server. This is how I handled the uploaded image file in the receiver.php:
move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)

I want to directly pass the image file to the remote server script, so this way I don't need to rewrite the whole upload script. I tried to post the image name, type, size as post variables, but I haven't got the ['tmp_name'] since it's not on localhost.
How can I solve this? Thank you guys for any help!

A:

Here's a possible solution;

Handle the upload on your web server and move the uploaded file to a local temp location
Then make a curl POST request to remote server and tell it what the uploaded file name & data is; as base64_encoded string
Remote server script receives the upload as a standard http post
All it now has to do is decode the file data, save it as the specified file name

So, this is how the solution looks like:
Sorry, i did not test this, but it should work.
index.php
<?php

// Handle upload
if(isset($_POST["submit"]))
{
    // Move uploaded file to a temp location
    $uploadDir = '/var/www/uploads/';
    $uploadFile = $uploadDir . basename($_FILES['userfile']['name']);
    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadFile))
    {
        // Prepare remote upload data
        $uploadRequest = array(
            'fileName' => basename($uploadFile),
            'fileData' => base64_encode(file_get_contents($uploadFile))
        );

        // Execute remote upload
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, 'http://1.1.1.1/receiver.php');
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $uploadRequest);
        $response = curl_exec($curl);
        curl_close($curl);
        echo $response;

        // Now delete local temp file
        unlink($uploadFile);
    }
    else
    {
        echo "Possible file upload attack!\n";
    }
}

?>

<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="index.php" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

Then, on the receiver.php, you can do the following:
// Handle remote upload
if (isset($_POST['fileName']) && $_POST['fileData'])
{
    // Save uploaded file
    $uploadDir = '/path/to/save/';
    file_put_contents(
        $uploadDir. $_POST['fileName'],
        base64_decode($_POST['fileData'])
    );

    // Done
    echo "Success";
}


Q:

Navigate to another man page within a man page

Say I have given man ls.
Within this man page I found another function/keyword that I wanted to check up. Say I found the function name by doing /fun_name. Now I want to see the man page of this fun_name. Only way I know of is to quit to present man page and do man fun_name.
Is there a shortcut?

A:

When inside the man page, do the following:

Press ! followed by a valid shell command.
For example : !man cat
You can exit by pressing q
It would say, !done  (press RETURN). You can either press ENTER key or continue pressing q to get out of the multiple man pages


Q:

Error 500 when using variables to instert to SQL database

I got this code, and it gives me an error 500.
I probaly got something wrong here, but i really need some help.
Here's my code
<?php include('index.php'); ?>
<?php include('config.php'); ?>
<?php
$fornavn = $_POST['fornavn'];
$efternavn = $_POST['efternavn'];
$postnummer = $_POST['postnummer'];
$alder = $_POST['alder'];

$sql = INSERT INTO medlemmer (fornavn, efternavn, postnummer, alder)
VALUES ('$fornavn', '$efternavn', '$postnummer', '$alder');

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();
?>

The POST tag is the same in index.php and so.
Please help.
Thanks in advance!

A:

You need to put your query in string "" first
<?php include('index.php'); ?>
<?php include('config.php'); ?>
<?php
$fornavn = $_POST['fornavn'];
$efternavn = $_POST['efternavn'];
$postnummer = $_POST['postnummer'];
$alder = $_POST['alder'];

$sql = "INSERT INTO medlemmer (fornavn, efternavn, postnummer, alder)
VALUES ('$fornavn', '$efternavn', '$postnummer', '$alder');";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();
?>

Also use prepared statement to prevent from sql injection
Turn PHP error ON so that you can get errors. Add following line in your PHP file
ini_set('display_errors',1);
error_reporting(E_ALL);


Q:

Is the title "The Last Jedi" singular or plural?

As we all know, the plural of Jedi is Jedi.
In my country (Poland) the local title ("Ostatni Jedi") also uses words that have the same singular and plural form, so it's not conclusive. How is it in other countries?
Could it be that the title of the movie refers not to a single Last Jedi (Luke Skywalker), but maybe to more than one person? Maybe including Rey, maybe Yoda, maybe the whole concept of "time for the Jedi to end"?

A:

Is the title “The Last Jedi” singular or plural?

Despite what some translations may suggest, the title is singular.
During an interview with ABC News, director Rian Johnson said:

It's so funny when people started asking that, when the title was announced, because I never even pondered that question ... That seems like, to me, the most uninteresting question ... In my mind, it's singular.

If one's to consider the director's opinion as the de facto answer, well, then, there it is.

A:

This is community-wiki, so please contribute!
Though Rian Johnson has stated the title is singular (as per Charles' answer), for the record, here's a list of international translations of The Last Jedi, categorized by whether they are singular, plural or indeterminate (such as in English or languages which do not have a singular/plural distinction at all). Titles with asterisks are taken from Wikipedia; those without are from the more official IMDB AKA page.
TO-DO:
Bosnia and Herzegovina (Bosnian title)  Posljednji Jedi
Malayalam                      സ്റ്റാർ വാർസ് : ദ ലാസ്റ്റ് ജെഡൈ *

PLURAL
Farsi (Iran)                   آخرین جدای
Bulgaria                       Последните джедаи
Estonia                        Viimased jedid
France (& Canada)              Les derniers Jedi
Hungary                        Az utolsó Jedik
Spanish-speaking countries     Los últimos Jedi
Portuguese-speaking countries  Os Últimos Jedi
French-speaking countries      Les derniers Jedi
German-speaking countries      Die letzten Jedi
Greece                         Οι τελευταίοι Τζεντάι
Italy                          Gli ultimi Jedi
Latvia                         Pēdējie Džedi *
Lithuania                      Paskutiniai Džedajai
Romania                        Ultimii Jedi
Russia                         Последние джедаи
Ukraine                        Останнi Джедаi
Serbia                         Poslednji džedaji
Israel                         אחרוני הג'דיי (Achroney haJedi)
Slovakia                       Poslední Jediovia

SINGULAR
Arabic                         الجيداي الأخير (Al-Jidai Al-Akheer)
Iceland                        Síðasti Jedinn *
India                          Aakhiri Yodha
Lithuania                      Paskutinis Džedajus [alternative] *
Croatia                        Poslednji Džedaj
Turkey                         Son Jedi
Georgia                        უკანასკნელი ჯედაი (Uk’anask’neli Jedai) *
Slovenia                       Poslednji jedi

INDETERMINATE
English (Original title)       The last Jedi
Poland                         Ostatni Jedi
Japan                          最後のジェダイ (Saigo no Jedai)
Korean                         스타워즈: 라스트 제다이
Taiwan                         最後的絕地武士 (Zuì hòu de Juédì Wǔshì) *
China                          最后的绝地武士 (Zuì hòu de Juédì Wǔshì) *
Vietnam                        Jedi Cuối Cùng
Czech Republic                 Poslední z Jediů
Thai                           สตาร์ วอร์ส: ปัจฉิมบทแห่งเจได  *

A:

The title of the film is spoken twice in a conversation late in the movie.

Luke Skywalker: I failed you, Ben. I'm sorry.
Kylo Ren: I'm sure you are! The Resistance is dead, the war is over, and when I kill you, I will have killed the last Jedi!
Luke Skywalker: Amazing. Every word of what you just said was wrong. The Rebellion is reborn today. The war is just beginning. And I will not be the last Jedi.

At a stretch Kylo’s comment could be using “Jedi” as a plural, grouping in the students he killed prior to Episode VII, but Luke’s response only makes sense if the word is singular (though he denies that he is truly the last).


Q:

Rails - Class not working for linkto to a controller/action

I needed to underline the active menu item for a submenu. I found I could use the following in my menu. I could do that by applying class:

<%= link_to "* RFQ", rfq_path(1), class: get_rfqs_class() %>

and have a helper item of
  def get_rfqs_class
    if controller_name == 'rfqs'
      return 'active'
    end
  end

I have a get_xxx_class() for each item and a corresponding helper.
That works great. However, I needed to do a little different link_to for another menu item

 <%= link_to "Pre Production Meeting",  controller:
'pre_production_meetings', action: 'show', id: 1 ,
op_id: $current_opportunity, class: get_pre_production_meetings_class() %>

The problem is that the different link_to format results in the underline not showing. If I do an inspect, it does show the class as active but I don't see the underline
Pre Production Meeting

I tried using divs and spans with the following code but had no luck.
   <% if controller_name == 'pre_production_meetings' then %>

 <%= link_to "Pre Production Meeting",  controller: 'pre_production_meetings', action: 'show', id: 1 , op_id: $current_opportunity, class: get_pre_production_meetings_class() %>

          <% else %>

 <%= link_to "Pre Production Meeting", controller: 'pre_production_meetings', action: 'show', id: 1 , op_id: $current_opportunity %>

          <% end %>

Is there something where using a link_to to a controller/action the way I did will prevent the class from being properly applied?
Also, I inspected the styles for a menu item that was working as expected
ul.art-hmenu>li>a.active {
    padding: 0 12px;
    margin: 0 auto;
    color: #145366;
    text-decoration: underline;
}

If I inspect the pre production meetings style, I don't see the a.active but see a.hover
ul.art-hmenu>li>a:hover, .desktop ul.art-hmenu>li:hover>a {
    color: #000000;
    text-decoration: none;
}

If I change the text-decoration to underline, then I see the underlining as expected.

A:

That instance of link_to uses this format:
link_to(body, url_options = {}, html_options = {})

You need to surround your url options in curly braces so the link looks like this:

Your class has been embeded into the url rather than the html.
This should solve your problem:
<%= link_to "Pre Production Meeting",
            {controller: 'pre_production_meetings', action: 'show', id: 1 ,
              op_id: @current_opportunity},
            class: get_pre_production_meetings_class() %>

Also, the $ is probably a typo.  I'm assuming it is an @.


Q:

How to ON or OFF audio recording using MediaRecorder

I'm implement one demo Video and Audio recording using MediaRecorder
Download the demo from hear : Android MediaRecorder Sample
There is one method prepareVideoRecorder() in MainActivity.java. in this method initialization and set Source Audio and video like:
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

Now i want to audio ON or OFF functionality.
For that i'll tried like this :
 if (!AppSetting.getValue(activity, Config.AUDIO, false)) {
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        }else {
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        }

But app is Crash with below error :
java.lang.IllegalStateException
at android.media.MediaRecorder.setAudioEncoder(Native Method)

So how to i solve this error or there is another solution for Audio ON or OFF:

A:

I Got the solution:

If my switch is ON then if part execute(Sound is record). if my switch is OFF then else part execute(Sound do not record).

if (AppSetting.getValue(activity, Config.AUDIO, false)) {
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setMaxDuration(duration);
            mMediaRecorder.setProfile(profile);
        } else {
            mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            mMediaRecorder.setOutputFormat(profile.fileFormat);
            mMediaRecorder.setVideoEncoder(profile.videoCodec);
            mMediaRecorder.setVideoEncodingBitRate(profile.videoBitRate);
            mMediaRecorder.setVideoFrameRate(profile.videoFrameRate);
            mMediaRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
            mMediaRecorder.setMaxDuration(duration);
        }


Q:

log4j 2 RollingFileAppender deleting content of log

The following configuration is supposed to create a new log file everyday:
<configuration status="trace">
  <appenders>

    <RollingFile name="RollingFile" fileName="../logs/excepciones.log" filePattern="../logs/excepciones.log.%d{yyyy-MM-dd}">
     <PatternLayout>
       <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
     </PatternLayout>
     <Policies>
       <TimeBasedTriggeringPolicy interval="1" modulate="true" />
     </Policies>
   </RollingFile>
 </appenders>
 <loggers>

   <root level="error">
    <appender-ref ref="RollingFile"/>
   </root>
   <root level="info">
     <appender-ref ref="RollingFile"/>
   </root>
 </loggers>
</configuration>

I do get a new file every day in the form excepciones.log-yyyy-MM-dd, the problem is that this new file contains only the last line that was inserted to excepciones.log before it was rolled to excepciones.log-yyyy-MM-dd, but I can't seem to figure out why. What I want is the whole content of today's log to be copied into a new file at 12:00 am.
So for example, yesterday, my log's content was:
this is line 1
this is line 2
this is line 3

Today, that file has been renamed to `excepciones.log-2014-07-07, but its content is now:
this is line 1

A:

What version of log4j2 are you using? Your problem description reminds me of LOG4J2-531 which was fixed in log4j2-rc1.


Q:

Using `pkg-config` as command line argument under cygwin/msys bash

I'm trying to use cygwin as a build environment under Windows. I have some dependencies on 3rd party packages, for example, GTK+.
Normally when I build under Linux, in my Makefile I can add a call to pkg-config as an argument to gcc, so it comes out like so:

gcc example.c `pkg-config --libs --cflags gtk+-2.0`

This works fine under Linux, but in cygwin I get:

:Invalid argument
make: *** [example] Error 1

Right now, I am just manually running pkg-config and pasting the output into the Makefile, which is truly terrible. Is there a good way to workaround or fix for this issue?
Make isn't the culprit. I can copy and paste the command line that make uses to call gcc, and that by itself will run gcc, which halts with ": Invalid argument".
I wrote a small test program to print out command line arguments:
for (i = 0; i < argc; i++)
    printf("'%s'\n", argv[i]);

Notice the single quotes.

$ pkg-config --libs gtk+-2.0
-Lc:/mingw/lib -lgtk-win32-2.0 -lgdk-win32-2.0 -latk-1.0 -lgdk_pixbuf-2.0 -lpang
owin32-1.0 -lgdi32 -lpangocairo-1.0 -lpango-1.0 -lcairo -lgobject-2.0 -lgmodule-
2.0 -lglib-2.0 -lintl

Running through the test program:

$ ./t `pkg-config --libs gtk+-2.0`
'C:\cygwin\home\smo\pvm\src\t.exe'
'-Lc:/mingw/lib'
'-lgtk-win32-2.0'
'-lgdk-win32-2.0'
'-latk-1.0'
'-lgdk_pixbuf-2.0'
'-lpangowin32-1.0'
'-lgdi32'
'-lpangocairo-1.0'
'-lpango-1.0'
'-lcairo'
'-lgobject-2.0'
'-lgmodule-2.0'
'-lglib-2.0'
'-lintl'
'

Notice the one single quote on the last line. It looks like argc is one greater than it should be, and argv[argc - 1] is null. Running the same test on Linux does not have this result.
That said, is there, say, some way I could have the Makefile store the result of pkg-config into a variable, and then use that variable, rather than using the back-tick operator?

A:

That said, is there, say, some way I could have the Makefile store the result of pkg-config into a variable, and then use that variable, rather than using the back-tick operator?

GTK_LIBS = $(shell pkg-config --libs gtk+-2.0)

A:

Are you sure that you're using the make provided by Cygwin? Use
which make
make --version

to check - this should return "/usr/bin/make" and "GNU Make 3.8 [...]" or something similar.


Q:

Android Textview Wraps and ugly formatting

I have created a android textview field .My problem is i want all text to come to new line as soon as there is a Enter or "/n" on the line .For Example :-
I have a text line below :-
 Twinkle, twinkle, little star,How I wonder what you are.
 Up above the world so high,Like a diamond in the sky.

I want this to come as shown below but when i use the below code it wraps the lines during runtime .Any Idea how can i do this .My Code is below
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".DisplayGanMessageActivity" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/title_activity_display_gan_message" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignLeft="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="18dp"
    android:text="
 Twinkle, twinkle, little star,How I wonder what you are.
 Up above the world so high,Like a diamond in the sky."/>

I got the below output from this :-
Twinkle, twinkle, little star,How I wonder what you are.Up above the world so high,Like a diamond in the sky

A:

Try this
<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignLeft="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="18dp"
    android:text="Twinkle, twinkle, little star,How I wonder what you are. \n Up above the world so high,Like a diamond in the sky."/>


Q:

Jetpack conditional navigation

I want to change my start navigation fragment based on a condition. My start fragment could be fragment one or two. Is there a way to implement it?

A:

Check out this question and its solution // Also added Java code here
Just converted Kotlin code to Java
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.home_nav_fragment);  // Hostfragment
NavInflater inflater = navHostFragment.getNavController().getNavInflater();
NavGraph graph = inflater.inflate(R.navigation.nav_main);
graph.setDefaultArguments(getIntent().getExtras());
graph.setStartDestination(R.id.fragment1);

navHostFragment.getNavController().setGraph(graph);
navHostFragment.getNavController().getGraph().setDefaultArguments(getIntent().getExtras());

NavigationView navigationView = findViewById(R.id.navigationView);
NavigationUI.setupWithNavController(navigationView, navHostFragment.getNavController());


Q:

"My last couple of years" — singular or plural?

Should I use "wasn't" or "weren't" in the following sentence?

My last couple of years as an Edison Eagle wasn’t all about fighting
  and bad friendships.

A:

Formal agreement requires weren’t. That’s because the subject of the sentence is the plural years, premodified by my last couple of. However, in terms of notional agreement, My last couple of years can be seen as an integrated whole that calls for a singular verb. Which you choose depends partly on your own view of the relative merits of formal and notional agreement, but also on the likely reaction of your intended audience to your choice.

A:

In most noun phrases with of it is the grammatical number of the head noun, not the noun in the prepositional phrase following it, that determines the grammatical number of the verb. So, we write:

The bottle of pills is missing.
The bottles of water are now cheaper.

But couple, in the noun phrase a couple of, is what the Cambridge Grammar of the English Language (p349) calls a number-transparent quantificational noun, meaning that it allows the number of the oblique to percolate up to determine the number of the whole NP. [Oblique is the term the CGEL uses for the noun in the prepositional phrase beginning with of, and NP stands for noun phrase.]
As well as a couple of, the CGEL lists a lot of, the rest of, plenty and others as number-transparent quantificational nouns.  The upward percolation is exemplified with the phrase a lot of:

A lot of money was spent on travel.
A lot of protesters were arrested.

On this basis it might seem clear that the OP's sentence should read:

My last couple of years as an Edison Eagle weren't all about fighting and bad friendships

since years percolates up to determine the plural of the verb. But, it is in fact not so clear, because plural nouns are often conceptualized as singular entities. That's why we say, for example:

Ten years is a long time.
$20,000 dollars is a lot of money.

The CGEL uses the term override for this common mismatch in grammatical number between subject and verb. So, if the writer is strongly conceptualizing the two years as a singular measure of time, then :

My last couple of years as an Edison Eagle wasn't all about fighting and bad friendships

would seem to be acceptable - although I suspect that rather more people would consider wasn't to be a mistake than weren't.

A:

This should definitely be weren't, as the subject of the sentence is years (which is plural). Without as an Edison Eagle, the sentence would be:

My last couple of years weren't all about fighting…

Adding as an Edison Eagle  will not change the basic sentence structure, so the sentence should still read:

My last couple of years as an Edison Eagle weren't all about fighting and bad friendships.


Q:

loading code from pastebin.com to tryfsharp.org

A page has a pastebin snippet embedded. I need a way to open tryfsharp.org with this snippet loaded in just by clicking a link at the page. It is possible if snippet is hosted at fssnip.net by using url in the following format "http://www.tryfsharp.org/Create?codeUrl={sourceurl}". When I insert pastebin url as parameter there, then completely wrong character set is loaded, including non-alphabetical characters.
For example, here http://pastebin.com/raw.php?i=hprEq4A8 is code "let a = 1", when I open this url http://www.tryfsharp.org/Create?codeUrl=http://pastebin.com/raw.php?i=hprEq4A8 , it should display code "let a = 1", instead it displays something completely wrong. Anyone managed to make this work?

A:

Use F# Snippets instead of Pastebin :-). If you post an F# snippet there, it will add colorization and tooltips (just like those you see in F# in Visual Studio) and you can load the snippet to Try F# too.
For example, this sample snippet has a "tryfsharp.org" link that takes you to Try F# and loads the snippet using the URL: http://www.tryfsharp.org/Create?codeUrl=http://fssnip.net/raw/iF
If you wanted to use Pastebin, then Pastebin needs to have clientaccesspolicy.xml file in the root (which tells Silverlight that accessing that domain is allowed). You can have a look at the file on fssnip.net So, this is not a feature request for Try F#, but for Pastebin.


Q:

Approaching of Milky way to M87

The Andromeda Galaxy is approaching the Milky Way at about 110 kilometres per second (68 mi/s).
What is the velocity that  Milky way  is approaching  M87  ?

A:

The Milky Way and M87 are moving apart at 1231 km/s.
http://ned.ipac.caltech.edu/cgi-bin/nph-objsearch?objname=M+87&img_stamp=yes&extend=no


Q:

If Statement Satisfied but not Entering?

I have some code that seems to behave as expected and occasionally satisfies an if loop I've created but the code never seems to enter the loop. Even where the if statement is satisfied.
The 'Warning' Messages a just to trigger a different font effect in the display box as the tool runs. The if statement on line 21 is the issue, though as I've said it triggers no errors.
BufferLayer = arcpy.da.UpdateCursor(Temp_Buff, ["OBJECTID"])
for Poly in BufferLayer:
    counta = Poly[0]
    arcpy.AddMessage("Assessing Intersection or Outlet {} of {}...".format(counta, total))
    arcpy.AddMessage("Isolating Intersection or Outlet...")
    # Selecting the Current Outlet from the master Layer
    arcpy.Select_analysis(Temp_Buff, Temp_Poly, "OBJECTID = {}".format(counta))
    # Clipping All Vertices
    arcpy.Clip_analysis(All_Points, Temp_Poly, Current_Points)
    # Identify and Sort Stream / River
    Points = arcpy.da.UpdateCursor(Current_Points, ["grid_code"])
    orders = []
    for Point in Points:
        orders.append(Point[0])
    orders.sort()
    countb = 1
    arcpy.AddMessage("Approximating Pour Point(s)...")
    # Append to Master List if a Pour Point, Delete Point if Not
    Points = arcpy.da.UpdateCursor(Current_Points, ["grid_code"])
    for Point in Points:
        arcpy.AddMessage("if {} == {} and {} >= {}".format(Point[0], orders[0], Point[0], Minimum_Stream_Order_To_Delineate))
        if Point[0] == orders[0] and Point[0] >= Minimum_Stream_Order_To_Delineate:
            if arcpy.Exists(Final_PP_Layer + "_O" + Point[0]):
                arcpy.AddWarning("Appending Pour Point to Respective Master Layer...")
                arcpy.Append_management(Point, Final_PP_Layer + "_O" + Point[0], "NO_TEST")
            else:
                arcpy.AddWarning("Creating New {} Order Master Pour Point Layer...")
                arcpy.CreateFeatureclass_management(Workspace, Final_PP_Layer + "_O{}".format(val), "MULTIPOINT", Current_Points, "DISABLED", "DISABLED", "PROJCS['NAD_1983_CSRS_New_Brunswick_Stereographic',GEOGCS['GCS_North_American_1983_CSRS',DATUM['D_North_American_1983_CSRS',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Double_Stereographic'],PARAMETER['False_Easting',2500000.0],PARAMETER['False_Northing',7500000.0],PARAMETER['Central_Meridian',-66.5],PARAMETER['Scale_Factor',0.999912],PARAMETER['Latitude_Of_Origin',46.5],UNIT['Meter',1.0]];-28216700 -23260100 10000;-100000 10000;-100000 10000;0.001;0.001;0.001;IsHighPrecision", "", "0", "0", "0")
                arcpy.AddWarning("Appending Pour Point to Respective Master Layer...")
                arcpy.Append_management(Point, Final_PP_Layer + "_O" + Point[0], "NO_TEST")

A:

@Hornbydd "Yeah it could be a duff path, your code does not show what Final_PP_Layer is so your concatenation of text may be invalid"
This was correct, python enters the loop with this syntax:
if arcpy.Exists(Final_PP_Layer + "_O{}".format(Point[0])):

Thank you!


Q:

__flash__removeCallback is undefined errors in IE9 while removing the dom element

probably the duplicate of '__flash__removeCallback' is undefined when deleting DOM element with Youtube iframe
I went through some sites but could not found the exact solution of why youtube throws this exception while removing the dom element with youtube iframe and what will be the solution??
Some solution that i have got are :

ytplayer.getIframe().src=''; -> I dont know how this could solve my problem?

2.$('#youtube iframe').attr('src', '');
    $('#youtube').remove() -> I have tried this but won't worked.
3.hide iframe before remove the parent element -> won't worked.
Please help me to resolve this issue.

A:

This appears to be an IE9-only bug.
It occurs when a Flash object interacts with a HTML document using JavaScript (ExternalInterface on the Flash/ActionScript-side) and rears it's ugly head when an IFRAME containing the HTML document w/ the Flash Object comes into play.
Seeing how you specify you're using the YouTube API, there is sadly nothing you can do to make sure the Flash unregisters itself and won't call JavaScript functions (or vice versa) when it's time to remove it as you rely on third party software running outside your applications domain.
If you don't NEED the YouTube API, but merely a quick way to get a video within your application, the safest bet is to use an old style object embed for IE9 and the API / IFRAME embedding for the rest of the sane world.
<object width="{WIDTH}" height="{HEIGHT}">
  <embed src="https://www.youtube.com/v/{VIDEO_ID}?version=3&autoplay=1"
         type="application/x-shockwave-flash"
         allowscriptaccess="always"
         width="{WIDTH}" height="{HEIGHT}"></embed>
</object>

Removing above object (you can use SWFObject's "embedSWF" and "removeSWF" just fine for this btw) will get the video player off your page, without throwing any _flash_remove.. warnings.
If you NEED the YouTube API / control over the video player state:
Have you tried invoking the "destroy"-method on the ytplayer ? Unvoke the destroy and while I'm reluctant to posting "answers" using timeouts, give the Flash object some time to unregister BEFORE your set the source of the iframe to an empty string (so the document unloads), then clear the iframe or it's parent container.
Though I remember from a previous project this drove us mad (the context being a single-page interface where videos were dynamically added and removed) and we resorted to writing our own Flash player fallback using the AS3 YT code. That's how annoying it got.


Q:

iPhone OS: Fetching a random entity instance using NSPredicate Nsfetchrequest and core data

Working on an app where I have a large collections of managed objects against which I want to fetch a few random instances.
My question is, is there any way I can use NSPredicate and NSFetchRequest to return several objects at random.
I saw that you could actually add a NSFetchRequest into the entity using the data modeler, any way to do the random fetch using this?
Also what would be the best method for determining the "count" of a table so I can set the bounds of the random number generator.
let me know if you need more details.
Thanks!
Nick

A:

Instead use the fetchLimit in conjunction with the fetchOffset that way you can efficiently fetch only a single entity into memory:
NSFetchRequest *myRequest = [[NSFetchRequest alloc] init];
[myRequest setEntity: [NSEntityDescription entityForName:myEntityName inManagedObjectContext:myManagedObjectContext]];
NSError *error = nil;
NSUInteger myEntityCount = [myManagedObjectContext countForFetchRequest:myRequest error:&error];

NSUInteger offset = myEntityCount - (arc4random() % myEntityCount);
[myRequest setFetchOffset:offset];
[myRequest setFetchLimit:1];

NSArray* objects = [myManagedObjectContext executeFetchRequest:myRequest error:&error];
id randomObject = [objects objectAtIndex:0];

A:

This may not be exactly how you implement this, but hopefully it will get you started.
Somewhere in your header or at the top of your implementation file:
#import <stdlib.h>
#import <time.h>

Elsewhere in your implementation:
//
// get count of entities
//
NSFetchRequest *myRequest = [[NSFetchRequest alloc] init];
[myRequest setEntity: [NSEntityDescription entityForName:myEntityName inManagedObjectContext:myManagedObjectContext]];
NSError *error = nil;
NSUInteger myEntityCount = [myManagedObjectContext countForFetchRequest:myRequest error:&error];
[myRequest release];

//
// add another fetch request that fetches all entities for myEntityName -- you fill in the details
// if you don't trigger faults or access properties this should not be too expensive
//
NSArray *myEntities = [...];

//
// sample with replacement, i.e. you may get duplicates
//
srandom(time(NULL)); // seed random number generator, so that you get a reasonably different series of random integers on each execution
NSUInteger numberOfRandomSamples = ...;
NSMutableSet *sampledEntities = [NSMutableSet setWithCapacity:numberOfRandomSamples];
for (NSInteger sampleIndex = 0; sampleIndex < numberOfRandomSamples; sampleIndex++) {
    int randomEntityIndex = random() % myEntityCount; // generates random integer between 0 and myEntityCount-1
    [sampledEntities addObject:[myEntities objectAtIndex:randomEntityIndex]];
}

// do stuff with sampledEntities set

If you need to sample without replacement, to eliminate duplicates, you might create an NSSet of randomEntityIndex NSNumber objects, instead of just sampling random ints.
In this case, sample from an ordered NSSet, remove NSNumber objects as you pull them out of the bag, and decrement myEntityCount for the purposes of picking a random NSNumber object from the set.


Q:

can i search from multi database in my model using django?

i have this code and work perfect .. but i want search in all my models how to do that ?
any idea for that ?
mycode
Models.py:
class OpratingSystems(models.Model):
# def etc ..
class AndroidGames(models.Model):
# def etc ..
class Antivirus(models.Model):
# def etc ..
class AndroidApks(models.Model):
# def etc ..
class PCgames(models.Model):
# def etc ..
class PCprogram(models.Model):
# def etc ..
class Homepage(models.Model):
# def etc ..

Views.py :
   def search(request):
    if request.method == 'GET':
        query= request.GET.get('q')
        submitbutton= request.GET.get('submit')

        if query is not None:
            lookups= Q(name__icontains=query) | Q(app_contect__icontains=query) | Q(page_url__icontains=query) | Q(app_image__icontains=query)

            results= Homepage.objects.filter(lookups).distinct()

            context={'results': results,
                     'submitbutton': submitbutton}

            return render(request, 'html_file/enterface.html', context)

        else:
            return render(request, 'html_file/enterface.html')

    else:
        return render(request, 'html_file/enterface.html')

html page :
     {% if submitbutton == 'Search' and request.GET.q != '' %}
 {% if results %}

  Results for {{ request.GET.q }} :

 {% for result in results %}
   {{result.name}}

 {{result.app_contect}}

 <big> See More & Download </big>

 {% endfor %}
 {% else %}

 No results for this search

 {% endif %}
 {% endif %}

this was my code and work in Homeoage model so how to use all model ?

A:

One solution would be by using the filter() methods and then combine all queries in a single with itertools.chain
if query is not None:

   query1 =Model1.objects.filter(title__icontains=query)
   query2 = Model2.objects.filter(modelfield__icontains=query)
....

#now you can combine all queries with this chain method

   from itertools import chain
   results= list(chain(query1,query2...)


Q:

Random word from text JavaScript/Ajax

I need to get 1 random word from text, but I don't now how to do it with Javascript.
Code:
function someFunction() {

    // something here

var word;

$.ajax({
     async: false,
     type: 'GET',
     url: link,
     success: function(data) {
        word = getWord(data); // get random word from data
     }
});

}

function getWord(text) {

// help me please)

}

I hope it's easy) Thanks all!

A:

Try something like this http://jsfiddle.net/Y9bCG/
alert(getWord("there is a book there"));
function getWord(data)
{
    var splits=data.split(' ');

    var randNumMax = splits.length-1;
    var randInt = (Math.floor(Math.random() * (randNumMax + 1)));
    return splits[randInt];
}


Q:

Settings, setting settings, and settings handlers

So, back in this question, I built a set of settings.  Now, I am trying to clean the entire system up.
This is the abstract base class:
public class SettingChangedEventArgs : EventArgs
{
    public int NewSetting { get; private set; }

    public SettingChangedEventArgs(int newSetting)
    {
        NewSetting = newSetting;
    }
}

public abstract class ApplicationSettingsProvider
{
    public abstract int GetCurrentSetting();
    public abstract void SetCurrentSetting(int setting);

    public event EventHandler<SettingChangedEventArgs> SettingChanged;
    public void OnSettingChanged(int newSetting)
    {
        var handler = SettingChanged;
        if (handler != null)
        {
            handler(this, new SettingChangedEventArgs(newSetting));
        }
    }
}

Here is a setting built on it:
public class ApplicationThemeProvider : ApplicationSettingsProvider
{
    public ApplicationThemeProvider()
    {
        ApplicationData.Current.DataChanged += (a, o) =>
        {
            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                OnSettingChanged((int)ApplicationData.Current.RoamingSettings.Values["Theme"]);
            });
        };
    }

    public override int GetCurrentSetting()
    {
        if (ApplicationData.Current.RoamingSettings.Values.ContainsKey("Theme"))
        {
            int value = (int)ApplicationData.Current.RoamingSettings.Values["Theme"];
            return (value >= 0 && value <= 2) ? value : 0;
        }
        return 0;
    }

    public override void SetCurrentSetting(int theme)
    {
        ApplicationData.Current.RoamingSettings.Values["Theme"] = theme;
        ApplicationData.Current.SignalDataChanged();
    }
}

I create an instance of the setting like this:
private static ApplicationSettingsProvider _ThemeProvider = new ApplicationThemeProvider();
private static HomePageVM Data = new HomePageVM(_ThemeProvider);
private static Settings settings = new Settings(_ThemeProvider);

public MainPage()
{
    this.InitializeComponent();
    SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;

    this.DataContext = Data;

    _ThemeProvider.SettingChanged += (s, e) => { Data.Theme = e.NewSetting; };
}

In the settings SettingsPane:
<StackPanel>
    <TextBlock FontSize="15" Margin="0,5">Text and background color:</TextBlock>
    <ComboBox Name="Theme" SelectionChanged="ThemeChanged">
        <ComboBoxItem Content="Black on White/Purple" Foreground="Black" Background="White"/>
        <ComboBoxItem Content="White on Black/White" Foreground="White" Background="Black"/>
        <ComboBoxItem Content="Black on White/Gold" Foreground="Black" Background="White"/>
    </ComboBox>
</StackPanel>

Which is handled like this:
private ApplicationSettingsProvider _ThemeProvider;

public Settings(ApplicationSettingsProvider themeProvider)
{
    this.InitializeComponent();

    _ThemeProvider = themeProvider;

    InitSettings();
}

private void InitSettings()
{
    Theme.SelectedIndex = _ThemeProvider.GetCurrentSetting();
}

private void ThemeChanged(object sender, SelectionChangedEventArgs e)
{
    _ThemeProvider.SetCurrentSetting(Theme.SelectedIndex);
}

In my VM for the Page:
private ApplicationSettingsProvider _ThemeProvider;

private int _theme = 0;
public int Theme
{
    get { return _theme; }
    set
    {
        if (_theme != value)
        {
            _theme = value;
            OnPropertyChanged();
        }
    }
}

public HomePageVM(ApplicationSettingsProvider themeProvider)
{
    _ThemeProvider = themeProvider;

    Theme = _ThemeProvider.GetCurrentSetting();
}

This is how I am using it in HomePage.xaml:
<ListBox Name="Items" Grid.Column="0" Grid.RowSpan="2" ItemsSource="{Binding ItemList}" DisplayMemberPath="Title" SelectionChanged="OnSelectionChanged"
         Tapped="Items_Tapped" Margin="-2,-2,0,-2" KeyDown="ItemsKeyDown" Style="{Binding Theme, Converter={StaticResource LBStylePick}}"
         ItemContainerStyle="{Binding Theme, Converter={StaticResource LBIStylePick}}" Padding="0,10" SelectedItem="{Binding CurrentItem, Mode=TwoWay}" />

I create my Converters like this:
<local:ThemeToLBStyleConverter x:Key="LBStylePick" />
<local:ThemeToLBIStyleConverter x:Key="LBIStylePick" />

And the C#:
public class ThemeToLBStyleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if ((int)value == 2) { return Application.Current.Resources["LBGold"]; }
        else if ((int)value == 1) { return Application.Current.Resources["LBDark"]; }
        else { return Application.Current.Resources["LBLight"]; }
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return new NotImplementedException();
    }
}

public class ThemeToLBIStyleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if ((int)value == 2) { return Application.Current.Resources["LBIGold"]; }
        else if ((int)value == 1) { return Application.Current.Resources["LBIDark"]; }
        else { return Application.Current.Resources["LBILight"]; }
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return new NotImplementedException();
    }
}

This looks rather complicated, although it is working perfectly.  In addition, I don't like how I am handling all the theme values with a plain int, an enum looks to be in order.  I am working on changing the ints to enums, but before I adjust every single thing that uses it, I would like to know if I should change this process in any way so all my work doesn't go to waste.
My other two settings can be viewed on PasteBin in the provided link.

A:

ThemeToLBStyleConverter and ThemeToLBIStyleConverter have identical code, save for the strings in the square brackets. They should both be subclasses of something else, with the strings as members.
In ApplicationThemeProvider, you should use .TryGetValue() rather than .ContainsKey() and a lookup.

A:

Your settings are very similiar and differ only in the name of the setting and the way you are retrieving the setting. This screams for injecting the setting name in the constructor in the baseclass and adding an interface for getting the values.
This could look like
public interface IIntegerSettingProvider
{
    int GetCurrentSetting();
}

public abstract class ApplicationSettingsProvider : IIntegerSettingProvider
{
    protected readonly string settingName;
    public ApplicationSettingsProvider(string settingName)
    {
        this.settingName = settingName;
        ApplicationData.Current.DataChanged += (a, o) =>
        {
         CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                OnSettingChanged((int)ApplicationData.Current.RoamingSettings.Values[settingName]);
            });
        };
    }

    public void SetCurrentSetting(int value)
    {
        ApplicationData.Current.RoamingSettings.Values[settingName] = value;
        ApplicationData.Current.SignalDataChanged();
    }

    public event EventHandler<SettingChangedEventArgs> SettingChanged;
    public void OnSettingChanged(int newSetting)
    {
        var handler = SettingChanged;
        if (handler != null)
        {
            handler(this, new SettingChangedEventArgs(newSetting));
        }
    }
}

The logic itself looks a little strange to me, although I don't know anything about windows phone development.
If a value is set by calling SetCurrentSetting() you are signaling a ApplicationData.Current.SignalDataChanged(); to which you had added a handler which then calls OnSettingChanged() which should by the way be protected instead of public.
Wouldn't it be easier to just call OnSettingChanged() from inside the SetCurrentSetting() method like:
public abstract class ApplicationSettingsProvider : IIntegerSettingProvider
{
    private readonly string settingName;
    public ApplicationSettingsProvider(string settingName)
    {
        this.settingName = settingName;
    }

    public void SetCurrentSetting(int value)
    {
        OnSettingChanged(value);
    }

    public event EventHandler<SettingChangedEventArgs> SettingChanged;
    protected void OnSettingChanged(int newSetting)
    {
        var handler = SettingChanged;
        if (handler != null)
        {
            handler(this, new SettingChangedEventArgs(newSetting));
        }
    }
}

This would lead for the ApplicationThemeProvider to
public class ApplicationThemeProvider : ApplicationSettingsProvider
{
    public ApplicationThemeProvider()
        : base("Theme")
    {}

    public int GetCurrentSetting()
    {
        if (ApplicationData.Current.RoamingSettings.Values.ContainsKey(settingName))
        {
            int value = (int)ApplicationData.Current.RoamingSettings.Values[settingName];
            return (value >= 0 && value <= 2) ? value : 0;
        }
        return 0;
    }
}

The only thing you would need to change in the classes which consumes the setting provider would be a cast of the provider to an IIntegerSettingProvider like
private ApplicationSettingsProvider _ThemeProvider;

public Settings(ApplicationSettingsProvider themeProvider)
{
    this.InitializeComponent();

    _ThemeProvider = themeProvider;

    InitSettings();
}

private void InitSettings()
{
    Theme.SelectedIndex = ((IIntegerSettingProvider)_ThemeProvider).GetCurrentSetting();
}

private void ThemeChanged(object sender, SelectionChangedEventArgs e)
{
    _ThemeProvider.SetCurrentSetting(Theme.SelectedIndex);
}

but hey we could do better than this. Why shouldn't we add the SetCurrentSetting() method and the SettingChanged eventhandler to the interface. If we do this we will use the interface here which is almost always better than coding against an implementation.
The interface would look like
public interface IIntegerSettingProvider
{
    int GetCurrentSetting();
    void SetCurrentSetting(int value);
    public event EventHandler<SettingChangedEventArgs> SettingChanged;
}

the ApplicationSettingsProviderfrom above can stay like it is.
The usage would then look like
private static IIntegerSettingProvider _ThemeProvider = new ApplicationThemeProvider();
private static HomePageVM Data = new HomePageVM(_ThemeProvider);
private static Settings settings = new Settings(_ThemeProvider);

public MainPage()
{
    this.InitializeComponent();
    SettingsPane.GetForCurrentView().CommandsRequested += OnCommandsRequested;

    this.DataContext = Data;

    _ThemeProvider.SettingChanged += (s, e) => { Data.Theme = e.NewSetting; };
}

and the handling like
private IIntegerSettingProvider _ThemeProvider;

public Settings(IIntegerSettingProvider themeProvider)
{
    this.InitializeComponent();

    _ThemeProvider = themeProvider;

    InitSettings();
}

private void InitSettings()
{
    Theme.SelectedIndex = _ThemeProvider.GetCurrentSetting();
}

private void ThemeChanged(object sender, SelectionChangedEventArgs e)
{
    _ThemeProvider.SetCurrentSetting(Theme.SelectedIndex);
}

This
public object Convert(object value, Type targetType, object parameter, string language)
{
    if ((int)value == 2) { return Application.Current.Resources["LBGold"]; }
    else if ((int)value == 1) { return Application.Current.Resources["LBDark"]; }
    else { return Application.Current.Resources["LBLight"]; }
}

does not look readable and can be improved by boxing object value only once and using some indentation like
private const string defaultResourceName = "LBLight";
public object Convert(object value, Type targetType, object parameter, string language)
{
    int current = (int)value;
    string resourceName = defaultResourceName;
    if (current == 2)
    {
        resourceName  = "LBGold";
    }
    else if (current == 1)
    {
        resourceName  = "LBDark";
    }

    return Application.Current.Resources[resourceName];
}

Stuffing single instructions on the same line than the ifcondition can IMHO be done only for a guard clause (separated by a new line) but doing this with an else ifand an else also reduces the readability to a minimum.


Q:

How to have a circular button with background image (Swift 4)

I have a circular button that I want to display an image through the photo library, but when I give it a background image it turns back into a square. I need to know how to have a button be both circular and contain a background image.

A:

Use
YourbuttonObject.layer.cornerRadius = YourbuttonObject.frame.height/2
YourbuttonObject.clipsToBounds = true

Now when you will set a backgroundImage it will be circular
or you can use a ImageView and use it like a button and set a backgroundImage for it and do
YourImageObject.layer.cornerRadius = YourImageObject.frame.height/2
YourIamgeObject.clipsToBounds = true


Q:

List index out of range (Python 2.7)

I feel like I am constantly having this problem when I am writing a program, what I want to do is iterate over every value in my nested list and say that if it's not a zero, make it one.
Here is the error I am getting:
Traceback (most recent call last):
  File "C:\Users\ryry3\Desktop\Python Projects\Games\Pygame Experiment\Sprint2.py", line 65, in <module>
    resetBoard()
  File "C:\Users\ryry3\Desktop\Python Projects\Games\Pygame Experiment\Sprint2.py", line 49, in resetBoard
    if board[i][j] != 0:
IndexError: list index out of range

Here is my full code:
import random

grid = [100,100]
board = [[0,0,0,0,0,0,1,0,0,0],
         [0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,1,0,0,0],
         [0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0],
         [0,0,0,5,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0]]

playerX = None
playerY = None
randX = 0
randY = 0

def getRandomGridPos():
    global randX, randY

    randX = int(random.uniform(0, grid[0]))
    randY = int(random.uniform(0, grid[1]))

def main():
    pass

def printBoard():
    print str(board[0]).replace(',', '')
    print str(board[1]).replace(',', '')
    print str(board[2]).replace(',', '')
    print str(board[3]).replace(',', '')
    print str(board[4]).replace(',', '')
    print str(board[5]).replace(',', '')
    print str(board[6]).replace(',', '')
    print str(board[7]).replace(',', '')
    print str(board[8]).replace(',', '')
    print str(board[9]).replace(',', '')

def resetBoard():
    i = 0
    j = 0

    while i < 10:
        if board[i][j] != 0:
            board[i][j] = 0
            j += 1
            print "Looping"
        if j == 10:
            j = 0
            i += 1
            print "J == 10"
        if i == 10:
            j = 0
            i = 0
            print "I == 10"
        else:
            j += 1

resetBoard()

Can someone help me find a solution and also help me not get this error anymore (explain why it happens)?

A:

UPDATE:
Sorry but I also encoutered another problem, my bad for not checking the code:
The final code should be:
while i < 10:
        if j == 10:
            j = 0
            i += 1
            print ("J == 10")
        elif board[i][j] != 0:
            board[i][j] = 0
            j += 1
            print ("Looping")
        else:
            j += 1

The problem I missed was that you should have checked the j boundary before trying to access the array, only then you should start the loop again.

The problem is in this part:
if j == 10:
            j = 0
            i += 1
            print "J == 10"
if i == 10:
            j = 0
            i = 0

if i = 9, j= 10 then we enter into the first if which changes i,j to be 10,10
Then the code continues and we enter the second if, thus reseting i and j making the loop go again and again...
Solve it by deleting the second if part, since the while condition will make sure we will never go to that case in the first place.


Q:

Can't get simple Bit Sequence Recognizer circuit to work (FSM)

This is a simple exercise for a Hardware course that I am taking. We are required to use Altera Quartus II and ModelSim to test the implementation; tools that I've never used before, so I might be missing something, and my explanations, lacking.
The circuit has 3 inputs (Data, Clock and Reset) and 2 outputs (Locked, Error). The sequence used in this exercise is 10001.
The problem ask to design a circuit that will recognize a sequence of bits. When the correct sequence is entered, you are granted access (the circuit enters the "UNLOCK" state; Locked output is 0). Otherwise, if at any point you enter the wrong bit, you trigger an alarm and you're supposed to remain in the "ERROR" state until the circuit is manually reset.
"Locked" is always 1 unless it gets to the "UNLOCK" state. "Error" is always 0 unless it gets to the "ERROR" state.
The circuit is supposed to always start out in a "RESET" state. Once it gets in the "UNLOCK" state, it stays there as long as the bits provided are 1, or goes to "RESET" if a 0 is encountered.
This is the state diagram that I've worked out:

Any help or ideas are welcome!
It turned out that almost all the logic behind my implementation is correct, the problem was a misunderstanding in using the CLRNs on the flip-flops and a typo in one of the assignments. As such, most of the images were removed to get rid of the clutter.
-- EDIT 1
With the following code (which should be correct), the waveform  is not as expected (at least the lock is not)
LIBRARY ieee;
USE ieee.std_logic_1164.all;

entity dlock is
    port
    (
        DATA  :  IN   STD_LOGIC;
        RESET :  IN   STD_LOGIC;
        CLOCK :  IN   STD_LOGIC;
        LOCK  :  OUT  STD_LOGIC;
        ALARM :  OUT  STD_LOGIC
    );
end dlock;

architecture bdf_type of dlock is

type STATE_type is (S_RESET, S1, S2, S3, S4, UNLOCK, S_ALARM);
signal state : STATE_type := S_RESET;

begin

process (clock) is
begin
  if (rising_edge(clock)) then
    -- `reset` always puts us back in the reset state
    if (RESET = '1') then
      state <= S_RESET;
    else
      case state is
        when S_RESET =>
          -- Reset; lock active and alarm off
          LOCK  <= '1';
          ALARM <= '0';
          if (DATA = '1') then
            -- Correct bit, proceed to next state
            state <= S1;
          else
            -- Incorrect bit; ALARM
            state <= S_ALARM;
          end if;
        when S1 =>
          if (DATA = '0') then
            state <= S2;
          else
            state <= S_ALARM;
          end if;
        when S2 =>
          if (DATA = '0') then
            state <= S3;
          else
            state <= S_ALARM;
          end if;
        when S3 =>
          if (DATA = '0') then
            state <= S4;
          else
            state <= S_ALARM;
          end if;
        when S4 =>
          if (DATA = '1') then
            state <= UNLOCK;
          else
            state <= S_ALARM;
          end if;
        when UNLOCK =>
          -- Lock inactive!
          LOCK <= '0';
          if (data = '0') then
            state <= S_RESET;
          else
            state <= UNLOCK;
          end if;
        when S_ALARM =>
          -- Alarm active in ALARM state
          ALARM <= '1';
      end case;
    end if;
  end if;
end process;
end bdf_type;

A:

Your reset, as written in the VHDL, is active low. This means you're holding the circuit in reset most of the time. Your data pattern looks like you thought your reset was active high.
Your error signal, insofar as I can see in the image of the waveform posted, is behaving correctly. Every time you exit reset for a cycle, your data is 0, which sends you to the error state. Of course this only persists for one cycle since you immediately reset again.
These are just glitches, if you zoom in you'll see that the phantom unlocks are happening for 0 time (or very small time periods depending on your gate models). This is one reason why the output of combinational logic isn't used for clocking data. Passing the value through a flip-flop will remove glitches.

EDIT:
Furthermore, your state assignment table and your state output table disagree with each other. One lists the Q values from Q2 downto Q0 and the other lists from Q0 to Q2, but both list the unlocked state as "110". This doesn't cause issues for the Error state since "111" reads the same forwards and backwards.
EDIT2:
As far as avoiding glitches... glitches are the nature of combinational logic.
You could have locked sourced directly from a flop without adding latency by having the input to a "locked" flop be dictated by the same preconditions of the unlocked state (i.e. locked_d = not((state=s4 or state=locked) and data=1) and use locked_q.
You could just avoiding having locked be a function of multiple state bits by converting the state machine machine encoding to a one-hot or hybrid one-hot (where there is a dedicated bit for the locked/error states because they drive output bits , but the other 5 states use 3 shared state bits).
Think of a state table like this:
Q4 Q3 Q2 Q1 Q0   State
 0  1  0  0  0   Reset
 0  1  0  0  1   S1
 0  1  0  1  0   S2
 0  1  0  1  1   S3
 0  1  1  0  0   S4
 0  0  X  X  X   Unlock
 1  1  X  X  X   Error
 1  0  X  X  X   X
 0  1  1  0  1   X
 0  1  1  1  X   X

Where Q4 is your error bit and Q3 is your locked bit
That said, avoiding glitches is usually not important because they don't cause problems when used in sequential logic as the D inputs or clock enables.


Q:

Good practices for handling a CDN in a CSS

h'm setting up a CDN on my website, and I have a question for which I couldn't find any answer.
I've CSS sprites, for instance (in my CSS file)
.social-icon-email_icon{ background: url('/img/sprite_social.png') no-repeat top left; background-position: 0 0; width: 32px; height: 32px; }

The thing is, I would like to have the sprite served by the CDN. Thus, I changed the url.
My problem is that I want to keep it as it is currently in local, but have it automatically switched to the CDN url when deployed.
So, what is the best practice ?

Two files, I deploy one on my production server, and I use the other for development. It seems problematic ; when I want to change something, I have to doit two times.
One dynamic file : not sure how to do it actually in CSS
Other ?

Thanks

A:

One way to deal with a thing like that, I have myself be doing a long time.
I serve my css file like this:
<link rel="stylesheet" type="text/css" href="css.php?ver=2">

Then, within the server side code, I do several replacements based on what version passed as argument, some browser sniffing whether to embed data in url's, like url(data:image/png;base64,...) and so on.
For your needs, you could mark your css values like this

background:url('/cdn_img/sprite_social.png')

and then it will be easy to do the replacement and change the "/cdn_" to "cdn.domain.com" or whatever you need.
I also use this solution to merge many css together into one, where I save a lot of callbacks to the server, one otherwise get with many link tags.
P.S. Using this, don't forget to set the ContentType to text/css


Q:

How to set a default value in a text_field?

I know this question has been asked a zillion times, but I still feel I'm missing something obvious. Given a model Address with a field city which we want to be initialized with a default value, say Awesome City.
What I've tried so far:
1) Default value in the view:
# @file: /app/views/addresses/_form.html.erb

<%= f.label :city %>

<%= f.text_field :city, :value => 'Awesome city' %>

This works but doesn't feel right. Also the user cannot change it, the value will still be Awesome city.
2) Overwriting the city method:
# @file: app/models/address.rb
def city
  self[:city] ||= 'Awesome city'
end

The field is rendered empty, so for some reason it doesn't work. If you try Address.new.city you get the default value though.
3) Assign the default value in the controller:
# address doesn't have a controller, we use nested forms
# belongs_to :parent
# @file: /app/controllers/parents_controller.rb
def new
  @parent = Parent.new
  @parent.build_address
  @parent.address.city = 'Awesome city'
end

This actually works but I don't think it should be in the controller, rather in the model.
4) Adding an after_initialize call (yes, it works, you don't have to overwrite the callback):
# @file: app/models/address.rb
after_initialize :set_default_city
def set_default_city
   self.city = 'Awesome city'
end

This works as well, but this will be called every time an object is instantiated as well, which we don't want.
5) JavaScript, this seems like an extreme measure, it should be easier than this.
Bottom line: what's the best way to add a default value? Everytime I have to give a field a default value it seems I'm trying to hard for such a simple thing. Are there other options which I'm missing?
Edit:: I'm using Rails 3.1.4 with Ruby 1.8.7/1.9.2

A:

You can define it in your migration file:
class CreateAddress < ActiveRecord::Migration
  def change
    create_table :addresses do |t|
      ...
      t.string :city, default: "Awesome City"
      ...

      t.timestamps
    end
  end
end

Other option is to define it in the new action, in your controller, which is more flexible... So, when you create a new address it will be started with the default value....
 def new
   @address = Address.new
   @address.city ||= "Awesome City"
   ...
 end

EDIT - possible solution to define default value in the model:
before_save :set_default_city
def set_default_city
   self.city ||= 'Awesome city'
end


Q:

MPAndroidchart rounded edges for colorized HorizontalBarChart

I want to make a colorized HorizontalBarChart with rounded edges using MPAndroidChart. I'm trying to change HorizontalBarChartRenderer for my chart for it. Here is my code:
HorizontalBarChart initialization:
List<Float> values = new ArrayList<>();
List<Integer> colors = new ArrayList<>();
// initializing

float[] valuesArray = new float[values.size()];
for (int i = 0; i < values.size(); i++) {
    valuesArray[i] = values.get(i);
}
List<BarEntry> yValues = valuesArray.length <= 0
    ? Collections.<BarEntry>emptyList()
    : Collections.singletonList(new BarEntry(valuesArray, 0));
BarDataSet barDataSet = new BarDataSet(yValues, "");
barDataSet.setColors(colors);
barDataSet.setValueFormatter(new ValueFormatter() {
    @Override
    public String getFormattedValue(float value, Entry entry,
        int dataSetIndex, ViewPortHandler viewPortHandler) {
            return "";
        }
});
chartView.setData(new BarData(new String[]{"sleep"}, barDataSet));

And extended HorizontalBarChartRenderer:
@Override
protected void drawDataSet(Canvas c, IBarDataSet dataSet, int index) {
    // ...
    c.drawRoundRect(new RectF(buffer.buffer[j], buffer.buffer[j + 1] + 10, buffer.buffer[j + 2], buffer.buffer[j + 3] - 10), 20, 20, mRenderPaint);
}

The result is:
How can I make rounded edges only for outer sides?
Something like this:

A:

I found a solution. My idea is to draw data as usual and after clearing some areas to make the edges rounded.
My code:
public class CircleHorizontalBarChartRenderer extends HorizontalBarChartRenderer {

    public CircleHorizontalBarChartRenderer(BarDataProvider chart, ChartAnimator animator, ViewPortHandler viewPortHandler) {
        super(chart, animator, viewPortHandler);
    }

    @Override
    protected void drawDataSet(Canvas c, IBarDataSet dataSet, int index) {
        Transformer trans = mChart.getTransformer(dataSet.getAxisDependency());

        mShadowPaint.setColor(dataSet.getBarShadowColor());

        float phaseX = mAnimator.getPhaseX();
        float phaseY = mAnimator.getPhaseY();

        // initialize the buffer
        BarBuffer buffer = mBarBuffers[index];
        buffer.setPhases(phaseX, phaseY);
        buffer.setBarSpace(dataSet.getBarSpace());
        buffer.setDataSet(index);
        buffer.setInverted(mChart.isInverted(dataSet.getAxisDependency()));

        buffer.feed(dataSet);

        trans.pointValuesToPixel(buffer.buffer);

        int length = buffer.buffer.length;
        float left = 0;
        float right = 0;
        float top = buffer.buffer[length - 3];
        float bot = buffer.buffer[length - 1];
        boolean leftSaved = false;

        for (int j = 0; j < buffer.size(); j += 4) {

            if (!mViewPortHandler.isInBoundsTop(buffer.buffer[j + 3]))
                break;

            if (!mViewPortHandler.isInBoundsBottom(buffer.buffer[j + 1]))
                continue;

            // Set the color for the currently drawn value.
            // If the index is
            // out of bounds, reuse colors.
            int color = dataSet.getColor(j / 4);
            mRenderPaint.setColor(color);
            if (color != 0 && !leftSaved) {
                leftSaved = true;
                left = buffer.buffer[j];
            }
            if (j > 4) { // it works but its ugly
                right = buffer.buffer[j - 2];
            }

            c.drawRect(buffer.buffer[j], buffer.buffer[j + 1] + 10, buffer.buffer[j + 2],
                    buffer.buffer[j + 3] - 10, mRenderPaint);
        }

        Paint erasePaint = new Paint();
        erasePaint.setAntiAlias(true);
        erasePaint.setStyle(Paint.Style.STROKE);
        int paintWidth = 20;
        erasePaint.setStrokeWidth(paintWidth);
        erasePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        c.drawRoundRect(new RectF(left - paintWidth / 2, top, right + paintWidth / 2, bot), 30, 30, erasePaint);
    }

}

PorterDuff.Mode.CLEAR will work only if you set layer type as software. So you need to call
setLayerType(View.LAYER_TYPE_SOFTWARE, null);

for chartView or for its parent view. If you don't need a transparent background, and background color in known, you can set this color for erasePaint, and do without sowtware layer type, which can worsen performance. And erasePaint.setXfermode also won't be needed for this case.
Final result:


Q:

Question regarding supremum of partially ordered sets

I have encountered a question while I was practicing the topic 'upper and lower bound of partially ordered sets'.

Let $\mathbb{Q}$ be the set of rational numbers.  Let
$$
B = \{ x \in \mathbb{Q} : x < \sqrt[3]{3} \}
$$
Prove that $\sup{B}$ and $\inf{B}$ does not exists.

Here is my proof  to prove that $\sup{B}$ does not exists -
Let $r$ be any upper bound of  $B$.
Then $r$ is a rational number hence $r\not=\sqrt[3]3$
But there always exists
$p \in \mathbb{Q}$ such that $\sqrt[3]3 < p < r$  as $\displaystyle\lim_{m\to\infty}(r-\frac1m)=r$, hence for all large enough $m$ we have $\displaystyle\sqrt[3]3<r-\frac1m<r$ and we can take $\displaystyle p=r-\frac1m$ for some $m$.
Hence $r$ is an upper bound of $B$ but not the least one proving that  $\sup{B}$ does not exists.
$■$
How can we prove that $\sup{B}$ does not exists?
Can there exist a more formal proof ?
A detailed answer would be helpful.

A:

Let $r$ be an irrational number,
$B = \{ x \in \mathbb{Q} : x < r \}$ and
${q_n}$ a sequence within $B$ that converges to $r$.
Let $b$ be, within $\mathbb{Q}$, the least upper bound of $B$.
If $b < r$, then exists $n$ in $N$ with $b < q_n$.
So r < b.
Let $\left\{p_n\right\}$ be a sequence rationals $> r$ that converges to $r$.
Thus some $n$ in $N$ with $p_n < b$.
As $p_n$ is an upper bound of $B$, a contradiction ensues.
Thusforth one concludes within the rationals that $\sup B$ is fantasy.
How to generate the sequences.
Since Q is a dense subset of R, every not empty open set will contain a rational.
Whence for all n in N, there is a rational $q_n$ in (r-1/n, r).


Q:

Which is better in term of speed, Shark or spark

I am very confusing about this two.I know shark is same as hive with 100x faster, work on spark. I want to know main difference between spark and shark. Which is better mean faster.
When I have to use spark or when shark?????

A:

Spark is a framework for distributed data processing, you can write your code in Scala, Java and Python. Shark was renamed to SparkSQL and it is some kind of SQL engine on top of Spark - you write SQL queries and they are executed using Spark framework.
Here's Spark programming guide: https://spark.apache.org/docs/latest/programming-guide.html
Here's Spark SQL guide: https://spark.apache.org/docs/latest/sql-programming-guide.html
So if you write a Spark SQL query, it would be converted to Spark code and executed, which means that in general you can write a Spark code that would work with  the same speed or faster than Spark SQL query


Q:

Django CreateView autofill custom user

I want to use Django's GCBV CreateView to autofill the created_by field on my model with the current user. The official docs have a good example here but I'm using a custom user model and having trouble making it work.
Here's my current setup:
# models.py
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=200)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )

# views.py
from django.contrib.auth import get_user_model
from django.views.generic.edit import CreateView
from myapp.models import Author

class AuthorCreate(CreateView):
    model = Author
    fields = ['name']

    def form_valid(self, form):
        form.instance.created_by = self.request.get_user_model()
        return super().form_valid(form)

However upon form submission I get the error:
AttributeError at /posts/new/
'WSGIRequest' object has no attribute 'get_user_model'

If I don't try to auto-include the user the form works fine which is why I don't believe the problem is with my custom user config. Here's what that code looks like:
class PostCreateView(CreateView):
    model = Author
    fields = ['name', 'created_by']

A:

To fix the particular error you're seeing should be able to use the self.request.user directly as shown in the example you linked. (Assuming the custom user model is correctly set up.)
form.instance.created_by = self.request.user

The get_user_model function is generally used like this to access the User class:
from django.contrib.auth import get_user_model
User = get_user_model()

generally in place of
from django.contrib.auth.models import User


Q:

Android screen orientation bug

I am using android HTC HERO 2.1 version.
The activity I write :
<activity android:name=".gogogo"
          android:label="@string/app_name"
          android:theme="@style/Theme.mine"
          android:screenOrientation="landscape"
          android:configChanges="orientation">

let my orientation change to landscape.
However, I figured out that every time I pressed "power" button and then come back to my activity, it always start at portrait.
I tried the game : TEETER , which was written not by me. Has the same problem too, any one know how to fix it??
Edit: it always start at portrait. --> I mean, if you come back from power, you have to scroll down to do everything, there is something like screen lock.
You can see that there is a "status bar" at the top of the screen and at this time, the orientation is "portrait". So after You scroll the "screen lock" a little bit down, you can see the activity (such as TEETER) is at "portrait" state. When you scroll all the way down, the activity's orientation will suddenly change to the state "landscape".
So the conclusion is : My activity is forced to orient once. And I really want to know how to fix it!

A:

Hai Steven Shih:
Pls go through this page of developer guide.
http://developer.android.com/guide/topics/manifest/activity-element.html

and try this line
 android:windowSoftInputMode="stateUnspecified|adjustPan"


Q:

Spring Validation Displaying Custom Message

Validation in Spring 3.x using @Valid annotation:
Below is snippet from the messages_en.properties. I have a form having Username and Password field. When user does not enter anything in Username field, it displays both these messages one below other.
NotEmpty.loginBean.username=Username cannot be Empty
Size.loginBean.username=Size must between 5 to 50 characters.

Any HTML tag given in the message.properties is not interpreted.
NotEmpty.loginBean.username=
Username cannot be Empty

Above would display
 as it is.
Questions:
1) Is there any ways to interpret HTML tag and display its output?
2) Can i show single message though both validation fails?

A:

Ad. 1) Yes, use htmlEscape="false":
<form:errors path="nip" cssClass="error" htmlEscape="false" />

Ad. 2) This is actually JSR303's Achilles' heel - it can be done, but is neither easy nor clean (see this issue). Order of validating each annotated field is undefined, so trick is to use @GroupSequence and custom groups like described here or here.
Alternative solution would be to use custom annotation with @ReportAsSingleViolation, but it will not distinct NotEmpty and Size errors as it'll have its own error message.


Q:

Does dagrun_timeout interfere when backfilling / clearing old DAGs?

I have a DAG like below, with dagrun_timeout set to 4 hours. When I go to the UI and clear all the tasks from the start_date to present, all DAGs are set to the running state.
After 4 hours, any DAG that has not marked itself as successful will be marked failed, even if they have not actually started yet. I am wondering whether this is intended behavior.
Should I remove the dagrun_timeout and put timeouts on the task level, if I want to rerun DAGs in this fashion? Or should I use airflow backfill instead if I want to rerun all DAGs without the dagrun_timeout interfering?
Ideally I'd like to be able to use the UI since other team members will want to rerun DAGs.

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': datetime(2019, 5, 1),
    'email': ['lol@example.com'],
    'email_on_failure': True,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=1),
}

dag = DAG(
    dag_id='example_dag',
    default_args=default_args,
    max_active_runs=8,
    schedule_interval='15 * * * *',
    dagrun_timeout=timedelta(minutes=60*4),
)

A:

I think it's intended behavior, but just a misleading parameter name. It has been discussed on the mailing list before, see https://lists.apache.org/thread.html/7bda30f518bedbaaa763ba73a5e3bbe386cb0d090834c819f81c65ec@%3Cdev.airflow.apache.org%3E.
Moving the timeout to the task level is a fair alternative, just understand it will be a little different since you'd probably want to determine a reasonable timeout per task. If it's critical that you are alerted if DAG runs take longer than 4 hours in the ordinary (non-backfill) scenario, then I'd add 4 hour SLAs on all the tasks. When you clear tasks for backfill, it will immediately trigger the SLA misses, but at least they should all happen at once in bulk and won't fail your runs.


Q:

SP metadata: certificate for signing and encryption

The specification says that:
Metadata for the OASIS Security Assertion Markup Language (SAML) V2.0

2.4.1.1 Element <KeyDescriptor>
The <KeyDescriptor> element provides information about the   cryptographic key(s) that
  an entity uses to sign data or receive  encrypted keys, along with additional
  cryptographic details. Its  KeyDescriptorType complex type consists of
  the following elements and  attributes:
use[Optional]
Optional attribute specifying the purpose of the key being described. Values are drawn from the KeyTypes enumeration, and consist of the values encryption and signing.
<ds:KeyInfo>[Required]
Optional element that directly or indirectly identifies a key.

As far as I know, for the sending of secure data in both directions, I should have:

My own private key
My own public key
Recipient's public key

Certificate of what key I should specifying in the SP- metadata and сan I use the same certificate for signing and encryption?
Vendor of IdP provided the so-called "metadata template" where indicated what and where should be spelled out.
Here is relevant part (verbatim):
...
<md:KeyDescriptor use="signing">
   <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
      <ds:X509Data>
         <ds:X509Certificate>
            <!--
             TODO It is necessary to insert here the certificate of the signature
             key of the service provider in X509 DER format and Base64 encoded
             -->
          </ds:X509Certificate>
      </ds:X509Data>
   </ds:KeyInfo>
</md:KeyDescriptor>

<md:KeyDescriptor use="encryption">
   <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
      <ds:X509Data>
         <ds:X509Certificate>
            <!--
             TODO It is necessary to insert here the certificate of the signature
             key of the service provider in X509 DER format and Base64 encoded
             -->
         </ds:X509Certificate>
      </ds:X509Data>
   </ds:KeyInfo>
</md:KeyDescriptor>
...

I do so:
...
<md:KeyDescriptor use="signing">
    <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <ds:X509Data>
            <ds:X509Certificate>
                MIID...ZiQ==
            </ds:X509Certificate>
        </ds:X509Data>
    </ds:KeyInfo>
</md:KeyDescriptor>
<md:KeyDescriptor use="encryption">
    <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <ds:X509Data>
            <ds:X509Certificate>
                MIID...ZiQ==
            </ds:X509Certificate>
        </ds:X509Data>
    </ds:KeyInfo>
</md:KeyDescriptor>
...

It does not work.
So, AFAIK for signing I should use the certificate of my private key, and for encryption I should use the certificate of the open key of IdP.
IMHO should be so.
...
<md:KeyDescriptor use="signing">
    <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <ds:X509Data>
            <ds:X509Certificate>
                <!-- certificate of my private key here-->
            </ds:X509Certificate>
        </ds:X509Data>
    </ds:KeyInfo>
</md:KeyDescriptor>
<md:KeyDescriptor use="encryption">
    <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <ds:X509Data>
            <ds:X509Certificate>
                <!-- certificate of the open key of IdP here -->
            </ds:X509Certificate>
        </ds:X509Data>
    </ds:KeyInfo>
</md:KeyDescriptor>
...

Am I right?

A:

Metadata of your own service should contain your public key with the certificate. And yes, you can use the same one for both signing and encryption.
When IDP wants to encrypt data to be sent to SP, it does so using public key of the SP. So there's no need to include "certificate of the open key of IdP" as an encryption key.
You mention that using the same key for both signing and encryption doesn't work, have you been able to get more details on what exactly fails and where?


Q:

Get all the file Contents of a repo at Specific Commit using PyGitHub

I want to get the file contents of all the files in the repo [changed and unchanged] using the Python [PyGitHub API]. But not sure how to achieve it. Simply, to browse the repo at that specific commit id in history.
Is there any other API to get the required data? or can  be done with PyGitHub itself.
Note: I'm using Github API v3.

A:

Provided you are not downloading a file too large (more than 1MB), as seen in PyGithub/PyGithub/issue 661, the idea is to:

request the Repository content at a specific commit
get the files returned by the first call

That is:
contents = repository.get_dir_contents(urllib.parse.quote(server_path), ref=sha)

Then:
for content in contents:
   if content.type != 'dir':
     file_content = repository.get_contents(urllib.parse.quote(content.path), ref=sha)
     // or
     file_content = repository.get_git_blob(content.sha)


Q:

Backbone model doesn't fetch response instant but renders view first

I've model with a parse function
var File = Backbone.Model.extend({
   ...
   parse: function(response) {
      console.log('Parsing response')
   }
});

var FileView = Backbone.View.extend({
  ...
  initialize: function(id) {
     this.file = new File({id: id.id});
     console.log('Fetching object')
     this.file.fetch();

     this.render();
   },

   render: function() {
      console.log('Rendering view');
      this.$el.html(this.template(this.file.JSON()));
   }
})

The expected result would be:
Fetching object
Parsing response
Rendering view

But this is what I got:
Fetching object
Rendering view
Parsing response

Why is this? According to the docs:

parse is called by Backbone whenever a collection's models are
  returned by the server, in fetch.

Why isn't the parse function called directly after fetching the model? How force it to do this?

A:

Yeah, but you're making an async call to the server to fetch the model, so render is actually being called before you get answer. You have to do, something like this:
this.file.fetch({success: function () {
    //call render here
}});


Q:

Are there non-periodic continuous functions with this property?

Suppose $ f$ is a real-valued continuous non-constant function defined on all of $ \mathbb{R}$. Let $ A = \text{image} f $. Suppose also that there is a  $L > 0$ such that for every half open interval $ I \subseteq \mathbb{R} $ with $| I | = L $, $\text{image} f|_{I} = A $. Must $ f$ be periodic?

A:

No; a counterexample is $x\mapsto \sin |x|$ with $A=[-1,1]$ and $L=4\pi$.


Q:

html form - how to call different php pages based on the button selected

Problem: How to make an HTML Form call different php pages from the action based on what button is pushed?
The code below is the solution I have now, but I figure there must be a better way to do this then creating multiple forms on the page?

    <form name="entry_form" action="entry_update_script.php" method="post" enctype="multipart/form-data">
        <input type="hidden" name="entry_id" value="">
        <input type="hidden" name="entry_item_id" value="">
        Truck/Railcar/Barge#:<input type="text" name="pro_number" value="">

        BOL #:<input type="text" name="bol" value="">

        <input type="submit" name="entry_submit" value="Add New Entry!">
    </form>
    <form name="entry_form_add" action="entry_view.php" method="post" enctype="multipart/form-data">
        <input type="hidden" name="entry_id" value="">
        <input type="submit" name="submit" value="Add New Item!">
    </form>

A:

    <form name ="sample" action="default.php">
         <input type="button" value = "blah1" onClick="submitAction('phpPage1.php')">
         <input type="button" value = "blah2" onClick="submitAction('phpPage2.php')">
    </form>


Q:

MPMoviePlayer-Notification doesn´t get called

HI,
i want to play a movie using MPMoviePlayerViewController and listen to a MPMoviePlayerPlaybackDidFinishNotification, but it doesn´t get called. Any ideas on that?
Would be helpful to get any hints on that.. Thanks you
Here´s my code:
NSString *url   =   [[NSBundle mainBundle] pathForResource:[sender contentName] ofType:@"m4v"];
    MPMoviePlayerViewController* moviePlayerController = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:url] ];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayBackComplete:) name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayerController];

    moviePlayerController.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
    [self presentMoviePlayerViewControllerAnimated:moviePlayerController];
    [moviePlayerController.moviePlayer play];
}

- (void) moviePlayBackComplete:(NSNotification*) notification {
    NSLog(@"moviePlayBackComplete complete");

    MPMoviePlayerController* moviePlayerController = [notification object];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayerController];

    [self dismissMoviePlayerViewControllerAnimated];
    [moviePlayerController release];
}

A:

You're trying to get notifications from a MPMovePlayerViewController but I'm pretty sure only MPMoviePlayerController provides them. Try and change your notification setup
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayBackComplete:) name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayerController.moviePlayer];


Q:

how to auto test a C program use files?

I have a C program and I need to test it using a file containing some test data and output the results automatically. How can I do this? Should I modify the program or should I write another program using C or something else like Python? Which is easier?
Here is my C program:
int main()
{
    double wh,sh,salary;
    int num = 0;
    int valid = 1;
    printf("Please input two non-negative numbers as a employee's working hours in one week and salary per hour.\n");
    printf("Notice that the salary per hour can't be greater than 1000\nAlso you can't input more than 10 sets of data\n");
    printf("Input them like this:\n20,34\nthen enter the Enter key\n");
    while(scanf("%lf,%lf",&wh,&sh) == 2 && num < 10)
    {
        if(sh <0 || wh <0)
        {
            printf("Salary per hour or salary per hour can't be negative!\n");
        }
        else if(wh > 168)
        {
            printf("Working hours in one week can't be more than 168!\n");
        }
        else if(sh > 1000)
        {
            printf("Salary can't be greater than 1000!\n");
        }
        else
        {
            num ++;
            if(wh <= 40)
            {
                if(sh <= 1000)
                {
                    salary = wh * sh;
                }
                else if(sh > 1000 )
                {
                    salary = wh * 1000;
                }
            }
            else if(wh > 40 && wh <= 50)
            {
                if(sh*1.5 < 1000)
                {
                    salary = 40*sh + (wh-40)*1.5*sh;
                }
                else if(sh*1.5 > 1000 && sh < 1000)
                {
                    salary = 40*sh + (wh-40)*1000;
                }
                else if(sh > 1000)
                {
                    salary = wh * 1000;
                }
            }
            else if(wh > 50)
            {
                if(sh*3 < 1000)
                {
                    salary = 40*sh + 10*1.5*sh + (wh-50)*3*sh;
                }
                else if(sh*1.5 < 1000 && sh*3 >=1000)
                {
                    salary = 40*sh + 10*1.5*sh + (wh-50)*1000;
                }
                else if(sh*1.5 >= 1000 && sh <= 1000)
                {
                    salary = 40*sh + (wh-40)*1000;
                }
                else if(sh > 1000)
                {
                    salary = wh*1000;
                }
            }
            printf("The total working hours is %lf, and salary per hour is %lf, salary is %lf\n",wh,sh,salary);
        }
    }
    return 0;
}

For this moment please ignore these literals floating around.
I suppose the file containing test data is like this:
1,2
34,34
67,43
...

I really have no idea how this test automation works,please help!

A:

in cmd prompt
enter
c:\>myprog.exe < input.txt > output.txt
put all ur testcases in input.txt
ur output will print in the output.txt file


Q:

Find a function f(x) that maximizes given integral

Problem. Given a functional
$J(f) = \int_0^{+\infty} e^{-3x} \ln(f(x)) dx \, .$
Find such a function $f(x)$ that maximizes the value of $J(f)$ under the following constraints:

$f(x) > 0$ for any $x$
$\int_0^{+\infty}f(x)dx = 1 \, .$

My thoughts. The constraints reminded me of the Exponential probability density function, which meets them perfectly:
$f(x) = \lambda e^{-\lambda x} \, .$
So I plugged it in and that worked great in a sense that I was able to find such a $\lambda$ for the Exponential distribution that delivers the maximum to $J(f)$ if we consider only functions of the above form. It turned out that the maximum is delivered by
$f(x) = 3 e^{-3x} \, .$
My question is: what's next? So I have some solution for $J(f)$, now how can I prove that there is no (or there is) some other function $f'(x)$ that delivers a greater value to $J(f)$?

A:

Euler Lagrange equation from calculus of variation gives $\frac{\partial (J(f) + \alpha (\int fdx -1))}{\partial f}=0$ which trivially gives the solution you have found. The $\alpha$ terms forces the constraint.


Q:

How to use LINQ to reduce a > to ?

I'm calling a method with a return type of Dictionary<string, List<string>>.
The way i'm calling it i expect the List<string> to always have just 1 string element. To simplify this i'd like to use Linq to convert the return type to Dictionary<string, string>.
I got as far as to use .ToDictionary(x => x.Key, x=> x.Value); but i'm stumped on how to get the correct values. Is a conversion like this possible with LINQ?

A:

Try with:
.ToDictionary(x => x.Key, x=> x.Value.FirstOrDefault());

The value of your dictionary is a List<string>, so you can use IEnumerable<T> extension methods. Now there is several options to get the first element. Take a look this article for more details


Q:

error: linker command failed with exit code 1

I get the error:
ndefined symbols for architecture x86_64:
  "_setVal", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1

I looked up other posts but nothing seems so solve the problem.
I think that I used include properly.
main.c:
#include "game.h"

int main(int argc, char *argv[]) {
setVal(board, 1, 0, 6);
}

game.h:
#ifndef GAME_H_
#define GAME_H_

bool SetVal(Board* board, int row, int col, int value);

#endif

game.c:
#include "game.h"

bool SetVal(Board* board, int row, int col, int value){
// code in here
}

What can be cause of the error?
Thank you.

A:

Typo:
int main(int argc, char *argv[]) {
    SetVal(board, 1, 0, 6);
//  ^
}


Q:

remove  background via css

I have an issue where I can't seem to get rid of the background colour of a p tag, is it possible to do this? I have set the divs backgrounds to images.
Output:

CSS
   .box {
display: inline-block; vertical-align: top; margin: -1px; text-align: left; padding: 25px;
}
#tables {
max-width: 1080px;
margin: 0 auto;
text-align: center;
}
#screenshots {
background: url(http://i.cubeupload.com/nAtNKD.jpg) no-repeat center;
width: 308px;
height: 280px;
}
#csmatches {
background: url(http://i.cubeupload.com/nAtNKD.jpg) no-repeat center;
width: 308px;
height: 280px;
}
#fixtures {
background: url(http://i.cubeupload.com/nAtNKD.jpg) no-repeat center;
width: 308px;
height: 280px;
}

HTML

Screenshots

Recent Match Results

Fixtures

A:

#csmatches p {
    background:none !important;
}


Q:

Why won't this CSS selector work for  when inside  tag?

I'm revising for my exam, going over answering some past questions without the markscheme. I am confused on this:
For the following rule, explain the effect and which elements will be affected:
p ul li {
   color:blue;
}

I wrote up some HTML on JSFiddle: http://jsfiddle.net/2nkmzgv2/
It's here anyway:

Should this be blue?

So nothing happens to the text. I would have thought it changes blue, but is nothing actually meant to happen and the purpose of the question was to throw you off or is my syntax/method wrong in the HTML content?

A:

It's because ol/ul items aren't allowed inside of p elements.
Should ol/ul be inside
 or outside?
Seems like a trick question for your exam then. Most likely you will want to brush up on the HTML spec since the question isn't truly based on CSS knowledge alone.
You are getting the described behavior because
 cannot contain block-level elements such as
 or
. The browser (e.g., Chrome) knows this is not possible and thus try to handle your illegal structure by placing your block element in between two paragraphs:

Because of this, the rule you have declared for that li does not apply.

p ul li {
  color: blue;
}

  Hello

I'm never blue.

  Goodbye

Other trick questions could be:
a a { color:red }
p p { color:blue; }


Q:

What if China did pay US tariffs?

The US president Donald Trump has repeated said that China will pay for the tariffs he has or plans to impose on Chinese goods entering the US. Many commentators has said that tariffs are paid at time of import by the importer, and that those costs are simply passed onto the consumer.
What would be the consequences if, instead of adding a tariff cost to the item being imported, the US Government instead deducted the same amount from the US debt that the Chinese Government owns? This would make it literally true that the Chinese are now paying for the trade deficit, and it would automatically stop once the Chinese no longer own US debt.
Besides making lenders extremely wary of buying US debt, what could be the economic repercussions from such a decision?

A:

the US Government instead deducted the same amount from the US debt that the Chinese Government owns

That would be equivalent to a partial sovereign default of the US: we don't like you, therefore our bonds you own are now worth less/crap.
More technically, it would be a repudiation of (some) sovereign debt:

Repudiation happens when the sovereign rejects its obligation to pay, which could
  happen before or after any payment is due. Governments typically avoid questioning
  the validity of their debts, or announcing their intention not to pay before missing a
  payment, since in practice, repudiation carries all the traumatic consequences of
  payment default [...]. Repudiation may go hand in hand with
  governments questioning the legitimacy of one or more obligations. The literature on
  “Odious Debt” includes a handful of examples (King 2016, Lienau 2014). In 2008,
  Ecuador claimed that two bonds issued by a previous government were illegitimate and
  pledged not to pay them. It launched a buyback offer the following year in the shadow
  of the illegitimacy claim, and ultimately secured nearly 2/3 debt relief with more than
  90 percent of the creditors participating.
[...]
Repudiation [...] is rare in modern times. Repudiations most often
  occur after a regime change, and examples of repudiations include those in the wake of
  communist revolutions—such as Russia in 1917, China in 1949, and Cuba in 1960; Rhodesia
  in 1965, after its unilateral declaration of independence from the United Kingdom; Zaire in
  1979; Ghana in 1979 and 1982; and North Korea in 1976.
Repudiation can go hand-in-hand with the concept of “odious debt,” which posits that a
  government is not obligated to pay for those debts incurred by a previous government contrary
  to the interests of the public. Though, the concept has strong moral appeal, it is difficult to
  define odious debt in a sufficiently limited way to allow its practical application (Reinhart and
  Rogoff 2009). The doctrine has not gained traction with arbitrators, courts, or credit rating agencies (Gelpern 2007; Blair 2014) and, the earlier example of Ecuador aside, states tend not to assert it explicitly.

As for effects, that's harder to predict. China would probably accelerate its sales of US treasuries, since the US move you propose is not going to impact all their holdings at once. The sooner they would sell, the fewer losses they would incur over time from the proposed US tax-like measure. On the other hand, selling too much too soon would hurt them too by dropping the price too much.
Russia substantially reduced its holding of US treasuries in 2018, presumably just based on fears:

Between March and May, Russia's holdings of US Treasury bonds plummeted by $81 billion, representing 84% of its total US debt holdings. [...]
"One theory is that this was Russia's revenge for US sanctions," said [Jason ] Bush [an analyst at consulting firm Eurasia Group].
Another theory is that Moscow feared further US sanctions that could cause its holdings of US debt to be frozen or even seized.

The Russian side didn't acknowledge this explicitly, but their central baker said something like

Russia assesses "all the risks: financial economic and geopolitical."

Russia however held a lot fewer US treasuries, only around 1/12 of China's even at their peak holdings. So Russia could sell the bulk of theirs relatively quickly.