text:
Q: Recursive function that returns the number of numbers greater then the first index of an array Recursive function that returns the number of numbers greater then the first index of an array
I've got a function that solves the problem but I'm not sure if it is the correct way to write the recursive function
int greaterThanFistIndex(int *v,int n){
    int a;
    if(n == 1){
        return 0;
    }else{
        a = greaterThanFistIndex(v,n-1);
        if(v[0] < v[n-1]){
            a++;
        }
    }
    return a;
}

the output of [3,5,1,6] should be 2

A:
I'm not sure if it is the correct way to write the recursive function

The code looks OK yet it breaks the spirit of using recursion.1
Such code could readily be done with a simple loop instead of n recursive calls.
int greaterThanFistIndex_iterate(const int *v,int n){
  count = 0;
  for (int i = 1; i<n; i++) {
    if (v[i] > v[0]) count++;
  }
  return count;
}

Could could halve the problem at each step.  At least the would have only log2(n) recursion depth rather than n as in OP's code.
static int greaterThanFistIndex_r_helper(const int *v,int n, int first){
  if (n <= 0) {
    if (n == 0) return 0;
    return *v > first;
  }
  int first_half = n/2;
  int second_half = n - first_half;
  return greaterThanFistIndex_r_helper(v, first_half, first) +
      greaterThanFistIndex_r_helper(v + first_half, second_half, first);
}

int greaterThanFistIndex_r(const int *v,int n){
  if (n <= 0) return 0;
  return greaterThanFistIndex_r_helper(v+1, n, *v);
}

Some compilers will detect OP's construct and perform tail end recursion optimization yet I see a simple loop a better approach.

Use recursion when it makes sense.  Use a loop when possible.
Note: better to use size_t than int for array size and indexing. (not shown here)

1
Code fails for n <= 0.
A better function signature would be size_t greaterThanFistIndex(const int *v, size_t n)


text:
Q: C++14 Can operator*= be constexpr? (Matrix class) I have the following matrix class :
class mat4
{
public:
    constexpr mat4() noexcept;

    constexpr mat4(const std::array<float, 16> &m) noexcept;
    constexpr mat4(std::array<float, 16> &&m) noexcept;

    constexpr mat4(const mat4 &other) noexcept;
    constexpr mat4(mat4 &&other) noexcept;

    /*constexpr?*/ mat4& operator*=(const mat4 &other) noexcept;

    mat4& operator=(mat4 other) noexcept; // Uses std::swap

    constexpr float& operator[](size_t index);
    constexpr float operator[](size_t index) const;

private:
    std::array<float, 16> matrix;
};

constexpr const mat4 operator*(mat4 lhs, const mat4 &rhs) noexcept;

I would like to implement operator* with respect to operator*= like it is usually done with operator+ and operator+=. The first argument is a passed by value to benefit of copy elision:
constexpr const mat4 operator*(mat4 lhs, const mat4 &rhs) noexcept
{
    lhs *= rhs;
    return lhs;
}

However, I see no way to implement operator*= as a constexpr function. Here is my implementation :
constexpr mat4& mat4::operator*=(const mat4 &other) noexcept
{
    std::array<float, 16> tmp; // The temporary is mandatory because the multiplication depends on the matrices *this and other.

    //matrix multiplication (three nested for loop to fill tmp)

    std::swap(this->matrix, tmp); // <-- ERROR: NOT CONSTEXPR
    return *this;
}

The other way I thought of doing it is to define operator*= with respect to operator* and write something like *this = *this * other in the body of the former. But then it would call operator= which is not constexpr because it also calls std::swap in his body.
Is there any way of making my operator+= a constexpr function?

redpajama_set_name: RedPajamaStackExchange


text:
Q: changing directory using bash script I am trying to SSH into a server and run a program. I was able to SSH using
#!/usr/bin/expect -f
spawn ssh username@serveraddress
expect "assword:"
send "mypassword/r"
#interact
cd /users/bill/work

But then I wanted to change to a specific directory and execute a program from that directory. So when it gets to cd part, I keep getting
couldn't change working directory to "/users/bill/work/": no such file or directory
while executing
"cd /users/bill/work/"
(file "./ssh.sh" line 8)

but I know that is a correct directory and I can cd to it from the interact command line. so, can I even use cd command if I am using expect?
Thank you,
BZ

A: The problem is, that, once you log in via ssh, you want to access the remote computers console. However, cd /users/bill/work is being executed on your system, as you are not typing it into the console, but executing it directly from the bash file, where truly no such file or directory exists. You might want to send the command instead to the remote computers conosle.


text:
Q: Display new items at the top of a ListView  I'm using a list to populate a ListView (). The user is able to add items to the list. However, I need the items to be displayed at the top of the ListView. How do I insert an item at the beginning of my list in order to display it in reverse order?

A: The ListView displays the data as it is stored in your data source.
When you are adding in your database, it must be adding the elements in the end. So, when you are getting all the data via the Cursor object and assigning it to the ArrayAdapter, it is in that order only. You should basically be trying to put data in the beginning of the database, rather that in the end, by having some time-stamp maybe.
Using ArrayList, you can do it by Collections.reverse(arrayList) or if you are using SQLite, you can use order by.

A: You can add element at the beginning of the list: like
arraylist.add(0, object)

then it will always display the new element at the top.

A: By default list adds elements at bottom. That is why all new elements you add will show at bottom. If you want it in reverse order, may be before setting to listadapter/view reverse the list
Something like:
Collections.reverse(yourList);

A: Another solution without modifying the original list, override getItem() method in the Adapter
@Override
public Item getItem(int position) {
    return super.getItem(getCount() - position - 1);
}

Updated: Example
public class ChatAdapter extends ArrayAdapter<ChatItem> {
public ChatAdapter(Context context, List<ChatItem> chats) {
    super(context, R.layout.row_chat, chats);
}

@Override
public Item getItem(int position) {
    return super.getItem(getCount() - position - 1);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView == null) {
        convertView = inflater.inflate(R.layout.row_chat, parent, false);
    }

    ChatItem chatItem = getItem(position);
    //Other code here

    return convertView;
}

}

A: You should probably use an ArrayAdapter and use the insert(T, int) method.
Ex:
ListView lv = new ListView(context);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, R.id...);
lv.setAdapter(adapter);
...
adapter.insert("Hello", 0);

A: mBlogList is a recycler view...
mBlogList=(RecyclerView) findViewById(R.id.your xml file);
mBlogList.setHasFixedSize(true);

LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
mBlogList.setLayoutManager(mLayoutManager);//VERTICAL FORMAT

A: You could always have a datestamp in your objects and sort your listview based on that..
   public class CustomComparator implements Comparator<YourObjectName> {
        public int compare(YourObjectName o1, YourObjectName o2) {
            return o1.getDate() > o2.getDate() // something like that.. google how to do a compare method on two dates
        }
    }

now sort your list
Collections.sort(YourList, new CustomComparator());

This should sort your list such that the newest item will go on top

A: You can always use a LinkedList instead and then use addFirst() method to add elements to your list and it will have the desired behaviour (new items at the top of the ListView).


text:
Q: Sum of roots of $p-3 = 5p^{2/3} - 6p^{1/3}=0$? In the middle of a solution of a question, the equation $$p-3 = 5p^{2/3} - 6p^{1/3}=0$$ is given. I am required to find out the value of the sum of roots for the next step, which for an equation $ax^3+bx^2+cx+d$ is equal to $-b/a$. I tried to put the equation in this format by cubing both sides, however I get $$p^3-27-9p^2+27p = 125p^2 - 216p - 90p(5p^{2/3} - 6p^{1/3})$$ which is in terms of $p^{2/3}$, therefore I think it cannot be right. What should I do? Is there any other method, or have I missed something in this method?

A: If
$$p^3-27-9p^2+27p = 125p^2 - 216p - 90p(5p^{2/3} - 6p^{1/3})$$
(I haven't checked that your algebra is correct) you can substitute
$$5p^{2/3} - 6p^{1/3}=p-3$$
to get rid of the fractional powers.
Note.  The pair of equations $p-3 = 5p^{2/3} - 6p^{1/3}=0$ has no solution, I am assuming you meant the single equation $p-3 = 5p^{2/3} - 6p^{1/3}$.

A: I do believe that this could be a bit simpler if you observe that the equation itself is already cubic by nature with variable $p^{1/3}$.
$$ \left(p^{1/3}\right)^3−3=5\left(p^{1/3}\right)^2−6p^{1/3} $$
So, assume that $q=p^{1/3}$, you can rewrite this cubic as
$$q^3 - 5q^2+6q-3=0$$
Assume this has roots $r$, $s$ and $t$, then we know from Vieta's formulas that :

*

*$r+s+t=5$

*$rs+st+tr=6$

*$rst=3$

We are actually interested in $r^3+s^3+t^3$ which we can obtain as :
$$r^3+s^3+t^3 = (r+s+t)^3 - 3 (r+s+t)(rs+st+tr)+3rst $$
and this leads to the final answer : $5^3 - 3\cdot5\cdot6+3\cdot3 = 44 $

A: Hint:  $p^{2/3} = (p^{1/3})^2$


text:
Q: Which is the fastest decoder for jpeg full-scale decoding? Which is the fastest decoder for jpeg full-scale decoding ?
I want to accelerate my apps' jpeg decoding speed, how can I do this?
I am using libjpeg now, it is a bit slow, is there any one faster than libjpeg?
I do not need partical decoding.
Many thanks!

A: I don't know which is the fastest, but these should be faster than IJG's libjpeg:
[free] libjpeg-turbo
[cost] Intel Performance Primitives (IPP) library


text:
Q: How to get code coverage in Android using Maven (android-maven-plugin) I have an Android Maven project (let's call it parent_project) that contains various submodules: my_library_project, app_using_my_library_project, test_project and extra_lib.
So, the structure would be like this:
parent_project
   * my_library_project (Android Library Project)
   * app_using_my_library_project (Demo app that uses the Android Library Project)
   * test_project (Project containing the tests instrumented against app_using_my_library_project)
   * extra_lib

What I would like is to generate test coverage for my Android project using Maven (and not Ant, I am already able to generate code coverage reports using Ant, following these instructions: https://wiki.jenkins-ci.org/display/JENKINS/Building+an+Android+app+and+test+project).
I have no strong preference for the code coverage tool used but I would prefer EMMA, since seems the most common in the Android development world.
I am using android-maven-plugin (http://code.google.com/p/maven-android-plugin/) in its 3.0.0-alpha-12 version and I have already tried to put in the configuration of my parent's pom.xml the next:
<test>
  <coverage>true</coverage>
  <createreport>true</createreport>
</test>

But that does not produce the desired code coverage report.
So:

*

*Is there any difference between the pom configuration for getting code coverage for a standard Java project and an Android project?

*Do you know any example Android project using Maven that has code coverage?

*Any hints on how to do this?

A: If you're going to stick with maven, and want a plugin for maven that will do the code-coverage job, I think Cobertura is a better choice, as Emma stable last build is from 2005.
Although in "Android Application Testing Guide" (a recent book from June this year) they talk about Emma and demonstrate how to use it for testing, I think people stick to it, because it's needed to build Android from source (and if Google use it for their own OS development, it should be the best, right?).
If you're not fanatically bound to Maven, I strongly recommend to try Robotium.
Robotium has full support for Activities, Dialogs, Toasts, Menus, and Context Menus.
It also supports code coverage (Ant based though, for now) and some people recognize it as one of the leading testing platforms for Android.
Edit:
According to the Cobertura site, it supports code coverage in Maven 1 and Maven 2 environments. Although, you can find examples with Maven 3 also.
A problem exists between pom configurations of Maven 2 and Maven 3. It seems for the reporting to work you have to basically move your old reporting plugins into the configuration section of the new maven-site-plugin. (See the article for details).
Another option is to try and use Sonar with Maven. Sonar has cobertura embedded (also options to embedd EMMA) and some people state that they had successfully reported code coverage, despite they had problems using the "stand-alone" cobertura plugin.

A: I could generate code coverage reported using emma maven plugin and display reports in sonar for an android application project. Just follow the configuration in https://code.google.com/p/maven-android-plugin/wiki/EmmaMaven.
But for library project I get a 0% coverage. It doesn't generate the metadata files. However as soon I change the library project to package as an apk, it works like a charm. It runs the tests in a emulator(configured in jenkins) and shows the coverage reports.
If you are looking out specifically for library project, this wont help. I will post if I find some solution which deals with library projects.


text:
Q: Reading data from memory mapped file in parallel? If mapped file data is fully resident in physical memory will there be any benefit of reading data in parallel for example by defining number of sections with start/end byte and have separate thread working each section? The goal is to allow for frequent quick reads of data from big binary file.
I've been doing some tests (Java NIO) where each thread (testing with 4 threads) has access to reference of mmap but since each thread changes internal pointer in mmaped file to read next set of bytes this doesn't seem safe. I'm thinking about splitting a file into 4 mmaped chunks for each thread?
UPDATE:
To give more context ultimately what I'm going after is having a data structure that will have a reference to number of mmaped files so then those references can be provided to some function that will do a loop scan testing for values and putting them into byte buffer.
UPDATE:
This is for read-only files.

A: You can create different FileChannel for each thread. Each Thread will read a different part.
As documentation says, FileChannels are thread-safe.
Your code would be something like this
package nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class HughTest {

    public static void main(String[] args) {

        try (FileChannel inChannel = new RandomAccessFile("file_Path", "r").getChannel()){

            // TODO Change in each thread the chunk size to read
            long fileSize = inChannel.size();
            ByteBuffer buffer = ByteBuffer.allocate((int) fileSize);
            inChannel.read(buffer);
            buffer.flip();
            // Do what you want

            inChannel.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

This code reads a file in a unique thread, you would have adapt the code inside a runnable class and pass the FileChannel size in constructor or elsewhere to read the entire file in parallel as described in this question: Can I seek a file from different threads independently using FileChannel?
UPDATE
Unfortunately MappedByteBuffer is not thread safe as it is a subclass of Buffer, as you can see here: Does memory mapped file support concurrent get/put? so you have to use a synchronize mechanism in order to do it in parallel.
One approach would be copy the entire file in a temporal one (this way you ensure that the file will never be modified), and then use a runnable implementation like this
   private class ThreadFileRead implements Runnable {

        private final long ini;
        private final long end;

        public ThreadFileRead(long ini, long end) {
            this.ini = ini;
            this.end = end;
        }

        @Override
        public void run() {
            MappedByteBuffer out = null;

            try {
                out = new RandomAccessFile("FILEPATH", "r").
                        getChannel().map(FileChannel.MapMode.READ_ONLY, ini, end);

                for (long i = ini; i < end; i++)
                {
                    // do work
                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }


text:
Q: An Applescript to remove duplicate fields within the same contact card I noticed that I have many (hundreds) duplicate field names and values in my OS X 10.8.5 Contacts. "Field names and values" are probably not the right words, but what I mean is, that I have many contact cards that seem to have identical fields like this:

The problem is not confined to social profiles. Also emails, addresses, phones, (and maybe more) suffer from duplication.
I got introduced to AppleScript yesterday, and although I do get it a little (can run them, can play around a bit with existing scripts, know about save :)), this is still beyond my capabilities:
I would be really helped by such an AppleScript that removes duplicate fields per card if they have the same type(?) and the same label(?) and the same value(?). (But keeping one instance.)
I can imagine that addresses (with street, postal code, etc), might be asking too much. But, non-composite "fields" would already clean up my address book significantly.
Apologies for surely not getting the technical terms right.

A: This is an example.  Tested on only two contacts which I manufactured duplicate fields. And placed them in a group for testing
This should give you an idea of one way to construct the code.
The example is as is, as I did not want to spend too much time on it. But worked in my tests.
The example will remove duplicate Social profiles and phone numbers fields in a contact.
In the Social profiles the delete action is repeated. This is because the first delete forces the contacts.app to replace the entry with an URL for the social media site.
The construction for the other fields should be relatively easy from here.
Each set of fields i.e phones, social profile, email should have it's own run handler to make the code more manageable. Like I have done here.
You should also note that doing any of this on a large set of contacts could take a very long time.
YOU SHOULD ALSO BACK UP THE ADDRESS BOOK CONTACTS BEFORE PLAYING WITH ANY OF THIS. AND USE AT YOUR OWN RISK
set targetGroup to "BD"

tell application "Contacts" to set thePeople to people of group targetGroup -- TEST GROUP OF PEOPLE
---- tell application "Contacts" to set thePeople to people  -- ALL PEOPLE

(* Run the Handler for  Social profiles*)
my deleteSocialEntries(thePeople)

(* Run the Handler for  phones *)
my deleteSocialPHONE(thePeople)

(* Handlers*)
on deleteSocialPHONE(thePeople)

    tell application "Contacts"

        (* iterate over the people - get each person in the contacts*)
        repeat with i from 1 to number of items in thePeople
            set this_person to item i of thePeople

            (*get all the phones of the person*)
            set theFields to (properties of phones of this_person)

            set keepers to {}
            (* iterate over the phones and get a phone's value*)
            repeat with i from 1 to number of items in theFields
                set this_item to item i of theFields
                set thisValue to value of this_item

                if thisValue is not in keepers then
                    (* Not in the list of keepers so add it*)
                    copy thisValue to end of keepers

                else
                    (* Was already  in the list of keepers try and delete it*)
                    try
                        set thisID to id of this_item
                        set thisD to (every phone of this_person whose id is thisID)

                        delete (item 1 of thisD)

                        save
                    end try
                end if

            end repeat

        end repeat
    end tell

end deleteSocialPHONE

on deleteSocialEntries(thePeople)
    set social to {"Twitter", "Linkedin", "Facebook"}
    tell application "Contacts"

        (* iterate over the people - get each person in the contacts*)
        repeat with i from 1 to number of items in thePeople
            set this_person to item i of thePeople

            (* iterate over the social media types for this person *)
            repeat with i from 1 to number of items in social
                set this_soc to item i of social
                (*get all the *type* of social profiles of the person*)
                set theFields to (properties of every social profile of this_person whose service name is this_soc)

                set keepers to {}
                (* iterate over the ocial profile  and get a user name value*)
                repeat with i from 1 to number of items in theFields
                    set this_item to item i of theFields
                    set thisValue to user name of this_item

                    if thisValue is not in keepers then
                        copy thisValue to end of keepers
                    else
                        (* Was already  in the list of keepers try and delete it*)
                        set thisID to id of this_item
                        set thisD to (every social profile of this_person whose id is thisID)

                        delete (url of item 1 of thisD)
                        delete (user name of item 1 of thisD)

                        delete (url of item 1 of thisD)
                        delete (user name of item 1 of thisD)
                        save

                    end if
                end repeat

            end repeat

        end repeat
    end tell

end deleteSocialEntries


text:
Q: 3 Dimensional Database in SQL I have a question. how do I store 3 dimensional data?
This is an example. Every user should fill this field.
2 Dimension

A: You create another table with foreign key references. For more dimensions, add more tables:
Devices
| deviceId | device | location |
| 1        | xx     | aa       |
| 2        | yy     | bb       |
| 3        | zz     | cc       |

Sensor
| sensorId | deviceId | Type   |
| 1        | 1        | temp   |
| 2        | 1        | rpm    |
| 3        | 2        | temp   |

Data
| dataId | sensorId | value  | timestamp        |
| 1      | 1        | 10     | 2020-01-01 00:00 |
| 2      | 1        | 10     | 2020-01-01 01:00 |
| 3      | 1        | 11     | 2020-01-01 02:00 |
| 4      | 1        | 12     | 2020-01-01 03:00 |
| 5      | 2        | 3100   | 2020-01-01 01:00 |
| 6      | 2        | 3200   | 2020-01-01 02:00 |
| 7      | 3        | 23     | 2020-01-01 01:00 |
| 8      | 3        | 23     | 2020-01-01 02:00 |

A: I would approach this by using three related tables:

*

*User

*RelativeType

*UserRelativeInfo

They would be related like this:


text:
Q: How to use umlauts with ruby's URI library Here is the problem: Ruby's URI library does not deal with umlauts; i.e.
irb> require "uri"
irb* URI("http://abc.de/äöü")
URI::InvalidURIError: bad URI(is not URI?): http://abc.de/äöü

How can I deal with that? This is Ruby 1.9.2, btw.

A: The Addressable gem is what you want to use to deal with IRIs.

A: Call URI.encode before parsing:
require 'uri'
uri = URI(URI.encode("http://abc.de/äöü"))

As a side note, be aware that if the URL contains a hash fragment (#something), you'll have to manually split it:
require 'uri'
uri = URI(URI.encode('http://example.com/page.html') + '#' + URI.encode('anchor'))


text:
Q: How do I remove keys from hash that have a bank value while skipping the first key I'm trying to remove any keys in a hash that has a blank value besides the first key. I'm also trying to do this on one line.
Here is what I have which gives a whole bunch of syntax errors. I keep fiddling with it to try fix the syntax errors but nothing works. Where am I going wrong?
hash.each_with_index do { |(key, value), i| value.blank? && i != 0 ? key.delete :    }

A: One liner:
hash.delete_if.with_index {|(k, v), i| v.nil? && i != 0 }

A: Using select:
h = { a: '', b: '', c: 1 }
puts h.select.with_index { |subh, i| !(subh[1].to_s.empty?) || i == 0 }
# => {:a=>'', :c=>1}

You should think carefully if you really want to rely on ordering when using a Hash though.


text:
Q: Why does Mingw change my identifier name at compile time? I have a small C++ library, compiles fine on Linux (which is my main dev platform). Now I'm trying to build it on a windows machine (XP3) with Mingw, and compiling fails, due to an unexplainable error.
For example, say I have the following method in class AAA, in namespace aaa, declared in file aaa.h:
void AAA::DrawText( foo z );

When compiling file aaa.cpp (that holds of course the methods implementation), I get the following error:
D:\dev\[...]\aaa.cpp:644: error: no 'void aaa::AAA::DrawTextA( foo z )' member function declared in class 'aaa::AAA'

Yep, you got it, no typo there... the compiler misread somehow the functions name, and added a letter to the function identifier !!!
This is absolutely beneath my comprehension. Never had such an issue on Linux. How can mingw / Gcc change an identifier ?
Name mangling ? No, this happens after compiling.
I checked of course the exact command line (I use an IDE): nothing wrong:
mingw32-g++.exe -W  -O3 -Wall    -I..\include -I"C:\program files\OpenCV2.1\include\opencv"  -c D:\dev\...\aaa.cpp -o ..\obj\Release\src\aaa.o

BUT: if I rename the function to, say,  DrawTxt(), then everything goes fine (but I can't do that). This means to me that the identifier is already defined somewhere. Opencv lib ? Grepped the tree, found nothing... And yes, I searched also the current include folder, nothing close.
The other solution that I see is that there is somewhere (?) a macro like:
#define DrawText DrawTextA

that gets activated in some situation.
So my questions are:

*

*Are there other possibilities for this curious name replacement in my code ? To me, the macro is the only way, if the identifier was already declared elsewhere, it would just throw an error, a compiler can not (well...) abruply change/replace/edit an identifier.

*How can I trackdown the problem ?

A: Well, I'm almost certain it's because somewhere this happens:
#define DrawText DrawTextA

Why? Because the suffix A often means "ascii" opposed to the suffix W which means "wide" (often for unicode). This is a common practice in Windows code to unify ascii and unicode builds with a simple define switch.
Also, it seems that the functions exists in the Windows library: http://msdn.microsoft.com/en-us/library/ms901121.aspx. Is windows.h is included in your project?

A: You included windows.h and the DrawText macro replaced DrawText with DrawTextA.
There's not a whole lot you can do about that other than avoid using names that Windows also uses. Not very appealing.


text:
Q: How can I get GA utm parameters in a secondary page in user's session I am using GA universal analytics. I want to get the utm_content parameter of the user, that had come to my page with some. But I want it to get it in any page user visit in that session.
I just thought about reading cookie, but the data is hashed and I understood that Google did not want that way. Some analysis on cookie
can I do it by any API method in Analytics.js or with any other solution?

A: I think you might be able to get use the tracker and call the get method.
It returns the value currently associated with the given field. This should be called on an instantiated tracker object.
ga(function(tracker) {
  car content = ga('get', 'campaignContent', 'content');
});

This function will execute once the analytics.js library has loaded. When the function executes, the tracker parameter will have a reference to the default tracker (assuming it was created prior to the function being called). The tracker reference is then used to get the campaignContent value.


text:
Q: How to make a JFrame display possible errors? Let's say I've got a JFrame and want it to display every exception that has been thrown during runtime in a JTextArea except the ones related to the frame itself. (obviously, because the frame wouldn't open up then). Is this possible?

A: You can gather the output of the stack trace by using a StringWriter and appending the result to your text area as a String. Something like this:
try {
    ...
} catch (Exception ex) {
    StringWriter sw = new StringWriter();
    ex.printStackTrace(new PrintWriter(sw));
    textArea.append(sw.toString());
}

A: No, it is not possible.  In order to display any information at all about a given exception, it is necessary to catch that exception.  You could arrange to catch exceptions that otherwise would go uncaught, and you can arrange to catch exceptions thrown by objects directly under your control, but no object can catch or handle exceptions that are first caught by some other object.

A: You can redirect System.out or System.err to a JTextArea.
See Message Console for one approach.


text:
Q: How to delete only first ocurrence of line without "}" in Powershell? I try to delete carriage return in a file, all lines have a "}" at end, but some lines, have a return carriage and the "}" its down.... Here an example of my code and file, but doesn't work. Thank You Very Much!!
Original File
The line with "INGENIERIA Y SERVICIOS LOS NOGALES SPA" it's the conflict.
Expected Result
Code:
$InputFile='Original.txt'
$OutPutFile='NewFile.txt'
(Get-Content $InputFile) | ForEach-Object -Begin {
$results = @()
} -Process {
$out = $.Split("}").GetUpperBound(0)
[int]$iOut = [int]$out
if($iOut -lt 1){$.Replace("`r`n","")}else{$_}
} | Set-Content $OutPutFile

Thanks!

A: You may do the following:
(Get-Content $InputFile -Raw) -replace '(?<!})\r\n' |
    Set-Content $outputfile

Reading a file using Get-Content without the -Raw or -ReadCount parameters, reads each line and outputs it as an array element. A line is output once its delimiter has been found. The default delimiter for Get-Content is the end of line character. -Raw allows newline characters to be preserved and the file is read as a single string.
(?<!}) is a negative lookbehind matching only when the preceding character is not a }. Then we simply match \r\n for CRLF.


text:
Q: Displaying Max value and ID Number attached to it I'm working on using aggregate functions in mysql and have run into a problem: I want to take the maximum value in a column and display it alongside the ID Number that maximum value is attached to.
So, I have a few columns. One contains an ID Number, one contains hours worked, and one contains funds raised (It's a test database of a fictional volunteer organization). Basically, I want to take whoever volunteered the most hours and display the number of hours they worked with the ID Number.
I can display the max hours just fine using this code:
SELECT MAX(HoursWorked) AS 'Most Active' FROM HoursWorked
However, when I try adding a function to find that ID Number, I either get an error or an ID Number that I do not want (I know it's the one I don't want because I looked at the table beforehand and know which ID Number is the one with the maximum hours).
How do I word it to fix the error?

A: My idea would be to do it in two steps

*

*find the max value

*find the rows where HoursWorked = max value

This can be done using the statement below with subquery:
SELECT id, name, HoursWorked FROM HoursWorked where HoursWorked = (select max(HoursWorked) from HoursWorked);`

In the subquery you are looking for the biggest value of HoursWorked using aggregate function max(), and then in main query you are trying to find all the rows where HoursWorked value is equal to this previously found max value.
This way you are able to identify the situation when two or more volunteers are the most active (the same number of hours worked)

A: If you are not grouping by any fields then you can pick the highest HoursWorked by sorting in descending order as follows:
SELECT TOP 1 ID, HoursWorked FROM HoursWorked ORDER BY HoursWorked DESC


text:
Q: How to watch for UNHANDLED exceptions only using WaitForDebugEvent family functions? I'm trying to catch unhandled exceptions in the application and restart it on them using WaitForDebugEvent function. But I can't tell when exception is handled by application (try..catch for example) and when is not. How do I do that? There seem to be no such data in DEBUG_EVENT structure.

A: If your not catching certain exceptions using WaitForDebugEvent, you might want to try injecting an UnhandledExceptionFilter as well. other than that, check that your processing matches Microsofts Example

A: In the EXCEPTION_DEBUG_INFO structure, which is in the DEBUG_EVENT structure, there is a field dwFirstChance:

If the dwFirstChance member is nonzero, this is the first time the debugger has encountered the exception. Debuggers typically handle breakpoint and single-step exceptions when they are first encountered. If this member is zero, the debugger has previously encountered the exception. This occurs only if, during the search for structured exception handlers, either no handler was found or the exception was continued.

So you will want to look for times where dwFirstChance is 0.
But if you just want to restart your app when it fails, it might be easier to create another app to watch for the failure of the first one, rather than using the Windows debugging api.


text:
Q: Expression Expected Im getting a build error with the following code...
Private Property GridViewSortDirection() As String

    Get
        Return If(TryCast(ViewState("SortDirection"), String), "ASC")
    End Get
    Set(ByVal value As String)
        ViewState("SortDirection") = value
    End Set

End Property

It is happening on the following line...
Return If(TryCast(ViewState("SortDirection"), String), "ASC")

Error returns...
Error   11  C:\inetpub\wwwroot\TPSupport\main\UserControls\grid.ascx.vb(192): error BC30201: Expression expected.
Any Idea's
Thanks
Its a convert from c#
private string GridViewSortDirection
{
   get { return ViewState["SortDirection"] as string ?? "ASC"; }
   set { ViewState["SortDirection"] = value; }
}

A: I am not familiar with VB but use of If keyword shows that you are doing comparison between result of TryCast and "ASC",
Try this way, by using appropriate comparison operator like
 Return If(TryCast(ViewState("SortDirection"), String) <> "ASC")

A: What compiler version are you using? I suspect that you inadvertently switched to a version of VB (< 9.0) that doesn't yet support the conditional operator.


text:
Q: html select element closes immediately upon a click in ios My issue is that I have two selects on a page and when I click on anyone one of them, the second one will automatically close when ai touch it, but only when I do it the first click, afterwards it works fine.
Here is my react element
"use client";

import React from "react";
import styles from "./Dropdown.module.scss";
import { BsChevronDown } from "react-icons/bs";
export const Dropdown = ({
  name,
  value,
  onChange,
  required = false,
  children,
}: {
  name: string;
  value: string;
  onChange: (e: React.ChangeEvent<any>) => void;
  required?: boolean;
  children: JSX.Element[];
}) => {
  return (

      <select
        className={styles.dropdown}
        value={value}
        name={name}
        onChange={onChange}
        required={required}
      >
        {children}
      </select>

        <BsChevronDown />

  );
};

Here is my CSS
.container {
  position: relative;
  display: flex;
  align-items: center;
}
.dropdown {
  width: 100%;
  border-radius: 4px;
  height: 45px;
  outline: none;
  border: 1px solid #e9ecef;
  padding: 8px 16px;
  background-color: transparent;
  cursor: pointer;
  font-family: Lato, sans-serif;
  font-size: 15px;
  letter-spacing: 0.5px;
  -moz-appearance: none; /* Firefox */
  -webkit-appearance: none; /* Safari and Chrome */
  appearance: none;
  color: black;
}

.caret {
  position: absolute;
  right: 16px;
  pointer-events: none;
  cursor: pointer;
  & > svg {
    color: #adb5bd;
  }
}

I made sure it wasn't caused by CSS.


text:
Q: Source code changes but not effect in Maven war I have a strange problem in Eclipse.When i change in Java files like Controller and  clean install maven.The controller as it is.There is no change in war.I delete all controllers but still my project working.I tried my methods like check build automtically,clear metadeta in workspace.Can anyone help me please.

A: When you change the source code and do mvn clean install you will get the newly compiled source code in the war. You probably made some other error like

*

*Changing the code of the wrong project.

*Changing code that is never called or does not affect the behaviour of the war.

*Not deploying or starting the new war, but some old version.


text:
Q: how can I add index as key value in a list of dict in python? I have a list like below -
[{'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z'}, {'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z'},
{'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z'}]

Need to add index key and its value in these three records.
Expected output -
[{'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z','index':0}, {'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z','index':1},
{'amount': 1100000, 'target': 120000, time': '2022-09-30T00:00:00.000Z','index':2}]

Please help.

A: Try:
lst = [
    {"amount": 1100000, "target": 120000, "time": "2022-09-30T00:00:00.000Z"},
    {"amount": 1100000, "target": 120000, "time": "2022-09-30T00:00:00.000Z"},
    {"amount": 1100000, "target": 120000, "time": "2022-09-30T00:00:00.000Z"},
]

for idx, d in enumerate(lst):
    d["index"] = idx

print(lst)

Prints:
[
    {
        "amount": 1100000,
        "target": 120000,
        "time": "2022-09-30T00:00:00.000Z",
        "index": 0,
    },
    {
        "amount": 1100000,
        "target": 120000,
        "time": "2022-09-30T00:00:00.000Z",
        "index": 1,
    },
    {
        "amount": 1100000,
        "target": 120000,
        "time": "2022-09-30T00:00:00.000Z",
        "index": 2,
    },
]

A: lst = [
{"amount": 1100000, "target": 120000, "time": "2022-09-30T00:00:00.000Z"},
{"amount": 1100000, "target": 120000, "time": "2022-09-30T00:00:00.000Z"},
{"amount": 1100000, "target": 120000, "time": "2022-09-30T00:00:00.000Z"},
]
for i in range(len(lst)):
    lst[i]['index']=i
print(lst)

Output

[{'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z', 'index': 0}, {'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z', 'index': 1}, {'amount': 1100000, 'target': 120000, 'time': '2022-09-30T00:00:00.000Z', 'index': 2}]


text:
Q: REST Jersey GET PUT conflict I am using jersey version 1.17.1 + tomcat 7.0.39 + Spring MVC 3.2.1.
The problem is that I am not able to figure out why my PUT handler stops working when I extend a @Path of a GET handler?
The following configuration/matching in my Spring MVC controller works as expected:
 @GET
 @Path("/{id}")   // <--- WORKS!
 [...]

 @PUT
 @Path("/{id}")   // <--- WORKS!
 [...]

but whenever I extend matching of the GET handler in order to be able to
handle not only
/anyId

requests but also requests of the forms
/anyId/
/anyId/anyfile.ext

then not touched the PUT matching stops to work:
 @GET
 @Path("/{id:.*[^/]}{fileName:.*}")   // <--- WORKS!
 [...]

 @PUT
 @Path("/{id}")                       // <--- Not working any longer:
                                      //      "405 Method Not Allowed"
 [...]

After changing matching of the GET Path to that above PUT requests get "405 Method Not Allowed" status code.
When I simplify back the GET Path like in the first case the PUT handler starts working again.
Is it a bug of Jersey or what?

A: The 405 indicates that there was no method matching that which was in the request for that resource. This would indicate that something (or several somethings) had a matching @Path annotation, but that (Java) method did not have the right method. (If you can, turn on verbose debugging when looking at what's going on; it helps. Turn it off when you're done though; it's going to be far too verbose for normally being left on.)
Now, it helps to understand that @Path is mapped to a regular expression that matches against the path in the request, and that if you don't specify otherwise, a path template portion (the {id}) is effectively matched by the regular expression [^?/;]+, i.e., as many as possible characters without going into the next part of the path, the query part, or any matrix parameters. (Don't know what a matrix parameter is? You probably don't want to know!)
In order to match all these forms:

/anyId
/anyId/
/anyId/anyfile.ext

you are best off using two Java methods per HTTP method:
@GET @Path("{id}")
…
@GET @Path("{id}/{file:.*}")
…

This works, but it's verbose.

It might be easier to instead return an object that represents the resource and which has the operations defined on it:
class MyResource {
    private String id, file;
    MyResource(String id, String file) {
        this.id = id; this.file = file;
    }
    // Can't remember if @Path is needed on these; "/" is a special case IIRC
    @GET @Path("/") @Produces(…)
    public String get() { … }
    @PUT @Path("/") @Produces(…) @Consumes(…)
    public String put(String message) { … }
}

@Path("{id}")
public MyResource getNoPath(@PathParam("id") String id) {
    return new MyResource(id, null);
}
@Path("{id}/{file:.*}")
public MyResource getNoPath(@PathParam("id") String id, @PathParam("file") String file) {
    return new MyResource(id, file);
}

Like that, you split the code that parses the path from the code that serves up the right method. I do this thing with CXF (another JAX-RS implementation) and it works rather well.

A: A 405 generally means that a suitable method could not be found.  Hard to tell with only the small snippet you have provided but you need to ensure that you have appropriate @Consumes annotations on your PUT methods.
You might also try changing your @Path to something like @Path("{id: [^/]+}/{fileName: .+}") and see if that helps.  If not, please supply your full controller.


text:
Q: How can I get a TABLE to respect the narrower environment in ConTeXt? The narrower environment in ConTeXt is very useful, but TABLEs misbehave inside of it. I would expect a TABLE in a narrower environment to align with the new margin, but instead, the TABLE is aligned with the global margin.
For example, the code below:
\starttext
    Normal text

    \setupnarrower[left=2cm]
    \startnarrower[left]
        Narrower text

        \blank[small]
        \bTABLE
            \bTR \bTC Misbehaving \eTC \bTC Table \eTC \eTR
            \bTR \bTC[nc=2]       :(              \eTC \eTR
        \eTABLE
    \stopnarrower
\stoptext

Produces this output:

How can I get the TABLE to align with the "Narrower text" instead of the "Normal text"?

A: The TABLE environment starts a \vbox, so if it occurs at the beginning of a sentence, it switches to vertical mode. To prevent that, add a \dontleavehmode.
\starttext
    Normal text

    \setupnarrower[left=2cm]
    \startnarrower[left]
        Narrower text

        \blank[small]
        \dontleavehmode
        \bTABLE
            \bTR \bTC Misbehaving \eTC \bTC Table \eTC \eTR
            \bTR \bTC[nc=2]       :(              \eTC \eTR
        \eTABLE
    \stopnarrower
\stoptext

which gives

A: use \midaligned command in front of Narrower Text and in front of \bTable and compile you will get


text:
Q: Background tasks and queue with django I built an infinite drawing app (similar to webcanvas) with django.
I made another small python app able to render areas of the canvas with cefpython.
My goal is to have background tasks on my server to render areas on the canvas which need to be updated (I would like to avoid slowing down my django server):

*

*the main django app would add a render task to a queue whenever users are modifying the canvas,

*the rendering app would use this queue and render the areas in a background thread.

What is the simplest way to do this?

A: I resolve same problem in such way:

*

*Queue stored in PostgreSQL (I used it because it already was, PostgreSQL has enough performance for my purpose and I didn't want overcomplicate infrastructure).

*Render are using multiprocessing module. It's running with upstart. I'm using upstart because it's easiest way to run separate app.

If you want to limit available resource for your application, you can setup
limit in upstart: limit rss 231236400 231236400 (size in bytes), or run application using cpulimit.


text:
Q: Getting italic Computer Modern numerals with Times Roman font elsewhere in math I am typesetting a document in Times Roman (using txfonts). However, the digits (0123456789) when italicized (with \textit{} or \emph{}) do not have the same script-y look as they do in Computer modern. With Times, they merely look slanted.
Is there a way I can use the italic versions of digits from Computer Modern in my otherwise Times Roman document? [I would like to have them available as separate symbols, say \eins, \zwei etc., instead of overwriting the default numbers.] I use script digits for a few purposes, including section headings, characteristic functions of sets (\mathord{\textit{1}}_A), power classes of sets (\mathord{\textit{2}}^\varOmega).

A: A comment up front: The txfonts package, which provides both text and math fonts, has been superseded for several years now by a pair of packages: newtxtext and newtxmath. I can see no good reason for using the txfonts package if the vintage of your TeX distribution is more recent than, say, 2012.
If you can at all switch to LuaLaTeX, it becomes very straightforward to handle almost any number of math fonts side-by-side within a single document. Indeed, for what you appear to have in mind, something like the following setup is entirely sufficient:
\usepackage[no-math]{fontspec}
\setmainfont{STIX Two Text}[Numbers={OldStyle,Proportional}]
\usepackage{unicode-math}
\setmathfont{STIX Two Math}

The "STIX Two" text and math fonts may be downloaded free of charge from https://sourceforge.net/projects/stixfonts/
A full MWE (the use of "old-style", proportional-width text-mode numerals is optional):

% !TeX program = lualatex
\documentclass{article}
\usepackage[no-math]{fontspec}
\setmainfont{STIX Two Text}[Numbers={OldStyle,Proportional}]
\usepackage{unicode-math}
\setmathfont{STIX Two Math}

% macros for characteristic functions and power classes of sets
\newcommand\cfset[1]{\mathit{1}_{\mkern-1.5mu#1}}
\newcommand\pcset[1]{\mathit{2}^{#1}}

\begin{document}
0123456789abcdef   % text: oldstyle numerals, proportional width

$0123456789abcdef$ % math: lining style numerals, fixed width

$\mathit{0123456789abcdef}$ "\mathit" automatically uses Latin Modern glyphs

$\cfset{K}$ $\pcset{\varpi}$
\end{document}


text:
Q: Why does curl -n fail in one script but not others? Why does curl -n fail in one script but not others?
curl 7.67.0 running on MacOS High Sierra
The following code in one script:
host="ftp.xxxxxx.com/public_html/"
/opt/local/bin/curl -n -T $file $host -v

Gives me this:
> USER xxxx
< 331 User xxxx OK. Password required
> PASS xxxxxxxxxx
< 230 OK. Current restricted directory is /

The following code in another script:
host="ftp.xxxxxx.com/public_html/"
/opt/local/bin/curl -n -T $file $host -v

Gives me this:
* Couldn't find host ftp.mgnewman.com in the .netrc file; using defaults
<snip>
> USER anonymous
< 331 User anonymous OK. Password required
> PASS ftp@example.com
  0     0    0     0    0     0      0      0 --:--:--  0:00:05 --:--:--     0< 530 Login authentication failed
* Access denied: 530

Both scripts are bash scripts and located in the same directory of the same machine. There is only one .netrc file. Obviously it is OK as one script uses it with success. The curl code and host variable are the same. In fact, the code in the first script was copied directly from the second script.
How do I figure out why one curl command can use the .netrc file but the other can't? There must be something in the second script that causes the curl failure, but I have no idea what it might be.

A: Your problem is the records in .netrc file. You have it for the first host and not for second host. What you can do is to add such record for second host. The expected format is:
machine <host name>
login <user-email or anonymous>
password <user-password or some mail for anonymous access>

Depend of the OS the required record can be:
machine <host name> login <user-email or anonymous> password <user-password or some mail for anonymous access>


text:
Q: Assign multiple numbers to one turtle in NetLogo For a course I'm following, I have to design some sort of AI that can navigate through a given 'terrain' which contains enemies (give damage), friends (lower the damage), obstacles (decrease energy) and stations (increase energy).
Before I proceed to the actual AI part, I want to have to the underlying point system in order. My question is; Is it possible to show 2 numbers at 1 turtle? I want to show damage as well as energy by the robot.
The energy part looks like the following:

to hit-station
   ask robots
    [ if pcolor = green
    [ set pcolor black set energy (energy + energy-from-station) ]
          ifelse show-energy?
          [ set label energy ]
          [ set label "" ]
]
end

Now this works perfectly fine since I made a switch for showing the energy. The problem arises when i want to add a number for the damage. I made a switch for this as well and the code part looks like the following:
    to hit-obstacle
      ask robots
      [ if pcolor = red
      [ set pcolor black set energy (energy + energy-from-obstacles) ]
           ifelse show-damage?
           [ set label damage ]
           [ set label "" ]
]
end

I don't receive an error but the damage doesn't seem to show (the damage code part is beneath the energy code part).
Is this possible and is there a way to assign a different color to the numbers?
Thanks a lot in advance,
J.V.

A: Using turtles-own, you can assign as many attributes to a turtle as you wish.  But a turtle can only have one value for its label.  You must decide what is to happen if you have a turtle that finds both a station and an obstacle.  You can show the energy, or show the damage, or show a label incorporating both.  In terms of your code above, note that you never set damage (only energy), so you are probably just seeing a 0 label when damage is reported.


text:
Q: Subdomain hosting I have www.mydomain.com hosted elsewhere. I have the registrar point mysubdomain.mydomain.com point to Windows2008 r2 a completely different server. I go to edit bindings for the site add mysubdomain.mydomain.com  but it never works bringing up the site.

A: Is your registrar the DNS host? You must also make sure it created an A-record for the subdomain to point to your Win2008R2 server. Try to ping your subdomain and see where it resolves. If the ip address resolves to something else than your Win2008 server, then it's a DNS misconfiguration. If the IP address is your Win2008 server, then it's a configuration problem on IIS.


text:
Q: TPUT=/bin/true Syntaxt Could someone please explain the shell syntax TPUT=/bin/true pls?
I could find the explanation on of TPUT and /bin/true separately but I can't understand how the 2 work together. I am new to shell, sorry if this is mundane question for most of you. Thanks !


text:
Q: iOS Unity Asset Bundle Download Restrictions - Particle Effects, Animations, and Animated Assets On the Official Unity Website (this article) they have a list of instructions for creating and persisting downloadable asset bundles on iOS devices. The following is an excerpt which arose some questions for me:

Please note: Any game scripts included in downloadable content must
  also be present in the main executable.

This post is the closest answer I kind find on the subject however shaders have dynamically executed code while animated assets and particles, to my knowledge, are executed from code already compiled within the Unity Game Engine.
Are particles, character animations and animated assets considered to be 'game scripts' by Apple? I would like to include these along with several static assets such as textures and meshes as downloadable content within my game.
Thank you.

A: I'm not sure I follow your question here, and I never worked with In App purchase. But I am developing with Unity and iPad and I can download AssetBundles with no major problems, so...

Are particles, character animations and animated assets considered to be 'game scripts' by Apple?

All that sure can be "added" later through downloading asset bundles. But maybe you'd need to make this control outside of Apple's purchase system, even while using it. All it takes is making a wrapper.


text:
Q: Nginx 403 error while using kubernetes volumes I am trying to use Kubernetes volumes for Nginx, but am facing an issue with it. After volumes are set Nginx is unable to serve the HTML page. Also am tried with PV and PVS this time also got the same error.
nginx.yml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx

spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      volumes:
        - name: nginxhtml
          # persistentVolumeClaim:
          #   claimName: pvc
          hostPath:
            path: /home/amjed/Documents/SPS/k8s/mongo/mnt
      containers:
        - name: nginx
          image: nginx
          volumeMounts:
            - name: nginxhtml
              mountPath: /usr/share/nginx/html

          ports:
            - containerPort: 80

---
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  selector:
    app: nginx
  type: LoadBalancer
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80

A: First, create folder that you want to mount inside minikube:
dobrucki@minikube:~$ minikube ssh
Last login: Tue Jan 11 13:54:50 2022 from 192.168.49.1
docker@minikube:~$ ls -l
total 4
drwxr-xr-x 2 docker docker 4096 Jan 11 13:56 nginx-mount

This folder is what is mapped to /usr/share/nginx/html inside Pods, so files you paste here will be displayed when you connect to your service.
Make sure that you have some .html file inside that folder, otherwise you will get 403 error. For me, example index.html is this:

Hello World

You also need to add securityContext fsGroup inside your Deployment manifest, so that /usr/share/nginx/html is owned by nginx user (101 uid).
Then, apply Deployment and LoadBalancer resources using this:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      securityContext:
        fsGroup: 101
      volumes:
        - name: nginxhtml
          hostPath:
            path: /home/docker/nginx-mount
      containers:
        - name: nginx
          image: nginx
          volumeMounts:
            - name: nginxhtml
              mountPath: /usr/share/nginx/html
          ports:
            - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  selector:
    app: nginx
  type: LoadBalancer
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80

After that you can check if the content is served correctly
dobrucki@minikube:~$ curl $(minikube service nginx-service --url)

Hello World

Let me know if you have more questions.

A: *

*reduce the replica count to 1

*verify that /home/amjed/Documents/SPS/k8s/mongo/mnt location is valid and is accessible from the pod


text:
Q: Field Modified shows date, but no time In a view of a document library I have the field "Modified" and this is showing only dates but no time. I would like to display the time aswell.
From my understanding it is ill advised to alter this field OOTB, but rather to create a calculated field and format it the way I want.
I have checked the column properties for this Modified-field, and it is set to "Date and time", which is why I find it curious that it only displays the date. In any case I have created another (calculated) field which I am attempting to format the way I want, but with not luck.
Under the Formula section of this new calculated field I am attempting to format "Modified" like this:
=TEXT([Modified],"dd.MM.yyyy hh:mm")

I want the result to appear like this 14.10.2014 15:59. However, when trying to save the above formula I get the "Sorry, something went wrong" page and the mention that the syntax is probably wrong. I am unable to see any obvious errors with the syntax and have tried a multitude of approaches - like removing the "", removing [] from modified and so forth.
I need the field to display time aswell and I am not sure if this is the best approach either. Anyone got any tips to how I could do this? Perhaps the calculated field approach isn't the best either?

A: The point is that formula expression is usually language dependent.
For example, is site locate is set to 1033 (English - United States), then the formula you have provided in the question is absolutely correct:
Syntax: TEXT(value,format_text) Source
But let's say the site locate is set to 1049 (Russia), in that case the proper syntax would be:
ТЕКСТ(значение;формат)

What matters here is delimiter, as you can see it is ; for 1049 locale  and not , like in case of 1033 locale.
Solution

*

*Identify the locate of SharePoint site (go to Regional Settings - see the figure 1)

*Go to A list of available functions and verify the proper
syntax for a function according to the language specified (see figure 2 and 3)

Figure 1. How to identify Locale settings

Figure 2. TEXT formula for 1049 locale (e.g. 1049 locale)

Figure 3 How to determine formula syntax

Update
How to set Time Format

References

*

*Overview of formulas and functions

*A list of available functions

A: Check your Site Columns definition; when I look at a Modified column in a document library, I see date and time.
Either Site Column or Site Content Type (I believe Site Column is the driver), check your params.
Column Name: Date Modified (from Existing Core Document Columns)
In additional column settings:
     Date and Time Format: **Date and Time**

A: In SharePoint 2016 the Modified column can be updated to a Display Format of "Standard" instead of "Friendly" to show the time (and, if applicable, current year).


text:
Q: Custom unwind segue class not work properly in Swift, why? The following unwind segue class is not presenting the original VC to its original state and sliding from left-right -->| and reloading the data as expected after being segue right to a secondary VC.
The original VC is in a UITabBarController, the tabbar at the bottom is still showing but the rest of the screen is blank.
Question: How do i unwind back reverting the initial segue to the secondary screen?
class UnwindSegueFromRight: UIStoryboardSegue {

override func perform(){

    let src = self.source
    let dst = self.destination

    src.view.superview?.insertSubview(dst.view, at: 0)
    dst.view.transform = CGAffineTransform(translationX: -src.view.frame.size.width, y: 0)

    UIView.animate(withDuration: 0.25,
                   delay: 0.0,
                   options: UIViewAnimationOptions.curveEaseInOut,
                   animations: {
                    dst.view.transform = CGAffineTransform(translationX: 0, y: 0)
    },
                   completion: { finished in

                    src.dismiss(animated: false, completion: nil)
    })
}
}//end class

I have the following SegueFromRight class which works perfectly. But my corresponding unwind segue to that above is not working.
class SegueFromRight: UIStoryboardSegue {

override func perform(){

    let dst = self.destination
    let src = self.source

    src.view.superview?.insertSubview(dst.view, aboveSubview: src.view)

    dst.view.transform = CGAffineTransform(translationX: src.view.frame.size.width, y: 0)

    UIView.animate(withDuration: 0.25,
                   delay: 0.0,
                   options: UIViewAnimationOptions.curveEaseInOut,
                   animations: {
                    dst.view.transform = CGAffineTransform(translationX: 0, y: 0)
    },
                   completion: { finished in
                    src.present(dst, animated: false, completion: nil)
    })
}
}


text:
Q: belongs_to_many userstamps in Rails Im tryign to update a model of mine so that it will have a created_by and updated_by field. Looking into some questions and answers here, it seems I don't have the same problem as them.
My TestCase model should have a created_by and updated_by foreign key, but it should both be a User class. Is that possible?
something like:
belongs_to :user, :foreign_key => 'created_by'
belongs_to :user, :foreign_key => 'updated_by'

Keep in mind that created by and updated_by can be different(meaning another user can edit the testcase)

A: Try to use:
belongs_to :creator, :class_name => "User", :foreign_key => 'created_by'
belongs_to :updater, :class_name => "User", :foreign_key => 'updated_by'

You should refer to that objects through:
item.creator
item.updater


text:
Q: Drupal: simple form forwarding data to another server I need to add a page with a form in my Drupal website. This form should be submitted to another server (there is a php script ready to receive it on such server).
So, I don't need any database update, just a page forwarding the data inserted by users to another domain.
Do you know what's the easiest way to do it ?
thanks
ps. Also, I need to create a drop down menu with a list of countries (and regions for each country) as submenu

A: I am surprised noone mentioned hook_form_alter and setting #action to an external URL. This will make the form post directly to the other server if you have control of it you can easily redirect back. Lot easier than POSTing from your server. Another way would be to iframe the other script and use the target attribute (set $form['#attributes']['target'] = 'the_iframe' in hook_form_alter). Then you can use JS to 'move' the page after the submit. Upload POSTs to an iframe, you can look into that JS as well. How do you post to an iframe? discusses iframes and forms.

A: In your form, you can set #action to whatever URL you want. It will post to that url. If you need a GET, instead of a POST, you should also set the #method.
function my_form_builder() {
  $form['search'] = array(
    //..builds some form elements
  );

  $form[#action] = 'http://example.com';

  return $form;

}

A: You could create a regular drupal form with the ususal validation stuff and instead of putting the date into the DB send it over to the other site (via post or get or whatever).

A: To POST to an external URL in your own custom form implementation or using hook_form_alter() to add another submit handler to an existing form, while not showing the request you will want to use drupal_http_request() to send a serverside http request. See this:
http://www.drupaler.co.uk/blog/validating-submitting-forms-other-websites-drupal/428
To accomplish this with the webform module you'll need what you learned above and something like the following:

*

*In D6 /Webform < 3
http://drupal.org/node/543674#comment-2499674

*In Drupal 7/Webform 3
http://www.midwesternmac.com/blogs/jeff-geerling/integrate-webform-3x-paypal


text:
Q: Reach parameters in trigger function postgreSQL I'm trying to write a trigger before insert to check if parameters match requirements. I tried many things and if I hardcode values for the d and e it works as expected and raise an error in case if e!=d. But when I replace it with variables from NEW it doesn't work. Table with a trigger has columns id and languagetag_id.
Could you please tell me what I do wrong?
CREATE or replace FUNCTION insert_name() RETURNS trigger AS $insert_name$
declare d int;
declare e int;
    begin
        d = (select distinct languagetagid from "scheme".table1 as a
                                    left join "scheme".table2 as b on (a.id = b.country_id )
                                    where b.id = NEW.id);
        e = NEW.languagetag_id;
    IF ( e != d ) THEN
                RAISE EXCEPTION 'error: % ', e;
    END IF;
    RETURN NULL;
    END;
$insert_name$ LANGUAGE plpgsql;

CREATE TRIGGER insert_name BEFORE INSERT or UPDATE ON "scheme".table
    EXECUTE PROCEDURE insert_name();

A: To access the NEW and OLD values, the trigger must be executed for every row, not for the entire statement
CREATE TRIGGER insert_name BEFORE INSERT or UPDATE ON "scheme".table
     FOR EACH ROW EXECUTE PROCEDURE insert_name();


text:
Q: Relationship between two probability measures Consider an actuarial risk model for a potential loss X with Pareto density $$f(x)=\frac{ac^a}{x^{a+1}}$$ for $x \geq c$, $a>0$, $c>0$..
What is the relationship between $P(A)$ and $PX^{-1}(X(A))$ for a given $A\in F$? Notice that $P(A)$ and $PX^{-1}$ are two probability measures.
I am really confused on $(X(A))$ in $PX^{-1}(X(A))$. I do not know how to interpret this.
I have in my notes that The probability distribution/law of $X$ is the induced probability measure $\mu = PX^{−1}$ on $R$:$$\mu(A)=PX^{−1}(A)=P(X^{−1}(A))\equiv P(X \in A)$$ for any $A\subseteq R$.
What I did so far is that I took $X$ as a bijective, since it is invertible. Then I wrote $A=X^{-1}(X(A))$ meaning these measures would be equal. Does this make any sense?


text:
Q: What does "genking" mean?
Possible Duplicate:
What is "ganking"?

While watching a youtube video, I came across a sentence that went something like "as an assassin, you want to be constantly 'genking' for your team mates." (Since it was a video, I'm not 100% about the spelling). I tried googling, but had trouble finding something helpful...
Could someone please enlighten me about the meaning of "genking"? Is it a general concept, or is it specific to the game League of Legends? I haven't actually played this game myself, I am just curious.
In case you'd like to see exactly what I'm talking about, it happens around 3:10 in this video.
Thanks in advance for your help!

A: I suspect they meant to say "ganking".

A: I think it was probably "ganking".  Assassins should theoretically be able to quickly slit the throat of random enemies that come up, so in a sense it's "overkill" like ganking.  See http://www.urbandictionary.com/define.php?term=ganking


text:
Q: Amazon SWF distributed storage I'm writing on Amazon SWF and faced with the problem:
I need to keep some values in place that available for all execution parts of SWF
For example, I store the value in activity and want to read it in child workflow.
Of course I can use staff like memcache, but may be exist any standard mechanism from SWF to perform this?

A: If value is small an activity should return it to the workflow in its result and the workflow will pass it to the child workflow as a parameter. If value is large then you can store it somewhere (S3 for example) and pass around reference to it.

A: From the SWF documentation:

Maximum input/result data size: 32,000 characters
This limit affects activity or workflow execution result data, input
  data when scheduling activity tasks or workflow executions, and input
  sent with a workflow execution signal.

If the data you want to move between is bigger than this, than you will need to use an intermediate storage, for example S3.


text:
Q: Combine prisms to focus on a value regardless of a branch I have a sum type of possible outcomes, and in every outcome there is a certain "Result" that I want to focus on. I know how to get that "Result" from each of the outcomes (I have a bunch of prisms for that), but I don't know how to combine these prisms so that I can grab the "Result" from the whole sumtype, without worrying which case I'm on.
Simplified example:
type OneAnother = Either Int Int

exampleOneAnother :: OneAnother
exampleOneAnother = Left 10

_one :: Prism' OneAnother Int
_one = _Left

_another :: Prism' OneAnother Int
_another = _Right

_result :: Lens' OneAnother Int
_result = ???
-- How can I combine _one and _another to get result regardless whether its left or right ?

A: Once a prism comes to focus, it loses the context. So I don't see a way to define _result in terms of _one and _another. But you can certainly do better than resorting to unsafePartial:
import Data.Lens.Lens (Lens', lens)
import Data.Profunctor.Choice ((|||), (+++))

type OneAnother = Either Int Int

_result :: Lens' OneAnother Int
_result = lens getter setter
  where
  getter      = identity ||| identity
  setter e x  = (const x +++ const x) e

Stole this from the profunctor-lens repository:
-- | Converts a lens into the form that `lens'` accepts.
lensStore :: forall s t a b . ALens s t a b -> s -> Tuple a (b -> t)
lensStore l = withLens l (lift2 Tuple)

It isn't exported somehow. With that help, the following solution should be generic enough:
import Prelude
import Control.Apply (lift2)
import Data.Lens.Common
import Data.Lens.Lens
import Data.Lens.Prism
import Data.Profunctor.Choice ((|||), (+++))
import Data.Tuple

_result :: Lens' OneAnother Int
_result = lens getter setter
  where
  getter      = identity ||| identity
  setter e x  = (const x +++ const x) e

lensStore :: forall s t a b . ALens s t a b -> s -> Tuple a (b -> t)
lensStore l = withLens l (lift2 Tuple)

data ABC
  = A Int
  | B (Tuple Boolean Int)
  | C OneAnother

lensABCInt :: Lens' ABC Int
lensABCInt = lens' case _ of
  A i -> map A <$> lensStore identity i
  B i -> map B <$> lensStore _2 i
  C i -> map C <$> lensStore _result i

Here ABC is your target sum type. As long as its each variant has a lens, you have a lens for it as a whole.

A: This is the best I've got so far. Yes, unsafePartial, explicit case matching ... Really hope there is something better.
_result :: Lens' OneAnother Int
_result = lens getter setter
  where
  getter :: OneAnother -> Int
  getter x@(Left _) = unsafePartial $ fromJust $ preview _one x

  getter x@(Right _) = unsafePartial $ fromJust $ preview _another x

  setter :: OneAnother -> Int -> OneAnother
  setter (Left _) x = review _one x

  setter (Right _) x = review _another x


text:
Q: How to move a view onto another view with animation I want to make a button which will move onto a specific view when pressed and will come back when pressed again. How can i achieve this? Is there any library or sample code?

A: You can use ObjectAnimator for achieving this, to animate a view to your desired directions.  There is also a simplified library
https://github.com/daimajia/AndroidViewAnimations
Let me Know if it helps you.


text:
Q: add an entry to the DPDB in aframe I'm using AFRAME in an app for the Pico Goblin device.
Unsurprisingly, I'm getting the "No DPDB device match." error and the camera moves at the wrong speed and appears upside down.
I realise this is because this device is unlikely to be in the official webvr-polyfill DPDB.json
Is it possible to add devices to this file and use within aframe?
Thanks

A: This is the repo where the dpdb file lives: https://github.com/immersive-web/webvr-polyfill-dpdb
You can indeed submit PRs there. A-Frame will pick it up in the next version.
In the meantime you can have a custom build of A-Frame that points to your fork of the webvr-polyfill that fetches your own DPDB.json


text:
Q: PhP Contact form in Wordpress So I bought a theme that has a simple PHP contact form that allows users to message each other, but when a sender fills out the form and submits it, the email comes from my default Wordpress Admin email and not the email address the user inputs in the form. So if the receiver tries to reply to their email, it's going to come to me (Admin) and not the person who sent the email.
Am I missing something here...seems pretty straight forward. I've tried changing it up and using $headers, etc., but nothing works... always just comes from my admin email.
Here is the form code:
<form method="post"><input type="hidden" value="<?php the_ID(); ?>" name="pid_rep" />

<?php echo __('Your Email'); ?>:

<input type="text" size="50" class="do_input"  name="email" />

<?php echo __('Message'); ?>:

<textarea rows="4" cols="40" class="do_input" name="message"></textarea>
    <<input type="submit" name="contact" value="<?php _e('Send Message'); ?>" />

</form>

Here is the handler:
    $email = $_POST['email'];
    $message = nl2br($_POST['message']);

A: As I know it is a WordPress security setting and you can't change it. The email sender's domain name must be equal with your website domain name.
Possible to define a custom, even not existing sender email address and sender name, you can do it with this plugin: WordPress Contact Form Slider


text:
Q: Web.Config transforms: Using Insert() to transform multiple elements Using Visual Studio 2013 Premium.
Goal: I have multiple WCF services defined in a web.config. To keep the web.config file readable and make adding services simpler, I want to use VS2013's XML transforms to add some boilerplate elements to each service definition for my dev/production environments.
Problem: I have multiple <service> tags, but only the first one is transformed properly.
Here's a simplified version of my Web.Config with two services defined:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="AppName.AccountManagerService">
        <endpoint address="AccountManagerService" binding="netTcpBinding"
          bindingConfiguration="" contract="Shared.Contracts.IAccountManagerService" />
      </service>
      <service name="AppName.TicketManagerService">
        <endpoint address="TicketManagerService" binding="netTcpBinding"
          bindingConfiguration="" contract="Shared.Contracts.ITicketManagerService" />
      </service>
    </services>
</configuration>

I want to create a Metadata exchange endpoint and do some other things (not shown) to each <service> tag.
Here's a simplified Web.Debug.Config showing only the MetadataExchange endpoint:
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.serviceModel>
    <services>
      <service xdt:Locator="XPath(/configuration/system.serviceModel/services/service)">
        <endpoint kind="mexEndpoint"
                  address="mex"
                  xdt:Transform="Insert()"
                />
      </service>
    </services>
  </system.serviceModel>
</configuration>

I get this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="AppName.AccountManagerService">
        <endpoint address="AccountManagerService" binding="netTcpBinding"
          bindingConfiguration="" contract="Shared.Contracts.IAccountManagerService" />

        <!-- Yay! -->
        <endpoint kind="mexEndpoint"
                  address="mex"
                />

      </service>
      <service name="AppName.TicketManagerService">
        <endpoint address="TicketManagerService" binding="netTcpBinding"
          bindingConfiguration="" contract="Shared.Contracts.ITicketManagerService" />

        <!-- Hey, where's the endpoint tag for this one? -->

      </service>
    </services>
</configuration>

I've tried these variations on the XPath argument in the xdt:Locator attribute of the :
1. /configuration/system.serviceModel/services/service
2. /configuration/system.serviceModel/services//service
3. //service

All of which transform only the 1st <service> section.
I've tried putting the xdt:Locator attribute on the <endpoint> tag, etc. to no avail.
I have multiple XPath visualizers and tools, and all of them match both <service> tags when used with XPath #1 above.  Also, this error happens in "Preview Transform" and the web deployment tool preview.
What am I doing wrong?
(My workaround, at this point, is to include the Mex endpoint and the rest of the debugging cruft in my original Web.Config, and then remove it with "RemoveAll()", but that makes my Web.Config really cluttered and hard to read.)

A: I recently ran into this issue, and it turns out it isn't supported.
My work around was adding a custom transform, and using that instead of Insert. The issue with their implementation is that the default Insert only modifies the first value (even though the XPath expression does retrieve a list).
The XDT source can be found here: http://xdt.codeplex.com/
The article I ran across that got me in the right direction: http://blog.appharbor.com/2012/07/27/custom-web-config-transforms-and-merges
What I did is add a new class to their source, and was able to achieve exactly what you are looking for.
internal class InsertMultiple : Transform
{
    public InsertMultiple()
    {
        //this is the line that allows it to apply the transform for all nodes
        //that were located with your XPath expression.
        ApplyTransformToAllTargetNodes = true;
    }

    protected override void Apply()
    {
        CommonErrors.ExpectNoArguments(Log, TransformNameShort, ArgumentString);

        TargetNode.AppendChild(TransformNode);

        Log.LogMessage(MessageType.Verbose, SR.XMLTRANSFORMATION_TransformMessageInsert, TransformNode.Name);
    }
}


text:
Q: Quick Java String/toString Printing one char on each line I need to take a String, and print each character of it on a seperate line.
I would use a for loop right?
    public String toString(){
    for (int count=0; count < password.length(); count++)
    {
        System.out.print(password.charAt(count));
        System.out.print("\n");

    }
    return password; // I am confused on this. I don't want it to
                       //return anything, really but I cannot make return type void

}

Is what I have, but I keep getting NullPointExceptions. I have a method above that stores the password from the input, and the variable is defined in the class. So, I figured it would pull it from that.
My Question is: How would I take a string and print each character from it, one on each line?

A: This would do the job:
String s = "someString";
for (int i = 0; i < s.length(); i++) {
    System.out.println(s.charAt(i));
}

A: First of all, "toString" is a bad choice for a function name because it's one of the standard methods available on every object. That's why its a compile error to make its return type "void". As for printing one char on every line:
public void printStringChars(String password) {
    if(password == null) {
        return;
    }

    for (int count=0; count < password.length(); count++) {
        System.out.println(password.charAt(count));
    }

}

A: No, you don't need a for loop. :)
one line code could achieve your goal:
System.out.println(yourString.replaceAll(".", "$0\n"));

A: If you don't want to return anything, you really shouldn't be overriding the toString() method. You should probably have a separate method such as:
public void printToConsole() {
    for (int count=0; count < password.length(); count++) {
         System.out.println(password.charAt(count));
    }
}

However, that's not the cause of your problem - I suspect the cause is that password is null. But you haven't shown us where you're trying to get that from...

A: You also can do this
import java.util.Scanner;

class que22 {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("enter here your string");

        String a;

        a = input.nextLine();

        for (int i = 0;i < a.length(); i++ ) {
            System.out.println(a.charAt(i));
        }
    }
}


text:
Q: get count of a value from multiple table I have two tables
tbl1
ID     | ID1    |  ID2
------ | ------ | ------
1      | 3      |   5

tbl2
   ID     | NAME   |  ID2
   ------ | ------ | ------
   1      | RAJ    |   5
   2      | SAM    |   3
   3      | RAM    |   5
   4      | RIO    |   2
   5      | ROY    |   5
   6      | TIM    |   5

Now what i am struggling to do was ,
Take the ID2 in tbl1 i.e., 5 then get the rows of ID2 in tbl2 with the value 5
Now count the number of rows with 5 in tbl2
check whether it is greater than or less than the value of ID1 in tbl1 i.e, 3
if greater then echo true else echo false .
In the above case it will be true as we have 4 entries of 5 which is greater than 3.
Kindly guide me how to achieve it

A: If I understand your question correctly, you need something like. But it might behave incorrectly if you have more that 1 row in tbl1 with ID2 as 5
select
case when (select count(*) from tbl1
                    inner join tbl2
                        on tbl1.id2=tbl2.id2 and tbl1.id2=5
          ) > ID1
    then 'TRUE'
    else 'FALSE'
end as result;

A: This query will be giving you the result for each row of tbl1:
select  tbl1.id, tbl1.id1, tbl1.id2,
        case when cnt.num > tbl1.id1 then 'TRUE'
             else 'FALSE'
        end as chk
  from  tbl1
        left join (
                    select  count(*) as num
                      from  tbl2
                     where  tbl2.id2 = tbl1.id2
                  ) cnt

A: I would write a query for that this way
select  t1.ID2, case when cnt > ID1 then 'true' else 'false' end
from    (
            select  t1.ID2, t1.ID1, count(*) cnt
            from    tbl1 t1
            join    tbl2 t2
            on      t1.ID2 = t2.ID2
            group by t1.ID2, t1.ID1
        ) t1

A: select * , count(*), if(count(*) = t1.ID1, true, false) Result
from t1
  inner join t2 on t1.ID2 = t2.ID2
group by t2.ID2

A: Try the following query:
SELECT
    IF((SELECT COUNT(*)
            FROM
                t2, t1
            WHERE
                t1.id2 = t2.id2) > t1.id1,
        'true', 'false') AS result
FROM
    t1;


text:
Q: Username bug in flair The flair for my network profile has a badly HTML-entitied apostrophe in my name:

It's only the network flair, though. Site-specific flairs are OK:

Could someone fix it?

A: This is fixed now, though it might take up to 24 more hours to completely fall out of cache.
Network flair data comes from the Stack Exchange API v2, and we were mistakenly using a "safe filter" in our query.

A: Which is strange, because the flair is PNG, not HTML.. {/Checks code} Oh, I see.. The code consists of a server kitty taking pictures of badly rendered HTML.
Seriously though, I would say that it's the result of stackexchange.com/stackauth.com escaping your username when passing it to the flair script, while *.SE.com doesn't do that.. Which makes sense, since the code behind stackexchange.com and *.SE is different. But we need an SE member to be sure.
Till the SE team feeds that server kitty, I suggest you check out the links at the bottom of this blog post.


text:
Q: SQL query to replace unmatching or null with a zero count I have a query that is design to return a static list of subcategories(sid) for a given category by zone(zid). Next to the subcategory name I need a count of businesses (bid) matching the subcategory in that zone. (ex. places (3) )  It works unless another zone has a business for the subcategory then the query doesn't recognize this as null or zero.  What is the best way to rewrite this so that it returns all subcategories and counts if the value exists only for that zone or else returns (0)
<?php
ob_start();
$sql = "Select COUNT(b.name)as cnt, s.name,s.sid, b.zid from subcategory s left JOIN business b on s.sid = b.sid where s.cid = '10' and b.zid is null or b.zid ='1'and s.cid = '10' group by s.sid ORDER BY s.name ";

$result = mysqli_query($conn, $sql);
$queryResults = mysqli_num_rows($result);

if ($queryResults > 0) { while ($row = mysqli_fetch_array($result))
{echo
"
".$row['name']."(".$row['cnt'].")
";
}
}

A: You can use the mysql Function "IFNULL"
Select IFNULL(COUNT(b.name), 0) as cnt, s.name,s.sid, IFNULL(b.zid, 0)
from subcategory s
left JOIN business b on s.sid = b.sid
where s.cid = '10' and b.zid is null or b.zid ='1'and s.cid = '10' group by s.sid ORDER BY s.name

This is going to replace the null values with 0.


text:
Q: Issue with hash table chaining in C My homework an introductory C class is to complete the implementation of a hash table with dynamic allocation. I have to use the header file provided and I'm not sure what I'm doing wrong. Header file:
/// structure for the nodes of the chains
struct node_s {
    char *key;
    int value;
    struct node_s *link;
};

/// This is the main structure for the overall table.
struct table_s {
    /// This should be used as a pointer to a dynamically
    /// allocated array of pointers to node structures.
    struct node_s **table;

    /// This is for storing the maximum number of buckets/lists in the table.
    size_t bins;

    /// This is for storing the current number of elements in the table
    size_t size;
};
    /// A convenience declaration for referring to a pointer to a HT..
    typedef struct table_s *hash_t;

What I need to implement:
/// Allocate a table with some initial empty bins.
/// @param bins -- the number of bins in the table (initally empty)
/// @return -- a pointer to a dynamically allocated hash table
hash_t create_table(int bins){
        struct node_s *nodes[bins];
        for(int i = 0; i < bins; i++){
                nodes[i] = NULL;
        }
        hash_t table = malloc(sizeof(hash_t));
        table -> table = nodes;
        table -> bins = bins;
        table -> size = 0;
        return table;
}

/// Set the value for a key in a given hash table.
/// @note -- if this is the first time setting this key, then the
///          table must make a dynamic copy of the string.  This
///          copy must be freed when the table is freed.
/// @note -- if the table exceeds a load factor of 1 after setting
///          the key/value pair, then this function should trigger
///          rehashing into a larger table.  It will then deallocate
///          the table field in the table_s structure, but it will
///          NOT free the table address in the table parameter.
/// @param table -- a pointer to a hash table

void set(hash_t table, char *key, int value){
        int index = hash(key) % table -> bins;
        printf("Index: %d\n", index);
        struct node_s *node = table -> table[index];
        struct node_s *newNode = malloc(sizeof(newNode));
        newNode -> key  = key;
        newNode -> value = value;
        newNode -> link = NULL;

        printf("New node, key: %s\n", newNode -> key);
        if(node == NULL){
                printf("Filled bucket!\n");
                table -> table[index] = newNode;
                table -> size = table -> size + 1;
        }else{
                printf("Chained!\n");
                while(node -> link != NULL){
                        node = node -> link;
                }
                node -> link  = newNode;
        }
        printf("\n");
}

What runs:
 char key[max_key];
    hash_t table = create_table(10);
    for (int i = 0; i < trials; i++) {
        int sample = rand() % max_num;
        sprintf(key, "%d", sample);
        set(table, key, sample);
    }

Output:
Index: 7
New node, index: 7, key: 83
NULL!
New bucket filled!

Index: 0
New node, index: 0, key: 86
NOT NULL!
Segmentation fault (core dumped)

Expected output:
Index: 7
New node, index: 7, key: 83
NULL!
New bucket filled!

Index: 0
New node, index: 0, key: 86
NULL!
New bucket filled!

And so on, until a collision when the node at index is not NULL, where newNode chains itself by replacing the NULL *link of the last node present.
I know my chaining isn't quite correct yet and needs to be expanded upon, but I'm just really confused as to why it's not registering the NULL at index and placing a new linked list node, and is instead trying to add onto the linked list as though there was a collision.

A: Coding tip: Don't put a space before/after the dot . or arrow -> operators.
Instead of this:
table -> bins

This:
table->bins

Your actual issue is this.  create_table isn't propertly allocating memory for bins.  Even worse, it's using an array on the stack.  That memory is undefined behavior as soon as create_table returns.  Better:
hash_t create_table(int bins){
        hash_t table = malloc(sizeof(hash_t));
        table->table = calloc(sizeof(struct node_s*) * bins); //malloc and zero-init
        table->bins = bins
        table->size = 0;
        return table;
}

Also, instead of this:
        if(node == NULL){
                printf("Filled bucket!\n");
                table -> table[index] = newNode;
                table -> size = table -> size + 1;
        }else{
                printf("Chained!\n");
                while(node -> link != NULL){
                        node = node -> link;
                }
                node -> link  = newNode;
        }

Just do this:
printf("%s\n", (table->table[index] ? "Filled bucked!" : "Chained!"));
newNode->link = table->table[index];
table->table[index] = newNode;

Each time a new node gets added to a bin, it becomes the head item in the bin's linked list.  The chaining happens at the front of the each bin's list instead of the back.


text:
Q: GAE uploading to database - or - how to create big dictionary in GAE? I have a GAE application. A new request is to have a huge database to store many items for some functionality.
The database needs to populated every week or so - and populating it is done by querying many external links which overall takes around 1-2 hours. So, doing it via GAE Cron is now out of the question.
Another option I was thinking was to create it in external server and then uploading it to GAE DB. Is it possible to upload the data created externally to GAE DB straightaway? The question is because there will be close to 10 M items in it, so adding items individually to a DB is not going to work due to 30 second time limit.
Thanks
K

A: It might be possible to use the bulk loader for your task.
Or simply create your own method that you talk to from your external cron script for populating the new data

A: You can use task queues to poll your external sites and load the data.


text:
Q: Socket connection over Mobile data I'm developing an Android application that is required to send data over the Internet without using WiFi.
Is it possible to connect a socket to a server via Mobile Data?
My application works with WiFi, but doesn't work with Mobile Data.

A: You haven't really said what's the problem, so here's a wild guess:
You're developing on a local server, on address 192.168.something.something. On your home WiFi everything works, on mobile data it can't find the server.
If so, 192.168.*.* are local addresses. They are bound to your router and requesting them never reaches the internet because they are handled locally, which is totally fine if you're connected to that router. On mobile data, however, you aren't using the router which would resolve a local address, but rather a mobile tower which has no idea what you're asking it for - it doesn't know 192.168.*.* is your computer, so you can't establish a connection.
For the most part, transmitting data over WiFi and mobile data should make no difference. If there is, the problem is probably somewhere else. So here, in order to make it work with mobile data you need an actual remote server (which could be hosted on your computer if your ISP allows that, but that's another topic).
You do need to provide a better explanation for your problem - what address you are accessing and what's the error? I only have this hunch (and I'm quite confident in it) because I have at least one more answer with identical solution somewhere on the site (and the question was quite similar), which means you probably could've found it using Google (edit: yup, here it is).


text:
Q: Create gradient on UIImage for text I am trying to replicate the gradient found on the bottom of these album artwork image views. It makes it very easy to read the text no matter what the background is.
How would I recreate this?

A: The gradient effect is known as a floor fade.
The gradient starts with 0.0 alpha black at the middle of the image, to about 0.2 alpha black at the bottom of the image.
You could add a CAGradientLayer to your image, along the lines of:
CAGradientLayer *bottomFade = [CAGradientLayer layer];
bottomFade.frame = CGRectMake(0.0, CGRectGetHeight(self.imageView.bounds), CGRectGetWidth(self.imageView.bounds), -(CGRectGetHeight(self.imageView.bounds) / 2.0));
bottomFade.startPoint = CGPointMake(0.5, 1.0);
bottomFade.endPoint = CGPointMake(0.5, 0.0);
bottomFade.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithWhite:0.0 alpha:0.0f] CGColor], (id)[[UIColor colorWithWhite:0.0 alpha:0.2f] CGColor], nil];
[image.layer addSublayer:bottomFade];