text:
Q: How to display an error message from servlet? I want to display an error message when the login and the password are wrong, I tried this attempt but it didnt't work, thanks.
index.html

<form action="Serv">
<input type="text" name="log">
<input type="password" name="pwd">
<input type="submit" value="send">
</form>

Serv.java
 response.setContentType("text/html;charset=UTF-8");
 PrintWriter out = response.getWriter();
 String u =request.getParameter("log");
 String p =request.getParameter("pwd");
 if(u != "admin"  && p!= "admin"){
 String someMessage = "Error !";
 getServletContext().getRequestDispatcher("/index.html").forward(request, response);
 out.println("");

out.println("");
out.println("");
}

A: Use single quotes inside when it is possible, try this:
String someMessage = "Error !";
out.println("");
out.println("");

A: It looks like you are not closing the quote or script tag, add the closing quote/angle bracket:
out.println("


text:
Q: LinearLayout of a WebView and a Button I recently struggled with an apparently simple Android layout: I wanted a WebView above a Button. It worked fine with the following parameters:
WebView:
  Height: wrap-content
  Weight: unset (by the way, what is the default?)

Button:
  Height: wrap-content
  Weight: unset

However if the web page became too big it spilled out over the button. I tried various combinations of weights and heights, and all except one either completely hide the button, or partially cover it. This is the one that works (copied from http://code.google.com/p/apps-for-android/source/browse/trunk/Samples/WebViewDemo/res/layout/main.xml):
WebView:
  Height: 0
  Weight: 1

Button:
  Height: wrap-content
  Weight: unset

If you change any of those, e.g. give button a weight or change the WebView height to wrap-content then it doesn't work. My question is: Why? Can someone please explain what on Earth the android layout system is thinking?

A: Something like the following should give you what you want.  The key is the layout_height="fill_parent" and layout_weight="1" for the WebView.
<LinearLayout android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
        <WebView android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1" />

        <Button android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
</LinearLayout>

Edit:  Whoops, I misunderstood your question.  It's the layout_weight that makes it not spill over the button (or textview in your example).  I'm not sure why it happens, but if there's one "fill_parent" item in your LinearLayout, in addition to one or more "wrap_content" items, you need to specify a layout_weight for the "fill_parent" item, or it'll take over the space for the rest of the widgets.

A: Well I since have understood this. The way the android layout system works is:

*

*All the things are laid out according to their specified height/width.

*Any remaining weight is distributed among the views according to their weights.

(Obviously this is never explained.)
Therefore to get it to work you want the button to be wrap-content, which makes it just as big as it needs to be, and the webview to be zero height (since it can shrink to zero). After step 1 you will have the button correct, and then webview zero-height.
Then you set the button weight to 0, and the webview weight to 1, so that any remaining space is given to the webview - i.e. it expands to fill the screen.
Makes perfect sense when you know the algorithm.

A: you can specify the heigth of your webView in pixels
android:layout_heigth = " 70px"

for example
hope it helps

A: You can try something like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
    android:layout_height="match_parent" >

        <WebView
                android:id="@+id/wv"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_above="@+id/btn" />

        <Button
            android:id="@+id/btn"
            android:layout_alignParentBottom="true" />
</RelativeLayout>

A: Ok, here's the code to make this:

The above picture has 2 rows of buttons: one on top and one on the bottom. In the middle is the WebView.
Here is my GitHub account where u can download the source code:
https://github.com/GeneChuang1/Android/tree/Android
Otherwise, here is the App breakdown:
The Java Code  (AndroidMobileAppSampleActivity.java):
package com.gene;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.gene.R;

public class AndroidMobileAppSampleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.app_page);

        WebView mainWebView = (WebView) findViewById(R.id.webcontent);

        WebSettings webSettings = mainWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        mainWebView.setWebViewClient(new MyCustomWebViewClient());
        mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

        mainWebView.loadUrl("http://www.google.com");
    }

    private class MyCustomWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
}

I have 2 XML layouts. One for the main webpage, the other is a pre-made menu that I  in the main webpage.
The XML Layout "app_page.xml":
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
        android:id="@+id/page_weekly_items_options_menu"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#d4dbe1"
        android:gravity="center"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/share"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedShare"></ImageView>

        <ImageView
            android:id="@+id/left_arrow"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedLeftArrow"></ImageView>

        <ImageView
            android:id="@+id/right_arrow"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedRightArrow"></ImageView>

        <ImageView
            android:id="@+id/notifications_pageweeklyitem"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedNotificationsPageWeeklyItem"></ImageView>

        <ImageView
            android:id="@+id/favorites_pageweeklyitem"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedFavoritesPageWeeklyItem"></ImageView>

    </LinearLayout>

    <RelativeLayout
        android:id="@+id/webcontent_container"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_below="@id/page_weekly_items_options_menu">

        <WebView
            android:id="@+id/webcontent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/menu"
            ></WebView>
        <include
            android:id="@+id/menu"
            layout="@layout/bottom_menu"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_alignParentBottom="true"
            android:gravity="bottom"
            android:layout_weight="1"
            />

    </RelativeLayout>

</RelativeLayout>

The other XML layout is "bottom_menu.xml":
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/bottom_scroll_menu"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom" >
    <!-- This layout is used by activity_main.xml.
    It is part of the main home page -->
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#17528c"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/Weekly"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedWeekly" >
        </ImageView>

        <ImageView
            android:id="@+id/Search"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedSearch" >
        </ImageView>

        <ImageView
            android:id="@+id/Favorites"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedFavorites" >
        </ImageView>

        <ImageView
            android:id="@+id/Notifications"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedNotifications" >
        </ImageView>

        <ImageView
            android:id="@+id/Profile"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedProfile" >
        </ImageView>

        <ImageView
            android:id="@+id/About"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/icon"
            android:clickable="true"
            android:onClick="userClickedAbout" >
        </ImageView>
    </LinearLayout>

</HorizontalScrollView>

The Android Manifest (just incase someone forgets the internet permission):
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="tscolari.mobile_sample"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />

    <uses-permission android:name="android.permission.INTERNET"/>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidMobileAppSampleActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Again, here is my GitHub account where u can download the source code:
https://github.com/GeneChuang1/Android/tree/Android
-Gene Chuang

redpajama_set_name: RedPajamaStackExchange


text:
Q: Direction of Coriolis force My doubt is all about finding the direction of coriolis force by using the direction of the moving object. I really find it difficult to determine the direction of coriolis force through direction of moving object. Because, the direction of the moving object is given in the form of degree and that too in a confusing way. For instance, an object is moving at 60°N latitude/colatitude. Here direction of the moving object is given in the form of latitude which is very confusing to me and just because of that I don't know how to find the direction of coriolis force?

A: Use 3-dimensional vectors and study the vector cross-product. The Coriolis force vector is proportional to $\mathbf{v}\times \mathbf{\omega}$, where $\mathbf{v}$ is the object's velocity vector, and $\mathbf{\omega}$ is the angular rotation vector of the coordinate frame as seen from an inertial frame.

A: On the Earth's surface, the direction of Corriolis force is only dependent on componets of motion that alters an objects distance to the axis of rotation of the earth.
Corriolis acts either East or West. When moving towards the equator the radius of rotation increases, a body must accelerate East to continue to orbit once per day.  When moving away from the equator the radius of rotation decreases, the object must accelerate West in order to slow down so that it orbits once per day.
The magnitude of the corriolis force also depends upon Latitude.Near the poles Coriolis effects are larger. So you need to know the Latitude of the object as well as its direction of motion to calculate coriolis effects. It sounds like that's what $60^\circ$N Latitude means, and there should be other direction information in the question if you have to calaculate Coriolis force, direction and also speed.
Try this picture

Z is up, y is north, x is east ($\psi$ is Latitude and $\omega$ is angualr velocity). Notice how the northern blue circle has a smaller circumference than the one at the equator, but it still rotates once per day. Objects moving north from the equator have to be slowed down to stay stationary on the surface of the earth.

A: Imagine you've launched a projectile from the equator directly towards the North Pole. The Earth's circumference at the equator is 24,901 miles, so let's say, for the sake of argument (and because it's a nice round number) that the speed at the equator is 1,000 miles per hour. Your projectile will therefore have an eastern velocity of 1,000 mph (the speed of the equator). As your projectile passes over 45° north latitude it will still have that eastern velocity of 1,000 mph, but the ground under it will be travelling at about 707 mph (cosine of 45°). In other words, the projectile will be travelling about 293 mph faster in an eastern direction than the ground.It's a simple thought experiment to do in the opposite direction and south of the equator.


text:
Q: Chrome Extension - Bookmark 2 returning as undefined I'm creating a chrome extension that allows navigation to the users first four bookmarks using ctrl+shift+number; everything is going well, and functional for the 1st, 3rd and 4th bookmark, but the 2nd bookmark seemingly returns undefined every time.
I have a feeling this is due to the way that I'm navigating the bookmark tree that is get from the chrome api, but I'm unsure where or how I can fix this at all. Another thought is that this function has to be resolved asynchronously, but I'm unsure why that would be, or why it would work with the other bookmarks if that is the case.
This is my js file
const bookmarks = [];

chrome.tabs.onCreated.addListener(function(tab) { //refresh bookmarks on new tab opening
    var bookmarkTreeNodes = chrome.bookmarks.getTree(
    function(bookmarkTreeNodes){
        bookmarksArray(bookmarkTreeNodes)
    })
})

chrome.commands.onCommand.addListener(function(command){
    var bookmarkTreeNodes = chrome.bookmarks.getTree( //also check bookmarks on command execution
        function(bookmarkTreeNodes){
            bookmarksArray(bookmarkTreeNodes)
        })
    printArray(); //temp
    console.log('command:',command.charAt(8)); //tab number temp
    tabSelected = command.charAt(8);
    chrome.tabs.update({
        url: ("" + bookmarks[tabSelected-1])
    })
});

function printArray(){
    for(var i = 0; i<bookmarks.length; i++){
        console.log(bookmarks[i]);
    }
}

function bookmarksArray(bookmarkTree){
    for(var i=0; i<bookmarkTree.length; i++){
        bookmarks[i] = ("" + bookmarkTree[i].url); //url is insert to each spot as string
        console.log("" + bookmarks[i])
        if(bookmarkTree[i].children){
            bookmarksArray(bookmarkTree[i].children)
        }
    }
}

A: You're ovwrwriting the same elements of bookmarks in the recursive calls to bookmarksArray(), since each loop starts at 0. Use push() to append to the array instead of writing to the same indexes as in bookmarkTree.

function bookmarksArray(bookmarkTree) {
  for (var i = 0; i < bookmarkTree.length; i++) {
    bookmarks.push(String(bookmarkTree[i].url));
    console.log(bookmarks[i])
    if (bookmarkTree[i].children) {
      bookmarksArray(bookmarkTree[i].children)
    }
  }
}


text:
Q: Creating a candlestick chart with multiple axes (not twin axis ) I have created a candlestick chart that displays the percentage deviation from the moving average, with the percentage as the left side Y-Axis parameter. I want to plot the closing price that corresponds to those percentages( derived by a formula present in my code) on the right side Y-Axis. I am not looking for a twin axis, however. How can I go about doing this?
Currently, I am able to make 2 subplots, with the candlestick on the upper plot and corresponding closing prices on the lower plot. This is my code:
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
import pandas_datareader.data as web
import numpy as np
from mpl_finance import candlestick_ohlc
import matplotlib.dates as mdates
from matplotlib.dates import DateFormatter, MonthLocator, YearLocator,  DayLocator
style.use( 'ggplot' )

start_year = int( input( 'Start year: ' ) )
start_month = int( input( 'Start month: ' ) ) #for months before     October, only type in the corresponding digit without the 0
start_day = int( input( 'Start day: ' ) )

print()

end_year = int( input( 'End year: ' ) )
end_month =int( input( 'End month: ' ) ) #for months before October,     only type in the corresponding digit without the 0
end_day = int( input( 'End day: ' ) )

start = dt.datetime( start_year, start_month, start_day )
end = dt.datetime( end_year, end_month, end_day )

print()

ticker = input( 'Ticker: ' ) #should be in Uppercase
ticker = ticker.upper()

df = web.DataReader( ticker, 'morningstar', start, end )

print()

file_name = input( 'What\'s the csv file name that is stored on your device? ( ticker.csv ): ' ) #input should be in Lowercase .csv format
file_name = file_name.lower()

df.to_csv( file_name )

df = pd.read_csv( file_name, parse_dates=True, index_col=0 )

alldays = DayLocator()              # minor ticks on the days
weekFormatter = DateFormatter('%b %d %Y')  # e.g., Jan 12 2018
dayFormatter = DateFormatter('%d')      # e.g., 12

plt.subplot( 2, 1, 1 )
ax = plt.gca()
#fig.subplots_adjust(bottom=0.2)
ax.xaxis.set_minor_locator(alldays)
ax.xaxis.set_major_formatter(weekFormatter)
# ax.xaxis.set_minor_formatter(dayrmatter)

print()

reply = input( 'How many days\' exponential moving average do you want?: ' )
n = int( reply )

df[ 'EMA' ] = df[ 'Close' ].ewm( span = n, adjust=False ).mean()

df[ 'H' ] = ( df[ 'High' ] - df[ 'EMA' ] ) / df[ 'EMA' ]
df[ 'L' ] = ( df[ 'Low' ] - df[ 'EMA' ] ) / df[ 'EMA' ]
df[ 'C' ] = ( df[ 'Close' ] - df[ 'EMA' ] ) / df[ 'EMA' ]
df[ 'OP' ] = ( df[ 'Open' ] - df[ 'EMA' ] ) / df[ 'EMA' ]

                                                                                #

df.dropna( inplace=True )

df_corr = pd.DataFrame()

#nbr_days = len( df[ 'Date' ] )

max_h = df[ 'H' ].max()
max_input = int( max_h  * 2.4 * 100 )

min_l = df[ 'L' ].min()
min_input = int( min_l * 2.4 * 100 )

#print( int( min_input ), int( max_input ) )

l = []

for i in range( min_input, max_input ):

value = i / 200

l.append( value )

df_corr['corr'] = l

df_corr.dropna( inplace=True )

df_merged = pd.concat([df.reset_index(), df_corr ], axis=1).set_index("Symbol")

df_merged.to_csv( 'combine2.csv', index=False )

df_ohlc = df_merged

latest_ema = df_ohlc[ 'EMA' ].tail( 1 )
print( latest_ema )

df_ohlc[ 'Price' ] = ( df_ohlc[ 'corr' ] * latest_ema ) + latest_ema  #you need to take the latest EMA

print( df_ohlc )

# plot_day_summary(ax, quotes, ticksize=3)

date_list = df_ohlc[ 'Date' ].map( mdates.datestr2num )

candlestick_ohlc(ax, zip(df_ohlc[ 'Date' ].map( mdates.datestr2num ),
                     df['OP'], df['H' ],
                     df['L'], df['C']),
             width=0.6, colorup= 'g' )

ax.xaxis_date()

##ax2 = ax.twinx()
##s2 = df_ohlc[ 'Price' ]
##ax2.plot( date_list, s2 )

##plt.figure( 2 )
##plt.subplot()
##plt.plot( df_ohlc[ 'corr' ], df_ohlc[ 'Price' ] )

#ax2.plot( df_ohlc[ 'corr' ], df_ohlc[ 'Price' ] )

plt.subplot( 2, 1, 2 )
plt.plot( df_ohlc[ 'corr' ], df_ohlc[ 'Price' ], '.-' )

ax.autoscale_view()
plt.setp(plt.gca().get_xticklabels(), rotation=45,    horizontalalignment='right')

plt.show()

This is the output:
     Date   Close      High     ...            OP   corr       Price
Symbol                                   ...
SPY    2017-05-30  241.50  241.7900     ...    -0.000663 -0.075 248.783803
SPY    2017-05-31  241.44  241.8800     ...    0.001416 -0.070  250.128581

Additionally, this is how the graph looks like:

Ideally, I want something like this, where the prices on the right y-axis correspond to the percentages on the left, not the dates. (done on Excel):

Even if plotting multiple axes is not possible, is there a way to link the two plots? For example, if I view 6% as a crucial point on the upper plot and want to check the corresponding price on the lower plot, is there a quicker way than manually checking the corresponding price on the lower plot?


text:
Q: Java @NotNull violation message to show other constraints' details Given a username field which cannot be null, must be between 4 and 64 characters long and match the regexp [A-Za-z0-9]+, when the username field is null, the error message is simply: must not be null. The desired outcome is must not be null AND length must be between 4 and 64 characters AND must match "[A-Za-z0-9]+".
Initial setup:
@NotNull
@Length(min = 4, max = 64)
@Pattern(regexp = "[A-Za-z0-9]+")
String username;

What I also tried:
@NotNull(message = """
        {jakarta.validation.constraints.NotNull.message}
        AND {org.hibernate.validator.constraints.Length.message}
        AND {jakarta.validation.constraints.Pattern.message}""")
@Length(min = 4, max = 64)
@Pattern(regexp = "[A-Za-z0-9]+")
String username;

But this latter's outcome is:
ConstraintViolationImpl{
  interpolatedMessage='must not be null AND length must be between {min} and {max} AND must match "{regexp}"',
  propertyPath=username, rootBeanClass=class app.User,
  messageTemplate='{jakarta.validation.constraints.NotNull.message} AND {org.hibernate.validator.constraints.Length.message} AND {jakarta.validation.constraints.Pattern.message}'}

The values for the constraints (min, max, regexp) are not accessed. How to render the actual values of these in the error message?

A: Most constraint annotations, including @Length and @Pattern, regard null as valid input. That's why you won't get what you want by just using these annotations.
Fortunately, it's really easy to do what you want by introducing a new constraint annotation:
@Constraint(validatedBy = {}) // no validator needed, it delegates to other constraints
@NotNull
@Length(min = 4, max = 64)
@Pattern(regexp = "[A-Za-z0-9]+")
@ReportAsSingleViolation // to prevent separate violations for the other constraints
@Target(FIELD)
@Retention(RUNTIME)
public @interface ValidUsername {

    String message() default """
        {jakarta.validation.constraints.NotNull.message}
        AND {org.hibernate.validator.constraints.Length.message}
        AND {jakarta.validation.constraints.Pattern.message}""";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

This is annotated with your constraints, which means these are applied when this annotation is checked.
The message will still contain place holders {min} etc., because these are not properties of this constraint itself. You can solve that in two ways:

*

*Don't use the templates but hard-code the message

*Add these properties to your annotation as well, and tell the Bean Validation framework to use these for the other annotations:

    @OverridesAttribute(constraint = Length.class)
    int min() default 4;

    @OverridesAttribute(constraint = Length.class)
    int max() default 64;

    @OverridesAttribute(constraint = Pattern.class)
    String regexp() default "[A-Za-z0-9]+";

Now all you need to do is replace the annotations on the username field with @ValidUsername.


text:
Q: Circular increment of a variable x by step=1 between two files How can I run a circular increment  (python 3.8) of a variable x by step=1 between two files "a.py" and "b.py"? Initially x=0 in "a.py";  if "b.py" (or "a.py") executes the other file, x becomes x=1 (first increment) then when "a.py" (or "b.py") runs the other file, x becomes x=2 (second increment)  and so on until x=10.
I have tried this (unsuccessful) attempt:
b.py
from a import *
u=v+1;
exec(open("a.py").read());

a.py
v=0;
from b import *
v=u+1;
print(v);
exec(open("b.py").read());

A: What you ask about is shared values.
But you need to re-design your app. Instead of two different files a.py and b.py you need single master file that combines both:
from multiprocessing import Process, Manager

def a_worker(shared_var, *args):
    print("A", shared_var.value, args)
    shared_var.value += 1

def b_worker(shared_var, *args):
    print("B", shared_var.value, args)
    shared_var.value += 1

if __name__ == "__main__":
    manager = Manager()
    var = manager.Value('i', 0) # shared variable

    print("Initial value: ", var.value)

    a_proc = Process(target=a_worker, args=(var, "a_args"))
    b_proc = Process(target=b_worker, args=(var, "b_args"))

    # Spawn processes
    a_proc.start()
    b_proc.start()

    # Wait for processes to terminate
    a_proc.join()
    b_proc.join()

    print("After a & b finished: ", var.value)

Here a_worker and b_worker are the functions that implement the business logic of a.py and b.py. For more details see Python multiprocessing library
UPDATE
Ping-pong strategy. Process A increments, then process B increments, then process A increments, then ... until the shared variable reaches 10:
from multiprocessing import Process, Manager, Pipe

def a_worker(shared_var, pipe):
    while shared_var.value < 10:
        print("A", shared_var.value)
        shared_var.value += 1
        pipe.send("Your turn")
        pipe.recv()
    pipe.close()

def b_worker(shared_var, pipe):
    while shared_var.value < 10:
        pipe.recv()
        print("B", shared_var.value)
        shared_var.value += 1
        pipe.send("Your turn")
    pipe.close()

if __name__ == "__main__":
    manager = Manager()
    var = manager.Value('i', 0) # shared variable
    a_conn, b_conn = Pipe()

    print("Initial value: ", var.value)

    a_proc = Process(target=a_worker, args=(var, a_conn))
    b_proc = Process(target=b_worker, args=(var, b_conn))

    # Spawn processes
    a_proc.start()
    b_proc.start()

    # Wait for processes to terminate
    a_proc.join()
    b_proc.join()

    print("After a & b finished: ", var.value)

This program uses pipe to coordinate A and B. Process A starts, does something, then passes control to B and waits until it passes back. Process B starts waiting for A, receives a message from A, increments the variable and passes the control back.


text:
Q: Is this an alternate characterization of $\lambda$-rings? Or, what is like a $\lambda$-ring but for symmetric rather than exterior powers? This is a question about $\lambda$-rings.  A $\lambda$-ring is a commutative ring together with operations $\lambda^n$ for each whole number $n$ which are analogous to the $n$th exterior power and satisfy the same identities.  There's the identity $$\lambda^n(x+y)=\sum_{i+j=n}\lambda^i(x)\lambda^j(y)$$ as well as more complicated identities for $\lambda^n(xy)$ and $\lambda^m(\lambda^n(x))$.
My question is: What if instead of exterior powers, we used symmetric ones?  As in, we could define an "$s$-ring" to be a ring together with operations $s^n$ satisfying identities analogous to the identities defining a $\lambda$-ring, but for symmetric powers instead of exterior powers.  For addition we get
$$s^n(x+y)=\sum_{i+j=n}s^i(x)s^j(y),$$
which is the same as before, but the multiplication and iteration identities are different; for instance, instead of
$$\lambda^2(xy) = \lambda^1(x)^2 \lambda^2(y) + \lambda^2(x) \lambda^1(y)^2 - 2 \lambda^2(x)\lambda^2(y)$$
and $$ \lambda^2(\lambda^2(x))=\lambda^1(x)\lambda^3(x)-\lambda^4(x)$$
we get $$s^2(xy) = s^1(x)^2 s^1(y)^2 - s^1(x)^2 s^2(y) - s^2(x) s^1(y)^2 + 2 s^2(x)s^2(y)$$
and $$ s^2(s^2(x))=s^2(x)^2 - s^1(x)s^3(x) + s^4(x).$$
(Those are the right analogues, right?  I just got those by, in the definitions of $P_k$ and $P_{k,j}$, replacing sets with multisets, and elementary symmetric polynomials with complete homogeneous ones.  I didn't actually think about symmetric powers, I just assume that it should work the same.)
My suspicion, based on what I've read, is that this should just be an alternate characterization of a $\lambda$-ring, that it should be possible to express the $s^n$ in terms of the $\lambda^n$ and vice versa.  But I don't really know this subject; I'm asking this because I kind of just stumbled across something that might be one of these "$s$-rings".
So: Is this an alternate characterization of a $\lambda$-ring?  (If so, could you provide a reference?)  And if not, is it a known sort of thing, and where would I read about it?

A: OK, I now have most of an answer, which I will post here.  That said... any references would really be appreciated.  I am still looking for references on the matter; I don't want to have to rederive this theory myself.
Anyway, yes, it seems to be an alternate characterization of a $\lambda$-ring, via the usual way of converting between $e_n$ (elementary symmetric polynomials) and $h_n$ (complete homogeneous polynomials), i.e., the relation $\sum_{i=0}^k (-1)^i e_i h_{k-i}=0$, or, in this context, $\sum_{i=0}^k (-1)^i \lambda^i(x) s^{k-i}(x)=0$.
Edit: You could also do the simpler $s^i(x)=(-1)^i \lambda^i(-x)$; this is equivalent by Vandermonde.
I don't quite have this proved, but if I make the probably-true assumption that when verifying these identities in the ring of symmetric functions, or the ring of symmetric functions in two types of variables, that I only need to check elements whose coefficients are nonnegative, then I can prove it.  Short version is, ring of symmetric functions is the free $\lambda$-ring on one generator, ring of symmetric functions is the free $\lambda$-ring on two generators (I don't have a reference for that but it seems to follow from the fact that ring of symmetric functions is the free $\lambda$-ring on one generator together with the fact that the elementary symmetric polynomials in two types of variables generate as a ring the ring of symmetric functions in two types of variables), so if it works there it works anywhere.  And of course it works there, because that's how the identities are defined (at least, as I said, for the elements without negative coefficients; I am having some trouble handling those).
So I'm not going to accept this answer, because I'm not considering this closed; I'm still looking for a reference so I don't have to rederive the whole theory myself. Thanks all!
Edit: OK, here's a reference that works -- it doesn't explicitly state everything, as such, but it essentially says it.  It calls the operations $S^i$, so I guess that's the notation to use.  http://lipn.univ-paris13.fr/~duchamp/Books&more/Lascoux/Cbms.pdf  I'll accept this answer once the system lets me (unless someone has a better one!); meanwhile I have another, less trivial, question about $\lambda$-rings which I'll ask on MathOverflow soon probably...
Edit: OK, over in chat, Darij Grinberg posted a better reference -- if he wants to post it as a separate answer I'll upvote it, though I can't accept it! -- which is Hazewinkel, Gubareni, and Kirichenko's book "Algebras, Rings, and Modules", volume 3; it discusses lambda rings in a way that puts the $\lambda^i$ and $\sigma^i$ (their terminology) on equal footing.  It doesn't explicitly write out the identities as I'd like, but taking a quick look I'm pretty sure they're easily derivable from what they do write.  Hooray!  This is probably as good as it's going to get.


text:
Q: How can I inspect a ValidationError exception while testing with django TestCase? I'm working with Django testing using a django.test.TestCase and I would like to know the pythonic way to inspect a validation error. I've come up with the below, which works, but it feels a little long winded and prone to error over a large number of tests
    self.valid_account.contact_number = "1234567" # Too short
    with self.assertRaises(ValidationError):
        try:
            self.valid_account.full_clean()
            self.fail("Did not raise validation error")
        except ValidationError as e:
            self.assertTrue('contact_number' in e.message_dict)
            raise e

Is there a better way to inspect and test an exception?

A: There's no point in using assertRaises if you're manually handling the exception. If you need to inspect the exception too, the solution is documented:

The context manager will store the caught exception object in its exception attribute. This can be useful if the intention is to perform additional checks on the exception raised

So in your case this would look like:
self.valid_account.contact_number = "1234567" # Too short
with self.assertRaises(ValidationError) as cm:
    self.valid_account.full_clean()

self.assertTrue('contact_number' in cm.exception.message_dict)


text:
Q: Run web.py python app with command line arguments that are not port number I need to provide an xml file as a command line argument to my web.py app. However, the library automatically takes the first command line argument as the port number, which I do not provide as an argument. Is there some sort of trick or workaround to provide an xml file as a command line argument?
#!/usr/bin/env python
import web
import sys
import xml.etree.ElementTree as ET

file = sys.argv[1]

urls = ('/get_user/(.*)', 'get_user',
    '/users', 'list_users')

app = web.application(urls, globals())

def read_xml(xml_file):
    with open(xml_file, 'r') as f:
        tree = ET.parse(f)
    return tree.getroot()

root = read_xml(file)

class list_users:
    def GET(self):
        output = 'Users:\n'
        for child in root:
            print 'child', child.tag, child.attrib
            output += (str(child.attrib['user']) +
            ': ' + str(child.attrib['name']) + ', ' + str(child.attrib['email'] + '\n'))
        return output

class get_user:
    def GET(self, name):
        for child in root:
            if child.attrib['name'] == name:
                output += str(child.attrib['name']) + ", " + str(child.attrib['email'])
            return output
        output = "The user (" + name + ") couldn't be found!"
        return output

if __name__ == "__main__":
    app.run()


text:
Q: How to stop divs from hidding when scrolling I have been collecting product prices for a market investigation project in my University. So far I have been looking at very basic pages or forms where I could extract every product´s name and price with a simple js, but I have encountered many pages like this one, where upon scrolling there is an event listener that updates the html to only have the code of the products the user can see.
My knowledge in javascript is not this advanced, and I can´t figure out how to make the html show all divs at the same time, so I can then extract them with one script.

A: Try to use Position: Sticky in your css file


text:
Q: how to declare Iterator for set of stacks in c++ I am creating a class that is a set of stacks. I want to use an iterator to get the element at the end and access its functions. But I get the following error
setOfStacks.cpp:40:6: error: expected ';' after expression
            set< stack<Type> >::iterator it = mSetOfStacks.end();
               ^
               ;

The class works with a template and is declared like this
template<typename Type>
class SetOfStacks
{
public:
        SetOfStacks(int capacityPerStack);
    void            push(Type object);
    Type            pop();
    bool            isEmpty();
private:
    void            createNewStackWithElem(Type object);
private:

        int                 mStackCapacity;
        set<stack<Type> >   mSetOfStacks;
};

Then in my insert function I try to get the stack at the end
set< stack<Type> >::iterator it = mSetOfStacks.end();
if( *it->size() < mStackCapacity )
    *it->push(object);

which is where I get the error when trying to declare the iterator
setOfStacks.cpp:40:6: error: expected ';' after expression
also, I tried
set<stack<Type> >::iterator it = mSetOfStacks.end();

but it did not work either
The entire push function
template<typename Type>
void SetOfStacks<Type>::push(Type object) {
    // if entire set is empty make a new stack
    if( mSetOfStacks.empty() ) {
        stack<Type> newStack;
        newStack.push(object);

        mSetOfStacks.insert(newStack);
    }
    else {
        // check if current stack within limits
        set< stack<Type> >::iterator it = mSetOfStacks.end();
        if( *it->size() < mStackCapacity )
            *it->push(object);
        else {
            // duplicate code, make another function
            stack<Type> newStack;
            newStack.push(object);

            mSetOfStacks.insert(newStack);
        }
    }
}

A: Within a function template the nested name iterator is a dependent name which is considered to be an object rather than a type. You want to indicate that iterator is a type using the typename keyword:
typename std::set<std::stack<Type> >::iterator it = mSetOfStacks.end();
// ^-- here

Templates are parsed in two stages: during the first phase the code is parsed for its logical components without any knowledge of template arguments or entities depending on the template arguments could look like. If there is a nested name depending on a template argument the compiler assumes this this name is an object rather than a type unless you explicitly state that it is a type using the typename keyword.

A: auto is the perfect keyword for this :
auto it = mSetOfStacks.end();

A: When using C++11, you don't need to specify the iterator type to define an iterator when initializing it from something like mSetOfStacks.end(). You can use auto instead:
auto it = mSetOfStacks.end();

Also, you should not access this iterator, since it points one element past the end. If you want the last element in the set, decrement the iterator before accessing it:
--it;
// then use *it

or refer to the last set by using a reference variable:
auto & lastSet = *(--it);
// then use lastSet instead of *it

If your compiler doesn't support auto, use Dietmar's solution.


text:
Q: Doctrine ORM: How to define a 1-n realtionship with a n-n connecting table So, this is a bit complicated: I have two tables, say cats and dogs.
They are in a many-to-many relationship (could be called friendships or whatever), so that Doctrine automatically creates a table cats_dogs for me with the appropriate fields. (that is rowid, cat_id, dog_id per default.)
Now, imagine I have a third table, award, where I want to award one of these friendships. Here I therefore need a field that references one row in cats_dogs. However, since this table does not really exist between my models, (Doctrine handles it for me) what would be the most elegant solution for this?
In the end, I want in my award model two fields, a cat and a dog, who need to be in a friendship.
I am using the annotation driver.

A: What stops you from manually creating the m:n table instead of having doctrine do it for you?

A: The Doctrine aims is to map objects from an E/R schema and to make easier the access to object connections. Therefore I believe that the table cats_dogs automatically provided by Doctrine is necessary as it is. It is concise and hits its purposes, i.e. it provides a list of all dogs of a cat or, vice versa, all the cats of a dog.
Thus, I can conclude that it is preferable to create a third entity (besides Cat and Dog) named Award which provides a one-to-one relationship with Cat and another one-to-one relationship with Dog. Making it consistent with the cats_dogs table is only up to you, and is not a Doctrine task by default. E.g., you can use some cascade persist option.
I believe that this is the most effective solution with Doctrine.
As a final remark, consider that each table should map a specific relationship between one or more entities, and in fact the table cats_dogs represents the friendship relationships, while the table Award will represent the awarded relationship relationship between two friends.


text:
Q: How I can show a webview in a tabwidget? How I can show a webview in a tabwidget?
When I open the tab, the webview opens in other new page without opens in a tabcontent.
Where is the problem?
code activity.class :

public class layout1i2 extends Activity{
  Button button1, button2;
  WebView webview1, webview2;
      @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout1);

          //declarar webvies i botó de tirar enrere       webview1 = (WebView) findViewById(R.id.webview1);       button1 = (Button)

findViewById(R.id.button1);       button2 = (Button)
  findViewById(R.id.button2);
                webview1.loadUrl("http://www.facebook.com");        webview1.setWebChromeClient(new WebChromeClient());
          button1.setOnClickListener(new OnClickListener()        {           @Override           public void onClick(View arg0)              {
          setContentView(R.layout.layout2);
          webview2 = (WebView) findViewById(R.id.webview2);
          button2 = (Button) findViewById(R.id.button2);
          button2.setOnClickListener(new OnClickListener()
          {
              @Override
              public void onClick(View arg0)
              {
                  setContentView(R.layout.layout1);
                  webview1 = (WebView) findViewById(R.id.webview1);
              }
          });             }

});

}
layout2.xml

      <RelativeLayout
          android:id="@+id/Layout2"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent" >

          <WebView
              android:id="@+id/webview2"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:autoLink="web"
              android:scrollbars="none"
              android:textColor="@android:color/black" />

          <Button
              android:id="@+id/button2"
              style="?android:attr/buttonStyleSmall"
              android:layout_width="60dp"
              android:layout_height="25dp"
              android:layout_below="@+id/webview2"
              android:layout_alignParentRight="true"
              android:layout_alignParentTop="true"
              android:layout_marginRight="35dp"
              android:layout_marginTop="19dp"
              android:text="Button2"
              android:textSize="14px" />

      </RelativeLayout>

layout1.xml

      <RelativeLayout
          android:id="@+id/Layout1"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent" >

          <WebView
              android:id="@+id/webview1"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:autoLink="web"
              android:scrollbars="none"
              android:textColor="@android:color/black" />

          <Button
              android:id="@+id/button1"
              style="?android:attr/buttonStyleSmall"
              android:layout_width="60dp"
              android:layout_height="25dp"
              android:layout_below="@+id/webview2"
              android:layout_alignParentRight="true"
              android:layout_alignParentTop="true"
              android:layout_marginRight="35dp"
              android:layout_marginTop="19dp"
              android:text="Button1"
              android:textSize="14px" />

      </RelativeLayout>

Thank's

A: Use this line:
web.setWebViewClient(new WebViewClient());


text:
Q: Versioning of PHP classes
Possible Duplicate:
Loading multiple versions of the same class

What is the best way to setup different versions of PHP classes and toggle them based on a configuration value?
Here's my scenario (using Zend Framework - shouldn't matter, but might):
I have 2 different versions of a web service that I'd like to be able to call. I need to switch between them using a value in my config file.
Right now, I have a class that acts as a factory and determines what version of the class needs to be returned based on the config value. Both versions of the class that the factory returns extend the same abstract class, so once the factory returns the object, I can treat both versions the same in the rest of the code. This seems fine to me in theory, but I end up with code that looks like this in my factory class, which doesn't seem to be good practice:
require_once APPLICATION_PATH . '/models/Search/SearchModelV' . $this->config->model->version . '.php';

$model_class = 'Search_Model_V' . $this->config->model->version;
return new $model_class();

I'm using PHP 5.3, so I've implemented namespaces. Just throwing that out there in case it can be used as a solution.

A: I think the solution is probably the "factory" pattern. This means that you have a static function that makes an appropriate object based on a parameter.  This is possible even on an abstract class, because you can declare and call static methods on abstract classes.
abstract class Search_Model_Abstract {
    public static function create($version) {
        $class = 'Search_Model_V' . $version;

        return new $class;
    }
}

You can then create the appropriate object with Search_Model_Abstract::create($this->config->model->version)
Note that this method really should also handle any exceptions that might be thrown from the constructors, and it should also check $version against possible values.

A: I think your theory is fine, and what's making it feel hacky is your implementation. Some suggestions.

*

*Use a global autoload mechanism to avoid requiring files all over the place. If you don't do this, you can at least apply (2) before feeding the config value into require_once.

*Validate the config setting before using it. I don't know what's valid in your case, but favor whitelisting to be sure you're getting an accepted value.

*Make sure you're able to instantiate the new object, and handle errors appropriately, before returning it.

A: In theory your application should not care about versions. It just have to use current one. That's the case with versions. For example in php we don't have file_get_contents, file_get_contents_v51, etc. We just use current available versions. For such situations changing include_path to "current" version, or symlink or build script with "copy", etc will do the work for you. But that's not your case. You need to have available different instances in same time. We are not talking not about versions, but "strategies". In such situation there is no escape of dynamically building the path to file. You only have a choice where to do dynamic include. As far as we talk about "same" classes with same name (I guess so), personally I'll choose to use dependency injection container and give container different config depending on "version" in config value.
e.g.
$config = array(
'service_v1.0' => array('path' => 'path/to/my/service/v1.0/');
'service_v1.1' => array('path' => 'path/to/my/service/v1.1/');
);
$version = 'service_v1.1';
DIContainer::create($config[$version]);

With such solution I don't care about dependencies (if so) of "current" service (e.g. different service key, different storage, etc.) as far as I can describe all of them in config and inject them. For more details about dependency injection you can read here.
My two cents about problem


text:
Q: Join two fields from same table in mysql SELECT  pms.id,
                    pms.id_from,
                    pms.id_to,
                    pms.fecha,
                    pms.leida,
                    usuarios.img_src  as avatar_from,
                    usuarios.alias as name_from,
                    usuarios.img_src  as avatar_to,
                    usuarios.alias as name_to
FROM pms
LEFT JOIN usuarios ON usuarios.id = pms.id_from
LEFT JOIN usuarios ON usuarios.id = pms.id_to

The problem that is two references of usuario (alias or img_src) per row:
And I get this error:
The following errors were reported:
Not unique table/alias: 'usuarios'

Or this
SELECT  pms.id,
                pms.id_from,
                pms.id_to,
                pms.fecha,
                pms.leida,
                usuarios.img_src  as avatar_from,
                usuarios.alias as name_from,
                usuarios.img_src  as avatar_to,
                usuarios.alias as name_to
FROM pms
LEFT JOIN usuarios ON usuarios.id = pms.id_from OR usuarios.id = pms.id_to

Works, but I get same name and image for each _to and _from
So, what's the way to go here?

A: Yes joining the same table will require unique alias for the table name something as
select
p.id,
p.id_from,
p.id_to,
p.fecha,
p.leida,
u1.img_src  as avatar_from,
u1.alias as name_from,
u2.img_src  as avatar_to,
u2.alias as name_to
from pms p
LEFT JOIN usuarios u1 ON u1.id = p.id_from
LEFT JOIN usuarios u2 ON u2.id = p.id_to

A: If you use the same table twice you need different alias names
SELECT  pms.id,
        pms.id_from,
        pms.id_to,
        pms.fecha,
        pms.leida,
        u_from.img_src  as avatar_from,
        u_from.alias as name_from,
        u_to.img_src  as avatar_to,
        u_to.alias as name_to
FROM pms
LEFT JOIN usuarios u_from ON u_from.id = pms.id_from
LEFT JOIN usuarios u_to ON u_to.id = pms.id_to


text:
Q: SurfDescriptorExtractor doesn't create the descriptor matrix I have a problem with SurfDescriptorExtractor in OpenCV. It doesn't create a matrix at all!
The thing is that I'm imposing the key points, and right now, to debug, I only use 4-5 of them. I create the key points with cv::Keypoint, and use the default constructor. I set the coordinate of the point and the octave to 3. The rest, I'm not touching it!
Here's a piece of code of what I'm doing:
SurfDescriptorExtractor extractor;
cv::detail::ImageFeatures &cdif = features[i];
Mat gray_image = imread(images[i], CV_LOAD_IMAGE_GRAYSCALE);
extractor.compute(gray_image, cdif.keypoints, cdif.descriptors);

And this is how I create my key points, this is what is in the loop:
  KeyPoint kp;
  kp.octave = 3;
  kp.pt.x = jpic.x;
  kp.pt.y = jpic.y;
  features[i].keypoints.push_back(kp);

So, is there a way to force the extractor to write something in the descriptor ?


text:
Q: strtolower() expects parameter 1 to be string, array given even though it is definitely a string public function getImages( $images )
{
    $ids = [];
    //\Kint::dump( $images['file'][0]['name'] );
    foreach( $images['file'] as $image ){

        $url = $image['url'];
        $name = $image['name'];

        if( strpos( strtolower( $name ) , 'jpg') !== false ){
            $assets = Asset::Find()
                ->filename( $name )
                ->all();
            if( count( $assets ) == 0 ){
                $ids [] = $this->createAssetFromUrl( $name, $url );
            }else{
                $ids [] = $assets[0]->id;
            }
        }

    }
    return $ids;
}

Hi im using this piece of code to get an images name from an array to determine whether it has already been downloaded or not however i keep getting this error
PHP Warning – yii\base\ErrorException
strtolower() expects parameter 1 to be string, array given
1. in /Applications/XAMPP/xamppfiles/htdocs/vebraaltowrapper/src/services/VebraAltoWrapperService.php at line 441
    //\Kint::dump( $images['file'][0]['name'] );
    foreach( $images['file'] as $image ){

        $url = $image['url'];
        $name = $image['name'];

        //\Kint::dump( strpos( strtolower( $name ) , 'jpg') );

        if( strpos( strtolower( $name ) , 'jpg') !== false ){
            $assets = Asset::Find()
                ->filename( $name )
                ->all();
            if( count( $assets ) == 0 ){
                $ids [] = $this->createAssetFromUrl( $name, $url );
            }else{
                $ids [] = $assets[0]->id;
            }
        }

The error says that $name is an array however if i dump $name it clearly shows its a string
$name string (12) "IMG_0693.JPG"
so i though perhaps it was strpos() or strtolower() causing the issue but if i dump the full condition within the if statement like so
\Kint::dump( strpos( strtolower( $name ) , 'jpg') );
  it seems fine and returns exactly what i was expecting
strpos(...) integer 9
so the error only happens when that condition is put in an if statement, am i missing something obvious or is this a bug in php?


text:
Q: How to implement shared resources in Pulumi I'm trying to understand how to implement Pulumi in our AWS environment.
I understand that a stack can be used to have the same resource structure for production and development, but that results in independant instances, which is great.
However we also have a shared management VPC where certain tools reside such as pgadmin, gitlab, monitoring tools,...
So what would be the best approach for that?

*

*Force a stack for that management project (if that is possible)?

*Put a constraint in code so that this management stuff is only deployed in production stack?

Or am I missing the approach of stacks here?

A: Your first thought is the right way to go.
Deploy shared resources in their own stack(s) and use Stack References to share information across stacks.
These links discuss these concepts:
https://www.pulumi.com/docs/intro/concepts/organizing-stacks-projects/
https://www.pulumi.com/docs/intro/concepts/programming-model/#stack-references


text:
Q: How do I alter my unit test to utilise mocks within the setUp function? I have a relatively basic phpunit test that contains 1 setUp function, and 2 tests - I am still learning phpunit so forgive my ignorance :) Note - I am using the Zend 2 Framework.
I would like the following phpunit test to use mocks but I am unsure how this would work?
<?php

namespace AcmeTest\MetricsClient\Zend;

use Acme\MetricsClient\NullMetricsClient;
use Acme\MetricsClient\Zend\NullMetricsClientFactory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceManager;

class NullMetricsClientFactoryTest extends \PHPUnit_Framework_TestCase
{
    private $serviceManager;
    private $factory;

    protected function setUp()
    {
        $this->factory        = new NullMetricsClientFactory();
        $this->serviceManager = new ServiceManager();
    }

    public function testIsZf2Factory()
    {
        $this->assertInstanceOf(FactoryInterface::class, $this->factory);
    }

    public function testCreatesNullMetricsClientService()
    {
        $nullClient = $this->factory->createService($this->serviceManager);
        $this->assertInstanceOf(NullMetricsClient::class, $nullClient);
    }
}

A: Use PHPUnit's MockBuilder
Here's a rough example using your code:
<?php

namespace AcmeTest\MetricsClient\Zend;

use Acme\MetricsClient\NullMetricsClient;
use Acme\MetricsClient\Zend\NullMetricsClientFactory;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceManager;

class NullMetricsClientFactoryTest extends TestCase
{
    private $serviceManager;

    private $factory;

    protected function setUp()
    {
        $this->factory = $this->getMockBuilder(NullMetricsClientFactory::class)
            ->disableOriginalConstructor()
            ->getMock();

        $this->serviceManager = $this->getMockBuilder(ServiceManager::class)
            ->disableOriginalConstructor()
            ->getMock();
    }

    public function testIsZf2Factory()
    {
        $this->assertInstanceOf(FactoryInterface::class, $this->factory);
    }

    public function testCreatesNullMetricsClientService()
    {
        $nullClient = $this->factory->createService($this->serviceManager);
        $this->assertInstanceOf(NullMetricsClient::class, $nullClient);
    }
}


text:
Q: Independence of time intervals in ANOVA? I am not sure how the independence assumption in ANOVA applies in this scenario...
We have observational data on the foraging depth of whales across the summer separated into time intervals. We want to see if the depth is consistent over the summer, so would it be appropriate to use ANOVA with the time intervals as the grouping category? Would they be considered independent? Is there a better method to analyze this?
also, does it matter that we can't identify whether the same whales are being counted in multiple time intervals?

A: Let's start with the final question.
If you believe suspect whales are homogeneous - i.e., overall behave the same way - it should not matter if they are the same whales.  You can do that much more expensive research later, it here is a doubt.
You aren't clear on 'time intervals'.  Should we assume you have one year, broken up into months or quarters, or many years?
Let's suppose you have one year of monthly data.  The typical approach is to split it into 'summer' and 'winter'.  Whether or not fall and autumn are included is a detail.
But, if you have a bunch of depth readings in each group, ANOVA should do it.


text:
Q: Comprobar que el valor de un campo cumpla con al menos una de 3 condiciones Estoy haciendo un programa el cual necesitas poner el documento español (NIF,NIE,CIF) y necesito comprobar que los datos introducidos son correctos.
El usuario ingresa el valor en un único input y debe coincidir con el formato de NIF, o de NIE, o de CIF.
Este es el código que tengo hasta ahora:
if (document.formProveedor.NIF.value!="") {
    var regNIF = /^([0-9]){8}([A-Z]){1}$/;
    var regNIE = /^([A-Z]){1}([0-9]){7}([A-Z]){1}$/;
    var regCIF = /^([A-Z]){1}([0-9]){8}}$/;

    if(regNIF.test(document.formProveedor.NIF.value) == false) {
        alert("El NIF introducido no es correcto.");
        document.formProveedor.NIF.focus();
        return false;
    }else if(regNIE.test(document.formProveedor.NIF.value) == false){
        alert("El NIE introducido no es correcto.");
        document.formProveedor.NIF.focus();
        return false;
    }else if(regCIF.test(document.formProveedor.NIF.value) == false){
        alert("El CIF introducido no es correcto.");
        document.formProveedor.NIF.focus();
        return false;
    }
}

EJEMPLOS:
NIF: 74063793K
NIE: Y9945517D
CIF: G82868043

*

*Cuando relleno el campo con un NIF y se ejecuta la función, me salta el alert

"El NIE introducido no es correcto."

*Cuando relleno el campo con un NIE y se ejecuta la función, me salta el alert

"El NIF introducido no es correcto."

*Cuando relleno el campo con un CIF y se ejecuta la función, me salta el alert

"El NIF introducido no es correcto."

A: Tu problema es que miras uno por uno: si metes un NIF, obviamente no es un CIF y te da el error, de manera similar pasa con un CIF o un NIE.
La solución más sencilla sería algo como (en pseudo-código):
function validarID(...)
    if (<es un NIF correcto>)
       return OK
    }
    if (<es un CIF correcto>)
       return OK
    }
    if (<es un NIE correcto>)
       return OK
    }

    return NO_OK
}

Pero una mejor solución sería seleccionar el validador primero, en un select, y aplicarlo al dato metido, porque un usuario podría meter por error un valor válido para un NIE cuando realmente quiere meter un CIF.

A: He reformulado la forma en que lo haces, y en mi opinión deberías de utilizar algún tipo de dropdown para elegir que tipo de validación quieres, así no tienes que escribir muchas lineas comparando que solo sea NIF, CIF, NIE, etc.
Primero que nada he hecho un array de objetos con su tipo y validación.
var validacion = [
    {
        tipo: 'NIF',
        regex: /^([0-9]){8}([A-Z]){1}$/,
    },
    {
        tipo: 'NIE',
        regex: /^([A-Z]){1}([0-9]){7}([A-Z]){1}$/,
    },
    {
        tipo: 'CIF',
        regex: /^([A-Z]){1}([0-9]){8}}$/,
    },
];

Con eso he hecho una funcion validar que toma dos parametros: tipo y numero, donde el tipo es NIE, NIF, DNI, CIF... y el numero el valor que quieres comprobar.
function validar(tipo, numero) {
  if(tipo == null || numero == null){
    alert('Error en los datos');
    return false;
  }

    var val = validacion.find(x => x.tipo == tipo);

    if (!val.regex.test(numero)) {
        alert('El ' + tipo + ' introducido no es correcto.');
        return false;
    }
}

Para llamarlo seria así:
validar('NIF', '74063693K'); // true
validar('NIF', '740dd693K'); // false
validar('NIE', 'Y9945517D'); // true
validar('NIE', '74063793K'); // false

Recuerda que para rellenar el parámetro tipo, estaría bien que utilizaras un dropdown.


text:
Q: Grunt plugin grunt-exec v2.0.0 doesn't execute a simple command while v1.0.1 does I was using grunt-exec v1.0.1 with this configuration in Gruntfile.js:
grunt.initConfig({
    exec: {
        tsc: {
            cmd: "tsc"
        }
    },
    ...
}

...

grunt.loadNpmTasks('grunt-exec');

grunt.registerTask('debug', [
    ...
    'exec:tsc',
    ...
]);

Then running grunt debug in console tsc is executed correctly.
In another project with similar configuration it's installed the last version of
 grunt-exec(v.2.0.0) and running grunt-debug the next error is returned:
Running "exec:tsc" (exec) task
>> Failed with: Error: spawn tsc ENOENT
Warning: Task "exec:tsc" failed. Use --force to continue.

With -verbose option it returns:
Running "exec:tsc" (exec) task
Verifying property exec.tsc exists in config...OK
File: [no files]

tsc
buffer   : disabled
timeout  : infinite
killSig  : SIGTERM
shell    : true
command  : tsc
args     : []
stdio    : [ignore,pipe,pipe]
cwd      : D:\Pruebas\Angular 2\ATemplate
exitcodes: 0
pid     : undefined
>> Failed with: Error: spawn tsc ENOENT
Warning: Task "exec:tsc" failed. Use --force to continue.

I know I can have it working using v1.0.1 of grunt-exec but I want to know how must I do it with v2.0.0. The project documentation in github has not given me a clue.

A: Looks like the grunt-exec version v2.0.0 uses some ECMAScript features that are not supported in older versions of node.
The first one i saw was:
Symbol.match, String.prototype.endsWith that is not supported in node < v6.10.2
See here: http://node.green/
Upgrade your node version to fix this issue.


text:
Q: fancybox beforeclose allow close when condition met I have a fancybox that opens an iFrame where a user can modify form data.  I want to make it so that if the fancybox is attempted to be closed that the user is asked if they wish to save any changes made.  I am wanting to do this using a jQuery UI Dialog box with buttons "Yes", "No" and "Cancel".  This dialog is generated and displayed using the fancybox beforeClose callback.  I have been able to prevent the fancybox from closing while the dialog is displayed by returning false, my question is, how can I now close the fancybox?  Using $.fancybox.close() simply triggers the fancybox beforeClose callback again (looping).
My Code:
$.fancybox.open({
    href:'/index.php?task=details_movie',
    type:'iframe',
    padding:10,
    minHeight: '90%',
    beforeClose: function() {
        if ($("#dialog-confirm").length == 0) {
            $("body").append('

Do you wish to save any changes made to the details of this movie?

');
            $("#dialog-confirm").dialog({
                modal:true,
                buttons: [
                    {
                        text: "Yes",
                        click: function() {
                            alert("Yes"); // perform save actions
                            $("#dialog-confirm").remove();
                        }
                    },
                    {
                        text: "No",
                        click: function() {
                            $.fancybox.close(); // this creates the loop back to beforeClose callback
                            $("#dialog-confirm").remove();
                        }
                    },
                    {
                        text: "Cancel",
                        click: function() {
                            $("#dialog-confirm").remove();
                            return false;
                        }
                    }
                ]
            });
            $(".ui-widget-overlay").css({"z-index": 99999});
            $(".ui-dialog").css({"z-index": 100000});
        }
        return false;
    }
});

A: After reading the post below I have been able to make the following changes to my code to achieve the desired result:
How can I stop a fancyBox from closing?

*

*Changed from using beforeClose callback to afterShow callback

*Unbound click event from fancybox close button

*Created a new click event for the fancybox close button with a function containing my previous beforeClose function

In this way the fancybox close button will now trigger the jQuery UI Dialog and depending on the button selected in this dialog will now be able to trigger the $.fancybox.close() function without it triggering the beforeClose loop as was my initial issue.
I also disabled the ability to close fancybox using the escape key to force the user to click the close button.
My updated code:
$.fancybox.open({
    href:'/index.php?task=details_movie',
    type:'iframe',
    padding:10,
    minHeight: '90%',
    keys : {
        close  : null // prevent close on escape pressed
    },
    afterShow: function() {
        $(".fancybox-close").unbind(); // unbind events from close button
        $(".fancybox-close").click(function() { // create own click event
            if ($("#dialog-confirm").length == 0) {
                $("body").append('

Do you wish to save any changes made to the details of this movie?

');
                $("#dialog-confirm").dialog({
                    modal:true,
                    buttons: [
                        {
                            text: "Yes",
                            click: function() {
                                // perform save functions
                                $("#dialog-confirm").remove();
                                $.fancybox.close();
                            }
                        },
                        {
                            text: "No",
                            click: function() {
                                $("#dialog-confirm").remove();
                                $.fancybox.close();
                            }
                        },
                        {
                            text: "Cancel",
                            click: function() {
                                $("#dialog-confirm").remove();
                            }
                        }
                    ]
                });
                $(".ui-widget-overlay").css({"z-index": 99999});
                $(".ui-dialog").css({"z-index": 100000});
            }
        });
    }
});


text:
Q: Django and Docker Compose access media folder between containers I'm working on a docker-compose app using Django and a container to check images validity, here's the project structure:
|-- backend
|   |-- backend
|   |   |-- asgi.py
|   |   |-- celery.py
|   |   |-- __init__.py
|   |   |-- settings.py
|   |   `-- urls.py
|   |-- manage.py
|   |-- media
|   |   `-- temp
|   |       `-- image.png

|   |-- profiles

|-- docker-compose.yml
|-- Dockerfile
|-- README.md
|-- requirements.txt

**|-- config/nginx/nginx.conf**

Here's the docker-compose configuration of django and nsfw:
  app:
    build: .
    volumes:
      - .:/app
    ports:
      - "8000:8000"
    env_file:
      - .env/.env.dev
    depends_on:
      - database

  nsfw:
    image: eugencepoi/nsfw_api
    logging:
      driver: none
    ports:
      - "5000:5000"
    depends_on:
      - app
    environment:
      - PORT=5000

  nginx:
    image: nginx:latest
    ports:
      - "8001:8001"
    volumes:
      - .:/app
      - ./config/nginx:/etc/nginx/conf.d

Nginx configuration:
client_max_body_size 10M;

upstream web {
  ip_hash;
  server app:8000;
}

server {

    location /media/ {
        autoindex on;
        alias /app/media/;
    }

    location / {
        proxy_pass http://web/;
    }

    listen 8000;
    server_name localhost;
}

And here's when I try to access the source:
"{"error_code":404,"error_reason":"Not Found","url":"http://nginx/media/image.png"}\n"

A: As I can see from the EugenCepoi/nsfw_api repository, the service only supports http request. Also in production server, Django can't serve media contents, hence you can use VOLUME to share contents between many containers. I recommend using a new NGINX service for serving the media files, so I am adding the nginx service to the docker-compose file:
services:
  app:
    build: .
    volumes:
      - .:/app
    env_file:
      - ./.env/prod.env
    depends_on:
      - database

  nsfw:
    image: eugencepoi/nsfw_api
    logging:
      driver: none
    ports:
      - "5000:5000"
    depends_on:
      - app
    environment:
      - PORT=5000
  nginx:
    image: nginx:latest
    ports:
      - "8000:8000"
    volumes:
      - .:/app
      - ./config/nginx:/etc/nginx/conf.d
volumes:
  media:

And create a nginx configuration file in in your project directory/config/nginx/somename.conf:
client_max_body_size 10M;

upstream web {
  ip_hash;
  server app:8000;
}

server {

    location /static/ {
        autoindex on;
        alias /app/path/to/static/;
    }

    location /media/ {
        autoindex on;
        alias /app/backend/media/;
    }

    location / {
        proxy_pass http://web/;
    }
    listen 8000;
    server_name localhost;
}

Now whatever content you add in app container's media folder, it will be available in /app directory of nginx container. Then nginx can serve these contents at nginx url.
url = "http://nginx:8000/media/temp/image.png"


text:
Q: How to change Linux to compile in C99 mode? I need to change the compile mode to C99, is there any way to do this ?
I am using vim so it's not and IDE at all.

A: I assume you use gcc. Use the -std=c99 flag.

A: Any POSIX complying system is supposed to have a compiler frontend named c99. On linux this is usually just a wrapper that sets the necessary options to gcc.
If you'd have to pass that to make you could give it CC=c99 on the commandline. Or you could just add a line to your bashrc (or equivalent) of
export CC=c99

A: I'm not sure how you compile your C code from vim, but in any way, you need to create a make file and execute it to compile. You need to specify the C99 switch, however note that it is not fully implemented in GCC.

Note that this standard is not yet
  fully supported; see
  http://gcc.gnu.org/gcc-4.4/c99status.html
  for more information

If you don't already have one, I included a generic make file that I use for C homeworks :
# ------------------------------------------------
# Generic Makefile
#
# Author: Yanick Rochon
# Date  : 2010-11-05
#
# Changelog :
#   0.01 - first version
# ------------------------------------------------

# project name (generate executable with this name)
TARGET   = <executable name here>

CC       = gcc -c
# compiling flags here
CFLAGS   = -std=c99 -Wall -I.

LINKER   = gcc -o
# linking flags here
LFLAGS   = -std=c99 -Wall

SOURCES  := $(wildcard *.c)
INCLUDES := $(wildcard *.h)
OBJECTS  := $(SOURCES:.c=*.o)
rm       = rm -f

$(TARGET): obj
    @$(LINKER) $(TARGET) $(LFLAGS) $(OBJECTS)
    @echo "Linking complete!"

obj: $(SOURCES) $(INCLUDES)
    @$(CC) $(CFLAGS) $(SOURCES)
    @echo "Compilation complete!"

clean:
    @$(rm) $(TARGET) $(OBJECTS)
    @echo "Cleanup complete!"

** EDIT **
I usually edit my C sources with GEdit and have a terminal opened (or I use the GEdit's terminal plugin) to compile (using make). You can also use a full grown IDE to edit your sources, such as SharpDevelop or Anjuta, but I find GEdit and a terminal to be my preferable dev tools for C. One reason being that I actually have to do everything myself (mostly) so I know what's going on :) The same can be achieved with Vim instead of GEdit.

A: export CFLAGS='-std=c99' && make $program


text:
Q: How to get Login customer entity_id in the template in Magento 2? How to get Login customer entity_id in the template in Magento 2
 print on list.phtml

A: Here you can do a customer collection to get all customers data, then you can add filters and you get what you want.
//Load customer data
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerObj = $objectManager->create('Magento\Customer\Model\Customer')->getCollection();
foreach($customerObj as $customerObjdata )
{
    \Zend_Debug::dump($customerObjdata ->getData());
}

Update
To get just the customer loggedin data
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerObj = $objectManager->create('Magento\Customer\Model\Session');
if($customerObj->isLoggedIn()) {
    \Zend_Debug::dump($customerObj->getCustomer()->getData());
    \Zend_Debug::dump($customerObj->getCustomer()->getEntityId());
}

A: Try below Code to get customer_id in PHTML.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$customerSession = $objectManager->get('Magento\Customer\Model\Session');
echo $customerSession->getCustomer()->getId(); // prints customer's entity_id

A: Hope this is what your looking for
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
    echo   $customerSession->getCustomer()->getId()."
";  // Get Customer Id
    echo   $customerSession->getCustomer()->getName()."
";  // Get  Full Name
    echo   $customerSession->getCustomer()->getEmail()."
"; // Get Email Name
    echo   $customerSession->getCustomer()->getGroupId()."
";  // Get Customer Group Id
  }


text:
Q: Check if PDO query is returning data or boolean I am developing a database class, which also performs data arrangement in case of queries that returns data sets. My issue is: i use one single method to perform all queries, but PDO always returns true or false on execute and i don't find a way to check if i have to fetch data and return it or simply return the execute result.
What happens is that when it is a select statement, for example, it shall return fetched data,but when it is a non-returning-data query, like update, for example, it simply shall return the boolean execute result.
Here's the method:
<?php
    public function query($sqlobj) {
        $stmt = $this->prepare_statement($sqlobj->sqlstring,array_values($sqlobj->sqlvalues));
        $res = $stmt->execute();

        if ([$res IS A DATASET]) {
           $res = $stmt->fetchAll();
        }

        return $res;
    }
?>

On mysqli, it was pretty simple, cause query returns false for failure, true for successful queries which doesn't return data(ex.: update statements) and a data set resource for successful queries that brings data from DB(SELECT, COUNT, DESCRIBE, etc.), so it was a simple check:
<?php
    if($res !== true && $res !== false){
        // fetch results
    }
?>

Is there a way to perform this check on PDO, too? I did a lot of research and found things about PDOStatement::rowCount and also somethings about using PDOStatement::fetch() and checking if it is returning false. This second appeared more interesting, but it doesn't solve the problem, yet, because i will get false for non-data-returning queries as well for returning-data queries with empty results. Any brilliant ideas, folks?

A: On comments, the user @NiettheDarkAbsol gave me the correct answer and as he didn't post the answer itself, i will do it.
The question is: how can i check it queries results is fetchable or not, if all the info PDO gives me is true for success or false for failure? The answer is PDOStatement::columnCount() method:
<?php
    public function query($sqlobj) {
        $stmt = $this->prepare_statement($sqlobj->sqlstring,array_values($sqlobj->sqlvalues));
        $res = $stmt->execute();

        if ($stmt->columnCount() > 0) {
           $res = $stmt->fetchAll();
        }

        return $res;
    }
?>

As he said, columnCount() will returns me the number of columns of a query result set, even when it is empty. If query returns a non-fetchable result, columnCount() will returns 0.
Thank you @NiettheDarkAbsol!

A: public function query($sqlobj) {
    $stmt = $this->prepare_statement($sqlobj->sqlstring,array_values($sqlobj->sqlvalues));
    $res = $stmt->execute();

    if ($res ) {
       $result  = $stmt->fetchAll();
      foreach ($result as $key => $row) {
          echo $link['your_column1'];
      }
    }

}


text:
Q: Jekyll spams build messages Whenever I use jekyll serve or jekyll build Jekyll spams the following message like 50 times:
Configuration file: F:/path/to/config/_config.yml
Configuration file: F:/path/to/config/_config.yml
Configuration file: F:/path/to/config/_config.yml
Configuration file: F:/path/to/config/_config.yml
Configuration file: F:/path/to/config/_config.yml
Configuration file: F:/path/to/config/_config.yml
... and so on ...
...

Build process is fine though. No errors or warnings. Any ideas how to prevent jekyll from doing that?


text:
Q: PHP, Don't submit if there is errors Below is my PHP code, currently, it shows all errors and etc, but if one of them are correct it will submit the form, How could I change my code so that if 1 is not correct is does not submit
<?php
$cusMsg = "";
$fNameMsg = "";

if (isset($_POST["submit"])) {
    $id = $_POST["custid"];

    if(empty($id)) {
        $cusMsg = ' Field was left empty';
    } else if(!is_numeric($id)) {
        $cusMsg = ' Customer ID must be numeric';
    } else if(strlen($id) != 6) {
        $cusMsg = ' Customer ID must be 6 digits long';
    } else {
        return true;
    }

}

if (isset($_POST["submit"])) {
    $fName = $_POST["customerfname"];
    $pattern = "/^[a-zA-Z-]+$/";

    if(empty($fName)) {
        $fNameMsg = ' Field was left empty';
    } else if(!preg_match($pattern, $fName)) {
        $fNameMsg = ' First name must only containt letters and hyphens';
    } else if(strlen($fName) > 20) {
        $fNameMsg = ' First name must not be longer than 20 characters';
    } else {
        return true;
    }

}

}
?>

A: Instead of else in the last use else if and pass this
else if(!empty($fName) && preg_match($pattern, $fName) && strlen($fName) < 20){
return true;
}

It just checks all your condition using AND operator and returns true only if all conditions are met

A: You could set a flag variable $submit to false by default.
if (isset($_POST["submit"])) {

   $submit = false; // Add this

   $id = $_POST["custid"];

   if (empty($id)) {

       $cusMsg = ' Field was left empty';

   } else if (!is_numeric($id)) {

       $cusMsg = ' Customer ID must be numeric';

   } else if(strlen($id) != 6) {

        $cusMsg = ' Customer ID must be 6 digits long';

   } else {

      $submit = true;
   }

  // Now check the value of $submit and write your code accordingly.

  if ($submit) {
     // Write your submit action
  } else {
     // Other action
  }

}


text:
Q: Angular same page with different routes and content Imagine I have two type of routes in my angular application :
/football and /basketball and I have separate components for these routes.
Now I have details page. details page is quite complicated and both football and basketball have same layout for details page, so I have one component for it and route like that: /details, not /football/details or /basketball/details. these are mini games, and in details page I can open both football and basketball game at the same time, so I think /football/details or /basketball/details routes implementation is logically wrong.
Layout is same but I need several things to be done differently inside details page depending I open details page from football page or basketball page, so I should know I am on football details page or basketball details page. So what will be the best route architecture for this kind of problem? I mean should I use queryParams? or maybe I am doing something wrong? what will be the best practice?

A: In the above scenario, to determine from which route you are landed on component page, you can either use queryparams or pass with data object in routing module.Below are the use cases of both.
1) this.router.navigate(['/path'], { queryParams: { type: 'football'} });
2) {
    path: '',
    component: detailsComponent,
    data: {
      type: 'football'
    }
  }

A: If it's the same page with different functionality, I would suggest using the /details route with queryParams - then create a service to handle the custom logic.


text:
Q: Regarding passing pointers as arguments I am trying to code a basic zero threshold function. such that if the value of the array element is greater than zero must remain same else it must be zero. But my problem is with passing the array values from main to the function using pointers. Here's the snippet. im is the input array and im2 is the array to store result. t is the threshold which is 0 and m is the order. On passing the input array from main to thresh function. I just checked the values of im in thresh function but all were showing 0, as commented in code below, instead of original values. where am i going wrong??
int thresh(double *im[], double *im2[], int t, int m)
{
    int i, j;
    printf("im:%f", im[0]); //here i am getting output as zero instead of 1
    for (i = 0; i < m; i++)
    {
        if (im[i] > t)
            im2[i] = im[i];
        else
            im2[i] = 0;
    }
    return 0;
}

int main()
{
    float im[4] = { 1,-2,3,-4 };
    float im2[4];
    int th = 0;
    thresh((float*)im, (float*)im2, th, 2);

    getch();
    return 0;
}

A: Turn on compiler warnings and read them. They are there to help. This is what I got on compilation:
$ gcc main.c
main.c: In function 'thresh':
main.c:10:23: warning: comparison between pointer and integer
             if (im[i] > t)
                       ^
main.c: In function 'main':
main.c:24:12: warning: passing argument 1 of 'thresh' from incompatible pointer type [-Wincompatible-pointer-types]
     thresh((float*)im, (float*)im2, th, 2);
            ^
main.c:4:5: note: expected 'double **' but argument is of type 'float *'
 int thresh(double *im[], double *im2[], int t, int m)
     ^~~~~~
main.c:24:24: warning: passing argument 2 of 'thresh' from incompatible pointer type [-Wincompatible-pointer-types]
     thresh((float*)im, (float*)im2, th, 2);
                        ^
main.c:4:5: note: expected 'double **' but argument is of type 'float *'
 int thresh(double *im[], double *im2[], int t, int m)
     ^~~~~~

So there is some stuff to fix.
First of, the prototype for thresh should be int thresh(double *im, double *im2, int t, int m) or even better int thresh(const double *im, double *im2, int t, int m)
Second, why are you mixing float and double? Stick to one, and stick to double unless you have a really good reason.


text:
Q: Chinese Character Encoding (UTF-8, GBK) I have a web crawler that is run on different websites (Chinese in this case).
Now when I retrieve the data and display it on my website, the Chinese characters all end up as garbage. Well I read about character encoding, And I found out that UTF-8 is generally the best encoding.
Now the problem is when I use UTF-8 - The data crawled from WEBSITE-1 are shown correctly but not for WEBSITE-2.
For WEBSITE-2, the character encoding gb18030 is working correctly.
My question is, is there a way to know the character encoding for a website so that I can build a generic solution ? I mean I can render a page on my local website knowing what character encoding to use. In this way I can code in the backend, and not really worry on the front end what encoding is required to open a page.
Right now I have two pages, 1 for UTF-8 chinese characters, and one for GB18030 chinese characters.

A: Use the html meta tag "Content-Type" for html < 5 or the meta tag "char-set" for html 5
W3schools charset


text:
Q: how to know when the tonegenerator has stopped playing I kneed to know when my tone generator has stopped playing.
I want to play the dtmf tone for 50 ms and then wait 50 to play the next tone.
i wanted to use this code.
private void playtones() {
    new Thread(new Runnable() {
        public void run() {
            for(int i=0 ; i<=19 ; i++){
                dtmftone.startTone(savetone.get(i) , 50);
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            }

        }
      ).start();

}

The sleep starts before the tone has stopped playing.
How can i check that the tone has stopped playing?
Or is there at better way to do this?
Thx for the help.

A: You should use the method wait(long millis) of ToneGenerator instead of Thread.sleep().
Be careful, the method does not wait the sound to have stopped, thus you have to take the duration of the beep into account:
int BEEP_DURATION = 50;
int WAITING_DURATION = 50;

...

for (int i = 0; i <= 19; i++) {
    dtmftone.startTone(savetone.get(i), BEEP_DURATION);
    synchronized(dtmftone) {
        dtmftone.wait(BEEP_DURATION + WAITING_DURATION);
    }
...

And I am not sure whether you want to wait 50ms between two beeps. If you don't, just delete the "+ WAITING_DURATION"


text:
Q: How can I plot histograms of all variables but color by one I want to plot histograms of all the variables in my dataframe, but I want to color (or fill) the plots by one of the variables. How can I do that?
This link shows how to plot histograms for all variables, but not how to color them by one. Conversely, I can plot a histogram for one variable and color it with the code below, but then I have to plot one by one.
ggplot(mtcars, aes(mpg, color=factor(vs))) + geom_histogram()

A: If you need to color all the facets based on one of the columns, this is what you are looking for:
library(tidyverse)

ggplot(gather(mtcars, key, value, -c(vs)), aes(value, fill=factor(vs))) +
  geom_histogram(bins = 10) +
  facet_wrap(~key, scales = 'free_x')

If you want to have a different color for each facet based on key this works:
library(tidyverse)

ggplot(gather(mtcars), aes(value, fill=key)) +
  geom_histogram(bins = 10) +
  facet_wrap(~key, scales = 'free_x')

Created on 2019-06-18 by the reprex package (v0.3.0)


text:
Q: dotless fails to build CSS randomly I am having trouble tracking the source of why dotless is failing to build stylesheets. We have 8 load balanced servers.
At certain times, a user will hit the site and the stylesheets will not compile, producing a blank page. I have not been able to get any information from error logs as to what failed. Once they fail to compile, they will not work again, requiring a restart.
We are using query string parameters so that our urls look like:
<link rel="Stylesheet" href="/less/_init.less?pageId=5308&pageName=index">

This string is populating fine on the site. Dotless is used to capture those parameters so that our less looks like:
.settings() when (@pageId = 5308) and (@pageName = index) { html {color:red;} }
.settings;

The site will be fine, and then suddenly not work. In our development environment we never saw this fail. But once it was launched with heavier traffic it began to fail frequently.
Anyone seen anything like this? It's consistent across all of our servers so it's definitely an issue with the code not compiling.
I did two things to the <dotless /> entry in my web.config that appears to have temporarily fixed this issue, but I think it is sub-optimal. I made minifyCSS="true" (which we had turned off for other reasons) and set cache="false".
It's my belief that turning off caching in the web.config was helpful in preventing the above problem, but harmful for performance.


text:
Q: How to display a control over app bar in WP8 app? Working on a popup menu displayed when an app bar icon button is clicked (similar to the Respond button submenu in the standard Email WP app). How can I position a control like StackPanel over the app bar when the app bar is visible?

A: In Windows Phone Application Bar is a system control, so it is created by system and appears "on" your application. You can try to use third-party control for Application Bar or try to calculate position for your StackPanel manually dependent on screen size and orientation.


text:
Q: PHP: Make Plugin apply on homepage in WordPress blog I'm using the Smart Syntax plugin in my WP blog. It highlights syntax utilizing Google's prettify.
The syntax highlighting works perfectly with my custom CSS rules, but it seems like the Javascript applying the CSS to my posts isn't being applied when a post is viewed on the homepage.
Here's the plugin's functions.php:
<?php

function smart_syntax_prettyprint($content)
{
    global $post;
    global $comment;
    $seeker     = "/(<pre)(.+)(<code.+class.+[\'\"])([^\'\"]+)([\'\"]>)/i";
    $prettified = '$1 class="prettyprint lang-$4"$2$3$4$5';
    $content    = preg_replace($seeker, $prettified, $content);
    return $content;
}

function smart_syntax_prettify_script()
{
    global $post;
    global $comment;
    $content      = $post->post_content . $comment->comment_content;
    $smart_syntax = get_option('_smart_syntax_options');
    $output       = preg_match_all('/(<pre)(.+)(<code.+class.+[\'"])([^\'"]+)([\'"]>)/i', $content, $matches);
    // find language tags
    if (!empty($matches[0]) && isset($matches[0])) {
        $langs = smart_syntax_remove_dupe_langs($matches[4]);
        foreach ($langs as $lg) {
            if ($lg = 'css') {
                $lang = $lg;
            }
        }
    }
    if (is_singular() && !empty($matches[0]) && isset($matches[0])) {

        if (!empty($lang) && isset($lang)) {
            $suffix = '?lang=' . $lang;
        }

        if (isset($smart_syntax['cdn_prettify']) && $smart_syntax['cdn_prettify'] == true) {

            $source = 'https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js' . $suffix;

        } else {

            $source = SMART_SYNTAX_URL . 'assets/js/src/run_prettify.js' . $suffix;

        }
        wp_enqueue_script('smart-syntax-prettify', $source, null, null, true);
?>
                <script>prettyPrint()</script>
            <?php

        if (isset($smart_syntax['custom_skin']) && $smart_syntax['custom_skin'] == true) {
            wp_enqueue_style('smart-syntax-skin', SMART_SYNTAX_URL . 'assets/css/smart_syntax.css', true, '1.0.0');
        } elseif ($smart_syntax['custom_skin'] != true && $smart_syntax['cdn_prettify'] != true) {
            wp_enqueue_style('smart-syntax-skin', SMART_SYNTAX_URL . 'assets/css/prettify.css', true, '1.0.0');
        }
    }
}

function smart_syntax_remove_dupe_langs($array)
{
    foreach ($array as $lang => $val)
        $sort[$lang] = serialize($val);
    $uni = array_unique($sort);
    foreach ($uni as $lang => $ser)
        $sorted[$lang] = unserialize($ser);
    return ($sorted);
}

And here's smart_syntax.php:
function smart_syntax_init() {
    $locale = apply_filters( 'plugin_locale', get_locale(), 'smart_syntax' );
    load_textdomain( 'smart_syntax', WP_LANG_DIR . '/smart_syntax/smart_syntax-' . $locale . '.mo' );
    load_plugin_textdomain( 'smart_syntax', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
    require_once SMART_SYNTAX_PATH . 'includes/functions.php';
    require_once SMART_SYNTAX_PATH . 'includes/admin-menu.php';
}

/**
 * Activate the plugin
 */
function smart_syntax_activate() {
    // First load the init scripts in case any rewrite functionality is being loaded
    smart_syntax_init();

}
register_activation_hook( __FILE__, 'smart_syntax_activate' );

/**
 * Deactivate the plugin
 * Uninstall routines should be in uninstall.php
 */
function smart_syntax_deactivate() {

}
register_deactivation_hook( __FILE__, 'smart_syntax_deactivate' );

// actions
    add_action( 'init', 'smart_syntax_init' );
    add_action('admin_menu','smart_syntax_menu' );
    add_action('wp_enqueue_scripts','smart_syntax_prettify_script');

//filters

    add_filter('the_content', 'smart_syntax_prettyprint', 10);
    add_filter('comment_text', 'smart_syntax_prettyprint', 10);

I know very little PHP. Doing add_filter('is_home','smart_syntax_prettyprint', 10); didn't help.
`

A: The reason the script isn't loading on the homepage is because the plugin is conditionally loading the script only on single posts and pages.
Inside function smart_syntax_prettify_script() you can remove is_singular() from this statement:
if (is_singular() && !empty($matches[0]) && isset($matches[0])) {

So that it reads:
if (!empty($matches[0]) && isset($matches[0])) {

Important Note
You will be editing the plugin itself, so it's recommended that you fork it in some way. Otherwise when the plugin author releases an update it'll override your change and revert it back.
You could also contact the plugin author and ask them to create an option to allow you to set on which page types the plugin should load.


text:
Q: how to reload a div in jQuery I have a div in which I have used submit button as follow :

        <?php do_action( 'woocommerce_checkout_billing' ); ?>
        <button id="sendmail3" class="btn btn-info">Submit</button>

in this when I click on button sendmail3 then a jquery is triggered as follow :
jQuery("#sendmail3").click(function(){
            var country = jQuery("#billing_country").val();
            var address = jQuery("#billing_address_1").val();
            var city = jQuery("#billing_city").val();
            var state = jQuery("#billing_state").val();
            //alert(state);
            var pincode = jQuery("#billing_postcode").val();

            var SecondData = "country="+country+"&address="+address+"&city="+city+"&state="+state+"&pincode="+pincode;
            var currenturl = jQuery(location).attr('href');
            var url = currenturl;
            jQuery.ajax({
                dataType : 'html',
                type: 'GET',
                url : url,
                data : SecondData,
                complete : function() { },
                success: function(data)
                    {
                        jQuery("#collapse2").hide();
                        jQuery("#collapse3").show();
                    }
            });
          });

I have one more div collapse3 as follow :

            <form name="checkout" method="post" class="checkout woocommerce-checkout" action="<?php echo esc_url( $get_checkout_url ); ?>" enctype="multipart/form-data">

            <?php do_action( 'woocommerce_checkout_billing' ); ?>

<?php _e( 'Your order', 'woocommerce' ); ?>

                <?php do_action( 'woocommerce_checkout_before_order_review' ); ?>

                    <?php do_action( 'woocommerce_checkout_order_review' ); ?>

                <?php do_action( 'woocommerce_checkout_after_order_review' ); ?>

                </form>
                <?php do_action( 'woocommerce_after_checkout_form', $checkout ); ?>

In this div data is loaded dynamically
What I want is that when I click on sendmail3 button then only the div collapse3 should be reloaded. How can I reload this div only without refreshing the page

A: I think this will work.
    success: function(data)
                {
                    jQuery("#collapse2").hide();
                    jQuery("#collapse3").append(data); //I change this to .append() or try .html(data);

                }

Hope this works.

A: You can use the load() method:

Load data from the server and place the returned HTML into the matched element.

$('.myDiv').load('urlToGetUpdatedContent');

A very clean way with built-in jQuery logic. See full documentation: http://api.jquery.com/load/

A: The idea is to fetch your page in specific div , like what you mentioned in your question by ajax call and then return the data to same div .
for example :
$("#sendmail3").click(function(){ var getdata= $("#collapse3").html(); ...

then make ajax call and put in the :
success: function(whatever-result) { $("#collapse3").html(getdata);...

that will only refresh the div with id
UPDATE
I think you are looking to send your form through this mentioned div then reload the div to show the form again , here is another solution :
$("yourform").submit(function(event){
  var target =$(this).attr('action');
  event.preventDefault();
   $.post( target, $(this).serialize(), function(data){
     $("#supposed-div").html(data);// this will force submitting this form only through this div
             });
      });

Then you can use JavaScript , JQuery or AJAX call ,it could be through the above code ,to let form come into div as it is .
At the beginning of this answer i used to suggest to get the $("div").html(); and put it as var getdata to be easy to put again into div.html after submission.