text:
Q: How to fix a Joomla plugin manifest? I've developed a simple plugin for Joomla! 3.6 but I can't get it installed on my server. I tried different setup methods and after some researchs I think that the problem resides inside my XML manifest.
The error I get is:
Attention: JInstaller: :Install: Cannot find Joomla XML setup file
Error: Cannot find installation package

My XML manifest is the following:
<?xml version="1.0" encoding="utf-8"?>
<extension version="3.6" type="plugin" group="mygroup" method="upgrade">
<name>plg_mygroup_emailnotify</name>
<author>Frollo</author>
<creationDate>2017-01-25</creationDate>
<copyright>Copyright (C) 2017 Frollo</copyright>
<license>GNU General Public License version 2 or later; see LICENSE.txt</license>
<authorEmail></authorEmail>
<authorUrl></authorUrl>
<version>1.0.1</version>
<description>PLG_MYGROUP_EMAILNOTIFY_XML_DESCRIPTION</description>

<files>
    <filename plugin="emailnotify">emailnotify.php</filename>
    <folder>language</folder>
</files>

<config>
    <fields name="params">

        <fieldset name="PLG_FIELDSET_GENERAL">
          <field name="general_mailfrom_address"
                 type="email"
                 label="PLG_GENERAL_MAILFROM_ADDRESS"
                 description="PLG_GENERAL_MAILFROM_ADDRESS_DESC"
            />

            <field name="general_mailfrom_name"
                   type="text"
                   default=""
                   label="PLG_GENERAL_MAILFROM_NAME"
                   description="PLG_GENERAL_MAILFROM_NAME_DESC"
                   size="30" />

        </fieldset>
        <fieldset name="PLG_EMAILNOTIFY_FIELDSET_ESTIMATE">
          <field
            name="estimate_approve_link"
            type="text"
            default="http://wwww.example.com"
            />
        </fieldset>

    </fields>
</config>
</extension>

EDIT - Some other details:
I have had no troubles installing other plugins or components on the server. The directory structure is the following:
+ emailnotify
  + language
    + it-IT
      - it-IT.ini
  - emailnotify.php
  - emailnotify.xml

A: Your xml manifest file have unclosed <extension> root node.

A: The problem was in the last fieldset. The default url contained some GET parameters, in the form
http://www.example.com/index.php?param1=param1&param2=param2

The presence of the & broke the XML, replacing it with & fixed the XML


text:
Q: 4D (or higher) popular vtk or netCDF dataset I am looking for a 4 dimensional(or higher dimension) popular dataset for my term project in Scientific visualization. I searched on the Internet and found 3D only. Any idea

A: If you are just looking for something small, the latest versions of ParaView come with a data set named can.ex2 (look in the Examples directory). For somewhat larger data you can download some examples from https://www.unidata.ucar.edu/software/netcdf/examples/files.html. The file tos_O1_2001-2002.nc is technically a 2D time series, but ParaView can load it up as a sphere in 3D. The file rhum.2003.nc is a true 3D time series. Both of these files are loaded as "NetCDF files generic and CF conventions".

redpajama_set_name: RedPajamaStackExchange


text:
Q: Eclipse PDE Build plugins output some folders are jar-ed I am running eclipse PDE Build from ant file. I succesfuly get the product but in the ant generated product I get some folders in plugins directory jar-ed unlike the folders I get during the export product from eclipse.
What can be the reason to have the plugins as jar but not folder ? Is there a parameter to set ?
ilke

A: Yes, in the MANIFEST.MF file of each plugin, you can specify this property:
Eclipse-BundleShape: dir
By default the plugin is jar-ed. With this option, it is expanded as a directory during installation of the plugin.
Note: This option is available since Eclipse 3.5 only.


text:
Q: Passing Apollo Client cache data with apollo Query I have two queries:
const GET_FILTERS = gql`
  query getFilters {
    filters @client {
      id
      title
      selected
    }
  }
`

And
const GET_POSTS = gql`
  query getPosts {
    posts {
      id
      author
      status
    }
  }
`

First one fetches the data from a local state using apollo-link-state and the second one is a external call.
I have a HOC for fetching posts setup like this:
const withPosts = (Component) => (props) => (
  <Query
    query={GET_POSTS}
  >
    {({loading, data, error})} => {
      if(loading) return null
      if(error) return null
      return <Component {...data} {...props}/>
    }}
  </Query>
)

The fetching of the posts is fine but what I would like to do is to add whatever is returned from GET_FILTERS query with every call to GET_POSTS query?
One thing I could do is to wrap withPost in to another, lets say withFilters HOC, and pass the result in to GET_POSTS query as variables but I have been wondering if there is any other way to access that data via some sort of context and for example cache.readQuery using only withPost HOC.

A: Apollo has 'native' tools for HOC pattern, you can compose many (named) queries and mutations to enhance component. IMHO it's much more readable and powerfull than using query/mutaions components.
You can pass queried (filter) values as variables via data.fetchMore - of course you can use query component for 'inner query'.
Using cache directly isn't required while query 'cache-first' fetchPolicy option can be used.


text:
Q: How to copy a txt line into an ArrayList in java? I'm trying to read a text and saving every line it has into a new element of an ArrayList. Is there anyway to continue reading and adding in the ArrayList until it gets to the end of file or whenever the reader doesnt find any other line to read?
Besides, what's best to use? Scanner or BufferedReader?

A: Traditionally, you'd do these operations:

*

*Create an instance of a Scanner or BufferedReader

*Set conditions to continually read the file (with a Scanner, through scanner.hasNextLine(); with a BufferedReader, there's a little bit more work to do)

*Get the next line from either and add it to your list.

However, with Java 7's NIO library, you don't need to do that at all.
You can leverage Files#readAllLines to accomplish exactly what it is you want; no need to do any of the iteration yourself.  You do have to provide a path to the file and a character set (i.e. Charset.forName("UTF-8");), but it works essentially the same.
Path filePath = Paths.get("/path/to/file/on/system");
List<String> lines = Files.readAllLines(filePath, Charset.forName("UTF-8"));

A: Try using BufferedReader like this:
static List<String> getFileLines(final String path) throws IOException {

    final List<String> lines = new ArrayList<>();

    try (final BufferedReader br = new BufferedReader(new FileReader(path))) {
        string line = null;
        while((line = br.readLine()) != null) {
            lines.add(line);
        }
    }

    return lines;
}

*

*Create an empty list for the results to go.

*Use a try-with-resources Statement on the BufferedReader to safely open and close a file

*Read lines until the BufferedReader returns null

*return the list

A: FWIW, if you are using Java8, you can make use of the the stream APIs, as shown below
public static void main(String[] args) throws IOException {

    String filename = "test.txt"; // Put your filename
    List fileLines = new ArrayList<>();

    // Make sure to add the "throws IOException" to the method
    Stream<String> fileStream = Files.lines(Paths.get(filename));
    fileStream.forEach(fileLines::add);
}

I've a main method here, just put this in your method and add the throws statement or a try-catch block
You also could convert the above to a one liner as
((Stream<String>)Files.lines(Paths.get(filename))).forEach(fileLines::add);

A: Since you want to read an entire line from a particular text file, i would recommend you to use the BufferedReader class.
You can create a BufferedReader object like this:
BufferedReader br = new BufferedReader(new FileReader(filenName));//fileName is a string
//that contains the name of the file if its in the same folder or else you must give the relative/absolute path to the file

Then use the readLine() function on the BufferedReader object to read each line of the file.
You can try something like the following.
    try
    {
        //read each line of the file
        while((line = br.readLine()) != null)//if it reaches the end of the file rd will be null
        {
          //store the contents of the line into an ArrayList object
        }
    }catch(IOException ex)
    {
        System.out.println("Error");
    }

A: You might use
final List<String> lines =
   Files.lines(Paths.get(path)).collect(Collectors.toList());

or the variant with lines(Path, Charset).


text:
Q: Question about an absolute value inequality. The question states:
Given $g(x) = |x-2| - |x| +2$, express $g(x)$ without absolute value bars if $x$ is in given interval -
$1.$ $[2, +\infty)$
$2.$ $[ -\infty, 0)$
$3.$ $[0,2)$
So I found the correct answers to be: (a) $0$, (b) $4$, (c) $4-2x$.
I have tried this problem multiple times, and the x values always seem to cancel out.
Can someone explain to me how to arrive to the correct answers shown?
Thanks

A: When $x > 2$ (i.e. case (a)), then all absolute values are positive.
$$g(x) = x - 2 - x + 2 = 0$$ for all $x$
When $x < 0$ (i.e. case (b)), then $$g(x) = -x + 2 + x + 2 = 4$$ as if $x = -n$ for some $n > 0$, then $|-n - 2| = |-(n+2)| = n + 2 = -x + 2$ and $|x| = |-n| = n = -x$.
When $0 \leq x < 2$ (i.e. case (c)), the above argument only applies to the first absolute value, as it becomes negative. Just let $x - 2 = -j$, $|-j| = j = -x + 2$. So $|x - 2| = -x + 2$ while $|x| = x$.
$$g(x) = -x + 2 - x + 2 = -2x + 4$$

A: The definition of |x| is "x if $x\ge 0$, -x if $x> 0$.  From that |x- 2| is $x- 2$ if $x- 2\ge 0$, $-(x- 2)= 2- x$ if $x- 2< 0$.  Since there are both |x- 2| and |x| we need to divide the real numbers into three intervals, $x< 0$, $0\le x< 2$ and $2\le x$.
If x< 0 it is also true that x< 2 so |x-2|- |x|+ 2= 2- x- (-x)+ 2=2- x+ x+ 2= 4. If $0\le x< 2$ $|x- 2|- |x|+ 2= 2- x- x+ 2= 4- 2x$.  If $2\le x$ 0 is also less than x so |x- 2|- |x|+ 2= x- 2- x+ 2= 0.


text:
Q: How to query json attributes with a space using json_extract_scalar function w/o 'INVALID_FUNCTION_ARGUMENT: Invalid JSON path' error? json_extract_scalar(eventprops,'$.campaign id')--threw error
json_extract_scalar(eventprops,'$."campaign id"')--threw error
json_extract_scalar(eventprops,'$.""campaign id""')--threw error
json_extract_scalar(eventprops,'$."campaign id"')--threw error
json_extract_scalar(eventprops,'$.["campaign id"]')--threw error

A: You need to remove a dot between $ and [.
json_extract_scalar(eventprops,'$["campaign id"]')


text:
Q: Scripting Engines & Obfuscation I'm trying to obfuscate a project that uses the Rhino engine. It has many scripts that call upon methods from classes and I've been having difficulties making it work.
When it obfuscates, it changes the method names and thus makes the scripts call on inexistent class methods.
The problem is, I could keep those classes from being obfuscated, but there are quite a number of them and I'd rather obfuscate them, for security purposes.
Is there any way I could make this work?

A: What obfuscator are you using?  Looks like you're using a commercial one that does total obfuscation.
Obfuscation works in two modes:
1) Total obfuscation -- which means that you'll need to obfuscate ALL the source files.  For things that you need to remain unchanged (so that you can call it from an outside script, say) you'll need to use your obfuscation software's "export" or "extern" or "prevent" lists.  And you have to do that one by one.  The good thing about this is that, if you throw in all your code, you don't have anything that you don't want to change (because there is, by definition, no outside code)
2) File obfuscation -- which means that the obfuscator will only change local variable names and optimize statements, but will not change public-facing names.  Therefore, you "outside scripts" will continue to work.  Most minifiers work in this mode, but the obfuscation value is very limited.
You have to pick among these two modes.  They roughly correspond to the Closure Compiler's Simple and Advanced modes.
If you need to obfuscate your code to prevent reverse engineering, then you must use total obfuscation, in which case you'll just have to do the amount of work to prevent changing of unwanted names, or as I said, throw in all your code.


text:
Q: Probability generating function for sum of dependent random variables Given $N\geq2$, we choose two different numbers randomly from $\{0,1,...,N-1\}$, and assign them to the random variables X and Y respectively. How can we calculate a PGF for the sum $X+Y$?
I noticed X and Y are dependent, so $g_{X+Y}(s)\neq g_{X}(s)g_{Y}(s)$. However, we know $Y|X$ is distributing uniformly on $\{0,1,...,N-1\}$ \ $\{X\}$.
Now, I started by $\mathbb{E}[s^{X+Y}]=\mathbb{E}[s^{X}s^{Y}]=\mathbb{E}[s^{X}\mathbb{E}[s^{Y}|X]]$. But I don't know how to continue.
I found that $\mathbb{E}[Y|X]=\frac{N^2-2X}{2(N-1)}$, but it doesn't seem to be helpful for calculating the PGF of X+Y.

Remarks:

*

*$\mathbb{E}[var] = $ Expected Value Of...

*$g_v(s)=$ The PGF of the random variable V.


text:
Q: Python Launcher Preferences on Mac OSX 10.10 I use some python scripts 2.7.5 with GUI on both OS Win/Mac. Until last month, Mac ran on OSX 10.8 . But since few weeks all Mac was update to OSX 10.10 and now I got a new prompt window about preferences of Launcher everytime i run a script. If I modify these preferences, the next start it would be reset. I tried to reinstall Python and delete plist in library but it still asks for preferences.
Scripts have .pyw extension and Finder is set to use Python Launcher when i double click. It worked fine on 10.8, I had not this window before and I don't care about it. The only preferences I want is to hide this window and just open the GUI script.
Any idea how to do this and why it change with Yosemite ?
Python Launcher Preferences (screenshot)


text:
Q: When are primaries not orthogonal in CFTs? I know from conformal symmetry that if two quasi-primaries have different dimensions, they will be orthogonal. Is there an example of a theory where two quasi-primaries which necessarily have the same dimension are NOT orthogonal?
For example, N free bosons have the same dimension but will have vanishing two point function for bosons of different flavors.

A: If operators have the same dimension, then by following the Gram-Schmidt process, we can construct a basis where the operators are orthogonal. Inversely, yes - in general, there can be operators with the same dimension that are not orthogonal.
As a simple example, if $O_1$ and $O_2$ are orthogonal operators with dimension $\Delta$  so that
$$
\langle O_i(1) O_j(0) \rangle = \delta_{ij}
$$
Define $O_3 = O_1 + O_2$. Then, $O_3$ also has dimension $\Delta$ and now
$$
\langle O_1(1) O_3(0) \rangle = 1 \neq 0~.
$$


text:
Q: Javascript, Jquery - Google TTS works on local machine but not on server I am making a prototype for a text-to-speech chat system and come across a problem with my code. On my local machine (running on c:/) the user enters a text and converts it to speech and it works great. But when i put the website on my server the function will not work at all. Any idea what i can do to make it work ?
Relevant code :
<input type="text" name="text" id="text">
 Send
<audio src="" class= "speech" hidden></audio>

$(function() {

    // Text to speech
    $('a.say').on('click', function(e) {
    e.preventDefault();

    if ($('#text').val() == '' ) { //Validering av tekstfelt
    alert('Vennligst skriv noe i tekstboksen.');
    }
    else {

    var text = $('input[name ="text"]').val();
    text = encodeURIComponent(text);
    console.log(text);
    var url = "https://translate.google.com/translate_tts?ie=UTF-8&q=" + text + "&tl=no";
    $('audio').attr('src', url).get(0).play();
     });
    });


text:
Q: How do I simply send my rails website to my designer so he can finish the design? Basically I need to send to my designer a non-finished rails website.
My Designer doesn't have ruby / Rails environnement installed and should be able to:

*

*modify the CSS

*add some html elements

I can manually check the diff after he worked.
Is there a way that I can make an easy extraction of my app or giving an access to the deployed one with capacity to re-root the css from his files?

A: Based on your question, your designer, in addition to the design, also writes code: he creates css files, and edit your views files. That makes him an integrator.
As such, he should learn the basics of source control management, such as git, svn or any system you prefer (my favorite is Bazaar, for its simplicity).
It is a best practice that will allow you to save some time and avoid a lot of headaches when merging your revisions. A nice side effect: he will be able to easily roll-back to a previous working version of the code, should anything bad have happened.


text:
Q: Euler numbers formula In this formula for Euler numbers:
\begin{equation*}
A_n = i^{n+1}\sum _{k=1}^{n+1} \sum _{j=0}^k{k\choose{j}} \frac{(-1)^j(k-2j)^{n+1}}{2^ki^kk},
\end{equation*}
what is $i$? I have to generate the $n^{th}$ Euler number, and I don't have $i$.
It is not the imaginary unit, is it?

A: Yes, it is $\sqrt{-1}$.  They will all divide out in the end.  A derivation of your formula is here.  The $i$'s come from changing the $\sin(x)$ function to its definition in terms of $\exp(x)$


text:
Q: How do I properly handle accessibility for Html table with no heading row I'm trying to build a design in app which appears to be tabular data, but does not have a header row.  I've attached an image of the design below:

I've tried to follow the normal markup examples all over the internet, but almost every example expects a header row.
I am building my table such: (with styling left off)

    Main Value

    100.21 g

    Sub Category 1
    58 %
    58.15 g

    Sub Category 2
    42 %
    42.08 g

    Additional Value

    71 g

I'd probably move on but then I start to get really bad results using Voice Over on a Mac.
For example, when I'm over Row 2, column 3, I get the heading for row 3 announced:

Maybe this is a bug?
Maybe these shouldn't be tables or should be composite of multiple tables?
I'd love any ideas for how to get Voice Over to read these well, or any information on how to semantically structure this kind of data.

A: Data tables always have two axis of information. They always must have an header row and an header column at least.
Otherwise, if you can't easily put header rows and columns to label things, even only mentally,  semantically speaking, it's not really a data table, even if it visually looks like one, and a more appropriate markup is needed, such as a simple list or a definition list, or just simple text presented in a grid layout.
In your example, it indeed looks like a real data table, with two piece of information in each row which are always the same across rows. That's even the base definition of a data table: a collection of items for which you  always have the same set of properties repeated.
IF we take the row "subcategory 1" as an example, what are these two values "58%" and "58.15g" ?
I need to find what they represent somewhere, and this information should be present in the header row.
The data might be so obvious for you that you don't need that header row, but it is probably not so obvious for your readers, screen reader users or not by the way.
So, my recommendation is to add it, and to make it visible on screen. It will also help perfectly sighted users to understand the data.
Beyond just understanding the data, it's also the opportunity to add filtering and sorting, and why not column and/or row reordering, very useful if the table is big.
Just a side note on colspan/rowspan: as a screen reader user myself, I think that, in most of the cases, it's better to have empty cells rather than colspan/rowspan.
They often make the navigation much harder for nothing, and it might oblige you to compexify the markup quite a lot to make everything announced correctly. A simple visually hidden "-" can help explicitly telling that the cell is empty or has no meaningful value, if it isn't clear enough.
A good usecase for rowspan/colspan is when you have several header rows or columns, in order to create groups. Quick example: a first header row with "morning", "afternoon", "evening" and "night", and a second header row with hours from 00 to 23.
Otherwise, it's often a bad idea to use colspan/rowspan inside the data themselves.


text:
Q: Pusher not triggering on Heroku Rails app, but works fine on localhost:3000 I am learning Pusher on a Ruby on Rails app and have it setup where user clicks a button, it submits a form to update an object, then triggers a Pusher event that sends an alert and changes the background color for all windows listening on that channel.
I have the site running on my local server localhost:3000 and on Heroku. On localhost:3000, this works like a charm - when I have windows open running the site both locally and on Heroku, and I click the button on the local site, all windows receive the alert and update the background color.
HOWEVER, when I try the same thing on Heroku, none of the windows receive the alert or change color. I've looked at the Debug Console on Pusher and it shows that a connection is made, but it does not show an API request sent:
Subscribed    35329.28868505   Channel:  client-open    23:52:33
Connection    35329.28868505   Origin:   http://testing-pusher.herokuapp.com    23:52:33
Disconnection  35303.28886132  Channels: client-open, Lifetime: 107.70291038s   23:52:32

Per Heroku's help page, I've installed the pusher gem and the addon.
Here is my trigger that runs in my switches#update:
@switch.update(color: params[:switch][:color])
Pusher['client-open'].trigger('new_message', {:color => @switch.color})

The listener/binding that runs on application.html.erb:
<script type="text/javascript" charset="utf-8">
$(function() {
    Pusher.log = function(message) {
        if (window.console && window.console.log) {
            window.console.log(message);
        }
    };

    var pusher = new Pusher('my_pusher_key'); // This has my actual key in it
    var channel = pusher.subscribe('client-open');
    channel.bind('new_message', function(data) {
        alert("I'm going to change your background color to #"+data.color);
        $("#appended").append("I'm going to change your background color to "+data.color);
        $(".color").css('background-color', '#'+data.color);
});

// Some useful Pusher debug msgs
pusher.connection.bind('connecting', function() {
    $('div#status').text('Connecting to Pusher...');
});

pusher.connection.bind('connected', function() {
    $('div#status').text('Connected to Pusher!');
});
    pusher.connection.bind('failed', function() {
      $('div#status').text('Connection to Pusher failed :(');
    });
    channel.bind('subscription_error', function(status) {
      $('div#status').text('Pusher subscription_error');
    });
  });
</script>

I have these two scripts in the header of the same file:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="http://js.pusherapp.com/2.0/pusher.min.js"></script>

How can I get Pusher to properly trigger on Heroku?
EDIT: Here are the Heroku logs. No errors that I can tell:
2014-05-07T18:40:46.291870+00:00 heroku[router]: at=info method=POST path=/switches/1 host=testing-pusher.herokuapp.com request_id=f3f9e17c-086b-4639-88ba-4a406828c4e7 fwd="24.20.217.80" dyno=web.1 connect=2ms service=72ms status=302 bytes=942
2014-05-07T18:40:46.224270+00:00 app[web.1]: Started PATCH "/switches/1" for 24.20.217.80 at 2014-05-07 18:40:46 +0000
2014-05-07T18:40:46.224278+00:00 app[web.1]: Started PATCH "/switches/1" for 24.20.217.80 at 2014-05-07 18:40:46 +0000
2014-05-07T18:40:46.227649+00:00 app[web.1]: Processing by SwitchesController#update as HTML
2014-05-07T18:40:46.415613+00:00 app[web.1]: Started GET "/" for 24.20.217.80 at 2014-05-07 18:40:46 +0000
2014-05-07T18:40:46.455745+00:00 app[web.1]: Completed 200 OK in 28ms (Views: 19.0ms | ActiveRecord: 1.4ms)
2014-05-07T18:40:46.230175+00:00 app[web.1]: Processing by SwitchesController#update as HTML
2014-05-07T18:40:46.424400+00:00 app[web.1]: Processing by SwitchesController#show as HTML
2014-05-07T18:40:46.451080+00:00 app[web.1]:   Rendered switches/_form.html.haml (7.4ms)
2014-05-07T18:40:46.230262+00:00 app[web.1]:   Parameters: {"utf8"=>"✓", "authenticity_token"=>"nqhkV37GG6ym+pM7j+Bdxh3aBltTLfNpPa6cnE6b92U=", "switch"=>{"color"=>"c4b6c2"}, "commit"=>"push me", "id"=>"1"}
2014-05-07T18:40:46.230298+00:00 app[web.1]:   Parameters: {"utf8"=>"✓", "authenticity_token"=>"nqhkV37GG6ym+pM7j+Bdxh3aBltTLfNpPa6cnE6b92U=", "switch"=>{"color"=>"c4b6c2"}, "commit"=>"push me", "id"=>"1"}
2014-05-07T18:40:46.287569+00:00 app[web.1]: Redirected to http://testing-pusher.herokuapp.com/
2014-05-07T18:40:46.287617+00:00 app[web.1]: Redirected to http://testing-pusher.herokuapp.com/
2014-05-07T18:40:46.287866+00:00 app[web.1]: Completed 302 Found in 57ms (ActiveRecord: 8.2ms)
2014-05-07T18:40:46.287875+00:00 app[web.1]: Completed 302 Found in 57ms (ActiveRecord: 8.2ms)
2014-05-07T18:40:46.409915+00:00 app[web.1]: Started GET "/" for 24.20.217.80 at 2014-05-07 18:40:46 +0000
2014-05-07T18:40:46.423250+00:00 app[web.1]: Processing by SwitchesController#show as HTML
2014-05-07T18:40:46.451349+00:00 app[web.1]:   Rendered switches/show.html.haml within layouts/application (12.7ms)
2014-05-07T18:40:46.446554+00:00 app[web.1]:   Rendered switches/_form.html.haml (7.4ms)
2014-05-07T18:40:46.452492+00:00 app[web.1]: Completed 200 OK in 28ms (Views: 19.0ms | ActiveRecord: 1.4ms)
2014-05-07T18:40:46.451312+00:00 app[web.1]:   Rendered switches/show.html.haml within layouts/application (12.7ms)

EDIT 2: Issue was just missing Pusher credentials on heroku. Added those via ENV and it worked fine. See comment

A: Are you seeing any errors or messages in the Heroku logs?
Also, have you tried a simple test-case on Heroku that does nothing else but send a message via the Pusher gem?

A: I think you need to change the Pusher app credential.
When you create the pusher app, you can select the cluster which represents local region cluster.
For example, 'ap3' means Asian Pacific (Tokyo) and 'eu' means 'Europe'.
So you'd better to change your Pusher app when deploy to server.

A: Late to the show, but if anyone else runs into this....
For me, I had to remove these from my config
const pusher = new Pusher({
  appId: 'APP_ID',
  key: 'APP_KEY',
  secret: process.env.PUSHER_SECRET,
  cluster: 'us2',
  // these two were causing pusher.trigger to not work on deployed server
  // useTLS: true
  // encrypted: true
})


text:
Q: Is the duration accurate for a video file by ffmpeg? I have an original video file "inputVideoFile.mp4"
I use ffmpeg to decode the input video file, process each frame, and then encode those frames to "outputVideoFile.mp4".
I do not get the delayed frames, which means the output video file should have less frames than the input video file.
However, when I use ffprob to see how many frames are in the two files, it shows their duration values are the same:
$ffprobe inputVideoFile.mp4
Duration: 00:00:04.08, start: 0.000000, birate: 7835 kb/s
$ffprobe outputVideoFile.mp4
Duration: 00:00:04.08, start: 0.000000, bitrate: 21055 kb/s
Why is it the case?
And BTW, what units for the one after second, in 00:00:04.08?  in ".08", is the unit 1/60 sec, or 1/100 sec?
Thanks!

A: No, it is not accurate.  It is a guess based on average bitrate and filesize.  Obviously, filesize is always accurate, but in some cases average bitrate is not properly recorded.  I don't know, however, if this is a fundamental problem of the file format or a problem caused by the system/program that created the video file.  For example, with Mythtv recordings, with the NuppelVideo formatted recordings, FFMPEG estimate would be off by 2-3x, that is, it estimates 1 hr recordings to be 2 or 3 hrs long.

A: I find the answer:
av_guess_frame_rate(a_AVFormatContext, a_AVStream, NULL)
It works!


text:
Q: Difference between use and realize relationships uml interface what is the difference between use and realization interface relationships? How to implement them into code (e.g. java)? (Maybe better explanation of my question: I have one interface, say I and two classes, say A and B. Class A realizes I and class B uses I. What is difference between these relationships and how it should be implemented?) ... I have found many definitions but still I dont see difference.
Thank you very much

A: A the "realize" relationship is implemented in Java with:
class A implements I {
    ...
}

The "use" can be many things: it just says that class B uses interface I in one way or another. Examples:
class B {
   I aField;
   ...
   void doSomethingWith(I obj) { ... }
   I createAnI() { ... }
   ...
}

A: As Maurice Perry said about Realize is correct.
To additional explain about Use Relationship in UML, it is a type of Dependency relationship. see here
A Use dependency relationship indicates that the consumer class does one of the following things:

*

*Temporarily uses a supplier class that has global scope,

*Temporarily uses a supplier class as a parameter for one of its operations,

*Temporarily uses a supplier class as a local variable for one of its operations,
Sends a message to a supplier class.

see IBM Documents here


text:
Q: Let $X$ be a K3 surface, show that $H_1(X,\mathbb Z)=0$ Let $X$ be a(n algebraic) K3 surface, i.e., $X$ is a smooth algebraic surface with trivial canonical bundle and $H^1(X,\mathcal{O})=0$. This assumption directly implies that $H^1(X,\mathbb C)=0$, so $H_1(X,\mathbb C)=0$ by Poincaré duality. In particular $H_1(X,\mathbb Z)$ is a torsion group.
Next, to show that $H_1(X,\mathbb Z)$ is actually $0$, the book says otherwise there is a nontrivial torsion element in fundamental group which allows us to pass to a finite covering $p:\tilde{X}\to X$, but $\tilde{X}$ is still a K3 surface, and considering any K3 surface has Euler characteristic 24, so $p$ has to be an identity map, which is a contradiction.
Here is my question: First homology group is the Abelianzation of fundamental group $H_1=\pi_1/[\pi_1,\pi_1]$, but why a nontrivial torsion element in $H_1$ has a nontrivial torsion representative in $\pi_1$?

A: First proof.
By GAGA principle, $X$ is a (connected compact) complex surface; using the Serre duality, one has
\begin{equation}
H^2(X,\mathcal{O}_X)\cong H^0(X,\omega_X)^{\vee}\cong\mathbb{C},
\end{equation}
and by a dimensional argument $H^3(X,\mathcal{O}_X)=0,\,H^4(X,\mathcal{O}_X)=0$.
Using the exponential sequence
\begin{equation}
0\to\underline{\mathbb{Z}}\to\mathcal{O}_X\to\mathcal{O}_X^{\times}\to0
\end{equation}
and passing to long exact sequence in cohomology, one has:
\begin{gather}
0\to H^0\left(X,\underline{\mathbb{Z}}\right)\cong\mathbb{Z}\to H^0(X,\mathcal{O}_X)\cong\mathbb{C}\xrightarrow{\exp}H^0\left(X,\mathcal{O}_X^{\times}\right)\cong\mathbb{C}^{\times}\to H^1\left(X,\underline{\mathbb{Z}}\right)\to H^1(X,\mathcal{O}_X)=0,\\
0\to H^1\left(X,\mathcal{O}_X^{\times}\right)\cong Pic(X)\to H^2\left(X,\underline{\mathbb{Z}}\right)\to H^2(X,\mathcal{O}_X)\cong\mathbb{C}\to H^2\left(X,\mathcal{O}_X^{\times}\right)\to H^3\left(X,\underline{\mathbb{Z}}\right)\to H^3(X,\mathcal{O}_X)=0,\\
0\to H^3\left(X,\mathcal{O}_X^{\times}\right)\to H^4\left(X,\underline{\mathbb{Z}}\right)\to H^4(X,\mathcal{O}_X)=0,\\
0\to H^4\left(X,\mathcal{O}_X^{\times}\right)\to0;
\end{gather}
so $H^3\left(X,\mathcal{O}_X^{\times}\right)\cong H^4\left(X,\underline{\mathbb{Z}}\right)$ and $H^4\left(X,\mathcal{O}_X^{\times}\right)=0$.
By exactness of
\begin{equation}
0\to\mathbb{Z}\to\mathbb{C}\xrightarrow{\exp}\mathbb{C}^{\times}\to0
\end{equation}
the previous sequence splits in
\begin{equation}
0\to H^1\left(X,\underline{\mathbb{Z}}\right)\to H^1(X,\mathcal{O}_X)=0
\end{equation}
so $H^1\left(X,\underline{\mathbb{Z}}\right)\cong H^1(X,\mathbb{Z})=0$.
By the Universal Coefficient Theorem for Cohomology, there exists a surjective morphism of Abelian groups
\begin{equation}
0=H^1(X,\mathbb{Z})\to\hom(H_1(X,\mathbb{Z}),\mathbb{Z})\to0,
\end{equation}
that is $H_1(X,\mathbb{Z})$ is either a non trivial torsion Abelian group or $0$.
Because $Pic(X)$ and $\mathbb{C}$ are torsion free groups (see remark 1.2.5), then also $H^2\left(X,\underline{\mathbb{Z}}\right)\cong H^2(X,\mathbb{Z})$ is a torsion free group; as consequence $H^{\dim_{\mathbb{R}}X-2+1}(X,\mathbb{Z})=H^3(X,\mathbb{Z})$ is a torsion free group; by Poincaré duality, $H_1(X,\mathbb{Z})$ is a torsion free group, and by previous reasoning $H_1(X,\mathbb{Z})=0$.
Remarks.

*

*Let $X$ be a compact, without boundary, oriented (real) manifold  of dimension $d$. The torsion subgroup of $H^p(X,\mathbb{Z})$ is isomorphic to torsion subgroup of $H^{d-p+1}(X,\mathbb{Z})$; where $p\in\{1,\dots,d\}$. (cfr. exercise 54)

*By this proof, one has the following (partial) result: $\pi_1(X)$ is a perfect group. For exact, $\pi_1(X)=0$; see the second proof.

*By Poincaré duality, $H^3\left(X,\mathcal{O}_X^{\times}\right)\cong H^4\left(X,\underline{\mathbb{Z}}\right)\cong H^4(X,\mathbb{Z})\cong H_0(X,\mathbb{Z})\cong\mathbb{Z}$ and $H^3\left(X,\underline{\mathbb{Z}}\right)\cong H^3(X,\mathbb{Z})\cong H_1(X,\mathbb{Z})=0$; so the non-trivial part of previous long exact sequence in cohomology is
\begin{equation}
0\to Pic(X)\to H^2\left(X,\underline{\mathbb{Z}}\right)\to\mathbb{C}\to H^2\left(X,\mathcal{O}_X^{\times}\right)\to0.
\end{equation}
Second proof.
Any K3 surface is diffeomorphic to a Fermat quartic surface (see example 1.1.3.i, remark 1.3.6.i and theorem 7.1.1), in particular they are simply connected (corollary 7.1.4); that is $\pi_1(X)=0$ and the relevant Abelianization $H_1(X,\mathbb{Z})$ is trivial.
References

*

*Davis J. F., Kirk P. (2001) Lectures Notes in Algebraic Topology, Graduate Studies in Mathematics 35 American Mathematical Society

*Huybrechts D. (2016) Lectures on K3-surfaces, Cambridge University Press

A: What book is this? The argument is incorrect. The existence of a nontrivial finite cover corresponds to the existence of a nontrivial subgroup of finite index, not the existence of a nontrivial torsion element. And this is guaranteed by the existence of a nontrivial finite quotient of $\pi_1$, which is in turn guaranteed by the existence of a nontrivial finite quotient of $H_1$.


text:
Q: Using an If statement in SVG I'm wanting to create a pattern book by using SVG as it seems quite a fun language and I was wondering if there's a way of using an if statement instead of typing all the different rectangles out one by one. The code that I have is

<SVG width="1000" height="1000">
  <rect x="10" y="10" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="50" y="100" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="150" y="200" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="240" y="150" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="190" y="30" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="95" y="56" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="19" y="81" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="290" y="190" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="200" y="300" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="189" y="359" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="286" y="389" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="260" y="346" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="20" y="370" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="355" y="410" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="320" y="385" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="61" y="399" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="100" y="450" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="160" y="425" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
  <rect x="300" y="400" width="150" height="150" style="fill:white;stroke:black;stroke-width:1;opacity:1"/>
</SVG>

As you can see, I have a fair bit of rectangles being displayed which does work, but I'm wondering if there's a way of using an if statement to make it easier to use.

A: SVG is not a language.  But you can use languages to build your SVG.  For example, in an HTML page, you can build the SVG thusly:

var mysvg = document.getElementById("mysvg");
var num = 20;
while (num-- > 0)
{
  var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
  rect.setAttribute("x", Math.random()*500);
  rect.setAttribute("y", Math.random()*500);
  rect.setAttribute("width", "150");
  rect.setAttribute("height", "150");
  rect.setAttribute("style", "fill:white;stroke:black;stroke-width:1;opacity:1");
  mysvg.appendChild(rect);
}
<svg id="mysvg" width="1000" height="1000">
</svg>

You can also embed the Javascript into the SVG to make it stand-alone and not rely on HTML.

<svg id="mysvg" width="1000" height="1000"
     xmlns="http://www.w3.org/2000/svg" version="1.1">
  <script type="application/ecmascript"> <![CDATA[
    var mysvg = document.getElementById("mysvg");
    var num = 20;
    while (num-- > 0)
    {
      var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
      rect.setAttribute("x", Math.random()*500);
      rect.setAttribute("y", Math.random()*500);
      rect.setAttribute("width", "150");
      rect.setAttribute("height", "150");
      rect.setAttribute("style", "fill:white;stroke:black;stroke-width:1;opacity:1");
      mysvg.appendChild(rect);
    }
  ]]></script>
</svg>

A: You appear to need a loop rather than an IF, but SVG has no concept of either.
You can generate your SVG using a programming or template language.
For example, with template toolkit (which you will need to install and run, it isn't an SVG feature):
[% SET data = [
    { x="10", y="10", width="150", height="150" },
    { x="50", y="100", width="150", height="150" },
    { x="150", y="200", width="150", height="150" },
    { x="240", y="150", width="150", height="150" },
    { x="190", y="30", width="150", height="150" },
    { x="95", y="56", width="150", height="150" },
    { x="19", y="81", width="150", height="150" },
    { x="290", y="190", width="150", height="150" },
    { x="200", y="300", width="150", height="150" },
    { x="189", y="359", width="150", height="150" },
    { x="286", y="389", width="150", height="150" },
    { x="260", y="346", width="150", height="150" },
    { x="20", y="370", width="150", height="150" },
    { x="355", y="410", width="150", height="150" },
    { x="320", y="385", width="150", height="150" },
    { x="61", y="399", width="150", height="150" },
    { x="100", y="450", width="150", height="150" },
    { x="160", y="425", width="150", height="150" },
    { x="300", y="400", width="150", height="150" }
]; %]

<svg width="1000" height="1000">
    [% FOR item IN data %]
        <rect x="[% item.x %]"
              y="[% item.y %]"
              width="[% item.width %]"
              height="[% item.height %]"
              style="fill:white;stroke:black;stroke-width:1;opacity:1" />
    [% END %]
</svg>


text:
Q: Dsymutil Warning I met a problem, in the use of libCrasheye.a library, to display the alarm.

while processing
  /Users/caiqiujun/Documents/iOS/Swift/WageWebsite/WageWebsite/Framework/crasheye/libCrasheye.a(CrasheyeUnityPlugin.o):
warning:
  /Users/test/Documents/crashsvn910/Crasheye/DerivedData/ModuleCache/1GC1H3S0HXFE/Foundation-3DFYNEBRQSXST.pcm:
  No such file or directory
note: Module debugging should be disabled when shipping static
  libraries.

Why show the above alarm?

A: As it say

Module debugging should be disabled when shipping static libraries.

So you have to contact the library's developer and ask to disable debugging of the library module before shipping his library.
So he as to recompile his application


text:
Q: Why am I getting an error: package com.google.android.maps does not exist? I am building an Android app and I keep getting this error...
/code bases/2016/app/src/main/java/com/app/apps/android/appt/object/Route.java:3: error: package com.google.android.maps does not exist
import com.google.android.maps.GeoPoint;
Android studio is red on the maps part...
import com.google.android.maps.GeoPoint;

This is my full Gradle file...
buildscript {
    repositories {
        jcenter();
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {

        classpath 'com.google.gms:google-services:1.3.0-beta1'
        classpath 'com.android.tools.build:gradle:1.5.0'
        // The Fabric Gradle plugin uses an open ended version to react
        // quickly to Android tooling updates
        classpath 'io.fabric.tools:gradle:1.21.5'

        //classpath 'io.fabric.tools:gradle:2.1.2'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

android {

    useLibrary 'org.apache.http.legacy'

    compileSdkVersion 23
    buildToolsVersion '24.0.0'

    dexOptions {
        //maxProcessCount 2
        incremental true
        javaMaxHeapSize "2g"
    }

    signingConfigs {
        config {
            keyAlias 'myApp'
            keyPassword '2012'
            storeFile file('/myApp')
            storePassword '2012'
        }
    }

    defaultConfig {
        applicationId "com.myApp.apps.android.maint"
        minSdkVersion 23
        targetSdkVersion 23
        versionCode 21
        versionName '3.51'
        signingConfig signingConfigs.config
    }

    buildTypes {
        debug {
            debuggable true
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        release {
            debuggable false
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.config
        }
    }

    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/DEPENDENCIES'
    }

    productFlavors {
        //releaseDev {}
        //releaseIOSTest {}
        releaseTest {}
        releaseLive {}
    }
}

repositories {
    jcenter();
    maven { url "https://jitpack.io" }
    maven { url 'https://maven.fabric.io/public' }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile('com.crashlytics.sdk.android:crashlytics:2.5.2@aar') {
        transitive = true;
    }
    compile 'com.google.android.gms:play-services-gcm:9.0.2'
    compile 'com.google.android.gms:play-services-location:9.0.2'
    compile 'com.google.android.gms:play-services-maps:9.0.2'
    compile 'com.android.support:appcompat-v7:24.0.0'
    compile 'com.android.support:support-v4:24.0.0'
    compile 'com.android.support:cardview-v7:24.0.0'
    compile 'com.android.support:recyclerview-v7:24.0.0'
    compile 'com.google.code.gson:gson:2.4'
    compile 'joda-time:joda-time:2.9.2'
    compile 'com.github.PhilJay:MPAndroidChart:v2.1.0'
    compile 'com.google.maps:google-maps-services:0.1.15'
    compile 'com.google.android:android:4.1.1.4'
}

apply plugin: 'com.google.gms.google-services'

A: You should upgrade your google repository library, and change the following code:
classpath 'com.google.gms:google-services:1.3.0-beta1'

to
classpath 'com.google.gms:google-services:3.0.0'

And:
compile 'com.google.maps:google-maps-services:0.1.15'

to
compile 'com.google.android.gms:play-services-maps:9.0.2'

Read more here https://developers.google.com/android/guides/setup


text:
Q: Django: Security of post api without any authentication I am creating api end points using django for my android mobile app.
I have a
signup POST api
login POST api and
notification token POST api

All these views will not need any token based authentication. I am afraid someknow knows the api they can misuse them.
How to protect them

A: Signup can be restricted by using a captcha...
Most bots would not be able to use it, and it would be annoying for some human to misuse it.
The login would take credentials and can be spammed but only few would actually login...
This should return a token which can be used to access all other APIs.
Also if you're worried about too many requests, you can throttle them.


text:
Q: Cannot Drop Database after Unit Test ANSWER: I wasn't clearing my ConnectionPools.
The solved scenario is:
SetUp:

*

*Check to see if the 'TEMP_NUnit' database (SQL Server 2005) exists on the local instance

*If it exists, drop it.

*Create a new blank database named 'TEMP_NUnit'.

Test:

*

*Instantiate the 'Upgrade Database' component.

*Check that essential properties of component are defaulting correctly.

*Point the component at the blank database and call .Upgrade()

*Check that the upgrade actually worked

TearDown:

*

*SqlConnection.ClearAllPools();

*Drop the 'TEMP_NUnit' database.

Original question is below the fold.

Hi All
The test scenario is:
SetUp:

*

*Check to see if the 'TEMP_NUnit' database (SQL Server 2005) exists on the local instance

*If it exists, drop it.

*Create a new blank database named 'TEMP_NUnit'.

Test:

*

*Instantiate the 'Upgrade Database' component.

*Check that essential properties of component are defaulting correctly.

*Point the component at the blank database and call .Upgrade()

*Check that the upgrade actually worked

TearDown:

*

*Drop the 'TEMP_NUnit' database.

Everything's going fine until I get to the TearDown phase. I always get the following error:

Cannot drop database "TEMP_NUnit"  because it is currently in use.

This is confusing me, because I'm closing (explicitly calling conn.Close in finally statements) and disposing (via using statement) all my DbConnection objects correctly. There shouldn't be anything running on the "TEMP_NUnit" database by the time the TearDown comes around.
If I close NUnit and then re-open it, step 2 of the SetUp always works first go.
I'm not sure what I'm doing wrong here. Any pointers in the right direction would be appreciated.

A: Ah, but you forgot to do this little thing before dropping the database:
SqlConnection.ClearAllPools();

By default the connection pool will maintain a connection to the database, even if you closed it before. Doing SqlConnection.ClearAllPools() will actually force all connections to be closed. You can then connect to master and drop the temp database.
It has caused me quite an amount of grief before :)

A: Might want to consider Michael Feathers Unit Testing Rules:
A test is not a unit test if:

*

*It talks to the database

*It communicates across the network

*It touches the file system

*It can't run at the same time as any of your other unit tests

*You have to do special things to your environment (such as editing config files) to run it.


text:
Q: Why does ir-keytable quit? To set IR on my clean Raspberry Pi 4, I am following the instructions at https://learn.pi-supply.com/make/ir-remote-control-support-on-raspbian-buster-justboom/.
One step at the beginning, even before installing lirc package, is to install and run ir-keytable:
$ sudo apt install ir-keytable
$ sudo ir-keytable

This command shows that my driver is gpio_ir_recv and the device is /dev/lirc1. Perfect.
Next, I run the command to test receiving IR signals:
$ sudo ir-keytable -c -p all -t

However, this command quits as soon as it is run. There are no new messages in /var/log/ folder either.
Wondering why this command would simply quit.
Note that lirc package as not yet been installed. As per the article, this step comes later.


text:
Q: Using Ajax with the Yii framework I need to load a page dynamically via something like Ajax. I'm on the Yii 2 framework in PHP.
Basically I just want to click a button and have the contents of another URL appear in a div on the same page. Very basic stuff, but it's not working for me.
I'm trying this code below

<a id="ajax" class="btn btn-lg btn-success" href="<?php echo"$url"; ?>">Choose Winner

And it's not working. $url is the url of the page I want to load.
Can anyone help?

A: I have updated your code. I have change  href="javascript:void(0);" and add  data-url="http://stackoverflow.com" . You can use your PHP code in data-url="<?php echo '$url'; ?>"
Here is UPDATED CODE :

$(document).ready(function(){
$('#ajax').click(function(){
  alert($(this).attr('data-url'));
$('#winner').load($(this).attr('data-url'));
return false;
});
});

Choose Winner

A: for some reason when I added the jquery library ON TOP of the ajax call it worked.


text:
Q: How to separate post titles with a comma in the loop? How do I list all my posts with a comma (but not after the last post)...
<?php
// WP_Query arguments
$args = array(
    'post_type'              => array( 'post' ),
    'tax_query' => array(
        array (
            'taxonomy' => 'day_time',
            'field' => 'slug',
            'terms' => 'mon-night')),
    'post_status'            => array( 'publish' ),
    'nopaging'               => false,
    'posts_per_page'         => '20',
    'ignore_sticky_posts'    => true,
    'order'                  => 'DESC',
    'separater'                         => ', ',
    'orderby'                => 'modified',
);

// The Query
$query = new WP_Query( $args );

// The Loop
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post(); ?>
        <?php the_title(); ?>
<?php   }
} else { ?>

<?php }

// Restore original Post Data
wp_reset_postdata();
?>

<?php } else { ?>
<?php } ?>

A: Instead of outputting everything immediately, save it to a variable so you can conditionally add a comma (and presumably a space) between items:
<?php
// The Loop
if ( $query->have_posts() ) {
    // Save the number of posts found
    global $wp_query;
    $total_posts = $wp_query->post_count;
    // Set a counter variable
    $i=0;
    while ( $query->have_posts() ) {
        $query->the_post();
        // Save the title to a variable instead of outputting
        $output .= get_the_title();
        // Increment the counter each time
        $i++;
    }
    // Outside the loop, since you only want 1 comma each time
    if($i != $total_posts) {
        // Add a comma and a space
        $output .= ', ';
    }
    // Last but not least, display the output
    echo $output;
}
?>


text:
Q: Is it possible to insert xml as a string to varbinary and it will be similiar to be inserted as a blob? Is it possible to insert xml as a string to varbinary and it will be similiar to be inserted as a blob? For example When i insert xml as a blob
declare @i int = 1
declare @file varchar(2000) = concat('K:\test\file',@i,'.xml');
declare @blob varbinary(max)
declare @sql nvarchar(max) = concat(N'select @blob = BulkColumn FROM
OPENROWSET(BULK ''',@file,''', SINGLE_BLOB) myfile')

exec sp_executesql @sql, N'@blob varbinary(max) output', @blob = @blob
output
select @blob

insert tab1 values (@blob)

File inserted as a blob look like this
When i insert the same xml but as a string
INSERT INTO tab1 VALUES ( Convert (varbinary(MAX), N'
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Dont forget me this weekend!</body>
</note>'  ))

It looks completaly different

@Jacob

@Siyual

A: It is a very bad idea to store a file as VARBINARY just as you read it from disk.
Some background
DECLARE @YourThirdVarbinary VARBINARY(MAX)=0xfffe3c006e006f00740065003e003c0074006f003e00;
SELECT CAST(@YourThirdVarbinary AS NVARCHAR(MAX));

The leading FFFE points to an UTF-16 little endian encoded file with a byte order mark.
The following 3C00 6E00 6F00 ... shows clearly, that you are reading 2-byte encoded characters.
SQL-Server uses UCS-2 internally and is not capeable to read each and any UTF-16 encoding natively. I assume, that you are living in a country, where you are dealing with many characters, which are not plain latin...
But the first example you provide is a single-byte encoded string:
DECLARE @YourFirstVarbinary VARBINARY(MAX)=0x3c6e6f74653E0D0A3c746f3e546f76653c2f746f3e;
SELECT CAST(@YourFirstVarbinary AS VARCHAR(MAX));

The missing 00 between your code points shows clearly, that this is 1-byte-storage without a BOM, probably some kind of UTF-8!
UTF-8 stores plain latin with one single byte, but special characters will take more bytes, up to 4 bytes for one single letter.
SQL-Server will treat a 1-byte encoded string as VARCHAR, which is extended ascii, relying on a COLLATION (including a code page) (multi-byte-codes must lead to errors!)
You will find the same codepoints forming the word <note>:
DECLARE @PureCodePoints VARBINARY(MAX)=0x3c6e6f74653E;
SELECT CAST(@PureCodePoints AS VARCHAR(MAX));

And as 2-byte code (see the NVARCHAR):
DECLARE @PureCodePointsWide VARBINARY(MAX)=0x3c006e006f00740065003E00;
SELECT CAST(@PureCodePointsWide AS NVARCHAR(MAX));

Clear advise

*

*Store your XML in a natively typed column! Advantage: XML is not stored as the text you see, but as a hierachy tree. This is much faster! With your approach you'd have to cast the VARBINARY to a string and parse this over and over again...

*Never store data as VARBINARY, if you cannot ensure, that you know the encoding in any case and that SQL-Server will be able to deal with this format.

A: The way you store your XML depends on what you're going to do with this data.

*

*if your goal is just to store and access the file, regardless of whether it is indeed an XML or not, varbinary or FILESTREAM is absolutely fine.

*if you know it is a text file (including XML) but don't require any XML-specific operations with it, you'd be okay with varchar or nvarchar.

*if you're going to do any kind of XML manipulations, xml would be the logical choice.

From my experience, there are some caveats in the latter:

*

*An XML might be signed and, if you should be careful not to break it. In this case, you should consider storing the XML as a binary, but add an extra XML column.

*If you have an XML that specifies an encoding that is not compatible with the one the application provides, you might have an error such as:

XML parsing: line 1, character 45, unable to switch the encoding

The following examples illustrate this scenario:
SELECT CAST(N'<?xml version="1.0" encoding="windows-1251"?><xml></xml>' AS xml)
SELECT CAST(N'<?xml version="1.0" encoding="utf-8"?><xml></xml>' AS xml)
SELECT CAST('<?xml version="1.0" encoding="utf-16"?><xml></xml>' AS xml)

while these are fine:
SELECT CAST(N'<?xml version="1.0" encoding="utf-16"?><xml></xml>' AS xml)
SELECT CAST('<?xml version="1.0" encoding="utf-8"?><xml></xml>' AS xml)
SELECT CAST('<?xml version="1.0" encoding="windows-1251"?><xml></xml>' AS xml)
SELECT CAST(N'<xml></xml>' AS xml)
SELECT CAST('<xml></xml>' AS xml)


text:
Q: Play/pause audio file with javascript command I have some javascript code that gets executed once somebody enters the konami code, and I want it to play if it isn't playind, and pause if it is playing. My code seems to be just wrong. Please help!

var rick = false;
var audio = new Audio('rick_roll.mp3');
var kkeys = [],
  konami = "38,38,40,40,37,39,37,39,66,65,13";
$(document).keydown(function(e) {
  kkeys.push(e.keyCode);
  if (kkeys.toString().indexOf(konami) >= 0) {
    $(document).unbind('keydown', arguments.callee);
    if (rick == false) {
      rick = true;
      audio.play();
    } else if (rick == true) {
      rick = false;
      audio.stop();
    }
  }
});

A: You should be doing something like this:

var rick = false;
var audio = new Audio('rick_roll.mp3');
var kkeys = [],
  konami = "38,38,40,40,37,39,37,39,66,65,13";
$(document).keydown(function(e) {
  kkeys.push(e.keyCode);
  if (kkeys.toString().indexOf(konami) >= 0) {
    kkeys = []; // <-- Change here
    if (rick == false) {
      rick = true;
      audio.play();
    } else if (rick == true) {
      rick = false;
      audio.pause(); // <-- another issue
    }
  }
});

You're unbinding the event listener after you get the code entered. You should instead clean old data and start waiting for it again.


text:
Q: Give url path in woocommerce single product I have given the a url path for image in wordpress using maya theme of woocommerce and the image is not showing the image path looks like

how can I remove the part
http://localhost/alphatest/wp-content/uploads/

I am using maya theme and woocommerce plugin in wordpress. the full code is like
<?php
/**
 * Single Product Thumbnails
 */

global $post, $woocommerce;
?>

    <?php
        $thumb_id = get_post_thumbnail_id();
        $small_thumbnail_size = apply_filters('single_product_small_thumbnail_size', 'shop_thumbnail');
        $args = array(
            'post_type'     => 'attachment',
            'numberposts'   => -1,
            'post_status'   => null,
            'post_parent'   => $post->ID,
            'post__not_in'  => array($thumb_id),
            'post_mime_type'=> 'image',
            'orderby'       => 'menu_order',
            'order'         => 'ASC'
        );
        $attachments = get_posts($args);
        if ($attachments) :
            $loop = 0;
            $columns = apply_filters('woocommerce_product_thumbnails_columns', 3);
            foreach ( $attachments as $attachment ) :

                if (get_post_meta($attachment->ID, '_woocommerce_exclude_image', true)==1) continue;

                $loop++;

                $_post = & get_post( $attachment->ID );
                $url = wp_get_attachment_url($_post->ID);

                $post_title = esc_attr($_post->post_title);
                $image = wp_get_attachment_image($attachment->ID, $small_thumbnail_size);

                echo ''.$image.'';

            endforeach;
        endif;
    ?>

A: Simply add Double Slash (//)Instead of the Domain name. Example:
http://www.google.com/wp-content/uploads/2013/10/image.png

will be as:
//wp-content/uploads/2013/10/image.png


text:
Q: What is the correct formula for the penalty term in an elastic net regression? I've a question concerning the penalty term in an elastic net regression. In The elements of Statistical Learning by Hastie, Tibshirani & Friedman the formula (3.54) on p.73 says the penalty term is given by:
$$
   \lambda \cdot \displaystyle\sum_{j=1}^p (\alpha \cdot \beta_j^2 + (1 - \alpha) \cdot |\beta_j|)
$$
This means for α=1 the formula transforms into a ridge regression. This is also consistent with the description in Zou & Hasti (2005, p. 303):

When α=1, the naive elastic net becomes simple ridge regression.

But almost every else (e.g., in the manual of the R package glmnet), it is written that ridge regression results if α=0. Actually, in the same book ("The elements...") on p. 681 in formula
(18.20) it says, the penalty term has the form:
$$
   \displaystyle\sum_{j=1}^p (\alpha \cdot |\beta_j| + (1 - \alpha) \cdot \beta_j^2)
$$
I wonder how this inconsistency can be explained. I would be grateful for any information.
Kind regards
Ulrich

A: I would not stress out over this. There isn't an established convention for representing how the elastic net penalty is parameterized (as evidenced by the different parameterizations within the same Elements of Statistical Learning text that you found), so you just need to be clear about how $\alpha$ is defined when discussing elastic net.
As a similar example, sometimes the LASSO objective function is expressed as $\sum_{i=1}^N (y_i - x_i^\top \beta)^2 + \lambda \|\beta\|_1$ while other times it is $\frac{1}{2}\sum_{i=1}^N (y_i - x_i^\top \beta)^2 + \lambda \|\beta\|_1$ or $\frac{1}{N}\sum_{i=1}^N (y_i - x_i^\top \beta)^2 + \lambda \|\beta\|_1$. Clearly the $\lambda$ in these different formulations are different, but it doesn't detract from discussion as long as everyone agrees on a definition beforehand.


text:
Q: In Python, is there a way to check how alike two files are and get the percentage of differences they have? I'm trying to compare a lot of scripts at once and most of them have small differences, like a different name inside a variable and such.
For the most part, the scripts should be identical in function, and I'd like to be able to test how actually different they are.
What I'm thinking of doing is taking in all of the input from both files and comparing them against each other, character by character, and increasing a count of some sort when a difference arises. I'm not sure what I would compare this count to to make a percentage, or if this is even the best way to go about this.
If you have an idea or advice to give me I would greatly appreciate it!

A: Two suggestions:
1) Check out this SO question and Python's difflib. This SO question specifically asks about difflib.
Also, a guy named Doug Hellmann has an excellent series of blog posts called Python Module of the Week (PyMOTW). Here is his post about difflib.
2) If those don't work for you, try searching for language-independent algorithms for file comparisons first, and think about which ones can be most easily implemented in Python. A simple Google search for "file comparison algorithms" came up with several decent looking possibilities that you could try to implement in Python:
Here is a published PDF with a diff algorithm
This site has a discussion of several different algorithms with links


text:
Q: How can I place a pdf asset into a empty PDF page? I have multiple PDF files with small sizes (e.g. 3cm x 2 cm) exported from Adobe Indesign.
I want to compose many of these into one new PDF which has the size of a whole page.
The small PDFs contain a plotter line in a special color which would get lost if I convert them into images.
How can I place these PDFs (at given positions) using python and without losing the special color.
I tried to read into pypdf, pypdf2 and reportlab but I got lost and the examples I found did not work. I do not need the full code, a hint into the right direction would be enough (even with another language if necessary).
Thanks

A: Try:
cpdf in.pdf -stamp-on stamp.pdf -pos-left "x y" AND -stamp-on stamp2.pdf -pos-left "x2 y2" AND ..... -o out.pdf
where in.pdf is a blank PDF of appropriate size, and x and y and x2 and y2 etc... are the coordinates required and ..... are parts of the command for the third, fourth etc. stamps.

A: Here is a sample code to do your task using PyPDF2.
from PyPDF2 import PdfFileMerger
merger = PdfFileMerger()
for pdf in pdf_files:
    merger.append(pdf)   #pdf_files is a list of the pdf files (path) to be merged.
merger.write(output_pdf) #output_pdf is the path of the merged pdf file.
merger.close()

A: Apart from joining / merging pages from different documents into one output PDF, PyMuPDF lets you also embed pages from PDFs into an existing page of some target PDF (as if it were an image).
You can select a subrectangle within the source page (a "clip") and the target rectangle of the target page. Multiple embedded source pages in the same target page are also supported.
This embedding maintains all original source page features - it will not be converted to an image.
Scaling between source / target rectangles will be done as necessary.
This snippet will take the full page number 0 of a source PDF and place it inside a rectangle of a page in the target PDF.
The source page will be positioned centered in the target rectangle.
import fitz  # import PyMuPDF
source = fitz.open("source.pdf")  # source PDF
target = fitz.open("target.pdf")  # target PDF
target_page = target[pagenumber]  # desired page in target

# if you want a new page, create it like so:
# target_page = target.new_page()

target_rect = fitz.Rect(100, 100, 300, 250)  # show source page here

# if you want to cover the full target page, use
# target_rect = target_page.rect

target_page.show_pdf_page(target_rect,
    source,  # the source document
    0,  # the source page number
    clip=None,  # any subrectangle on source page
)

# if desired, more pages from other sources can be put on same target page


text:
Q: MySQL checksum to all tables in a database I am evaluating a PHP/MySQL based software.
I want to look which tables affected when certain operations triggered.
After some googling, I was told that checksum table tbl_name can do the job. I just need to know how to use checksum for all the tables in the db.
To checksum all the tables one by one manually definitely not preferred as the database contains hundreds of tables.

A: Checksumming all tables seems like a lot of expensive calculation work just to detect which tables changed.
I'd suggest to get this information using the sys.schema_table_statistics table.
mysql> select table_schema, table_name, rows_fetched, rows_inserted, rows_updated, rows_deleted
  from sys.schema_table_statistics where table_schema='test'
+--------------+---------------------+--------------+---------------+--------------+--------------+
| table_schema | table_name          | rows_fetched | rows_inserted | rows_updated | rows_deleted |
+--------------+---------------------+--------------+---------------+--------------+--------------+
| test         | sysbench_results    |          870 |           144 |            0 |            0 |
+--------------+---------------------+--------------+---------------+--------------+--------------+

You probably want to reset the counters between your tests. Use sys.ps_truncate_all_tables()
mysql> call sys.ps_truncate_all_tables(FALSE);
+---------------------+
| summary             |
+---------------------+
| Truncated 31 tables |
+---------------------+

mysql> select table_schema, table_name, rows_fetched, rows_inserted, rows_updated, rows_deleted
  from sys.schema_table_statistics where table_schema='test';
+--------------+---------------------+--------------+---------------+--------------+--------------+
| table_schema | table_name          | rows_fetched | rows_inserted | rows_updated | rows_deleted |
+--------------+---------------------+--------------+---------------+--------------+--------------+
| test         | sysbench_results    |            0 |             0 |            0 |            0 |
+--------------+---------------------+--------------+---------------+--------------+--------------+

The sys schema comes pre-installed in MySQL 5.7.
If you use MySQL 5.6, you may need to install it yourself. It's just an SQL script that creates some views into the performance_schema. Very easy to install.
You can get the sys schema here: https://github.com/mysql/mysql-sys

A: You could generate the CHECKSUM statements for all tables:
SELECT CONCAT('CHECKSUM TABLE ', table_name, ';') AS statement
FROM information_schema.tables
WHERE table_schema = 'YourDBNameHere'

Then copy this output and paste it into Workbench or whatever tool you need to use.  If you need to do this from within application (e.g. PHP) code, then you would probably have to use pure dynamic MySQL.

A:
I want to look which tables affected when certain operations triggered.

What do you mean by this?
Do you know what operations have been triggered, and you're merely attempting to understand what effect they had on your database (e.g. to verify their correctness)?  Or do you not know what operations have been triggered (e.g. during some interval) but you nevertheless want to understand how the database has changed, perhaps in an attempt to determine what those operations were?
There are very few situations where I would expect the best approach to be that which you are exploring (inspecting the database for changes).  Instead, some form of logging—whether built-in to the RDBMS (such as MySQL's General Query Log or perhaps through triggers as suggested by Sumesh), or more likely at some higher level (e.g. within the accessing application)—would almost always be preferable.  This leads me to lean toward thinking you have an XY Problem.
However, on the assumption that you really do want to identify the tables that have been modified since some last known good point in time, you can query the INFORMATION_SCHEMA.TABLES table, which contains not only the CHECKSUM for every table in the RDBMS but also other potentially useful information like UPDATE_TIME.   So, for example, to identify all tables changed in the last five minutes one could do:
SELECT TABLE_SCHEMA, TABLE_NAME
FROM   INFORMATION_SCHEMA.TABLES
WHERE  UPDATE_TIME > NOW() - INTERVAL 5 MINUTE

A: For those who came here for an answer how to get checksum for all the tables in one query (as it was in my case):
SET group_concat_max_len = CAST(
    (
        SELECT SUM(LENGTH(TABLE_NAME)) + COUNT(*) * LENGTH(', ')
        FROM information_schema.tables WHERE `TABLE_SCHEMA` = 'your_database_name'
    ) AS UNSIGNED
);

SET @sql_command:= (
    SELECT CONCAT(
        'CHECKSUM TABLE ',
        GROUP_CONCAT( TABLE_NAME ORDER BY `TABLE_NAME` SEPARATOR ', ' )
    )
    FROM information_schema.tables
    WHERE `TABLE_SCHEMA` = 'your_database_name'
    ORDER BY `TABLE_NAME`
);

PREPARE statement FROM @sql_command;
EXECUTE statement;
DEALLOCATE PREPARE statement;

The mere idea is to create CHECKSUM TABLE statement which include all tables names in it. So yes, it is some sort of little bit upgraded version of answer given by Tim Biegeleisen.
First we set maximum permitted result lenght for GROUP_CONCAT() function (which is 1024 bytes by default). It is calculated as  number of symbols in all table names inculding the separator which will be putted between these names:
SET group_concat_max_len = CAST(
    (
        SELECT SUM(LENGTH(TABLE_NAME)) + COUNT(*) * LENGTH(', ')
        FROM information_schema.tables WHERE `TABLE_SCHEMA` = 'your_database_name'
    ) AS UNSIGNED
);

Then we put all the tables names together in one CHECKSUM TABLE statement and store it in string variable:
SET @sql_command:= (
    SELECT CONCAT(
        'CHECKSUM TABLE ',
        GROUP_CONCAT( TABLE_NAME ORDER BY `TABLE_NAME` SEPARATOR ', ' )
    )
    FROM information_schema.tables
    WHERE `TABLE_SCHEMA` = 'your_database_name'
    ORDER BY `TABLE_NAME`
);

And finally executing the statement to see the results:
PREPARE statement FROM @sql_command;
EXECUTE statement;
DEALLOCATE PREPARE statement;

Unfortunately you can't further manipulate with result set using MySQL statements only (i.e. insert to table or join with other result sets).
So if you require to do some comparisons you will eventually need to use additional code in your favorite programming language (or use capable software) to accomplish the task.

A: The question does not state using a shell script to accomplish things isn't allowed, so I'll post one such approach here (PHP is able to invoke shell scripts - see http://php.net/manual/en/function.shell-exec.php - if safe mode is not enabled):
If your script has shell access at its disposal and a checksum tool - like md5sum - one can also do something like this to collect checksums for each table:
#!/bin/bash
DATABASEPATH="/var/lib/mysql/yourdatabase"
cd "$DATABASEPATH" &&
for TABLEFILE in `ls -t *.ibd`; do
  SUMANDTABLE=`md5sum "$TABLEFILE"`
  echo "${SUMANDTABLE//.ibd}"
done

And optionally, if you don't want a checksum calculated for all tables, you could also check if the modification date of the "$TABLEFILE" is within range. If not, you just exit the script (the ls -t orders by modification date, descending).
To access modification date use something like e.g. stat -c %Y "$TABLEFILE". This would give you the modification date in seconds since Epoch.
To access current date, also in seconds since Epoch use: date +%s.
One can then subtract the modification date from the current date to establish how many seconds ago a "$TABLEFILE" has changed.
Another related method, which in some cases could apply, would be to save the ls -t *.ibd listing (without even calculating checksums, just store filenames in order), then start an operation and at the end of that operation check for difference in file listing with another execution of ls -t *.ibd.


text:
Q: Can Delphi XE4 import iOS ObjC Class ? ( Static Library *.a ) Can Delphi XE4 import iOS ObjC Class ? ( Static Library *.a )
ObjC Code  :  test.a
// test.h ---------------------------------------------------------------
#import <Foundation/Foundation.h>
@interface mycalc : NSObject {
   BOOL busy;
  }
- (int) calc : (int) value;
@end

//  test.m --------------------------------------------------------------
#import "test.h"
@implementation mycalc
 -(int) calc:(int)value {
    busy = TRUE;
    return ( value + 1);
  }
@end

Delphi XE4 Code "Unit1.pas" for Testing
Unit1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes,
  System.Variants,System.TypInfo,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
  //
  Posix.Dlfcn,
  Macapi.ObjectiveC,Macapi.ObjCRuntime,
  iOSapi.CocoaTypes,iOSapi.foundation,iOSapi.uikit,iOSapi.CoreGraphics;

{$Link libtest.a} // <-- ObjC Static Library (3 Architectures included)
                  //     But Compiled binary size is always same,
                  //     with or without "$Link libtest.a" lines.

type
  //
  mycalc = interface(NSObject)
   ['{12891142-0F45-410D-A9EF-212F1AE23294}'] // Any Unique GUID
   function  test(value : integer) : integer; cdecl;
  end;

  mycalcclass = interface(NSObjectClass)
   ['{42891142-0F45-410D-A9EF-212F1AE23295}'] // Any Unique GUID
   end;

  //the TOCGenericImport maps objC Classes to Delphi Interfaces
  // when you call Create of TObjc_TestClass
  TmycalcClass = class(TOCGenericImport<mycalcclass, mycalc>) end;

  // -------------------------------------------------------------------------
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
  public
  end;

var
  Form1: TForm1;

implementation

{$R *.fmx}

procedure TForm1.Button1Click(Sender: TObject);
 Var
  occalc : mycalc;
  rtn    : integer;
  handle : integer;
begin
 handle := dlOpen('libtest.a',RTLD_LAZY); // ## Q2 : Is It Right ?
 occalc := TmycalcClass.Create;           // ## Q3 : Error :
                                          //          Can't found ObjC Class mycalc
 rtn := occalc.test(100);
 Button1.Text := 'rst:' + IntToStr(rtn);
end;

end.

I rewrite the code with Lars' advice XE4 ( Firemonkey + iOS Static Library) , Pascal conversion from Objective C Class?,
Compiling is OK.
But, After running the program in iPad3 device, When press the button,
It shows "ObjectiveC class myclac cound not be found"
My Questions are
Q1.  Is it right syntax for XE4 & iOS Static Library ?
Q2.  with / wihtout Line {$Link libtest.a}
     Compiled size is same always. What's is wrong in my code ?
Q3.  I know iOS App can't use static library except apple library.
     So, dlOpen is not required. Is it right ?
Always Thanks
Simon, Choi


text:
Q: ArcGIS raster to vector with shapefile feed procedure Does a procedure like Polygonize raster to vector exist in ArcGIS that can do the following?
I have a raster image, a shapefile (.shp) with all the regions of interest and I need a vector output with those polygons only.

A: To convert from rasters to polygons go to ArcToolbox -> Conversion Tools -> from raster -> Raster to polygon.
The raster must be an integer type. ie the values in each cell must be 1,2,3 not 1.1, 3.1415926 etc
After you have your polygons from the raster images and tidied them up (error check them as well) do a spatial clip using the second polygon layer so you only have polygons inside (or touching depending on what you want) the area of interest.


text:
Q: Store weekdays and time of the day table in database I have the following data (this is not a real table in database, it's just a group of information I need to store with each post in my database):
X = yes / true
O = no  / false

Weekday   | Morning | Day | Evening | Night |
---------------------------------------------
Monday    |    X    |  O  |    O    |   X   |
Tuesday   |    X    |  O  |    O    |   X   |
Wednesday |    O    |  O  |    X    |   X   |
Thursday  |    O    |  X  |    O    |   O   |
Friday    |    X    |  X  |    X    |   X   |
Saturday  |    O    |  O  |    X    |   O   |
Sunday    |    X    |  X  |    X    |   O   |

How should I store data like this in a database? Im not too experienced with database design and all the possible ways I could think of waste a lot of space. Normalization is not a requirement for this.
I don't need to query by this data, I just need to store it efficiently in parent object/entity.

A: You may think of creating a table with 28 columns, being each group of 4 columns corresponding to the 4 times of each day. Something like:
CREATE TABLE <name> ( SUNDAY_MORNING VARCHAR(1) ,
                      SUNDAY_DAY     VARCHAR(1) ,
                      SUNDAY_EVENING VARCHAR(1) ,
                      SUNDAY_NIGHT   VARCHAR(1) ,
                      MONDAY_MORNING VARCHAR(1) ,
                      MONDAY_DAY     VARCHAR(1) ,
                      MONDAY_EVENING VARCHAR(1) ,
                      MONDAY_NIGHT   VARCHAR(1) ,
                      ...
                    ) ;

Of course, KEYs may need to be defined, but it is not possible to suggest anything based on the provided info.
As per your concern of SPACE, this structure will se MUCH LESS space than you can imagine.

A: From what you've said, I'd create a table with 4 columns (Morning, Day, Evening, Night) and a Primary Key to reference the individual datasets (like the one you've shown). Then I'd use a bitfield for each row entry. For example Monday = 1, Tuesday = 2, Wednesday = 4, Thurs = 8, Friday = 16, Saturday = 32, and Sunday = 64.
Your dataset provided (here as PK 001) could be saved in a single row as:

 PK       | Morning | Day | Evening | Night |
001          83        88    116       23

The morning value is 83, because Monday (1) + Tues (2) + Friday (16) + Sunday (64) = 83.
You'd only need to use a datatype that can store a 128-bit number max. This depends on which database you use but many databases have a binary(64) type that would work.
You would then use the bitwise & operator to test if a day is represented by a particular value:
83 (Morning Value) & 16 (Friday) = 16 (Friday, therefore true)
88 (Day value) & 4 (Wednesday) = 0 (therefore false)
116 (Evening value) & 32 (Saturday) = 32 (Saturday, therefor true)
Alternatively, you could create a bitfield column for each Day of the Week, and the value would be Morning = 1, Day = 2, Evening = 4, and Night = 8.
Your given dataset would be represented as a single row in the database as:

 PK   | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
 001     9     9     12    2     15    4     7


text:
Q: Using XML data encoded to JSON on PHP I've just created a php file to query some data from an API.
A normal returned data should be like :
{
@attributes: {
    Status: "OK"
},
Errors: { },
Warnings: { },
RequestedCommand: "checking",
CommandResponse: {
    @attributes: {
    Type: "check"
    },
    DomainCheckResult: [
        {
        @attributes: {
            Domain: "example1.com",
            Available: "true",
            ErrorNo: "0",
            Description: "",
            IsPremiumName: "false",
            PremiumRegistrationPrice: "0",
            PremiumRenewalPrice: "0",
            PremiumRestorePrice: "0",
            PremiumTransferPrice: "0",
            IcannFee: "0",
            EapFee: "0"
        }
        },
        {
        @attributes: {
            Domain: "example2.com",
            Available: "true",
            ErrorNo: "0",
            Description: "",
            IsPremiumName: "false",
            PremiumRegistrationPrice: "0",
            PremiumRenewalPrice: "0",
            PremiumRestorePrice: "0",
            PremiumTransferPrice: "0",
            IcannFee: "0",
            EapFee: "0"
        }
        },
    ]
},
Server: "asd",
GMTTimeDifference: "--5:00",
ExecutionTime: "2.622"
}

Now, When I try to get the attributes values such as "Domain" and "Available" and the other ones to put them in some variables, I do the following :
$client = new Client();
        $res = $client->request('POST', 'http://api.website.com/xml.response', [
        'form_params' => [
        'ApiUser' => 'myuser',
        'ApiKey' => 'apikey',
        'UserName' => 'myuser',
        'ClientIp' => 'myip',
        'Command' => 'check',
        'List' => $list
            ]
        ]);
        $xml = simplexml_load_string($res->getBody(),'SimpleXMLElement',LIBXML_NOCDATA);
        $json = json_encode($xml);
        $data = json_decode($json, true);
        echo $data->CommandResponse[0];

But it tells me :

Trying to get property of non-object

What am I doing wrong? Please help me. Thank you.

A: It has something to do with the second parameter of the json_decode function. This tells the function if it should convert the json string into an array or an object (see the PHP documentation). In your case you create an array, but want to access it as an object. So either you change your json_decode($json, true) to json_decode($json) or you echo $data->CommandResponse[0] to echo $data['CommandResponse'][0].
Hope that helps!


text:
Q: How to include both of `jquery.tools.js` and `jquery.tokeninput.js`
Possible Duplicate:
Can JQuery UI and JQuery tools work together?

I have a page which requires JQuery's tokeninput (for drop-downs) and also JQuery's "tools" (for tooltips etc.)
If I do
<script type="text/javascript" src="jquery.tools.js"></script>
<script type="text/javascript" src="jquery.tokeninput.js"></script>

Then Chrome gives me the error:
Uncaught TypeError: Object function (a,b){return new c.fn.init(a,b)}
has no method 'type'    (jquery.tokeninput.js:139)

If I put the JS calls the other way around, then everything loads, but the tokeninput method is not available on the textfields.
If I have just the jquery.tokeninput.js file then the tokeninput works well, everything is OK, apart from the features introduced in jquery.tools.js aren't available, such as tooltip.
FYI: My entire list of scripts that I include are:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery-1.8.10-redmond/js/jquery-ui-1.8.10.custom.min.js"></script>
<script type="text/javascript" src="jquery.tools.js"></script>
<script type="text/javascript" src="jquery.tokeninput.js"></script>
<script type="text/javascript" src="jquery.colorbox.js"></script>
<script type="text/javascript" src="jquery.fileinput.js"></script>

A: OK the answer appears to be here:
https://stackoverflow.com/a/1721944/220627


text:
Q: java.net.UnknownHostException : api.openweathermap.org I'm following a course on udacity 'Developing Android Apps'. Following is the code of ForecastFragment class which is suppose to get data in json format from the url(http://api.openweathermap.org/data/2.5/forecast/daily?q=Delhi,in&mode=json&cnt=7&units=metric).
public  class ForecastFragment extends Fragment {

    public ForecastFragment() {
    }

    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);

          }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        String[] data = {

                "Today-Sunny-34", "Tommorow-Rainy-233", "Wednesday-Cloudy-21", "Thursday-Monayblue-18", "Frida-Rainy-23", "Saturday-Rainy-22", "Sunday-Strorm-100"
        };

        List<String> weekForecast = new ArrayList<String>(Arrays.asList(data));
        ArrayAdapter<String> mForecastAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast);
        ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
        listView.setAdapter(mForecastAdapter);

        return rootView;
    }

    public void onCreateOptionsMenu(Menu menu,MenuInflater inflater){

       inflater.inflate(R.menu.forecastfragment, menu);

    }

    public boolean onOptionsItemSelected(MenuItem item){

        int id = item.getItemId();
        if(id==R.id.action_refresh){
            FetchWeatherTask fetch = new FetchWeatherTask();
        fetch.execute();
        return true;}

        return super.onOptionsItemSelected(item);

    }

    public class FetchWeatherTask extends AsyncTask<Void,Void,Void>{

        private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
        @Override
        protected Void doInBackground(Void... params) {
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
            String forecastJsonStr = null;

            try {
                URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=Delhi,in&mode=json&cnt=7&units=metric");

                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) return null;
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line + "\n");
                }
                if (buffer.length() == 0) return null;
                forecastJsonStr = buffer.toString();
                Log.v(LOG_TAG,"Forecast Json String" + forecastJsonStr);
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error", e);
                return null;
            } finally {
                if (urlConnection != null) urlConnection.disconnect();
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e("placeholder fragment", "error closing stream", e);
                    }
                }
            }
            return null;
        }
    }
}

However, I'm repeatedly getting this error.
07-20 12:49:14.063    2392-2486/com.example.android.sunshine.app        E/FetchWeatherTask﹕ Error
java.net.UnknownHostException: api.openweathermap.org
        at java.net.InetAddress.lookupHostByName(InetAddress.java:512)
        at java.net.InetAddress.getAllByNameImpl(InetAddress.java:300)
        at java.net.InetAddress.getAllByName(InetAddress.java:259)
        at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69)
        at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
        at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322)
        at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
        at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285)
        at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267)
        at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:205)
        at com.example.android.sunshine.app.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:119)
        at com.example.android.sunshine.app.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:83)
        at android.os.AsyncTask$2.call(AsyncTask.java:185)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
        at java.util.concurrent.FutureTask.run(FutureTask.java:138)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
        at java.lang.Thread.run(Thread.java:1027)

Following are the things I've already checked:-

*

*mobile phone has internet access.

*AndroidManifest.xml declares the permission for internet usage.
The url works fine in the browser,but I'm clueless as to why this error is coming up.
Also, I'm running the app on my android phone(api 10).
If anyone could please provide a solution or point me in the right direction,it would be great. Thank you.

A: I had the same issue. Yet I did not turn WiFi on on my mobile phone. Activating wifi solved the problem for me.

A: I copied your Async class as-is and ran it in a new project on a KitKat VM on my Mac machine. Here are the results:
07-19 14:40:32.070    1670-1683/centerorbit.com.myapplication V/FetchWeatherTask﹕ Forecast Json String{"city":{"id":1273294,"name":"Delhi","coord":{"lon":77.216667,"lat":28.666668},"country":"IN","population":0},"cod":"200","message":0.0095,"cnt":7,"list":[{"dt":1437285600,"temp":{"day":29,"min":28.21,"max":29,"night":28.21,"eve":29,"morn":29},"pressure":984.15,"humidity":88,"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],"speed":1.66,"deg":64,"clouds":36},{"dt":1437372000,"temp":{"day":29.15,"min":25.17,"max":31.21,"night":27.92,"eve":31.21,"morn":26.55},"pressure":986.25,"humidity":95,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":3.22,"deg":86,"clouds":88,"rain":10.65},{"dt":1437458400,"temp":{"day":30.46,"min":25.15,"max":31.57,"night":27.94,"eve":31.1,"morn":25.15},"pressure":988.81,"humidity":83,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":6.41,"deg":111,"clouds":68,"rain":0.45},{"dt":1437544800,"temp":{"day":30.63,"min":26.12,"max":32.69,"night":28.12,"eve":32.69,"morn":26.12},"pressure":991.01,"humidity":81,"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"speed":3.57,"deg":118,"clouds":64},{"dt":1437631200,"temp":{"day":34.27,"min":25.81,"max":35.34,"night":27.1,"eve":33.11,"morn":25.81},"pressure":989.86,"humidity":78,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":2.06,"deg":74,"clouds":8,"rain":3.94},{"dt":1437717600,"temp":{"day":31.12,"min":25.71,"max":31.12,"night":26.68,"eve":30.83,"morn":25.71},"pressure":991.3,"humidity":0,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":1.06,"deg":184,"clouds":13,"rain":7.82},{"dt":1437804000,"temp":{"day":31.68,"min":25.88,"max":32.17,"night":27.01,"eve":32.17,"morn":25.88},"pressure":989.57,"humidity":0,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":1.28,"deg":226,"clouds":52,"rain":5.89}]}

It appears that your code is fine, and something is not right with your system/network. I would recommend restarting your phone/computer to see if that fixes the issue. If not, try using a different network (disconnect from your home WiFi and use Cell network).

A: You have registered permission in androidManifest to access Internet
<uses-permission android:name="android.permission.INTERNET"/>

A: Append APIKey at the end of URL
To get APIKey you have to create acount on openweathermap.org
       e.g.  http://api.openweathermap.org/data/2.5/forecast/daily?q=Delhi,in&mode=json&cnt=7&units=metric&appid=yourapiid"
Detail Process to Get APIKey is


text:
Q: Problemas com mascara jquery e input Eu estou tentando colocar um valor no dentro de um input que seja mascarado tanto na digitação quanto no valor inserido.
Bom, eu tenho uma lista de imóveis cadastros no banco de dados no qual eu puxo pro front, ok?
E nao entrando em muitas especificações, sempre que insiro um valor no INPUT (Ex.: 100.000,00) ele vem tranquilo formatado, no entanto quando eu clico em "Salvar" (do meu sistema, irrelevante agora) o valor do input muda pra 100.00. Segue abaixo o código do front:

    Preço
    <input type="text" maxlength="" class="form-control input-sm moeda" name="valor" value="<?= $imovel->valor ?>" placeholder="Preço">

Por favor, estou tentando de tudo e sempre dá nisso.
Abaixo o código do mask:
$('.moeda').mask('999.999.999,99');

Está dentro de um ready tranquilo, aqui ta tranquilo.
De novo, meu PROBLEMA É:

*

*Não consigo fixar o valor de entrada com o valor gravado na input.

Grato a todos que puderem ajudar!!!
EDIT 1: Depois de algumas sugestões de vocês o problema persistiu. A mascara na digitação está ótima. Eu sempre testo usando o valor 100.000,00 e o resultado impresso fica 100,00.
100.000,00 => 100,00
10.000,00 => 10,00
1.000.000,00 => 1,00
Viram que ele ta pegando sempre os dígitos antes do 1º ponto e acrescentando os ",00" [Fim EDIT 1]

A: Como o input é tipo text, e possui virgulas, o que o input está retornando é uma string, e pra isso, terá que formatar o value do mesmo transformando em um número:

function formatVal(val){
  let valor = val;
  let valTot = 0;
  return valTot += Number(valor.replace('.', '').replace(',', '.'));
}

console.log(formatVal('100.000,97'))

No let valor ali, no caso, você vai pegar o valor do input. (acho que agora se sabe fazer rs) ai com o número formatado desse jeito, da pra você fazer os cálculos que precisa.

A: Já tentou usar a função mask do Jquery:
Veja:


text:
Q: Django Error during template rendering no such column I was trying to show the list of the User's to-do lists using view.html. The error says:

no such column:testapp_todolist.user_id".

But I don't understand where this column is and how it is related to the red line in my view.html:
{% for td in user.todolist.all %}

Can you please explain in details how do I add this column?
Here's my models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class ToDoList(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="todolist", default=0)
    name = models.CharField(max_length=200)

    def __str__(self):
        return self.name

class Item(models.Model):
    todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE)
    text = models.CharField(max_length=200)
    complete = models.BooleanField()

    def __str__(self):
        return self.text

A: Try solving this by writing this on your console:

*

*python manage.py makemigrations

*python manage.py migrate
Those commands are going to create tables for the TodoList model in the database.

A: user does not have the object todolist, todolist is a foreign key in Item. You should do:
list = ToDoList.objects.filter(user=YOUR_USER_HERE)

or
# if you want to get the todolist of the currently logged in user
list = ToDoList.objects.filter(user=request.user)


text:
Q: AngularFire pagination and recommended practices by the Firebase team I've searched for a clean way to implement infinite scroll pagination using angularfire and I found a rather simple way of doing it.
This morning I've watched the videos about the new version of firebase.
I found this video explaining that unwrapping promises inside of a controller is an anti-pattern because angular takes care of that for us in it's digest cycle when doing this in the router resolver and injecting this a dependency in the controller.
So I was like... hmmm, is it even possible to implement infinite scrolling using the router resolver instead of doing it inside a controller since it mean making an other query ?
If you had multiple thousands of entries, would you rather do an anti-pattern or load all the data while the user is looking at a spinner for X seconds ?
Well, your thoughts on the question interest me.
Thanks

A: well, you can take at look at this, it'll give you good ideas of how to implement it, maybe you can wrap it within angularFire as a new service, that's what I'm trying to do.
https://github.com/deltaepsilon/firebase-paginator
https://www.youtube.com/watch?v=CH9ptm4NeTw
the problem of using this library directly is that you have to trigger a digest cycle each time you paginate to update the paginated collection to the view. so I'm looking forward of how to integrate it well by extending the $firebaseArray service.


text:
Q: Prove that xf(x) is continuous with a specific case. We got
$$
f(x) = \begin{cases}
\sin \frac1x,&x\neq 0
\\
0,&x = 0
\end{cases}
$$
I have to prove that g is continuous, where $ g: \mathbb R \rightarrow \mathbb R, x \rightarrow xf(x)$. How can I do this?

A: We have
$$g (0)=0*f (0)=0$$
and for $x\ne 0,$
$$g (x)=x*f (x)=x\sin(\frac {1}{x}) .$$
but
$$\forall x\ne 0\;\; |\sin (1/x)|\le 1$$
thus
$$\forall x\ne 0\;\; 0\le |g (x)|\le |x|$$
and by squeeze theorem
$$0\le \lim_{x\to 0,x\ne0}g (x)\le 0$$
then
$$\lim_{x\to 0,x\ne 0}g (x)=g (0)=0$$
$g $ is continuous at $\mathbb R $.

A: Away from $0$, it's clearly continuous as a product of continuous functions. So you just need to show continuity at $0$, i.e. for $\epsilon>0$ you can find a $\delta>0$ with $|x|<\delta\Rightarrow |g(x)|<\epsilon$. In fact you can just take $\delta=\epsilon$, since $|\sin(1/x)|\leq 1$.