text:
Q: Same SSID on router and Access Point? I have a L-shaped house with an ASUS router in one end. My problem is that the wifi strength is quite bad in the other end of the house and sometimes even non-existing.
I have a extender/access point (Asus RP-AC52) that I think will solve my problems, I'm not quite sure how to configure it though.
My options are:

*

*Use it as an wireless extender.

*Use it as an access point in the other end of the house (a wire is available)

The problem this nr 1 is that it seems to still be too far away. The wifi is still unreliable in the other end of the house.
Options nr 2 seems like the best, but I'm wondering how it works when connected to a wifi router? Can they have the same ssid? Does the access point have it's own dhcp? Can the clients switch network seamlessly?
Thanks!

A: I felt the need to post an answer too to clear out the small inaccuracies from the other answer. (sorry, not meant to be rude)
You mention two choices.

*

*Use it as extender

*Use it as separate accesspoint.

Both solutions have their pro's and cons. Lets list those first.
Use it as an extender
When you setup the device as extender, you will repeat the signal that comes into the device.
The pro is that this allows you to roam through the entire network without losing connection.
The con is that you get less speed as bandwidth is reserved for the connection to the other access point it extends.
Use it as a separate accesspoint
When you setup the device as new accesspoint, a new wifi point is added to the network that devices can connect to.
The pro is that it reduces load on the other wifi points and gets better coverage because the signal is stronger. Also because you run a network cable to that point, speeds get near the max it can be for the entire wifi.
The con is that you will not automatically switch to this wifi which can give weird issues and may appear to not work. This also will give you small dropouts when it switches.
Which is better?
Although the con for the access point is a big one, it still is a better trade off when done correctly.
Keep in mind that even if you use the same SSID and password for both networks, your wifi will still see them as two and will stay connected to the same wifi point until the signal is so weak it disconnects, in which case it automatically switches over to the other network. This unfortunately does mean that you still get slow speeds when you are far away from the first wifi point and still barely in range.
Because both wifi's have the same SSID, you cannot switch yourself manually. It is this exact reason why you want to avoid naming both wifi devices with the same SSID. Give both a different SSID, so you can switch yourself when you want to, or even better, choose to not connect to one of the two networks at all, so you are always connected to either, and choose the one where you need to have wifi coverage the most.
With this in mind, it can be a big win to choose the location of the second accesspoint carefully, so you can make that your main wifi point without connecting to the other and only use the other device in those rare cases when you need it.
You configure this by linking a cable between a LAN port from both the router AND the device that becomes the Access Point. You will want to turn off DHCP though. Let the main device handle that. In the configuration you will have to specify something for the WAN port, it doesn't really matter what this is as long as it is something arbitrary and non-existent, preferably still in the same network range, but not inside the subnet.
By this I mean... Say, you have your network setup as 192.168.10.x, then you will want to put the WAN to 192.168.y.x where y is any number other than 10.
Also, make sure the LAN ipaddress of the Access point is static and set to any number inside the range of the network, but outside of the DHCP range on a free address, so you can manage the device whenever you need to.

A: You are best to make it an access point (not extender) since you have a wire (Ethernet).
Extenders drop bandwidth significantly (Wireless calls home causing double traffic). I do not use Extenders.
Access Point:    Hook it up as follows:

*

*LAN port on access point to network.

*Give the access point a static IP on your network.

*Turn DHCP OFF on access point.

Which is better:   Ethernet connected Access Point wins hands down. Better signal strength, better reliability
You can give the access point the same SSID as your main network. That does not make it a mesh so roaming will not be automatic but still workable.
You need a Ubiquiti or like device to make a mesh.

A: Extenders connect to the router via wifi, which is slower and less reliable than connecting via ethernet, but access points connected via ethernet require running a cable. Both also offer a different kind of flexibility: an access point can be anywhere, but only if there is a cable there. An extender must be in range of both the main wifi network broadcast by your router, and any device that wants to connect to the network.
In your L-shaped house with a router in one arm of the L, the approximate best place for an extender is at the junction between the two arms of the L, and the approximate best place for an access point is in the other arm of the L. You would want to test this, but if you already have a cable installed, it's a no-brainer to use an access point in my opinion.
The other answers are not correct that your devices will not automatically swap between networks, though. The decision as to whether to name the networks from different access points the same thing (use the same credentials if you do this) or name them different things is up to you, and you should test both modes with your devices. Using one network name does keep things simpler.
There is no part of the Wifi standards that deals with when and how to swap between access points using the same SSID (network name) or networks with different name that the device is allowed to connect to automatically. It's completely at your device's discretion which networks and access points to choose, and when to scan for a potentially-better network and swap the connection. These days most devices are pretty smart about swapping network when there is a better option, but you can always test with your specific devices and see which option works best.
This concept of having overlapping signals using the same or different SSIDs, and how your device will choose which one to connect to, is also completely different to mesh networking. Mesh networking is more to do with how the access points themselves connect to one another using wireless or wired connections, and how they negotiate those connections. The principle of mesh networking is that the access points themselves are not hierarchical or pre-configured and they will figure out for themselves how to connect together for the best result.
But from the perspective of your device looking at the networks and access points that are offering it a place to connect to the internet, these details are irrelevant and do not usually form part of its decision about which network or access point to connect to.
If your device is in access point mode, it should disable its own DHCP and allow the router's DHCP to take precedence, but if this doesn't happen, you should disable the access point's DHCP in the settings.


text:
Q: Connection problems in Laravel 5.7 Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0

Fatal error: Unknown: Failed opening required 'C:\xampp\htdocs\Laravel\Blog\server.php' (include_path='C:\xampp\php\PEAR') in Unknown on line 0

Someone knows, why did this happen?

A: In your project folder, the server.php file is missing so you got this error
The solution will to create another project then copy the newly created server.php this will solve it.
Another Solution is:

*

*Open the link: https://github.com/laravel/laravel/blob/master/server.php

*Copy all code

*Open Notepad and paste your copy code

*save Notepad file and set name server.php

*Copy the server.php file and paste it inside your Laravel project

Run your project again in browser Now you will not get an error and the Laravel project will work properly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set Fontfile From assets folder in ffmpeg (android studio) I want to set font file in ffmpegn from assets folder in android. Can someone suggest me how can i do that. Following is my drawtext command :-
 drawtext=fontsize=60:fontfile=/system/fonts/DroidSans.ttf:fontcolor=green:text=Post:x=150:y=150

A: Write file by loading asset data as bytes
final filename = 'font.ttf';
var bytes = await rootBundle
    .load("packages/flutter_video_editor/assets/font/aller.ttf");

String dir = (await getApplicationDocumentsDirectory()).path;
final path = '$dir/$filename';

final buffer = bytes.buffer;
await File(path).writeAsBytes(
    buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes));

File file = File('$dir/$filename');

print('Loaded file ${file.path}');
_flutterFFmpegConfig.setFontDirectory(file.path, null);

return file.path;


text:
Q: Error with a webservice call in Android using Complex types i have a problem with a webservice in Android.I send a call to a ASP.Net application and my application don't receive a good response.
I have a similar code to call another method that uses Strings and work fine but this call use complex types and don't work.
I expect to receive a String but actually i receive an exception:System.Web.Services.Protocols.SoapException: Server can not process the request ---> System.ArgumentNullException:Value can not be null.
I use Ksoap2 library.
This is my class:
package docService;

import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import andro.util.Log;
import com.sistems.doc.EnviarArchivo;

public class CallSoapNew extends Thread {

public final String SOAP_ACTION = "http://myweb.com/doc/AppendNew";

public final String OPERATION_NAME = "AppendNew";

public final String WSDL_TARGET_NAMESPACE = "http://myweb.com/doc";

public final String SOAP_ADDRESS = "http://myweb.com/Service.asmx";

public vo run() {
    try {
        String resp = Call(EnviarArchivo.documentalTyped,
                EnviarArchivo.values, EnviarArchivo.hypValues,
                EnviarArchivo.ocLogin, EnviarArchivo.controlInfo,
                EnviarArchivo.ip);
        EnviarArchivo.result = resp;
    } catch (Exception ex) {
        EnviarArchivo.result = ex.toString();
    }
}

public String Call(String documentalTyped, List<String> values,
        List<String> hypValues, String ocLogin, String controlInfo,
        String ip) {
    SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
            OPERATION_NAME);
    PropertyInfo pi = new PropertyInfo();
    pi.setName("documentalTyped");
    pi.setValue("847632423876");
    pi.setType(String.class);
    request.addProperty(pi);

    SoapObject object = new SoapObject(WSDL_TARGET_NAMESPACE, "values");
    object.addProperty("Column", "38d192861");
    object.addProperty("Value", "nombreeterte");
    request.addSoapObject(object);

    SoapObject obj = new SoapObject(WSDL_TARGET_NAMESPACE, "hypValues");
    obj.addProperty("Column", "38d192861");
    obj.addProperty("Url", "nombreeterte");
    obj.addProperty("Alternative", "nrtyrtyrtyrtyrrte");
    obj.addProperty("Title", "nomette");
    obj.addProperty("Ijmg", "ntterterterte");
    request.addSoapObject(obj);

    pi = new PropertyInfo();
    pi.setName("ocLogin");
    pi.setValue(ocLogin);
    pi.setType(String.class);
    request.addProperty(pi);

    pi = new PropertyInfo();
    pi.setName("controlInfo");
    pi.setValue("hghg");
    pi.setType(String.class);
    request.addProperty(pi);

    pi = new PropertyInfo();
    pi.setName("ip");
    pi.setValue("321563");
    pi.setType(String.class);
    request.addProperty(pi);

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    //envelope.dotNet = true;
    envelope.setOutputSoapObject(request);

    HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
    Object response = null;

    httpTransport.debug = true;

    try {
        httpTransport.call(SOAP_ACTION, envelope);
        response = envelope.getResponse();
    } catch (Exception exception) {
        response = exception.toString();
    }
    return response.toString();
}

}
This is the XML that content the variable httpTransport:
<v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
<v:Header />
    <v:Body>
        <n0:AppendNew ="o0" c:root="1" xmlns:n0="http://myweb.com.com/doc">
            <documentalTyped i:type="d:string">847632423876</documentalTyped>
            <n0:values i:type="n0:values">
                <Column i:type="d:string">38d192861</Column>
                <Value i:type="d:string">nombreeterte</Value>
            </n0:values>
            <n0:hypValues i:type="n0:hypValues">
                <Column i:type="d:string">38d192861</Column>
                <Url i:type="d:string">nombreeterte</Url>
                <Alternative i:type="d:string">nrtyrtyrtyrtyrrte</Alternative>
                <Title i:type="d:string">nomette</Title>
                <Ijmg i:type="d:string">ntterterterte</Ijmg>
            </n0:hypValues>
            <ocLogin i:type="d:string">jhbb77fd2</ocLogin>
            <controlInfo i:type="d:string">hghg</controlInfo>
            <ip i:type="d:string">321563</ip>
            </n0:AppendNew>
        </v:Body>
</v:Envelope>

And this is the XML that i receive:
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
    <soap:Fault>
    <faultcode>soap:Server</faultcode>
    <faultstring>System.Web.Services.Protocols.SoapException: El servor no puede procesar la solicitud. --->
System.ArgumentNullException: El valor no puede ser nulo.\r\n
Nombre del parámetro: g\r\n   en System.Gu..ctor(String g)\r\n
en CommonService.CheckSession(String user, String ip, ocSessionType ocSessionType)\r\n
en ocService.AppendNewLdapUser(String documentalType, List`1 values, List`1 hypValues, String ocLogin, String userLogin, String ldapUser, String controlInfo, String ip)\r\n
en ocService.AppendNew(String documentalType, List`1 values, List`1 hypValues, String ocLogin, String controlInfo, String ip)\r\n
--- Fin del seguimiento de la pila de la excepción interna ---
    </faultstring>
    <detail />
    </soap:Fault>
    </soap:Body>
</soap:Envelope>

Can anybody help me?Thanks


text:
Q: No se puede abrir fichero generado con PHPExcel ¿Por qué al descargar mi archivo como Excel desde una página PHP me da un error de que no se puede abrir o la extensión no es válida? ¿Tendrá que ver esta parte del código donde le doy nombre y extensión?
<?php
function activeErrorReporting()
{
  error_reporting(E_ALL);
  ini_set('display_errors', TRUE);
  ini_set('display_startup_errors', TRUE);
  date_default_timezone_set('Europe/London');
}

function noCli()
{
  if (PHP_SAPI == 'cli')
    die('This example should only be run from a Web Browser');
}

function getHeaders()
{
  // Redirect output to a client's web browser (Excel5)
  header('Content-Type: application/vnd.ms-excel');
  header('Content-Disposition: attachment;filename="01simple.xlsx"');
  header('Cache-Control: max-age=0');
  // If you're serving to IE 9, then the following may be needed
  header('Cache-Control: max-age=1');

  // If you're serving to IE over SSL, then the following may be needed
  header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
  header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  header ('Pragma: public'); // HTTP/1.0
}

A: Tienes que remover las comillas del nombre de archivo, puedes intentar con los siguientes headers, aunque si el archivo está mal formado de igual forma te enviará error al abrirlo.
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=01simple.xls");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);

Habría que revisar el archivo con un editor de texto para corroborar que PHP no está generando ningún tipo de Output como errores o similares dentro del archivo.


text:
Q: Call a function template using a function pointer I need to use a function template which is available in a header file via a function pointer which is available as a struct member.
For example:
File: mytemplate.h
template<typename T> const bool GT(const T& pa_roIN1, const T& pa_roIN2)
{
    bool temp = false;
    if(pa_roIN1 > pa_roIN2){
        temp = true;
    }
    return temp;
}

template<typename T> const bool EQ(const T& pa_roIN1, const T& pa_roIN2)
{
    bool temp = false;
    if(pa_roIN1 == pa_roIN2){
      temp = true;
    }
    return temp;
}

template<typename T> const bool GE(const T& pa_roIN1, const T& pa_roIN2)
{
    bool temp = false;
    if(pa_roIN1 >= pa_roIN2){
      temp = true;
    }
    return temp;
 }

File: mystruct.h:
struct mystruct {
    std::string  funcName;
    bool (*funcPtr)(int,int);
};

typedef std::map<int, mystruct> mystructList;

File: mycpp.cpp:
#include "mytemplate.h"
#include "mystruct.h"

mystruct MyGreaterStruct[3] = {
  {"GREATER_THAN", &GT},
  { "EQUAL", &EQ},
  { "GREATER_N_EQUAL", &GE}
};

mystructList MyList;
int main(void)
{
     int size = sizeof(MyGreaterStruct)/sizeof(mystruct);
     for(int i = 0; i < size; i++) {
       MyList.insert(std::pair<int, mystruct>(i,MyGreaterStruct[i])); }

     for(mystructList::iterator iter = MyList.begin(); iter != MyList.end(); iter++) {
        printf("\nResult of func : %s for values 100,50 : %d",iter->second.funcName.c_Str(),iter->second->funcPtr(100,50));
     }
}

I am not sure this the correct way of doing it. But there is no result that gets printed on the console.

A: The error you get when compiling your code tells you what is wrong:
mycpp.cpp:8:1: error: no matches converting function 'GT' to type 'bool (*)(int, int)'
 };
 ^
mytemplate.h:1:33: note: candidate is: template<class T> const bool GT(const T&, const T&)
 template<typename T> const bool GT(const T& pa_roIN1, const T& pa_roIN2)
                                 ^

There's no way to instantiate that template to match the signature of the function pointer, as the template takes two references as arguments, while the pointer takes two ints.  If you can't change either the struct or the templates, and you are using C++11, you could try using lambdas instead:
mystruct MyGreaterStruct[3] = {
  {"GREATER_THAN", [](int a, int b)->bool { return GT(a, b); } },
  { "EQUAL", [](int a, int b)->bool { return EQ(a, b); } },
  { "GREATER_N_EQUAL", [](int a, int b)->bool { return GE(a, b); } }
};

but no matter how you slice it, you need to either change the arguments or use a little function that converts the arguments from one form to the other.


text:
Q: How to initialize value of another view controller In my app when user redirect to app from browser I am presenting registration page. In that I want to insert value from url variable. So first I am fetching value from url and then displaying that page with  textbox value.But it is not setting textbox value.
my code:
    - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    NSString *urlString=[NSString stringWithContentsOfURL:url encoding:nil error:nil];
 NSRange r = [urlString rangeOfString:@"gratzeez://" options:NSCaseInsensitiveSearch];

    if(r.location != NSNotFound){
        NSLog(@"founddddd");
        NSLog(@"gratzeez url %@",url);
        //NSString *str=[url valueForKey:@"email"];
        NSArray *query = [[url query] componentsSeparatedByString:@"&"];
        NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:[query count]];
        for(NSString *parameter in query)
        {
            NSArray *kv = [parameter componentsSeparatedByString:@"="];
            [parameters setObject:[kv count] > 1 ? [[kv objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding] : [NSNull null]
                           forKey:[[kv objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding]];
        }

        NSLog(@"Parameters: %@", parameters);

        [self.tabBar dismissViewControllerAnimated:NO completion:nil];
        RegistrationViewController *RegistrationVC=[[RegistrationViewController alloc] initWithNibName:@"RegistrationViewController" bundle:nil];
        RegistrationVC.txtEmail.userInteractionEnabled=NO;
        NSLog(@"q = %@", [parameters objectForKey:@"email"]);

        UINavigationController *navController=[[UINavigationController alloc]initWithRootViewController:RegistrationVC];
        RegistrationVC.txtEmail.text=[parameters objectForKey:@"email"];
        NSLog(@"value%@",RegistrationVC.txtEmail.text); //here getting null value
        [self.tabBar presentViewController:navController animated:NO completion:nil];
        navController.navigationItem.leftBarButtonItem=nil;
        return YES;

    }

what is I present registrationviewcontroller by this way.?
RegistrationViewController *RegistrationVC=[[RegistrationViewController alloc] init ];

    NSLog(@"q = %@", [parameters objectForKey:@"email"]);
    UINavigationController *navController=[[UINavigationController alloc]initWithRootViewController:RegistrationVC];

    NSLog(@"txtemail %@ value%@",RegistrationVC.txtEmail,RegistrationVC.txtEmail.text);
    [self.tabBar presentViewController:navController animated:NO completion:^{
        RegistrationVC.txtEmail.userInteractionEnabled=NO;
        RegistrationVC.txtEmail.text=[parameters objectForKey:@"email"];
    }];

Now again this is giving null for both.

A: As we've seen in comment, your txtEmail is not created when you try to assign it a value.
I suggest you to add a completion block to the method presentViewController:animated:completion:. At this point, your controller RegistrationVC will be loaded and its views (and subviews) created, and so you would be able to assign values to your elements :
[self.tabBar presentViewController:navController animated:NO completion:^{
    RegistrationVC.txtEmail.text=[parameters objectForKey:@"email"];
}];


text:
Q: Как убрать префикс .php Здравствуйте, нужно скрыть префикс *.php в url сайта (используя htaccess)
Тоесть было url.ru/index.php стало url.ru/index.
Только есть один нюанс, нужно скрыть не только для index.php, но и для всех остальных тоесть какой файл не был созан url.ru/*.php стало url.ru/*

A: Делаем замену в .htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php


text:
Q: Using filter with empty values in PyQGIS In my script, at the moment of having the layers loaded, I filter all the ToC layers with a unique value for all the layers.
I use the setSubsetString('"FIELD" = \' VALUE \ '') method, but when it does not find any field with that value, it throws me the following error:

wkb outbounds

How can I solve this? I am using QGIS 2.14.

A: I don't know what you call the setSubsetString method, but
did you try something 'lighter' like the following?
"Field" like '%VALUE%'


text:
Q: NSTextField rec'd focus? How can I know when an NSTextField has rec'd focus?
Is there a delegate method that will tell me when the user has clicked the mouse in (or otherwise selected) my NSTextField?
thanks
tom

A: Subclass NSTextField and override -becomeFirstResponder.


text:
Q: How do I make the program fail? Prolog I have a recursive program with this structure:
P1(I,SOL):-
  'does something',
  P(I,[I],SOL).

P1(A,B,SOL):-
  'does something',
   P2(A1,B1,B2,SOL).

P2(A,_,_,SOL):-
  goal(A).

P2(A,B,C,D):-
  'does something',
   MARK,
  'does something',
  P2(A1,B1,B2,SOL).

At MARK I have a condition (C<Limit).
The problem is when that condition fails, the program doesn´t fail. I think it backtracks and keeps running not going anywhere but consuming a lot of memory, How do I make the program fail if the condition is not met?


text:
Q: Do POST request with Android DefaultHTTPClient cause freeze on execute() I need post data to server.
I use this code:
HttpClient client = new DefaultHttpClient();
try {

    HttpPost httppost = new HttpPost(serverUrl);

    StringEntity se = new StringEntity(data);
    httppost.setEntity(se);
    httppost.setHeader("Accept", "application/json");
    httppost.setHeader("Content-type", "application/json");

    // Execute HTTP Post Request
    HttpResponse response = client.execute(httppost);
    int statusCode = response.getStatusLine().getStatusCode();
    Log.i(TVProgram.TAG, "ErrorHandler post status code: " + statusCode);

} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (client != null) {
        client.getConnectionManager().shutdown();
    }
}

But problem is that Android freeze on execute() method, application is blocked out and after some time Android tell me that application doesn't respond.
I tried to debug into SDK classes and it freeze in AbstractSessionInputBuffer class on the line 103 which is
l = this.instream.read(this.buffer, off, len);

I also tried it run the request in separated thread, but the same problem.
I tested it on Android 2.1 (emulator) and Android 2.2 real mobile device.
I also tried to set HTTP proxy and use Fiddler to check HTTP communication data are received by server and server also send correct answer and HTTP code 200. All seems to be ok.
What is wrong please?
UPDATE: When I use AndroidHttpClient which is part of Android 2.2 SDK it works great. But it is not in earlier version of Android. So I include it's source code in my app for now. But AndroidHttpClient use DefaultHTTPClient internally, so problem will be in configuration of DefaultHttpClient.

A: I am using a POST HTTP request successfully. Here is my code. I removed pieces using handler to display messages etc. and the handler itself.
The POST string is like "&NAME=value@NAME2=value2"...
protected class ConnectingThread implements Runnable
{
    Message msg;
    private Handler mExtHandler;
    private String mData;
    private String mUrl;

    /**
     * @param h (Handler) - a handler for messages from this thread
     * @param data (String) - data to be send in HTTP request's POST
     * @param url (String) - URL to which to connect
     */
    ConnectingThread(Handler h, String data, String url) {
        mExtHandler = h;
        mData = data;
        mUrl = url;
    }

    public void run() {
        try {
            // TODO use the handler to display txt info about connection

            URL url = new URL(mUrl);
            URLConnection conn = url.openConnection();
            conn.setConnectTimeout(CONN_TIMEOUT_MILLIS);

            conn.setDoOutput(true);
            BufferedOutputStream wr = new BufferedOutputStream(conn.getOutputStream());
            wr.write(mData.getBytes());
            wr.flush();
            wr.close();

            String sReturn = null;

            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            int length = conn.getContentLength();
            char[] buffer = new char[length];
            int read = rd.read(buffer);
            if(read == length)
                sReturn = new String(buffer);
            rd.close();
            buffer = null;
         // TODO use the handler to use the response

        } catch (Exception e) {
            //....
        }
        // TODO use the handler to display txt info about connection ERROR
    }

}

A: Isn't client.execute(httppost); synchronous ?
You probably need to put this in a thread, else it will freeze the UI.

A: Yes it is being freezed just becoz you haven't implemented this as Asynchronous process. Because while it makes web request, your UI will wait for the response and then it will be updated once the response is received.
So this should be implemented as Asynchronous process, and user should be notified (with  progress bar or progress dialog) that there is something happening.
Now, Instead of implementing Runnable class, in android its preferrable and recommended to use AsyncTask, its also known as Painless Threading.

*

*Do you background tasks inside the doInBackground() method.

*Do your display type of operations inside onPostExecute() method, like updating listview with fetched data, display values inside TextViews....etc.

*Display ProgressBar or ProgressDialog inside the onPreExecute() method.

A: Use AndroidHttpClient helped me in this situation.
But now complete AndroidHttpClient and DefaultHttpClient are obsolete in current version of Android so it is not important now.


text: Q: I would like to deploy an API using pytorch. Is there any good deployment location? I made an API using pytorch, fastAPI and opencv, but when I deploy it to heroku, it's too big to deploy. So, I'm thinking of deploying on another site. Is there any good site? Hopefully you can use it for free without having to think about the size of pytorch, fastAPI and opencv.


text:
Q: What is the best practice for nifi production deployment I have a three node nifi cluster. We just installed nifi packages on linux machines and cluster with separate zookeeper cluster. I am planning to monitor nifi performance via nagios but we saw hortonworks ambari provides fetures for management and monitoring also.
What is the best practice for nifi deployment on prod

*

*how should we scale up

*how can we monitor nifi

*Should we monitor queue/process performance

*Should use something like ambari

regards..

Edit-1:
@James actually I am collecting user event logs from several sources within company.
All events are first written to Kafka. Nifi consumes kafka, does simple transformations like getting a field from payload to attribute.
After transformations data is written to both elasticsearch and hdfs. Before writing to hdfs we are merging flowfiles so writing to hdfs is in batches.
I have around 50k/s event.


text:
Q: How to filter data by time on django? I have some problem for filter data in django with time, i want filter select option pagi will show data time from 00:00 to 10:00, if select option siang will show data from 10:01 to 18:00, if select option malam it will show data from 18:00 to 23:59,
I have code template/index.html like this:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>This Is Latihan</title>

  <form action="{% url insert %}" method="POST">{% csrf_token %}
      Nama Maskapai   : <input type="text" name="airline" id="airline" value="{{ airline }}"></input>

      Waktu Berangkat : <input type="text" name="time" id="time" value="{{ time }}"></input>

      <input type="submit" name="save" value="save">
  </form>

    No.
    Maskapai
    Waktu
    Action

    {% for i in maskapai %}

      {{ forloop.counter }}
      {{ i.airline }}
       {{ i.time }}
      <form action="{% url action %}" method="POST">{% csrf_token %}

        <input type="hidden" name="index" value= "{{ forloop.counter0 }}" />
        <input type="hidden" name="time" value= "{{ i.time }}" />
        <input type="submit" name="delete" value="delete">
        <input type="submit" name="up" value="up">
        <input type="submit" name="down" value="down">

      </form>

  {% endfor %}

  <form action="{% url filter %}" method="POST">{% csrf_token %}
    <select name="maskap">
      <option value="all">-Pilih Maskapai-</option>
      {% for pil in pilihan %}
      <option value="{{ pil }}"> {{ pil }} </option>
      {% endfor %}
    </select>

    <select name="waktu">
      <option value="allwak"> -Pilih Waktu- </option>
      <option value="pagi">pagi</option>
      <option value="siang">siang</option>
      <option value="malam">malam</option>
    </select>
    <input type="submit" name="name" value="FILTER">
</form>

And This is my view code :
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
import time

maskapai_glob = []
pilihan_glob = []
def index(request):
    return render_to_response('index.html', locals(), context_instance=RequestContext(request))

def insert(request):
    if request.POST:
        airline = str(request.POST.get('airline'))
        times = str(request.POST.get('time'))
        try:
            # Diisi ReGex Jam
            tim = time.strptime(times,'%H:%M')
            # time = "%s:%s" % (tim.hour, tim.minute)
            insert_data = {'airline':airline, 'time':times}
        except Exception, err:
            print err
            return HttpResponse("""
Jam Salah
<button onClick='window.history.back()'>back</button>""")

        maskapai = [i for i in maskapai_glob]
        pilihan = [i for i in pilihan_glob]

        maskapai.append(insert_data)
        maskapai_glob.append(insert_data)

        if len(pilihan) == 0:
            pilihan.append(airline)
            pilihan_glob.append(airline)
        elif len(pilihan) >= 1:
            if airline in pilihan:
                pass
            else:
                pilihan.append(airline)
                pilihan_glob.append(airline)

        return render_to_response('index.html', locals(), context_instance=RequestContext(request))

def action(request):
    if request.POST:
        if request.POST.get('delete'):
            val_maskapai = []
            index = int(request.POST.get('index'))
            airline = str(request.POST.get('airline'))
            del maskapai_glob[index]

            maskapai = [i for i in maskapai_glob]
            pilihan = [i for i in pilihan_glob]

            for i in range(len(maskapai_glob)):
                val_maskapai.append(maskapai[i]['airline'])

            for i in pilihan_glob:
                if i in val_maskapai:
                    pass
                else:
                    pilihan_glob.remove(i)
                    pilihan.remove(i)

            return render_to_response('index.html', locals(), context_instance=RequestContext(request))

        elif request.POST.get('up'):
            index_up = int(request.POST.get('index'))
            index_down = index_up - 1
            data_one = maskapai_glob[index_down]
            data_two = maskapai_glob[index_up]
            if index_up == 0:
                pass
            else:
                maskapai_glob[index_down] = data_two
                maskapai_glob[index_up] = data_one
            maskapai = [i for i in maskapai_glob]
            return render_to_response('index.html', locals(), context_instance=RequestContext(request))

        elif request.POST.get('down'):
            index_down = int(request.POST.get('index')) # data can be down
            last_index = len(maskapai_glob) - 1
            if index_down == last_index:
                pass
            else:
                index_up = index_down + 1 # data can be up
                data_one = maskapai_glob[index_down] # data down
                data_two = maskapai_glob[index_up] # data up
                maskapai_glob[index_down] = data_two
                maskapai_glob[index_up] = data_one
            maskapai = [i for i in maskapai_glob]
            return render_to_response('index.html', locals(), context_instance=RequestContext(request))

def filter(request):
    if request.POST:
        getmask = request.POST.get('maskap')
        getwaktu = request.POST.get('waktu')

        if getmask:
            if getmask == 'all':
                maskapai = [i for i in maskapai_glob]
                pilihan = [i for i in pilihan_glob]
                #Mulai dari sini
                if getwaktu == "pagi":
                    maskapai = [] #maskapai
                    pilihan = [i for i in pilihan_glob] #pilihan option

                    data_pilihan = request.POST.getlist(str('waktu')) #mengambil data dari select (maskap)
                    list_pilihan = [str(i) for i in data_pilihan] #list pilihan dari data maskap

                    for i in range(len(maskapai_glob)):
                        if 'pagi' in list_pilihan:
                            #maskapai.append(maskapai_glob[i])
                            return HttpResponse("test");
                    #return HttpResponse("test");
                    return render_to_response('index.html', locals(), context_instance=RequestContext(request))
                #Sampai sini

                return render_to_response('index.html', locals(), context_instance=RequestContext(request))

            else:
                maskapai = [] #maskapai
                pilihan = [i for i in pilihan_glob] #pilihan option
                data_pilihan = request.POST.getlist(str('maskap')) #mengambil data dari select (maskap)

                list_pilihan = [str(i) for i in data_pilihan] #list pilihan dari data maskap

                for i in range(len(maskapai_glob)):
                    if maskapai_glob[i]['airline'] in list_pilihan:
                        maskapai.append(maskapai_glob[i])

                return render_to_response('index.html', locals(), context_instance=RequestContext(request))

Method filter is function to filter.

A: You are currently using global variables instead of Django's ORM - this is a  bad practice!  Follow the tutorial to learn how to create DB models with Django.
Assuming you are using Django's ORM, try:
FILTERS = {
 'pagi': (None, "10:00"),
 'siang': ("10:00", "18:00"),
 'malam': ("18:00", None),
}

a, b = FILTERS[request.POST['waktu']]

and then query your DB, assuming you have a date DateField and a time TimeField in your model MyModel:
qs = MyModel.objects.filter(date=x)
if a:
    qs = qs.fiter(time__gte=a)
if b:
    qs = qs.fiter(time__lt=b)


text:
Q: ImportError while using AWS Lambda in Python (via zappa serverless); Numpy I have an ImportError issue with my AWS Lambda function

*

*I can run this code locally without ImportError

*I use zappa serverless for uploading my code to AWS Lambda--which requires a virtual environment and is an end-to-end solution for creating and updating Lambda functions

*I previously had this code working on AWS Lambda

I'm not sure of the change I made (#3) that made this code go from working to ImportError. The log output is as follows.
[ERROR] Runtime.ImportModuleError: Unable to import module 'dailycore': Unable to import required dependencies:
numpy:

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the numpy C-extensions failed. This error can happen for
many reasons, often due to issues with your setup or how NumPy was
installed.

We have compiled some common reasons and troubleshooting tips at:

    https://numpy.org/devdocs/user/troubleshooting-importerror.html

Please note and check the following:

  * The Python version is: Python3.8 from "/var/lang/bin/python3.8"
  * The NumPy version is: "1.23.3"

and make sure that they are the versions you expect.
Please carefully study the documentation linked above for further help.

Original error was: No module named 'numpy.core._multiarray_umath'

I'm unclear if this is a Numpy issue, a Python issue, or a Zappa issue. Two changes I made that may have had an impact:

*

*I separated out some of my personal code, uploaded it to github, and installed it as packages within the virtual environment using pip

*I uninstalled Python from my machine and reinstalled it--as I had two versions causing conflict. Upon my reinstallation (Python 3.8), I changed the installation directory from its default.

The code runs from VS Code locally and wholly contained from within the virtual environment (i.e. I don't have any packages installed via pip on my machine outside of virtual environments at this point). The suggestions above may or may apply to this error. I've tried adding a system PATH variable to my Python 3.8 directory. I've tried downgrading numpy to 1.23.0. I've tried uninstalling all dependencies within the virtual environment and reinstalling them.
UPDATE: I found this link and am looking into these comments: https://github.com/Miserlou/Zappa/issues/1222
UPDATE2: I deleted the virtual environment and re-created per a suggestion at the link above. This did not work.
UPDATE3: I think my issue relates to the private package dependencies I installed via pip from my personal github repos (#2-2). This link may be related. Something about dependencies not being at the top level. I am unsure how to fix this issue and/or repackage my private repo or install correctly. Any clarification is appreciated.
UPDATE4: I've isolated my issue to the private package dependencies and how they get called. A the solution may be related to Lambda Layers, tutorial here. Looking into this.

A: The ImportModuleError is related to this python package: alpha_vantage and not either of my initial theories. I am unsure as to why, though. It seems like it has something to do with Alpha Vantage's setup.py file; although I could be mistaken.
I have removed the reference to Alpha Vantage for now, but if anyone knows why installing this package would throw a numpy error, please elaborate. I think the only reference to numpy would be through the pandas package--which is only an optional install (i.e. extras_requires in setup.py)


text:
Q: Using Generics in Matrix Addition/Multiplication I'm trying to create a custom class the creates matrices and, among other things, performs operations that add up all of the cells or multiply them all. However, I want to use generics so the matrices can be any type of number: float, double, int, etc. I have thus set up the class like this:
public class Matrix<num>

Upon initialization, the instantiation of this class creates a matrix based on user supplied data, stored in the instance's .matrix variable. Now, in the code where I want to add up all of the cells, I do something like this:
public num addMatrices(num[][] toAdd){
        num result;
        if (toAdd.length != this.rows && toAdd[0].length != this.columns){
            System.out.println("Matrix mismatch. Try Again.");
            return toAdd[0][0];
        }
        for (int i=0; i<rows; i++)
            for (int j=0; j<rows; j++){
                result = this.matrix[i][j] + toAdd[i][j];
            }
    }

I'm running into multiple problems, however. First of all, I can't initialize result to zero, which makes it hard to perform += operations. Secondly, when I try to add the cells of the two matrices, the compiler tells me that the + operator is undefined for the type num.
I thought the whole point of generics was to have a catchall type so I could do things like use floats in one case and ints in another, but if I need to specify the type for operators like +, I'm not sure where the advantage comes in...

A: You can't perform operations like + and - on Objects (some special cases excluded).  Generics are all about Object types, so your use case for them isn't ideal.
That said, you can turn your declaration into something like public class Matrix<num extends Number>, which will let you pass in Integer, Double, BigInteger, etc.  then you can then use something like num.longValue() or num.doubleValue() to get the long or double representations of your numbers.  You would then need to return a double or long or whatever from your method instead of your generic type, though.
the other option would be to create a custom container class that has methods for add, subtract, etc.  Then your class declaration can be public class Matrix<num extends Custom>.  You would have to figure out how to account for adding longs to doubles and returning the Custom type.

A: The problem is that you num can be anything. So, for example, what would it need to do if you created a Matrix<Object>?
You could try to make your number extend from Number, but even then you won't be able to use + because java don't know what to cast this generic to.
You could create a method similar to your Matrix with generic that does that. Something like
public static <NUM extends Number> NUM add(NUM[][] matrixA, NUM[][] matrixB, NumFunction<NUM> function) {
    // all equals to your add method, but the result you get with
    result = function.apply(this.matrix[i][j], toAdd[i][j]);
}

public interface NumFunction<NUM extends Number> {
    NUM apply(NUM operA, NUM operB);
}

You will need to duplicate NumFunction to every type of Number, or create one generic that checks what type of Number is with "instanceof". It's not very pretty :P


text:
Q: pagination with lazy loading in primefaces donesn't work properly I am getting a problem with lazy loading in dataTable but couldn't to know where the problem is,
here is my xhtml page code:
 <f:view xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
    <title>Application</title>
</h:head>
<h:body>
    <h:form>
        <h:panelGrid columns="2">
          <h:outputLabel value="Element per page"/>
          <p:selectOneMenu value="#{applicationManagementListBean.pageSize}">
              <f:selectItem itemLabel="5" itemValue="5"/>
              <f:selectItem itemLabel="10" itemValue="10"/>
              <f:selectItem itemLabel="30" itemValue="30"/>
              <f:selectItem itemLabel="50" itemValue="50"/>
              <p:ajax event="change" update="applicationDataList"/>
          </p:selectOneMenu>
        </h:panelGrid>
        <p:commandButton value="New application"
            action="inscription.xhtml?faces-redirect=true" ajax="false" />
        <p:dataTable id="applicationDataList" value="#{applicationManagementListBean.applications}"
            var="app" paginator="true"
            rows="#{applicationManagementListBean.pageSize}" lazy="true"
            paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}">

            <p:column headerText="Code">
                <h:outputText value="#{app.code}" />
            </p:column>

            <p:column headerText="Name">
                <h:outputText value="#{app.name}" />
            </p:column>

            <p:column headerText="Abreviate name">
                <h:outputText value="#{app.abrevName}" />
            </p:column>

            <p:column headerText="Status">
                <h:outputText value="#{app.status.description}" />
            </p:column>

        </p:dataTable>
    </h:form>

</h:body>
     </f:view>

and the bean code:
@ManagedBean
@ViewScoped
public class ApplicationManagementListBean implements Serializable {

    private static final long serialVersionUID = 1L;

    @ManagedProperty(value = "#{applicationManagementService}")
    public ApplicationManagementRemote applicationManagementService;

    private Integer pageSize = 3;
    private DataProxyLazyDataModel data;

    public void setApplicationManagementService(
            ApplicationManagementRemote applicationManagementService) {
        this.applicationManagementService = applicationManagementService;
    }

    public LazyDataModel<Object> getApplications() {
        data = new DataProxyLazyDataModel(applicationManagementService);
        data.setPageSize(pageSize);
        return data;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public DataProxyLazyDataModel getData() {
        return data;
    }

    public void setData(DataProxyLazyDataModel data) {
        this.data = data;
    }

  }

when  I click on the next page button nothing happen
please help
thanks a lot
best regards, Rachid
primegaces 3.4.2, liferay portal 6.1, eclipse

A: try adding setRowCount() to your lazyDataModel.
for example:
lazyDataModel.setRowCount(rows);

where rows represents total records in your Database to display in DataTable.
In your case code is:
data.setRowCount(rows);


text:
Q: How to write the Python result to synapse azure database? I am trying to write the result obtained using the pyspark in the notebook as a table to the database using the following code:
%%pyspark
sample=sample.head()

%%spark
spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true")
park_df = spark.createDataFrame(sample)
park_df.write.mode("overwrite").saveAsTable("default.sample")

Unfortunately, I'm getting the following error:
Error : <console>:31: error: not found: value park_df
val $ires9 = park_df
             ^
<console>:29: error: not found: value park_df
       park_df = spark.createDataFrame(sample)

A: You may try to below to code to write the python result to synapse azure database:
%%pyspark
sample = [('CA',22,45000),('WA',35,65000)]
spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true")
park_df = spark.createDataFrame(sample, ['state','age','salary'])
park_df.write.mode("overwrite").saveAsTable("default.sample")


text:
Q: Code to show related posts (custom post type and custom taxonomy/category) is messing with other code I'm using a code to show related posts on the page on one of the posts. It works OK, but I've just noticed that it makes the next part of the code to stop working as expected.

$custom_terms = wp_get_post_terms( get_the_ID(), 'categoria');
$args = array(
  'post_type' => 'oferta',
  'posts_per_page' => 6,
  'no_found_rows' => true,
  'tax_query' => array(
       array(
          'taxonomy' => 'categoria',
          'field' => 'slug',
          'terms' => $custom_terms[0]->slug,
      ),
   )
);

// Assign the current post ID to a variable.
$current_post_id = get_the_ID();

// Make the custom posts query.
$loop = new WP_Query( $args );

// Post counter; if the value has reached 5, then we exit the `while` loop below.
$counter = 0;

// Display the posts.
echo '
';
while ( $loop->have_posts() ) {
    if ( $counter >= 5 ) {
        break;
    }

    $loop->the_post();
    // Display the post if it's not the current post with the ID $current_post_id
    if ( $current_post_id !== get_the_ID() ) {
        echo '
'.get_the_title().'
';
        $counter++;
    }
}
echo '
';

That works as expected. It shows up to 5 related posts, not including the current post (the post you are visiting).
But then I have other code that is supposed to get the title of the current post.
echo '
Más datos de ' . get_the_title($post->ID) . '
';

This line works OK if I put it before the code for related posts (it shows the title of the current post). But if I put this line after the code for related posts, then it shows the title of one of the related posts instead of the title of the current post.
I guess the code for related posts is messing with the $post->ID part, but I don't know enough PHP to know how to solve this.
Any tips or ideas would be much appreciated. Thanks!

A: It seemed like you did not call wp_reset_postdata() which in short, restores the context of the template tags (e.g. the_title() and get_the_title()) from a secondary query loop back to the main query loop.
More details at https://developer.wordpress.org/reference/functions/wp_reset_postdata/#more-information.
So basically, you just need to call wp_reset_postdata() like so, and then the issue in question would disappear:
echo '
';

// Restores the $post global.
wp_reset_postdata();

// Now this should show the correct title.
echo '
Más datos de ' . get_the_title($post->ID) . '
';


text:
Q: Proving the AIP theorem?#2 How do you prove the AIP theorem?
(Alternate Interior Angles and Parallel theorem) I already know you can prove the CAP theorem(Corresponding Angles and Parallel theorem), and the SAP theorem from it,but I don't know how to prove the AIP as a start.
The AIP Theorem.
Given:
     If transversal $n$ intersects two lines in such a way that a pair of alternate exterior angles are equal, then the two lines are parallel.
Statement:
   Line $n$ intersects lines $l$ and $m$ such that a pair of alternate exterior angles are congruent.

A: If $\angle 3 = \angle 6$, then by the vertical angles theorem (even seeing the name, I have no clue what the CAP theorem is supposed to be) $\angle 6 = \angle 3 = \angle 2$, whence $\angle 6$ and $\angle 4$ are supplementary, which if $m$ and $n$ intersect on that side would form a triangle with the third angle at the intersection being $0$ degrees, which cannot be. So they cannot intersect on the side of angles 4 and 6. Similarly, they cannot intersect on the side of angles 3 and 5. Therefore they cannot intersect.

A: Its like this:
First, you assume l is not parallel to m.
Then they inersect and form a triangle. By the exterior angle theoreom (a exterior angle is bigger than its remote interior angles), you have one of the alternate interior angle is larger than the other, and therefore are not congruent. This contradicts the given (the alternate interior angle are congruent) and so the l is not parallel to m assumption is false, since it caused the contradiction. Therefore l is parallel to m.


text:
Q: Replace NAs based on values surrounding them Let's say I have a vector that is full of NAs except for every 5th value, which could either be one of two levels:
RNGkind('Mersenne-Twister')
set.seed(42)

x <- NULL
for(i in 1:1000){
  x <- c(x,c(sample(c('Hey', 'Hullo'), 1, rep = F), rep(NA, 4)))
}
x

I want to fill the NAs based on what is surrounding them:
"Hullo" NA NA NA NA "Hey": NAs become "Hey"
"Hullo" NA NA NA NA "Hullo" NAs become "Hullo"
"Hey" NA NA NA NA "Hullo": NAs become "Hullo"
"Hey" NA NA NA NA "Hey": NAs become "Hey"

I've come up with a for loop that looks at each element iteratively and fills the NAs based on a lot of if statements:
for(i in 1:length(x)){
  if(!is.na(x[i])){
     next
   }else{
    if(x[i-1] == 'Hullo' & x[i+4] == 'Hullo' | x[i-1] == 'Hey' & x[i+4] == 'Hullo'){
      x[i:(i+3)] <- 'Hullo'
    }else{
      x[i:(i+3)] <- 'Hey'
    }
  }
}

But it's a bit of a hacky way of doing it, nor does it deal with the tail-end of the vector, where there could be an NA. Ideally, the last group of NA would match the output from the last group.
If it makes it any easier, there will always be four NAs in between two non-NAs.
Is there:

*

*a more elegant/faster way to do this?

*a way to fill up the end of the vector without having to do it manually?

EDIT: Added what the last group of NAs would be and to confirm that non-NAs would always occur at consistent intervals (every 5th element)

A: Here is a solution using the tidyr package :
xres <- tidyr::fill(data = data.frame(x, stringsAsFactors = FALSE), x, .direction = "up")
xres <- tidyr::fill(data = xres, x, .direction = "down")
xres$x

First you fill in one direction, and then fill in the other direction to get last values

A: If I well understood your question, I try to answer using the tidyverse approach.
Load the libray:
library(tidyverse)

Load your data:
var1 <- c("Hullo",NA,NA,NA,NA,"Hey")
var2 <- c("Hullo",NA,NA,NA,NA,"Hullo")
var3 <- c("Hey",NA,NA,NA,NA,"Hullo")
var4 <- c("Hey",NA,NA,NA,NA,"Hey")

my_df <- as.data.frame(cbind(var1,var2,var3,var4))

Then use the fill function:
my_df %>%
    fill(... = var1:var4,.direction = "up")

this is the result:
   var1  var2  var3 var4
1 Hullo Hullo   Hey  Hey
2   Hey Hullo Hullo  Hey
3   Hey Hullo Hullo  Hey
4   Hey Hullo Hullo  Hey
5   Hey Hullo Hullo  Hey
6   Hey Hullo Hullo  Hey


text:
Q: SQL column data inside an if I want to use the data of a mysql column inside an "if" but unfortunately I don't know how to do and I think i'm searching with the wrong terms.
So here is my code :
$reqcle=$bdd->prepare("SELECT * FROM clebeta WHERE cle='".$clebeta."'");
    $reqcle->execute();
    $countcle=$reqcle->rowCount();
    $askcleutil=$reqcle->fetchAll();
    //on vérifie d'abord que la clé existe en base de données
    if($countcle == 1){
        //on continue le traitement et on vérifie si la clé n'est pas déjà utilisée
        if($askcleutil[2] == "0"){
            //on continue le traitement et on vérifie l'existence du pseudo minecraft en base de données
        } else {
            //on affiche que la clé est déjà utilisée
        }
    } else {
        //on affiche une erreur : clé inexistante
    }

It's in my last if : if($askcleutil[2] == "0")
I want to test the value of the 'active' column inside my DB but I don't know how to do
Sorry if i'm not clear but I don't know how to explain this clearly

A: You use selectAll(), so you miss your loop.

Returns an array containing all of the result set rows (http://php.net/manual/en/pdostatement.fetchall.php)

You need like this:
foreach ($askcleutil as $row) {
    if ($row['a_col_name_of_your_selected_row'] == 0) {
       // Handle
    }
}


text:
Q: Test-ServiceBusName / Test-EventHub / Function-App Hi i have a powershell script that can deploy some artifacts to azure. some of the artifacts are

*

*functionapp

*functionappservice

*eventhubnamespace / eventhubname

*storageaccount
I used the below parameters to validate whether storage account and eventhub namespace is available or not.
Test-AzureRmEventHubName
Get-AzureRmStorageAccountNameAvailability

I cannot find any other cmd-lets that does the same thing for other resources like service bus / servicebus queue etc..
Thanks

A: I can suggest a work around for checking existence
#replace the below condition with get command for the specific resource that you want to check
if(Get-AzureRmEventHub -ResourceGroupName Rgroup -Namespace testnamespace -Name testname -ea SilentlyContinue){
"not found"
}
else{
"found"
}

but if cmdlets like Test-AzureServiceBusName is available then it is definitely better


text:
Q: Drop down menu hidden behind div I'm trying to make an drop down menu, and it's not going well. My submenu is hidden behind my wrapper/page/content. I've tried setting an z-index to different elements, also tried giving my menu and submenu giving:
z-index: 999999;

But nothing works..
Can you guys help?
http://jsfiddle.net/L8Y3K/

A: please remove overflow:hidden; from header id it will solve your problem
http://jsfiddle.net/L8Y3K/1/

A: Try Select2 jquery plugin. it works with overflow: hidden
http://jsfiddle.net/jEADR/2442/


text:
Q: Why does window.screen not work on macOS safari So I'm trying to redirect mobile pages on my website. If someone is on a mobile device then it would send them to the mobile site rather than the desktop site. It works on Chrome. However, it is not working on macOS Safari. Any idea why? The JavaScript is below:
<script>
        if (screen.width <= 420) {
        document.location="mobileindex.html";
    }
</script>

A: screen.width returns the width of the screen, not the browser window. This is good as it means that we can't falsely redirect users to the mobile site.
In Chrome, we can test that our logic works using the Device Emulator. When a page is loaded in the Device Emulator, screen.width returns the width of the device being emulated, rather than the host computer's screen.
However, in Safari, the corresponding Responsive Design Mode does not work this way. screen.width will always return the width of the computer monitor in Safari, not the width of the emulated device.
In other words, this is a problem with Safari's implementation, not your code. It will work fine on an actual mobile device.


text:
Q: Remove Space before text in DIV I am creating a div for meta data that has a line going through the back of it and for some reason, space is being added to the beginning of the line and I'm not sure why.
Here is the CSS:
.mline {
    border-top: 1px solid #E7E7E7;
    height: 0px;
    margin: 20px 0 20px 0;
    text-align: center;
}
.mline > div {
    background-color: #FFFFFF;
    line-height: 30px;
    padding: 0 5px 0 5px;
    position: relative;
    text-transform: lowercase;
    top: -16px;
}
.mline * {
    display: inline-block;
}
.mline h1 {
    font-size: 12px;
    font-weight: normal;
}
.info {
    line-height: 16px;
}
.info li:after {
    content:" \2022 ";
}
.info li:last-child:after {
    content:"";
}
.liked, .like:hover {
    color: red !important;
}

And here's the HTML:

3/5/13

21 notes

reblog

You can see the error on my site here: http://nellyswritingroom.tumblr.com/
And in this jsfiddle: http://jsfiddle.net/xrVh4/1/
I'm not sure what's going on because it's definitely not margins or padding. Any help would be greatly appreciated!

A: In the jsfiddle example, I assume left padding is being added by default to the ul.info element.
The site, however, has the following lines in newstyle.css:
ul, ol {
    margin-left: 2em;
}

If you don't want any margins or padding, you can clear them with:
.info {
    line-height: 16px; // already there - I'm not adding this
    margin: 0;
    padding: 0;
}

Example

A: It seems that it is, in fact, padding, on the ul element; adding the following CSS declaration removes that space:
.info {
    padding-left: 0;
    /* other stuff unchanged */
}

JS Fiddle demo.

A: The line is the border-top you have applied. The reason it all can't be seen is because you have covered it with a negative top with the child element, that has a bg color fff


text:
Q: Add arrow down css to the radius button I have a radius button and want to add an arrow down icon inside this button.
Here is what I have so far:

.test {
  border: 2px solid #ffffff;
  background: #444444;
  width: 25px;
  height: 25px;
  border-radius: 6px;
  text-align: center;
  color:#ffffff;
}
.down {
  position : absolute;
  top      : 6px;
  left     : 10px;
  width    : 0;
  height   : 0;
  z-index  : 100;
  border-left   : 10px solid transparent;
  border-right  : 10px solid transparent;
  border-top : 10px solid white;
}

Just in case the snippet doesn't work, here is a fiddle.
Why isn't the arrow inside the button?
Here's what I want:

A:

.test {
    border: 2px solid #ffffff;
    background: #444444;
    width: 25px;
    height: 25px;
    border-radius: 6px;
    text-align: center;
    position: relative;
}

.down {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    width: 0;
    height: 0;
    z-index: 100;
    border-left: 10px solid transparent;
    border-right: 10px solid transparent;
    border-top: 10px solid white;
    margin: auto;
}

A: if you want to know how to show an arrow,you can use Boot Strap by adding it's  reference on top of your HTML code and use it's components:

.test {
    border: 2px solid #ffffff;
    background: #444444;
    width: 25px;
    height: 25px;
    border-radius: 6px;
  text-align: center;

}

.down-arrow{
  margin-top:7px;

  }
<!DOCTYPE html>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

    <title></title>
 <meta charset="utf-8" />

there is another simple way,in which you can use font awesome components ,check it out on google

A: try using postion:relative; maring:0px auto; for down class


text:
Q: Swashbuckle: include a type to "definitions" section of swagger file I have a webapi in my application with action that can return some data. Data is described by type "CurrentTask" that has a property "Payload".
There are more that one type of task in my application and depending on the type payload prop can be in different shape, so in my contract it has type "object". Beside that I have classes for each type of payload and backend code mostly works with this classes rather that with object.
I think it'll be great to exapnd this experience to frontend part too. So I'm wondering if there is a way (applying attribute to payload class for example) to tell Swashbuckle to include this payload types to "definitions" section in swagger file.
Thanks for help!
Code snippets for better understanding:
class TaskController : Controller
{
    [HttpGet]
    public Task<CurrentTask> Next()
    {

    }
}

class CurrentTask
{
    public string Id { get; set; }

    public string Type { get; set; }

    public object Payload { get; set; }
}

class Task1Payload
{
    public string Text { get; set; }
}

class Task2Payload
{
    public string PictureUrl { get; set; }
}


text:
Q: Не работает INSERT INTO (MySQL PHP Денвер) Есть БД:
CREATE TABLE `tovar` (
`id` INT NOT NULL AUTO_INCREMENT,
`code` VARCHAR(12),
`partRu` VARCHAR(100),
`partUk` VARCHAR(100),
`sectionRu` VARCHAR(100),
`sectionUk` VARCHAR(100),
`nameRu` VARCHAR(100),
`nameUk` VARCHAR(100),
`descriptRu` TEXT,
`descriptUk` TEXT,
`price` DECIMAL(9,2),
`dateCreate` DATE,
`number` MEDIUMINT,
`unit` VARCHAR(15),
`pathImg` VARCHAR(255),
`madeIn` VARCHAR(50),
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

Для 4-х разных переменных INSERT в БД работает:
$query = "INSERT INTO `tovar` (id, code, partRu, partUk) VALUES (NULL, '$code', '$partRu', '$partUk')"; // РАБОТАЕТ-Запись в БД произведена!
$query = "INSERT INTO `tovar` (id, code, nameRu, nameUk) VALUES (NULL, '$code', '$nameRu', '$nameUk')"; // РАБОТАЕТ-Запись в БД произведена!

Для 6-ти переменных INSERT в БД НЕ работает:
$query = "INSERT INTO `tovar` (id, code, partRu, partUk, nameRu, nameUk) VALUES (NULL, '$code', '$partRu', '$partUk', '$nameRu', '$nameUk')";   // не РАБОТАЕТ

Ошибка записи в БД :

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''nameR', 'nameU')' at line 1

Пробовал и полную запись в БД для всех переменных сразу:

You have an error in your SQL syntax.

Никогда раньше (2 года) не сталкивался с таким фокусом.
Перепробовал кучу вариантов в разных таблицах - всё одно и то же.
Переменные - самые простые, присвоил перед записью, например $nameRu = "nameR";

A: Попробуйте cделать запрос похожий на этот, и зачем вы пишите id ? у вас же AUTO_INCREMENT стоит он автоматически заполнить поле id
"INSERT INTO `$table` SET `ip`='".$ip."', `article`='".$likeds."'";

или так
"INSERT INTO `table` (`time_add`, `type`, `adv`, `user_id`, `username`, `text`) VALUES ('".TIME."', '".$type."', '".$id."', '".$_SESSION['user_id']."', '".$users_info['username']."', '".$text."')"

A: Не работал INSERT для вставки части полей. Причина была в отсутствии значений по умолчанию для всех полей


text:
Q: CSS file isn't properly linked when I change the .html file to a .php This problem is exclusive to the index.html file, and as I said before, the CSS that works when it's an html, stops working when the extension is changed. I inspected the ref link on both instances and when it's a php, the CSS files end up being the php file itself. I'm assuming that it maybe can't access the css for some weird reason? I'm not sure how that translates to only when it's a php. I've done the same procedure to other pages, and it works fine.
If it means anything, part of what stops working is the Foundation I'm using.
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Foundation</title>
<link rel="stylesheet" href="stylesheets/app.css" />
<link rel="stylesheet" href="stylesheets/main.css" />
<script src="bower_components/modernizr/modernizr.js"></script>
<script src="js/foundation/foundation.js"></script>
<script src="js/foundation/foundation.clearing.js"></script>
</head>

I also found that any href links stop working as well.

A: I guess it is delivered using a wrong MIME type. Try forcing CSS MIME type by setting the headers like below:
header("Content-type: text/css");

Moreover, make sure that, using PHP, you should execute using a server. i.e., the following URL is right:
http://domain/path/to/index.php
http://localhost/project/index.php

And not:
file:///c:/wamp/www/project/index.php
file:///c:/myproject/index.php
file:///c:/xampp/htdocs/index.php


text:
Q: Why isn't autovaccum running/completing? My PostgreSQL instance (AWS Aurora) isn't autovacuuming. Or it is, but it is somehow being interrupted or stopped. I'm not canceling any autovacuum queries (though I suppose AWS itself could be).
The phi.claim table has 8M rows. There are ~10k updates/hour. When I vacuum manually, 16-38M row versions are removed:
rivet=> vacuum verbose phi.claim;
INFO:  vacuuming "phi.claim"
INFO:  scanned index "claim_pkey" to remove 38136154 row versions
DETAIL:  CPU: user: 6.49 s, system: 0.17 s, elapsed: 14.97 s
INFO:  scanned index "claim_claim_set_id_external_id_idx" to remove 38136154 row versions
DETAIL:  CPU: user: 13.53 s, system: 0.70 s, elapsed: 113.82 s
INFO:  scanned index "claim_claim_set_id_idx" to remove 38136154 row versions
DETAIL:  CPU: user: 9.72 s, system: 0.43 s, elapsed: 62.43 s
INFO:  scanned index "claim_code_modifier_quantities_idx" to remove 38136154 row versions
DETAIL:  CPU: user: 77.79 s, system: 3.93 s, elapsed: 617.93 s
INFO:  scanned index "claim_account_id_provider_npi_id_idx" to remove 38136154 row versions
DETAIL:  CPU: user: 21.52 s, system: 0.98 s, elapsed: 159.36 s
INFO:  scanned index "claim_usage_code_idx" to remove 38136154 row versions
DETAIL:  CPU: user: 33.96 s, system: 1.63 s, elapsed: 144.92 s
INFO:  scanned index "claim_schedule_id_idx1" to remove 38136154 row versions
DETAIL:  CPU: user: 24.14 s, system: 1.10 s, elapsed: 64.30 s
INFO:  scanned index "claim_account_id_idx" to remove 38136154 row versions
DETAIL:  CPU: user: 13.53 s, system: 0.85 s, elapsed: 42.84 s
INFO:  scanned index "claim_claim_set_id_ref_ref_ordinal_key" to remove 38136154 row versions
DETAIL:  CPU: user: 8.18 s, system: 0.29 s, elapsed: 37.81 s
INFO:  scanned index "claim_usage_mapping_id_idx" to remove 38136154 row versions
DETAIL:  CPU: user: 11.94 s, system: 0.69 s, elapsed: 62.10 s
INFO:  "claim": removed 38136154 row versions in 7715817 pages
DETAIL:  CPU: user: 121.46 s, system: 3.13 s, elapsed: 351.33 s
INFO:  index "claim_pkey" now contains 6921839 row versions in 85211 pages
DETAIL:  16137555 index row versions were removed.
8093 index pages have been deleted, 0 are currently reusable.
CPU: user: 0.00 s, system: 0.00 s, elapsed: 0.00 s.
INFO:  index "claim_claim_set_id_external_id_idx" now contains 6921839 row versions in 251232 pages
DETAIL:  38136154 index row versions were removed.
134582 index pages have been deleted, 7101 are currently reusable.
CPU: user: 0.00 s, system: 0.00 s, elapsed: 0.00 s.
INFO:  index "claim_claim_set_id_idx" now contains 6921839 row versions in 159050 pages
DETAIL:  32725206 index row versions were removed.
77874 index pages have been deleted, 1705 are currently reusable.
CPU: user: 0.00 s, system: 0.00 s, elapsed: 0.00 s.
INFO:  index "claim_code_modifier_quantities_idx" now contains 6921839 row versions in 872749 pages
DETAIL:  38136154 index row versions were removed.
500736 index pages have been deleted, 28272 are currently reusable.
CPU: user: 0.00 s, system: 0.00 s, elapsed: 0.00 s.
INFO:  index "claim_account_id_provider_npi_id_idx" now contains 6921839 row versions in 346059 pages
DETAIL:  38136154 index row versions were removed.
101429 index pages have been deleted, 4627 are currently reusable.
CPU: user: 0.00 s, system: 0.00 s, elapsed: 0.00 s.
INFO:  index "claim_usage_code_idx" now contains 6921839 row versions in 381840 pages
DETAIL:  38136043 index row versions were removed.
242568 index pages have been deleted, 8961 are currently reusable.
CPU: user: 0.00 s, system: 0.00 s, elapsed: 0.00 s.
INFO:  index "claim_schedule_id_idx1" now contains 6921839 row versions in 185598 pages
DETAIL:  38136142 index row versions were removed.
121734 index pages have been deleted, 5088 are currently reusable.
CPU: user: 0.00 s, system: 0.00 s, elapsed: 0.00 s.
INFO:  index "claim_account_id_idx" now contains 6921839 row versions in 169603 pages
DETAIL:  38134646 index row versions were removed.
108740 index pages have been deleted, 5087 are currently reusable.
CPU: user: 0.00 s, system: 0.00 s, elapsed: 0.00 s.
INFO:  index "claim_claim_set_id_ref_ref_ordinal_key" now contains 6921839 row versions in 176903 pages
DETAIL:  19975782 index row versions were removed.
19912 index pages have been deleted, 0 are currently reusable.
CPU: user: 0.00 s, system: 0.00 s, elapsed: 0.00 s.
INFO:  index "claim_usage_mapping_id_idx" now contains 6921839 row versions in 138713 pages
DETAIL:  32942459 index row versions were removed.
69121 index pages have been deleted, 0 are currently reusable.
CPU: user: 0.00 s, system: 0.00 s, elapsed: 0.00 s.
INFO:  "claim": found 85733 removable, 6921839 nonremovable row versions in 8537156 out of 8537156 pages
DETAIL:  2 dead row versions cannot be removed yet, oldest xmin: 668246244
There were 15562466 unused item pointers.
Skipped 0 pages due to buffer pins, 0 frozen pages.
0 pages are entirely empty.
CPU: user: 380.79 s, system: 16.85 s, elapsed: 1880.08 s.
INFO:  vacuuming "pg_toast.pg_toast_132182"
INFO:  scanned index "pg_toast_132182_index" to remove 198150 row versions
DETAIL:  CPU: user: 0.04 s, system: 0.00 s, elapsed: 0.55 s
INFO:  "pg_toast_132182": removed 198150 row versions in 54329 pages
DETAIL:  CPU: user: 0.82 s, system: 0.01 s, elapsed: 2.49 s
INFO:  index "pg_toast_132182_index" now contains 132146 row versions in 1010 pages
DETAIL:  198150 index row versions were removed.
371 index pages have been deleted, 0 are currently reusable.
CPU: user: 0.00 s, system: 0.00 s, elapsed: 0.00 s.
INFO:  "pg_toast_132182": found 190401 removable, 112368 nonremovable row versions in 79637 out of 84372 pages
DETAIL:  0 dead row versions cannot be removed yet, oldest xmin: 668278370
There were 3794 unused item pointers.
Skipped 0 pages due to buffer pins, 4725 frozen pages.
0 pages are entirely empty.
CPU: user: 1.50 s, system: 0.05 s, elapsed: 6.25 s.
VACUUM

rivet=> select version();
                                   version
-----------------------------------------------------------------------------
 PostgreSQL 11.4 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.9.3, 64-bit
(1 row)

rivet=> show autovacuum;
 autovacuum
------------
 on
(1 row)

rivet=> show log_autovacuum_min_duration;
 log_autovacuum_min_duration
-----------------------------
 10s
(1 row)

rivet=> show autovacuum_max_workers;
 autovacuum_max_workers
------------------------
 3
(1 row)

rivet=> show autovacuum_naptime;
 autovacuum_naptime
--------------------
 5s
(1 row)

rivet=> show autovacuum_vacuum_threshold;
 autovacuum_vacuum_threshold
-----------------------------
 50
(1 row)

rivet=> show autovacuum_analyze_threshold;
 autovacuum_analyze_threshold
------------------------------
 50
(1 row)

rivet=> show autovacuum_vacuum_scale_factor;
 autovacuum_vacuum_scale_factor
--------------------------------
 0.1
(1 row)

rivet=> show autovacuum_analyze_scale_factor;
 autovacuum_analyze_scale_factor
---------------------------------
 0.05
(1 row)

rivet=> show autovacuum_freeze_max_age;
 autovacuum_freeze_max_age
---------------------------
 200000000
(1 row)

rivet=> show autovacuum_multixact_freeze_max_age;
 autovacuum_multixact_freeze_max_age
-------------------------------------
 400000000
(1 row)

rivet=> show autovacuum_vacuum_cost_delay;
 autovacuum_vacuum_cost_delay
------------------------------
 5ms
(1 row)

rivet=> show autovacuum_vacuum_cost_limit;
 autovacuum_vacuum_cost_limit
------------------------------
 600
(1 row)

How can I diagnose why autovacuum isn't actually vacuuming correctly?


text:
Q: Calculate grade in Python with letter I'm writing a program to calculate the average and letter grade of a class. Every time I run the code it prints "Your Grade is an A". I think something is wrong with my def average() function, but I cannot figure it out.
It also only prints the Letter grade, and not the score also
homework1 = int(raw_input('Enter homework1 score: '))
homework2 = int(raw_input('Enter homework2 score: '))
quiz = int(raw_input('Enter quiz score: '))
exam = int(raw_input('Enter Final Exam Score: '))
if homework1 > 100:
        print 'Score cannot be greater than 100'
if homework1 < 0:
        print 'Score cannot be less than 0'
if homework2 > 100:
        print 'Score cannot be greater than 100'
if homework2 < 0:
        print 'Score cannot be less than 0'
if quiz > 100:
        print 'Score cannot be greater than 100'
if quiz < 0:
        print 'Score cannot be less than 0'
if exam > 100:
        print 'Score cannot be greater than 100'
if exam < 0:
        print 'Score cannot be less than 0'

numbers = [homework1, homework2, quiz, exam]

def average(numbers):
    total = sum(numbers)
    total = float(total)
    return total / len(numbers)

def get_average(numbers):
    homework = average("homework1, homework2")
    quiz = average("quiz")
    exam = average("exam")
    return .2*quiz + .2*exam + .6*homework

def get_letter_grade(score):
    if score >= 93.333:
        return "Your grade is an A"
    elif score >= 90:
        return "Your grade is an A-"
    elif score >= 86.667:
        return "Your grade is a B+"
    elif (avg >= 83.333):
        return "Your grade is a B"
    elif (avg >= 80):
        return "Your grade is a B-"
    elif (avg >= 76.667):
        return "Your grade is a C+"
    elif (avg >= 73.333):
        return "Your grade is a C"
    elif (avg >= 70):
        return "Your grade is a C-"
    elif (avg >= 66.667):
        return "Your grade is an D"
    elif (avg >= 65):
        return "Your grade is an D-"
    else:
        return "Your grade is a F"
    if (avg == 0):
        return "There is an error"

print get_letter_grade(get_average)

A: After debugging the code, I can see that you're passing get_average() (the function) to get_letter_grade() as a paremeter.
print get_letter_grade(get_average)

So that's the first thing. Also, what Tom Karzes already said about parsing strings to the average() when it clearly expects a list of numbers.

A: You are getting "Your grade is an A" everytime because you're calling get_letter_grade function with the function get_average as an input.
Since the evaluation get_average > 93,333 is always True, then you won't get any other answer.
Give another go.

A: I recommend reviewing your code. But to fix the problems in your code, this would do it:
homework1 = int(raw_input('Enter homework1 score: '))
homework2 = int(raw_input('Enter homework2 score: '))
quiz = int(raw_input('Enter quiz score: '))
exam = int(raw_input('Enter Final Exam Score: '))
if homework1 > 100:
        print 'Score cannot be greater than 100'
if homework1 < 0:
        print 'Score cannot be less than 0'
if homework2 > 100:
        print 'Score cannot be greater than 100'
if homework2 < 0:
        print 'Score cannot be less than 0'
if quiz > 100:
        print 'Score cannot be greater than 100'
if quiz < 0:
        print 'Score cannot be less than 0'
if exam > 100:
        print 'Score cannot be greater than 100'
if exam < 0:
        print 'Score cannot be less than 0'

numbers = [homework1, homework2, quiz, exam]

def average(numbers):
    total = sum(numbers)
    total = float(total)
    return total / len(numbers)

def get_average(numbers):
    # you accessed your array in the wrong way
    homework = average(numbers[0:1])
    quiz = average([numbers[2]])
    exam = average([numbers[3]])
    return .2*quiz + .2*exam + .6*homework

def get_letter_grade(numbers):
    # here, you mixed up 'score' and 'avg' which were both not defined
    score = get_average(numbers)
    if score >= 93.333:
        return "Your grade is an A"
    elif score >= 90:
        return "Your grade is an A-"
    elif score >= 86.667:
        return "Your grade is a B+"
    elif (score >= 83.333):
        return "Your grade is a B"
    elif (score >= 80):
        return "Your grade is a B-"
    elif (score >= 76.667):
        return "Your grade is a C+"
    elif (score >= 73.333):
        return "Your grade is a C"
    elif (score >= 70):
        return "Your grade is a C-"
    elif (score >= 66.667):
        return "Your grade is an D"
    elif (score >= 65):
        return "Your grade is an D-"
    else:
        return "Your grade is a F"
    if (score == 0):
        return "There is an error"

# You used to call the get_letter_grade with a (not called) function as an argument
print get_letter_grade(numbers)


text:
Q: How to deploy a reactJS application on tomcat server? I am trying to build a ReactJS application which i would like to host on a tomcat server.
I already used the command npm run build and the build is ready.. Where do i copy these files in my tomcat server? DO i need to create another application and deploy it on the server which invokes the React Application?

A: Follow below steps:

*

*Goto 'webapp' folder in tomcat and create a folder(mostly your project name)

*Copy the files from your ReactJs build folder to the folder created in tomcat(note: your build folder should have index.html)

*Launch the url http : //localhost:< port > /< folder-name> in browser. By default port will be 8080

Instead if you have WAR file, you can go to http://localhost: < port > /manager/html and deploy it.


text: Q: JPEG2000 API for Python I am about to run a simulation in which I need to encode and decode image files with JPEG2000.  I need an API that gives me flexibility to tune coding parameters and set output quality.  Is there any API for Python to do so?


text:
Q: How am I getting this error if I'm not using the .equals method? String signInMethod;
...

...
if (signInMethod != null) {
    if (signInMethod.equals("google")) {
        intent.putExtra("signInMethod", "google");
    } else if (signInMethod.equals("email")) {
        intent.putExtra("signInMethod", "email");
    }
} else {
    intent.putExtra("signInMethod", "alreadySignedIn");
}

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference

How am I getting this error if I'm not using the .equals method?

A: Use this.
  String signInMethod = null;
    if(TextUtils.isEmpty(signInMethod)){
        Toast.makeText(context, "Some thing wrong please try again", Toast.LENGTH_SHORT).show();
    }else {
        if (signInMethod.equalsIgnoreCase("google")) {
            intent.putExtra("signInMethod", "google");
        } else if (signInMethod.equalsIgnoreCase("email")) {
            intent.putExtra("signInMethod", "email");
        } else {
            intent.putExtra("signInMethod", "alreadySignedIn");
        }
    }

A: Looks like an issue with local variable's default value. Make sure that you initialize your signInMethod with at least a null.
public void myMethod() {
    String signInMethod = null; // <--- THE FIX
    ...

    ...
    if (signInMethod != null) {
        if (signInMethod.equals("google")) {
            intent.putExtra("signInMethod", "google");
        } else if (signInMethod.equals("email")) {
            intent.putExtra("signInMethod", "email");
        }
    } else {
        intent.putExtra("signInMethod", "alreadySignedIn");
    }
}

A: Java Compiler does not assign any value(even null) to a local variable. you have to initialize it as "Null" to make it work otherwise the IF statement does not work


text:
Q: compact subset and proof $X$ be a compact subset of $\mathbb{R}$ and let $f$ be a real-valued function on $X$. Prove that $f$ is continuous if and only if $\{(x,f(x)) : x ∈ X\} $ is compact subset of $\mathbb{R}^2$.
how should we start to proof?

A: Since we are talking about $\Bbb R$, one preferred way is to work with sequences. $X\subseteq\Bbb R$ is compact iff all sequences of $X$ has convergent subsequence with limit point in $X$.
Similarly, $f$ is continuous iff it preserves limit, i.e. $\lim(x_n)=z$ in $X\ $ implies $\ \lim(f(x_n))=f(z)$.
So, for one direction we assume that $\ \Gamma_f:=\{(x,f(x))\,:\,x\in X\}\ $ is compact and that we have given a sequence $x_n\in X$ with $\lim(x_n)=z$, and we have to prove that $\exists\lim(f(x_n))=f(z)$.
For the other direction, we assume that $f$ is continuous and we have given an arbitrary sequence $g_n\in \Gamma_f$, and -- using that $X$ is compact -- we should select a convergent subsequence of $(g_n)$.

A: $p:\Gamma\to\mathbb{R}$  is given by $p(x,f(x))=x$, is continuous bijection from graph $\Gamma$ to $\mathbb{R}$ so $p$ is Homeomorphism (assuming $\Gamma$ is compact), $\Gamma=\{(x,f(x)):x\in\mathbb{R}\}$
$p^{-1}:\mathbb{R}\to\Gamma$ is given by $p^{-1}(x)=(x,f(x))$
consider a map $q:\Gamma\to\mathbb{R}$, $q(x,f(x))=f(x)$
Now observe that $f=q\circ p^{-1}$ composition of two continuous function.


text:
Q: Does every unbounded countable ordinal have an unbounded sequence? Let $S$ be a countable well-ordered set which is unbounded (i.e. it has no maximum). Does there exist an unbounded increasing sequence in $S$?

A: Hint: let $f : \omega \to S$ enumerate $S$. Starting at $1$, remove $i$ from the domain of $f$ if $f(i) < f(j)$ for some $j < i$. The result is an unbounded partial function from $\omega$ to $S$, which you can convert into  a sequence by renumbering the arguments.

A: I found a related question which answers this question too.
A generalization of "any countable limit ordinal is the union of a sequence of increasing ordinal"

A: Yes.
Let $s_1$ be an element of $S$. Because $S$ is unbounded, $s_1$ can't be the maximum element. Therefore, there exists at least one element of $S$ greater than $s_1$. Call this element $s_2$. $S$ also can't have $s_2$ as its maximum element, so there must be an element of $S$ (call it $s_3$) greater than $s_2$.
Repeat this process ad infinitum, and you have an unbounded increasing sequence.


text:
Q: Power BI Custom Matrix Design i have a table i need to design where rows are the actual values as below

i tried to use table, the results were as below, which is not what i want:

i tried to use a matrix , i couldnt reach the desired design as well:

can any one have any idea how to do such thing?

A: i solved it using same concept adopted in the below solution
Custom aggregate column in power bi matrix
best regards,
Georges


text:
Q: Create the same border type around all my controls I tried to create my own Border class and then insert it in my controls but then it seems I cannot assign names to everything inside the borders:
..
<my:ElementBorder>
        <StackPanel Name="ifBlock" Background="#E0E8FF" />
</my:ElementBorder>
..

How can I get around this? Can I use templating somehow for that?
EDIT:
Sorry that I was unclear. Yes I subclassed Border with my own XAML file and got this compiler error with the code above:

Error 2   Cannot set Name attribute
  value 'ifBlock' on element
  'StackPanel'. 'StackPanel' is under
  the scope of element 'ElementBorder',
  which already had a name registered
  when it was defined in another scope.

The contents of my ElementBorder class aren't very interesting but I'll post it anyway:
<Border x:Class="DVPE.ElementBorder"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    BorderThickness="4"
    CornerRadius="4">
</Border>

A: By introducing code-behind you have created an additional NameScope.  You can remove this extra NameScope at runtime by clearing the NameScope after calling InitializeComponent():
public ElementBorder()
{
  InitializeComponent();
  NameScope.SetNameScope(this, null);
  ...
}

Although this will work, it is not your best solution.  You would be better off creating a style that a UserControl.
There are two ways to do this:  With a subclass and without.
With a subclass
Create your ElementBorder subclass and override the default style.  Do not call InitializeComponent():
public class ElementBorder
{
  static ElementBorder
  {
    DefaultStyleKeyProperty.OverrideMetadata(typeof(ElementBorder), new FrameworkPropertyMetadata(typeof(ElementBorer)));
  }
  // any additional implementation
}

In your xaml file, instead of including a  tag, create a ResourceDictionary containing a style with the settings you want:
<ResourceDictionary xmlns=... >

  <Style TargeType="{x:Type my:ElementBorder}">
    <Setter Property="BorderThickness" Value="4" />
    ...

Merge this ResourceDictionary into the one defined in app.xaml or themes/Generic.xaml using a <MergeDictionary> tag
Note that you can just put the style in the ResourceDictionary in your app.xaml instead of creating a separate file.
Using this is identical to using your original ElementBorder:
<my:ElementBorder>
  <StackPanel  ...

Without a subclass
This requires less code.  Just put a Style in a ResourceDictionary as before, except give it a x:Key and use Border as it's target type:
<ResourceDictionary>

  <Style x:Key="ElementBorderStyle" TargeType="{x:Type Border}">
    <Setter Property="BorderThickness" Value="4" />
    ...

This can be used as follows:
 <Border Style="{StaticResource ElementBorderStyle}">
   <StackPanel ...

If you want all of your borders to have the new style, it is even easier.  Just omit the x:Key and use Border as your TargetType:
<ResourceDictionary>

  <Style TargeType="{x:Type Border}">
    <Setter Property="BorderThickness" Value="4" />
    ...

This will cause all borders to get the style, so you can just write:
<Border>
  <StackPanel ...

Answer to additional question asked in comment below
To set the BorderBrush the same as the Background:
  <Style TargeType="{x:Type Border}">
    <Setter Property="BorderBrush" Value="{Binding Background, RelativeSource={RelativeSource Self}}" />
    ...

To set the child's Background to the Border's background:  Generally not necessary since as long as child's background color isn't set, the border's background color will show through.  The only exception is in negative-Margin or RenderTransform situations where the child doesn't render entirely inside the containing border.  In that case you will need to bind the child's Background to the Border's Background.  This can't be done in a style applied to the BorderBrush without using an attached property.  But if you're ok doing it without a style:
<Border x:Name="myBorder">  <!-- Style applied here -->
  <StackPanel Background="{Binding Background, ElementName=myBorder}" ...

this can also be done with an unnamed border with {Binding Background, RelativeSource={RelativeSource FindAncestor,Border,1}.
If you want to do it entirely in the style, you'll have to add some code.  Basically, create a class with an attached property named something like "MyBindingTools.BindChildBackgroundToMyBackground".  Add a PropertyChangedCallback so that when that property is set to "true", a binding is created on the child, basically:
BindingOperations.SetBinding(border, BackgroundProperty, new Binding("Background") { Source = this });

In addition you will need to monitor the Border's Child property so that when it changes the binding can be added to the new Child and removed from the old Child (if any).
I wouldn't recommend you do any of this unless you really need to, though.  In your specific situation you can probably either bind the child manually or create a template that contains both the Border and the child control.  Either of these would be better solutions that creating the attached property as I described.

A: Name scopes are found by searching the logical tree.
If you rolled your own Border (as opposed to subclassing the Border class), name scope problems can be caused by:

*

*Failing to call AddLogicalChild

*Not correctly overriding the LogicalChildren enumeration

On the other hand, if you subclassed the existing Border (or any Decorator) it would handle the logical tree.
This can also be caused if an explicit NameScope is set on your border.  In that case, the name would be assigned but FindName won't find it at the Window/UserContol/template level.
Posting the relevant sections of your ElementBorder class might help us give you a better answer.

A: This is known as Namescope problem Check here for more details:
http://dotnet.dzone.com/news/c-and-wpf-namescope-my-name-is


text:
Q: Cakephp 3 DebugKit No CakePHP 2 eu costumo habilitar/desabilitar o DebubKit pelo AppController, de acordo com o usuário que está logado no sistema:
// AppController -> CakePHP 2
public function beforeFilter(){
   parent::beforeFilter();
   ...
   if($this->usuario_logado_id > 1)
      Configure::write('debug', 0);
}

Porém, no CakePHP 3, o DebugKit é carregado do arquivo "Application.php"
// Application.php -> CakePHP 3
public function bootstrap(){
   parent::bootstrap();
   ...
   $this->addPlugin(\DebugKit\Plugin::class);
}

Existe alguma forma de desabilitar o DebubKit pelo AppController como faço no Cakephp 2 ?
Já tentei muitas formas diferente, mas sem sucesso.

A: Você, programador, vai usar a aplicação em ambiente de desenvolvimento. Os demais usuários vão usá-la em ambiente de produção. A cópia que está na sua máquina deve ter o debug ativado. A cópia que está no servidor deve tê-lo desativado. Não se mistura isso, e também não se deve colocar esses arquivos no git. É mais seguro fazer via ftp.


text:
Q: Issue with long text tooltip I have an issue with long text tooltip, whenever I am scrolling down to tooltip with long text it getting blur and scorll is continuously moving and whole screen getting disturb and moving continuously.
Could anybody please help me for this issue.
$.fn.aToolTip = function (options) {
    /** setup default settings */
    var defaults = {
        // no need to change/override
        closeTipBtn: 'aToolTipCloseBtn',
        toolTipId: 'aToolTip',
        // ok to override
        fixed: false,
        clickIt: false,
        inSpeed: 200,
        outSpeed: 100,
        tipContent: '',
        toolTipClass: 'defaultTheme',
        xOffset: 5,
        yOffset: 5
    }
}


text:
Q: What is the best algorithm for finding the closest color in an array to another color? I have a color (RGB) being read from a sensor. I also have a list of "known" colors, each paired with a string name.
What would the best way (ie behave like a human choosing colors) to pull the name of the nearest color out of this list?
I've tried a shortest cartesian distance with RGB, but that makes grey closer to green than to black or white.

A: Jon Skeet is right. You need to use a system with Hue as a component instead of RGB if you are concerned about the color component of the match differing too much. HSL or HSV will both work fine for this purpose.
Then you need to fiddle with the distance formula to weight up hue until you are happy with the results. Note that you will find the problem is actually essentially insoluble unless you have a large number of colors to match against or your input colors are confined to a small range of possible values. This is because although it might seem you can pin any color you want to one of 8 (red, orange yellow, green, blue, violet, black and white) or one of 16, in reality you'll find your algorithm will always find what seem to be obviously incorrect matches because with 3 axis of movement (hue, saturation, value or red, green, blue), there are a lot more "basic" colors than you might think at first glance.

A: I would think that if you treat colors as RGB coordinates in 3-space and compute distance from sampled to known values, you could determine the closest match. I probably would also try scaling R G B according to eye sensitivity (ie, Y = 0.3*R + 0.59*G + 0.11*B) you'd achieve the best result

A: Rather than using RGB, try using an HSL (Hue, Saturation, Lightness) or HSV (Hue, Saturation and Value) color model. Then experiment with different elements of bias, e.g. hue being more important than luminance when you're calculating the distance.