text:
Q: Short circuit USB port with multimeter I've installed new car audio into my car. It works fine for a few months now.
There is a USB port on the car audio for charging. Before actually using it, I wanted to test if it is safe enough and outputs about 5V.
So without giving a second thought, I grab my multimeter and set settings for direct voltage measurement. As I touched USB port ground and +5V pins, there was a pop in speakers and car audio shutted down, which pretty much indicated a short circuit.
After the incident I checked youtube video on how to measure USB port with multimeter. In the video, man used small metal pin between usb port pin and multimeter positive probe. (https://www.youtube.com/watch?v=xvSg1RiYDKQ)
So, as I understand, small metalic pin plays a role to reduce current?
But how come measuring car battery or wall socket is fine by using multimeter probes, but not with USB port? Why short happened?
I have little knowledge about electronics and probably shouldn't stick multimeter probes in things, but curiosity took the best of me. Would appreciate any help or links to understand the issue.

A: As mentioned in the video, the outer metallic, rectangular casing is connected to the ground. So inserting the thick lead of the multi meter to touch the positive supply will cause the lead to short the positive supply and the outer casing which is ground.
The thin metal pin is used only to ensure a gap between the pin and the outer casing while it is touching the positive supply. It is is not a mistake proof method. If that pin leans too much, it can still short the supply and the ground. The pin may not limit the current.

A: To test tiny things like that, I will often (as in almost always) make a break-out cable.
Get an old usb cable and cut the end of with about 10cm or 4 inches of cable. Strip the outer covering off and then separate and bare the wires.
Often I will put them into a terminal block with labels if the colors don't indicate what they are (usually red is +, black - and the other two data but do check).
That way I reduce the chances of shorting things, but I did my apprenticeship as a vehicle electrician, so making and using things like that is a habit.


text:
Q: socket communication in java this.cin = new DataInputStream(this.csocket.getInputStream());

public class ReceiveMessage extends Thread{
    public void run(){
        while(stop == false)
            try {
                if(cin.available()>0)
                    receMessage();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

    // choke, unchoke, interested, notinterested, have, bitfield, request, piece
    public void receMessage(){
        int rv=0;
        byte[] length = new byte[4];        // total length
        try {
            rv = cin.read(length, 0, 4);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(rv <=0)
            return;

        byte[] type = new byte[1];
        try {
            cin.read(type, 0, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        int size = byte2int(length) -4 -1; //size of payload
        clearPayload();
        if(size > 0){
            try {
                cin.read(this.payload, 0, size);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        byte mtype = type[0];
        switch(mtype){
            case (byte)0:
                receNoPayload((byte)0);
                break;
            case 1:
                receNoPayload((byte)1);
                break;
            case 2:
                receNoPayload((byte)2);
                break;
            case 3:
                receNoPayload((byte)3);
                break;
            case 4:
                receHave(payload);
                break;
            case 5:
                receBitField(payload);
                break;
            case 6:
                receRequest(payload);
                break;
            case 7:
                recePiece(payload, size);
                break;
            default:
                System.out.println("wrong message type!");
        }

}

the code above is used to read data from socket. I create a thread to read data from socket.and then analyze the data according the type of message contained in data.
Now, the problem is if I transfer 100 bytes into socket, I can do everything correctly; however, if I transfer 1000 bytes into socket, sometimes, the data read out is wrong. for example, the variable type cannot be greater than 7 normally. But now the type read out is greater than 7, which is wrong.
in both case, I do not change anything, except the size of data transferred.
please help me, thank you! I have done everything I can do, but i still cannot figure it out.

A: *

*Get rid of the available() call. The read() will block if there is no data. At present you're just burning the CPU.

*Check the result of each read. You can't assume it filled the buffer. Or use DataInputStream.readFully() instead.

redpajama_set_name: RedPajamaStackExchange


text:
Q: scroll in jquery menu instead of background On a mobile version of the website I've a hamburger jquery menu that shows all the menu and submenu items. So far so good, but the problem is, if I have a lot of menu items, it will not fit the screensize thus some of the items or not visible. It would be a simple solution to just scroll in the menu itself to access them.
In short: how do I enable scrolling in the jquery menu when the menu is open?
I've included a screenshot to give you an idea how my menu looks like:

/* Site navigation */
.navbar {
  position: relative;
  width: 100%;
  height: 70px;
  background-color: rgba(0,120,191,0.8);
  z-index: 9999;
}
.default-menu {
  display: block;
  float: right;
}

/* Expanding submenus */
ul.jquerymenu li.parent {
  position: relative;
}
ul.jquerymenu li.parent span.parent {
  display: none;
}
.ie ul.jquerymenu li.parent span.parent {
  display: none;
}
ul.jquerymenu li.parent span.closed {
  background: transparent;
}
ul.jquerymenu li.parent span.open {
  background: transparent;
}
ul.jquerymenu li.parent ul {
  margin: 0;
  width: auto;
  position: absolute;
  top: 70px;
  left: 0;
  box-shadow: -3px 3px 10px 0px rgba(0,0,0,0.2);
}
ul.jquerymenu li.parent ul li {
  width: 100%;
  background-color: #006699;
  text-align: left;
  margin: 0 !important;
  padding: 0 !important;
  line-height: 1;
}
ul.jquerymenu li.parent ul li a {
  padding: 20px !important;
  margin: 0;
  display: block;
  line-height: 1.5;
  text-decoration: none;
  color: #fff;
}

.hamburger.mean-container {
  position: absolute;
  z-index: 1;
  right: 0;
}
.mean-container .mean-bar {
  width: 100%;
  height: 70px;
  min-height: 70px;
  position: relative;
  background: transparent;
  padding: 0;
}
.mean-container .mean-nav ul li {
  margin: 0;
  font-size: 1.6rem;
}
.mean-container .mean-nav ul li:hover {
  background: rgba(23,41,59,0.8);
}
.mean-container .mean-nav ul li a {
  display: block;
  float: left;
  width: 88%;
  padding: 20px;
  margin: 0;
  text-align: left;
  color: #fff;
  text-decoration: none;
  text-transform: uppercase;
  border-top: 0;
}
.mean-container .mean-nav ul li a:hover {
  color: #fff;
}
.mean-container .mean-nav {
  float: left;
  width: 100%;
  background: #006699;
  margin-top: 70px;
}
.mean-container a.meanmenu-reveal {
  width: 36px;
  height: 30px;
  padding: 20px 16px;
  font-size: 2.8rem;
  line-height: 32px;
}
.mean-container a.meanmenu-reveal span {
  display: block;
  background: #fff;
  height: 5px;
  margin-top: 5px;
}
.mean-container .mean-nav ul li a.mean-expand {
  margin-top: -2px;
  width: 100%;
  height: 44px;
  padding: 12px !important;
  text-align: right;
  position: absolute;
  right: 0;
  top: 0;
  z-index: 2;
  font-weight: 500;
  background: transparent;
  border: 0!important;
  border-left: 0 !important;
  border-bottom: 0 !important;
  font-size: 3rem;
}
.mean-container .mean-nav ul li a.mean-expand:hover {
  background: transparent;
}
.mean-container .mean-nav ul li li a {
  border-top: 0;
}

X

De rijschool

De auto's

Voordelen

Bovag

De instructeurs

Slagingspercentage

Ervaringen

+

Opleidingen

Overzicht

Automaat

Handgeschakeld

Theorielessen

+

Specialisme

Aanpassingen

Automaat

Rijles ADHD

Rijles en ASS

Rijtest

Vastgelopen

+

Trainingen

Hybride rijden

+

Prijzen

Auto

Theorie

+

Contact

Aanmelden

Informatie aanvraag

Bel mij terug

Contactgegevens

-


text:
Q: Drawing samples from multinomial using Theano I'm currently implementing a convolutional RBM and I'm using Theano for that.
My current implementation seems to be pretty slow and profiling showed that it's mainly due to the Gibbs sampling steps.
In fact, I am using Theano's shared randomstreams to generate multinomial samples.
However, I found an improved version of Theano's random stream here which meets all the performance demands I have.
Unfortunately, this experimental random generator only supports two-dimensional matrices and I have to use it for a tensor4-object (4D-Matrix) as this is the result from Theano's nnet conv2d operation.
Do you know if there's an efficient way to draw samples from a 4D-matrix that has the following structure:
Samplesize x 1 x N x M
where I would like to draw from one of columns (third dimension), giving me a code like this:
    for sample in range(numSamples):
        for col in range(numCols):
            drawMultinomial(n=1, pvals=data[sample,0,col,:])

But this code would be really slow and I'd like to do this efficiently and on the GPU.
So any help would be much appreciated.

A: So I found the solution that worked out for me with a rather simple dimshuffle/reshape combination that is undone after the sampling.

def sampleVisibleLayer (self, V):
    reshaped = V.dimshuffle(0, 1, 3, 2).reshape((V.shape[0]*V.shape[3], V.shape[2]))
    S_reshaped = self.theano_rng.multinomial(n=1,pvals=reshaped)
    S = S_reshaped.reshape((V.shape[0], 1, V.shape[3], V.shape[2])).dimshuffle(0, 1, 3, 2)

This solution worked well for me even though the batch size has some limits following this approach.
Since the reshaped matrix can become very large, we can run into situations were the random generator raises an error message even though it's not mentioned in the documentation.
The solution is also quite fast since dimshuffle and reshape are performed in O(1).


text:
Q: How to change the button background color on mouse over using Trigger I trying to write simple code that contain button that will change the background color on mouse over.
I want to do it using Triggers - so i write this code - but i dont know how to continue
  <Button Background="#fafafa" >
        <Button.Triggers>

            <EventTrigger RoutedEvent="Button.MouseEnter"/>

                  // What to do here to having thi background color change ?

        </Button.Triggers>
    </Button>

A: The best way is to change Buttons template. This post describes how to do that. In buttons template under VisualStateManager you will find vsm:VisualState x:Name="MouseOver" . Change its content as you need.
Or if you want do that with triggers, than take a loot to Behaviors and Triggers in Silverlight post on silverlightshow.net.


text:
Q: ¿Cómo cargar datos de una estructura en un archivo de texto? Lo que intento es que en el archivo de texto almacene la información de la función altacontacto, pero al abrir el archivo se genera la información mas caracteres aleatorios.
#include<stdio.h>
#include<stdlib.h>

typedef struct{
    int id;
    char nombre[15];
    char apellidop[15];
    char apellidom[15];
    char telefono[10];
    char correo[50];
} CONTACTO;

Ésta es mi estructura en la que almacena los datos.
char altacontacto(CONTACTO *cnt);
void guardarcontactoarchivo(CONTACTO *cnt);

int main()
{ CONTACTO cnt;

  altacontacto(&cnt);
  guardarcontactoarchivo(&cnt);

  return 0;
}

char altacontacto(CONTACTO *cnt)
{
    printf("Ingrese los valores para la estructura:\n");
    printf("Numero de registro: ");
    fflush(stdin);
    scanf("%i",&cnt->id);
    printf("Nombre: ");
    fflush(stdin);
    scanf("%s",&cnt->nombre);
    printf("Apellido paterno: ");
    fflush(stdin);
    scanf("%s",&cnt->apellidop);
    printf("Apellido materno: ");
    fflush(stdin);
    scanf("%s",&cnt->apellidom);
    printf("Telefono celular: ");
    fflush(stdin);
    scanf("%s",&cnt->telefono);
    printf("Correo electronico: ");
    fflush(stdin);
    scanf("%s",&cnt->correo);
    return cnt;
}

En esta función hago que se almacenen los datos en la variable cnt para después utilizarlos.
void guardarcontactoarchivo(CONTACTO *cnt)
{
    FILE * ArchivoSalida;

    ArchivoSalida=fopen("Texto.txt","wt");

    if(ArchivoSalida!=NULL)
    {   //Si se creo el archivo
        //fputs(&cnt, ArchivoSalida);
        printf("\nArchivo modificado exitosamente.");
        fwrite(&cnt,sizeof(CONTACTO),cnt->id,ArchivoSalida);
        fclose(ArchivoSalida);
    }
    else //No se creo el archivo
        printf("\nError al crear el archivo.");

}

Aquí es donde intento guardar los datos en un archivo, al revisarlo si aparecen los datos pero tambien aparecen caracteres aleatorios; además de aparecer toda desordenada la información.

A: Prueba a cambiar la función fwrite por esta:
fwrite(&cnt,sizeof(CONTACTO),1,ArchivoSalida);

Entiendo que el fichero que te crea no es de texto y de ahí los caracteres raros, no veras el id bien porque es un entero en la estructura y no una cadena de caracteres.
El tercer parámetro de fwrite es el numero de registros o contactos guardados( creo que uno en tu caso) y no el id. A saber lo que te guarda si pones mas de uno, lo que hay en memoria libre digamos.

A: fwrite recibe un puntero a la información a escribir. cnt ya es un puntero, por lo tanto no tiene sentido obtener un puntero a un puntero.
Además, cnt es un parámetro que vive como variable local de la función. Así que la dirección de cnt será diferente a la de la variable original. Probablemente sea por eso que ves letras raras.
Por otro lado, el 2º parámetro de fwrite indica el tamaño de cada elemento a escribir y el 3º la cantidad de elementos a escribir. No es un desplazamiento. Cómo quieres escribir un solo elemento debería ser 1. Así:
fwrite(cnt, sizeof(CONTACTO), 1, ArchivoSalida);


text:
Q: Inserting in inside a function I am a newbie at interacting with mongo and I am trying to make a function using the in property:
def find_inthe(key,*values):
    rdo=col.find({key:{'$in':list(values)}})
    for a in rdo:
        return a

print(find_inthe('hair_colour','white','brown','black'))

However the problem I am finding is that it is returning only the first of the values and as a find_one.
If I try the same outside the function:
rdo=col.find({'hair_colour':{'$in':['white','brown','black']}})
for a in rdo:
    print(a)

It will return all the dictionaries of the collection.
My desired output would be that the function returns all the dictionaries with the selected colour hairs

A: $in is not at fault here. It's your return a in the loop. Why don't you return the whole thing?
def find_inthe(key,*values):
    rdo = col.find({key:{'$in':list(values)}})
    return list(rdo)


text:
Q: How to Stop Double Clicking/Double Posting of form? Using UiApp to collect data from a form, but I have users double clicking the submit button. This runs doPost twice.  Granted, they have to click mighty fast to get it to actually post twice, but it happens.
My questions is: has anyone had experience in disabling the submit button, say with an onMouseUp?  Is there a better way to do this?  I've been told to be wary of adding multiple onClick handlers to buttons, as it can be unstable.  Any stable solutions to this?
I have to use a submit button as there is a file upload in the form.

A: I've faced this problem and ever since Google introduced ClientHandlers, there is a way out.
Just add a client handler to your submit button disabling it (and remember to enable it when you are done with the server handler function or doPost)
var plswait = app.createClientHandler().forEventSource().setEnabled(false).setText('Please wait...');
var btnSubmit = app.createSubmit().addMouseDownHandler(plswait);

is my favourite.

A: I had the same problem, but to work around it I created a second "false" button that becomes visible when the submit button is clicked, at the same time the "real" submit button visibility is set to false. Here's the basic code:
var button = app.createSubmitButton('Submit').setId("button")
  .setEnabled(false)

var falseButton = app.createButton('Submit').setId("falseButton")
  .setEnabled(false)
  .setVisible(false);

var handler = app.createClientHandler()
    .forTargets(button).setVisible(false)
    .forTargets(falseButton).setVisible(true);

button.addClickHandler(handler);

panel.add(app.createHorizontalPanel().add(button).add(falseButton);

A: The first answer didn't work for me because the MouseDown handler didn't let the ServerHandler run. But it gave me the right direction. I just added the Client handler to disable the button before I added the Server Handler...and that seemed to work to prevent the double click. Like this:
  var submitButton = myapp.createButton("Submit");
  var myServerHandler = myapp.createServerClickHandler("myServerHandler");
  var pleaseWait = myapp.createClientHandler().forEventSource().setEnabled(false).setText('submitting...');
  submitButton.addClickHandler(pleaseWait);
  submitButton.addClickHandler(myServerHandler);


text:
Q: Restrict FB app install to premium accounts of my website I am developing a FB application that i want only some users of my website (premium) can access and install on their company FB brand page.
What i need to achive is similar to what Getsatisfaction and Uservoice are doing with their apps, that only premium accounts can see in their dashboard, do you mind how to do this?

A: When the user purchases you application you need to ask him to access his pages, then you save them to an helper table.
After that you'll send them to the install dialog.
Your page tab index will need to have a roadblock, where you check if the page accessing the app (that you can get trough the signed_request) is allowed (if it is in the helper table), otherwise you block the application.
Am I making myself clear?
Anything let me know.


text:
Q: Couldn't find method reproducir(View) in a parent or ancestor Context for android:onClick defined on view class material.textview.MaterialTextView Estoy tratando de llamar un elemento que se encuentra en un layout y a través de un adaptador lo asigno a el viewpager pero al momento de llamar el elemento desde el fragment sea el textview o el boton para que a través de un metodo me lleve a otro fragment pero me genera el error:
java.lang.IllegalStateException: Could not find method reproducir(View) in a parent or ancestor Context for android:onClick attribute defined on view class com.google.android.material.textview.MaterialTextView with id 'dateTv'
video.xlm
<TextView
 android:id="@+id/dateTv"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="end"
 android:layout_margin="8dp"
 android:background="@drawable/shape_rect"
 android:drawableStart="@drawable/ic_play"
 android:drawablePadding="5dp"
 android:gravity="center"
 android:padding="5dp"
 android:textColor="#000"
 android:textSize="8sp"
 android:onClick="reproducir"/>

<Button
 android:id="@+id/btnplay"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="end"
 android:text="VER"
 android:onClick="reproducir"
 android:layout_marginRight="5dp"/>

VideoFragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val vtv = layoutInflater.inflate(R.layout.row_video, null)
        btnplay = vtv.findViewById(R.id.btnplay)
        run = vtv.findViewById(R.id.dateTv)

binding.viewPager?.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int,
            ) {
                val titulo = lista[position].titulo.toString().trim()
                Toast.makeText(requireActivity(), titulo, Toast.LENGTH_SHORT).show()

            }

            override fun onPageSelected(position: Int) {

                    }
                })
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })
}

private fun reproducir(view: View) {
        findNavController().navigate(R.id.videofullFragment)
    }

A: El error :

Could not find method in a parent or ancestor Context for
android:onClick attribute

indica que estas llamando un método (reproducir() ) que no existe en el layout .xml que cargas en la Activity o en este caso el Fragment desde donde llamas el método.
El método debe existir en el layout .xml que cargas desde tu Fragment, en este caso si existe en video.xml debes cargar este layout:
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.video, null);
    }

Algo que es muy importante es que el método no debe definirse con el modificador private, únicamente debes definirlo de esta forma:
fun reproducir(view: View) {
    findNavController().navigate(R.id.videofullFragment)
}


text:
Q: Is it possible to play video using Avplayer in Background? I am using Avplayer to show video clips and when i go back (app in background) video stop. How can i keep playing the video?
I have search about background task & background thread  ,IOS only support music in background (Not video)
 http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html
here is some discussion about play video in background
1) https://discussions.apple.com/thread/2799090?start=0&tstart=0
2) http://www.cocoawithlove.com/2011/04/background-audio-through-ios-movie.html
But there are many apps in AppStore, that play video in Background like
Swift Player :  https://itunes.apple.com/us/app/swift-player-speed-up-video/id545216639?mt=8&ign-mpt=uo%3D2
SpeedUpTV :  https://itunes.apple.com/ua/app/speeduptv/id386986953?mt=8

A: If you try to change the background mode:
Sorry, App store wont approve it.MPMoviePlayerViewController playback video after going to background for youtube
In my research, someone would take the sound track out to play in te background when it goes into background as the video would be pause and get the playbacktime for resume playing when go into foreground

A: It is not possible to play background music/video using Avplayer. But it is possible using
MPMoviePlayerViewController. I have done this in one of my app using this player & this app
is run successfully to appstore.

A: Try with this snippet, I've already integrated this with my app & it's being useful for me..hope this will work for you!!
Follow the steps given below:

*

*Add UIBackgroundModes in the APPNAME-Info.plist, with the selection
App plays audio

*Then add the AudioToolBox framework to the folder frameworks.

*In the APPNAMEAppDelegate.h add:
-- #import < AVFoundation/AVFoundation.h>
-- #import < AudioToolbox/AudioToolbox.h>

*In the APPNAMEAppDelegate.m add the following:
// Set AudioSession
 NSError *sessionError = nil;

    [[AVAudioSession sharedInstance] setDelegate:self];

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];

*/* Pick any one of them */

*// 1. Overriding the output audio route

//UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  //AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute,
  sizeof(audioRouteOverride), &audioRouteOverride);

========================================================================
// 2. Changing the default output audio route
UInt32 doChangeDefaultRoute = 1;

AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);

into the
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

*

*but before the two lines:
[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
Enjoy Programming!!

A: Swift version for the accepted answer.
In the delegate:
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)

In the view controller that controls AVPlayer
override func viewDidAppear(animated: Bool) {
    UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
    self.becomeFirstResponder()
}

override func viewWillDisappear(animated: Bool) {
    mPlayer.pause()
    UIApplication.sharedApplication().endReceivingRemoteControlEvents()
    self.resignFirstResponder()
}

Don't forget to "import AVFoundation"

A: This method supports all the possibilities:

*

*Screen locked by the user;

*List item

*Home button pressed;

As long as you have an instance of AVPlayer running iOS prevents auto lock of the device.
First you need to configure the application to support audio background from the Info.plist file adding in the UIBackgroundModes array the audio element.
Then put in your AppDelegate.m into
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions:
these methods
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

and #import < AVFoundation/AVFoundation.h >
Then in your view controller that controls AVPlayer
-(void)viewDidAppear:(BOOL)animated
{
  [super viewDidAppear:animated];
  [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
  [self becomeFirstResponder];
}

and
- (void)viewWillDisappear:(BOOL)animated
{
    [mPlayer pause];
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
}

then respond to the
 - (void)remoteControlReceivedWithEvent:(UIEvent *)event {
        switch (event.subtype) {
            case UIEventSubtypeRemoteControlTogglePlayPause:
                if([mPlayer rate] == 0){
                    [mPlayer play];
                } else {
                    [mPlayer pause];
                }
                break;
            case UIEventSubtypeRemoteControlPlay:
                [mPlayer play];
                break;
            case UIEventSubtypeRemoteControlPause:
                [mPlayer pause];
                break;
            default:
                break;
        }
    }

Another trick is needed to resume the reproduction if the user presses the home button (in which case the reproduction is suspended with a fade out).
When you control the reproduction of the video (I have play methods) set
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];

and the corresponding method to be invoked that will launch a timer and resume the reproduction.
- (void)applicationDidEnterBackground:(NSNotification *)notification
{
    [mPlayer performSelector:@selector(play) withObject:nil afterDelay:0.01];
}

Its works for me to play video in Backgorund.
Thanks to all.

A: In addition to fattomhk's response, here's what you can do to achieve video forwarding to the time it should be after your application comes in foreground:

*

*Get currentPlaybackTime of playing video when go to background and store it in lastPlayBackTime

*Store the time when application goes to background (in userDefault probably)

*Again get the time when application comes in foreground

*Calculate the duration between background and foreground time

*Set current playback time of video to lastPlayBackTime + duration

A: If you are Playing video using WebView you can  handle using javascript to play video on background.
strVideoHTML = @"

  ";

NSString *html = [NSString stringWithFormat:strVideoHTML,url, width, height,videoid;
webvideoView.delegate = self;
[webvideoView loadHTMLString:html baseURL:[NSURL URLWithString:@"http://www.your-url.com"]];

On view diappear call
strscript = @"manualPlay();
[webvideoView stringByEvaluatingJavaScriptFromString:strscript];

A: I'd like to add something that for some reason ended up being the culprit for me. I had used AVPlayer and background play for a long time without problems, but this one time I just couldn't get it to work.
I found out that when you go background, the rate property of the AVPlayer sometimes seems to dip to 0.0 (i.e. paused), and for that reason we simply need to KVO check the rate property at all times, or at least when we go to background. If the rate dips below 0.0 and we can assume that the user wants to play (i.e. the user did not deliberately tap pause in remote controls, the movie ended, etc) we need to call .play() on the AVPlayer again.
AFAIK there is no other toggle on the AVPlayer to keep it from pausing itself when app goes to background.


text:
Q: Assign default value to variable if one not set, in Bash I know I can do:
echo ${var:-4}

to print 4 if var is null,
but how to assign -n in this case..?
echo ${var:--n} does not work.
although this does work..
echo ${var:---n}

but in that case it prints out --n and I need it to print -n.

A: The problem is not in the default, but in echo: -n has a special meaning for it (check help echo). Use printf instead:
printf '%s\n' "${var:--n}"


text:
Q: Homology Whitehead theorem for non simply connected spaces (One version of) the Whitehead theorem states that a homology equivalence between simply connected CW complexes is a homotopy equivalence. Does the following generalisation hold true?

Suppose $X,Y$ are two connected CW complexes and $f:X\to Y$ is a continuous map that induces isomorphisms of the fundamental groups and on homology. Then $f$ is a weak equivalence.

It would be enough to show that the map $\tilde{f}$ obtained by lifting $f$ to the universal covers (for some arbitrary choice of base points) is a homology equivalence, but I've never studied the homology spectral sequence, so I don't know the relationship between the homology of the universal cover $\widetilde{X}$ and that of $X$, and I don't know how to prove that $\tilde{f}$ is a homology equivalence.
Also, are there any good, reasonably self contained and short accounts of the homology of covering spaces, preferably online?
EDIT 1 I've seen some lecture notes (second paragraph on page 5) where this theorem is used (without further comment). They used this proposition to establish that a certain type of homotopy colimit is well defined up to weak equivalence.
EDIT 2 Theorem 6.71 from Kirk and Davis (page 179 of the document or 164 internally) is probably what I need, but it involves isomorphisms with local coefficient systems for homology for the base spaces.
EDIT 3 Thank you @studiosus for the reference. I don't quite understand yet, could you help out? If I get it (using the theorem of the source), there are finite connected two dimensional complexes $X,Y$ and a homotopy equivalence $X\vee S^2\simeq Y\vee S^2$, yet $X$ and $Y$ aren't homotopy equivalent. From the assumption it follows immediately that $$X\hookrightarrow X\vee S^2\to Y\vee S^2\twoheadrightarrow Y$$ gives an isomorphism of the fundamental groups. From $$\tilde{H}(X)\oplus\tilde{H}(S^2)\simeq\tilde{H}(X\vee S^2)\simeq\tilde{H}(Y\vee S^2)\simeq\tilde{H}(X)\oplus\tilde{H}(S^2)\;,$$ $\tilde{H}(S^2)\simeq \Bbb Z[2]$ and the fundamental theorem of finitely generated abelian groups, it follows at once that $\tilde{H}(X)\simeq\tilde{H}(Y)$ abstractly. The only problem I have is that it doesn't seem to me that we get a map $X\to Y$ that induces isomorphisms on $\pi_1$ and is a homology equivalence, actually, I don't see why there should be a homology equivalence $X\to Y$ at all.

A: There are two finite 2-dimensional complexes $A, B$ which are not homotopy-equivalent but are homology-equivalent, i.e., there exists a continuous map
$$
f: A\to B
$$
inducing isomorphism of fundamental groups and homology groups. See the last paragraph (page 522) of this paper, the actual example is due to Dunwoody.
Edit 1: The homology equivalence part follows from Dyer's paper, see the link above (read the very last paragraph of his paper). Dyer's results are by no means obvious: He proves that equality of Euler characteristics plus one extra condition ($m=1$, whatever $m$ is) imply homology equivalence of 2-d complexes with isomorphic fundamental groups. Then Dyer verifies his conditions in the case of Dunwoody's example (the only nontrivial condition is $m=1$, since equality of Euler characteristics is clear).
Edit 2: The correct version of the "homological Whitehead's theorem" is indeed requires a cohomology isomorphisms with sheaf coefficients, see the discussion and reference here.

A:
...it turns out there are non-trivial  high dimensional smooth knots $S^n\subset S^{n+2}$
  such that $\pi_1$ of the knot complement $X$ is
  infinite cyclic. The inclusion of the meridian $S^1 \subset X$ is a
  homology isomorphism, a $\pi_1$ isomorphism but is never a weak
  equivalence since by a result of Levine if it were then the knot would
  be trivial (we should assume $n \ge 3$ here).

John Klein @ https://mathoverflow.net/a/104534/1556

A: You know already that the answer for your question is no, nevertheless, there is a generalisation which you might like:

Suppose that $X$, $Y$ are path-connected, simple CW-complexes. If $f:X\rightarrow Y$ induces isomorphism in $H_n$ for all $n\geq 0$, then $f$ is a homotopy equivalence.

A: This is meant as a question directed at @studiosus and anybody who's familiar with his example.

M. Dyer's theorem seems to state, as a special case, that

Theorem Suppose $X,Y$ are finite, at most 2 dimensional, connected CW complexes with isomorphic fundamental groups (so called $[G,2]$-complexes, where $\pi_1(X)\simeq G\simeq\pi_1(Y)$). If $X$ and $Y$ have the same Euler characteristic $\chi$, and $\chi>\chi_{\min}(G,2)$, then $X$ and $Y$ are homology equivalent.

(From what I understood, when $\chi>\chi_{\min}(G,2)$ then automatically $m=1$, see the first sentence under his theorem)

To the trefoil knot group presentation $G=\langle a,b\mid a^3b^{-2}=1\rangle$ corresponds a $[G,2]$-complex with one $0$ cell, two $1$ cells and one $2$ cell ($Y$ in Dyer's paper) so that $\chi(Y)=0\geq\chi_{\min}(G,2)$, and thus with $X=Y\vee S^2$, which is manifestly still a $[G,2]$-complex, $1=\chi(X)>0\geq\chi_{\min}(G,2)$. This $X$ corresponds to the presentation $G=\langle a,b\mid a^3b^{-2}=1, 1=1\rangle$.
There is another presentation for $G$ defined in Dunwoody's paper with a complicated presentation (still on two generators and two relations, it's on the last page of his paper, so with $\chi=1$), and I take it, that the realization $Z$ of this presentation has $X\not\simeq Z$ (while, I take it, $X\vee S^2\simeq Z\vee S^2$).
So since $X$ and $Z$ are $[G,2]$-spaces with identical Euler characteristic equal to $1>0\geq\chi_{\min}(G,2)$, they should automatically have $m=1$ and thus be homology equivalent by M.Dyer's therem (for him this means: there is a map that is an isomorphism on $\pi_1$ and $H_*$), yet they aren't homotopy equivalent by Dunwoody's theorem.

Is this correct?

$\chi_{\min}(G,2)$ is the minimum over all Euler characteristics of $[G,2]$-complexes.The fact that $\chi_{\min}(G,2)$ is well defined strikes me as believable, at least not implausible, and I'm willing to accept it. Indeed, it seems that every $[G,2]$-complex $X$ should define a presentation $P$ of $G$, and a subcomplex $X'$ with the same $1$-skeleton, but possibly less $2$-cells, thus with smaller Euler characteristic, homotopy equivalent to the $[G,2]$-complex obtained from the presentation $P$. So it seems that, in order to show $\chi_{\min}(G,2)$ is well defined, one can forget about general $[G,2]$-complex and only consider those associated to presentations of $G$. Adding a new relation increases the Euler characteristic by one. Adding a new generator should introduce at least one new relation, thus at least one new $2$-cell, so it seems that ($\#$ of $2$-cells)$-$($\#$ of $1$-cells)$+1$ can only increase by adding new generators and relations to a given presentation of $G$. So it seems one can do the following:

*

*From any $[G,2]$-complex $X$ extract a subcomplex $X'$ with fewer $2$ cells and identical $1$ skeleton (thus reducing $\chi$) that remains a $[G,2]$-complex and is homotopy equivalent to a $[G,2]$-complex associated to a presentation of $G$.

*From a given presentation of $G$ extract a "minimal" presentation of $G$. Intuitively one that can't be reduced by either considering less generators or relations. From the intuitive argument above it follows that adding new generators or relations to a presentation can only increase teh Euler characteristic, so passing to "minimal" presentations should reduc the Euler characteristic of the associated $[G,2]$-complex.

*Only study the Euler characteristics of $[G,2]$-complexes associated to "minimal" presentations of $G$.

*Somehow show that they all have the same Euler characteristic, which then must be $\chi_{\min}(G,2)$.

EDIT 1 Proposition 1 on page 14 of these notes gives a lower bound for the Euler characteristic of any $[G,2]$-complex associated to any presentation of (finitely presentable) $G$ in terms of the rank of its first and second homology groups. So steps 3 and 4 aren't necessary, 4 might even be wrong.

A: The answer is no. An easy example is provided in Allen Hatcher's Algebraic Topology, Example 4.35.
http://www.math.cornell.edu/~hatcher/AT/ATch4.pdf
There, a CW-complex $X$ is formed by attaching an appropriate $(n+1)$-cell to the wedge $S^1 \vee S^n$ of a circle and an $n$-sphere. The inclusion of the $1$-skeleton $S^1 \to X$ induces an isomorphism on integral homology and on homotopy groups $\pi_i$ for $i < n$ but not on $\pi_n$.
That example is also worked out as Problem 1 here:
http://www.home.uni-osnabrueck.de/mfrankland/Math527/Math527_HW10_sol.pdf


text:
Q: Finding the Current User login in a Content Query Web Part? I have the unique requirement of needing to get the current user's id (domain\logon) for use within a Content Query Web Part.  If no documents are retrieved with the CQWP I need to craft a custom url in the format site/employees/currentuserlogon/.  How do i get that  information?
The proposed functionality would be as follows:
A user accesses a generic top level page with a Content Query Web Part pulling the most recent form that the user authored.  If there is no form that the user authored, than a custom link will appear that allows the user to create a form.  The link is user specific, using the logon account as part of the site path.

A: I haven't done much with the CQWP because I find it falls down as soon as you want to do anything really hard. That said, there's a CAML variable you can use in a DVWP:
<ParameterBinding Name="UserID" Location="CAMLVariable" DefaultValue="CurrentUserName"/>

It probably is available somehow in a CQWP, too.

A: Hopefully someone here knows of a this can be done without needing to write custom code. However I have found before the need to extend the CQWP to send through extra information such as this to the XSLT.
Waldek Mastykarz has some great tutorials for the CQWP and many other things on his blog, of which this is one should help you.

A: Agreed with Marc on this one the DVWP adds the parameter he mentions above in by default which represents the current userID.  Its also really easy to specify a template which will be used when no results are returned.  Just click on 'Common Data View Tasks' and select Data View Properties.  Under General tick 'Display text if no matching items are found'.
This adds a template to the XSL called 'dvt_1.empty' you can edit this to display your link.  All the logic is pre-built for you.


text:
Q: Is there a built in function for printed text to clear in php? When you write echo in php "text is printed in the output"
How can you clear it after it is printed?

A: Clean (erase) the output buffer
// clean the output buffer
ob_clean();

Please refer this link
For below example, there is no output on the browser
echo 'This is text.';
ob_clean();

A: It depends on context. When you run PHP in CLI you can for e.g. execute a shell command to clear it, shell_exec('clear');, but on macOS terminal it does not work. Maybe there on other it will.


text:
Q: Past Simple for long actions Should I say,

My son was coughing yesterday night

or

My son coughed yesterday night?

Past Progressive usually describes long actions that happened at a spesific time in the past, but still here it's also about a long action that happened in the past.
I would be thankful to anyone who would answer.

A:
My son coughed yesterday night

Would mean that he coughed once and that was all.

My son was coughing yesterday night

Is a longer action and ould mean that he was coughing for a length of time, not just once

A: I agree with the first answer...

My son coughed yesterday night

^ sounds like a one-time thing. While the meaning could be the same, it would be a very strange way to describe a prolonged period of coughing.


text:
Q: Codeigniter - Form validation callbacks What is wrong with this code ?
The problem is that the is_empty method is called but is_image not.
$this->load->library('form_validation');
$this->form_validation->set_rules('userfile', 'image', 'callback_is_empty|callback_is_image');

Here is the is_image method
public function is_image()
{
  echo 'Hello from is_image';
}

A: Your custom callback functions need to return "True" or "False".

A: I am not sure, but have you tried to use
'callback_is_empty||callback_is_image'

instead of
'callback_is_empty|callback_is_image'

also have you read this:
http://ellislab.com/codeigniter/user_guide/libraries/form_validation.html#callbacks
Sorry I couldn't been more usefull.


text: Q: Why does Apache Flume regex extractor accept only "1 digit" ? I am using Apache Flume regex extractor interceptor with multiplexing channel selector. When I am trying to use regex "^ID:([0-9]+)," for filtering, only the events containing 1 digit, e.g. ID:4, are captured. Why are all the events containing more digits, e.g. ID:100, ignored?


text:
Q: Position div under an absolutely positioned div with a responsive height I'm trying to position my navigation under a css slideshow (which isn't finished yet). The slideshow is positioned absolutely so my nav is shooting to the top of the window. How can I force the navigation under the slideshow when the images' heights are responsive to the width of the window?

A: If the slideshow you're making is custom code and not some plugin, I have a suggestion. Inside the slideshow you can put a div, give it position relative, and then put your nav inside that div. The nav would be position absolute and give it "bottom: n px;" where n is the height of your nav. Hope that makes sense!


text:
Q: What is it that determines the degree of a tile, and to what extent does the shape of a tile determine its degree? I'd be interested to learn if/what the geometric or algebraic approach to acquiring a tile of degree $2, 3, \ldots, n$ (i.e. a tile of an arbitrary degree) would be? Asked another way- what is it that determines the degree of a tile, and to what extent does the shape of a tile determine its degree?
By degree of a tile, I mean the number of other tiles which are adjacent to it, and by adjacency, I mean tiles which share a common boundary.
And I am referring to any tiling of the plane initially - though maybe it would be simpler to look at a regular tesselation of the plane, first. Then, would there be a finite or infinite number of ways of dividing the plane to acquire tiles of degree $2, 3, \ldots, n$? A related question could be, to what extent does the type of tiling affect my question? Presumably the degree of a tile and the symmetry group must be interconnected?

A: The degree of a tile is not determined by its shape. Consider the following two  tilings of $1\times 2$ rectangles:

One of these has degree $4$ at every tile, and one has degree $6$ at every tile.
If all tiles meet along some portion of their border, and not just at a corner, then (so long as there are finitely many shapes of tile used) the average degree will always be $6$; this is a consequence of Euler's formula for planar graphs.


text:
Q: modify assembly generated by visual studio before linking I would like to know if there is a away how to modify assembly generated by compiler before the linking stage. As I have no idea how to do that?

A: The assembly code generated by the Microsoft's C/C++ compiler is meant to be informational only. In general it cannot be assembled by MASM into an .OBJ file equivalent to what the compiler would generate directly.
For example, consider this simple C++ hello world program:
#include <iostream>

int
main() {
    std::cout << "Hello, world!" << std::endl;
    return 0;
}

When I compile it using Microsoft's C++ compiler (using /Fa to generate assembly) and then use MASM to try assemble the generated .ASM file this is what I get:
t146.asm(1277) : error A2008:syntax error : _Args_0
t146.asm(1339) : error A2008:syntax error : _Args_0
t146.asm(1773) : error A2008:syntax error : _Args_0
t146.asm(2176) : fatal error A1010:unmatched block nesting : ??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@PBD@Z

There'd be even more errors, but the last error causes the assembler to bail out and give up trying to assemble the rest of the file.
In addition to the errors there are also certain things missing from the generated assembly that exist in the generated object file. One example are COMDAT sections which show up in generated assembly as comments because MASM doesn't support them.
So if you were hopping to have Visual Studio generate assembly that you would then programically modify and assemble, it won't work. You could use the GNU C/C++ compiler instead since it doesn't generate object files directly. Instead GCC generates assembly which is turned into an object file by the GNU assembler. So it always generates valid assembly. An other option would be to modify the generated object files, which could actually be easier.
However the big problem is that what you're ultimately trying to accomplish, "modify pointer accessing", is a much more difficult task than you apparently think it is. There all sorts of ways pointers can be used in the code generated by the compiler. You would both need to recognize all of them and then identify which are actually the kind of pointer accesses you're interested in.
I recommend just using explicit serialization in your program. Even if you have to write your serialization code from scratch, it should be a lot easier than messing about the code generated by the compiler.


text:
Q: EXCEL: Getting a range of cells to always total 100%, even if new percentages are added or taken away (other cells update) I am trying for an Excel formula that will perform the following: I have a series of rows that hold percentages (e.g. total % of business by account), and a sum row which, of course, equals 100%. I am trying to make this dynamic. So, for example, I add 5% to one of the cells where there was 0%, and the distribution changes in the other cells in the range to still equal 100%. Like, slicing the pie differently and always getting to 100%. Thanks for any assistance!
My experience level with Excel is better than most, but limited. To frame it for the pros, I can peform lookups, ifs, countifs, that level of stuff. So, I started looking online and stumbled into a few things I found  with MMULT, SEQUENCE, OFFSET, COUNTIF... they're not doing what I'm asking though. It's possilbel I don't know the name or phrase for what it is I am looking to do for my staff, and that is dead-ending me.


text:
Q: Math is broken in my Android app's recent update(s) Unsure if related, but I'm using LibGDX and maintaining a long-existing app on Google Play.
In a recent update, I started receiving sporadic, random crashes. They all looked like this:

There seems to be no common denominator for the reason, device, or OS (only Android 9, and 10 however).
The code in question has never changed, it's been in place for years. The underlying Table/Cell (LibGDX) code is also very much the same, and unchanged. Here is the line causing the problem:
Table importTable = new Table();
importTable.pad(0).align(Align.center);
importTable.defaults().pad(0).space(0).spaceRight(10 * App.assetScaling).expandX();

Function:
/** The space cannot be < 0. */
public Cell<T> spaceRight (float spaceRight) {
    if (spaceRight < 0) throw new IllegalArgumentException("spaceRight cannot be < 0: " + spaceRight);
    this.spaceRight = Fixed.valueOf(spaceRight);
    return this;
}

Specifically, the code spaceRight(10 * App.assetScaling)
App.assetScaling is either 1.0f or 0.5f, it is set at the app's creation. It never changes. This code runs right after the app starts, as it's creating menus and whatnot.
How...is this somehow evaluating to < 0? Or, as the error reports show, it's actually "basically 0", just with some floating point error. The number App.assetScaling is NEVER set to not either 0.5f or 1.0f.
For people plagued with this, they cannot start the app, as it keeps crashing. Upon uninstall/reinstall, however, it was fixed.
Is there...any caveat with compilation/app updates (caching?...) that, would cause math to, "break", so to speak? This error came out of nowhere a few updates ago, I've since pushed out other updates, and this crash seems to be dwindling but, not gone completely...


text:
Q: Efficient way to create nested dictionary using pandas dataframe colums as keys I have a data frame like:
df = pd.DataFrame({'Geography': ['Geog1', 'Geog1', 'Geog1', 'Geog1','Geog2', 'Geog2','Geog2', 'Geog2'],
               'Goal': ['G1', 'G1', 'G2', 'G2','G1', 'G1', 'G2', 'G2'],
               'Indicator': ['G1I1', 'G1I2', 'G2I1', 'G2I2','G1I1', 'G1I2', 'G2I1', 'G2I2'],
               'Year': [2016, 2016, 2016, 2016,2016, 2016, 2016, 2016]
               'Data': [3, 5, 2, 6,7, 4, 6, 6]})

and I want to convert it to a nested dictionary like:
[{'Geography': Geog1, 'Info': [{'Goal': 'G1 ', 'Indicators': [{'Indicator': 'G1I1', 'dataYears': [{'Year': 2016, 'Data': 3}]}, {'Indicator': 'G1I2', 'dataYears': [{'Year': 2016, 'Data': 15.0, }, {'Year': 2011, 'Data': 21.0}]....

I've managed to do this with the following (highly inefficient code):
j = (df.groupby(['Geography','Goal','Indicator'])
     .apply(lambda x: x[['Year','Data']].to_dict('r'))
     .reset_index()
     .rename(columns={0:'dataYear'}))
j = (j.groupby(['Geography','Goal'])
     .apply(lambda x: x[['Indicator','dataYear']].to_dict('r'))
     .reset_index()
     .rename(columns={0:'Indicators'}))
j = (j.groupby(['Geography'])
     .apply(lambda x: x[['Goal','Indicators']].to_dict('r'))
     .reset_index()
     .rename(columns={0:'Goals'})
     .to_dict('r'))

My question is: does anyone know a way to do this more efficiently? I have seen answers elsewhere but they typically create a new nested level for each new column but I want to include multiple columns in some levels of the dictionary (e.g., Year, data).

A: You easily fix it this way:
x = [df.to_dict()] #create a list x whose content is the dictionary of you dataframe


text:
Q: Uploaded media 500 server error - Umbraco I have migrated an Umbraco install to a new server.
However, I now get a 500 server error whenever I try and open a media file.
I can upload files successfully to the root 'media' folder but I cannot seem to then navigate to these files.
Does anyone know what could be causing this?

A: This link suggests touching the global.asax, while this one makes me wonder whether you removed the Label datatype by any chance.
What version of Umbraco are you using? I would also look in the database, in the UmbracoLog table for any errors that might point you in the correct direction.

A: What type of media files don't work?  Is it just certain extensions?  Or everything (including images)?
If it is simply certain extensions, you may need to verify that IIS is allowing those extensions.

A: As other poeple have mentioned, ideally we need to see the error message. Additionally, can you check if your server can serve up files of that type from other location? If so then it's a permissions issue (check the permissions on the old server match the new one, remember to give read, write and modify permissions to "IIS_IUSRS", "Network Service" and "IUSR" Windows accounts), but if you cannot serve any files of that type at all then you need to add the MIME extensions (added in IIS - see here)


text:
Q: Got an exception when tried to modify xml response in custom filter I have a problem with modifying servlet response in my filter. Here is the part of
my code:
public class MyFilter implements Filter {

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        System.out.println("BEFORE filter");
        PrintWriter out = response.getWriter();
        CharResponseWrapper responseWrapper = new CharResponseWrapper((HttpServletResponse) response);

        chain.doFilter(request, responseWrapper);

        String servletResponse = new String(responseWrapper.toString());

        out.write(servletResponse);
        out.close();

        System.out.println("Response: " + servletResponse);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }

}

This code works fine when servlet returns html-page, but if servlet tries to return xml I get an exception:
SEVERE: Servlet.service() for servlet ViewerServlet threw exception
java.lang.IllegalStateException: getWriter() has already been called for this response
    at org.apache.catalina.connector.Response.getOutputStream(Response.java:579)
    at org.apache.catalina.connector.ResponseFacade.getOutputStream(ResponseFacade.java:183)
    at javax.servlet.ServletResponseWrapper.getOutputStream(ServletResponseWrapper.java:102)
    at org.apache.axis.transport.http.AxisServlet.sendResponse(AxisServlet.java:902)
    at org.apache.axis.transport.http.AxisServlet.doPost(AxisServlet.java:777)
    at org.eclipse.birt.report.servlet.BirtSoapMessageDispatcherServlet.doPost(BirtSoapMessageDispatcherServlet.java:265)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at org.apache.axis.transport.http.AxisServletBase.service(AxisServletBase.java:327)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.eclipse.birt.report.servlet.BirtSoapMessageDispatcherServlet.service(BirtSoapMessageDispatcherServlet.java:122)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.epam.bi.filter.RptGenerationTimeCalcFilter.doFilter(RptGenerationTimeCalcFilter.java:34)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.eclipse.birt.report.filter.ViewerFilter.doFilter(ViewerFilter.java:68)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
    at java.lang.Thread.run(Thread.java:619)

Does anyone face such problem? Any ideas how to make it work?
Thanks in advance.


text:
Q: How To Restrict a Column To Only A Default Value When I add a "default value" expression to a column, if I do not specify a value for that column during an insert, the column automatically gets its default value. But if a value is supplied during insert, that value is used. How do you restrict a column to only have a default value so that an insert statement cannot write an arbitrary value in that column?
EDIT:
The default value I have in mind is NEWID()

A: For this sort of specific requirement, I would use an INSTEAD OF trigger set on the table. Here's a simple example showing how this would work.
-- I chose this table structure (nullable elements) so no error would be thrown on insert,
--  and because no values are expected from the user for these columns
CREATE TABLE Bob (
    dataElement varchar(200) not null,
    LastUpdate datetime,
    UnchangeableID UniqueIdentifier
    )
GO

CREATE TRIGGER tr_MakeItHard1 ON Bob
INSTEAD OF INSERT
AS
BEGIN
    INSERT INTO Bob (DataElement, LastUpdate, UnchangeableID)
    SELECT dataElement, GETDATE(), NewID()
    FROM inserted
END

GO
CREATE TRIGGER tr_MakeItHard2 on Bob
INSTEAD OF UPDATE
AS
BEGIN
    -- Here, you can either choose to allow manual updates of the LastUpdate value
    -- from the insert, or only update the data here. I chose to only allow updates
    -- here.
    Update Bob
    SET dataElement = i.dataElement,
        LastUpdate = GetDate()
    FROM inserted i
END
GO

DECLARE @uid uniqueidentifier

SELECT @uid = NewID()

INSERT INTO BOB values ('Data Element Insert', '20100101', @uid)

SELECT b.*,
    @uid as Generated
FROM Bob b

DECLARE @uid uniqueidentifier
SELECT @uid = NewID()

UPDATE Bob
SET dataElement = 'Data Element Update',
    LastUpdate = '20120101',
    UnchangeableID = @uid

SELECT b.*,
    @uid as Generated
FROM Bob b

/*
Results of the queries -- the top row is from the INSERT, the row below is from the UPDATE

dataElement             LastUpdate              UnchangeableID                          Generated
Data Element Insert     2017-01-05 08:59:12.187 7829000B-5BC8-4488-A006-DCB2933C5C95    3670E5AA-FBD4-49C0-88CF-8E2DE9F89BFC
Data Element Update     2017-01-05 09:04:57.527 7829000B-5BC8-4488-A006-DCB2933C5C95    86E9617D-F238-4E46-BE8F-85A318853593

*/

A: You could put a constraint on the table to prevent values other than that value from being inserted (example here uses 0)
CREATE TABLE dbo.ConstraintTest (C1 INT NOT NULL, C2 INT DEFAULT(0));
ALTER TABLE dbo.ConstraintTest ADD CONSTRAINT PK_ConstraintTest PRIMARY KEY (C1);
ALTER TABLE dbo.ConstraintTest ADD CONSTRAINT CHK_ConstraintTest_C2is0 CHECK (C2 = 0);

INSERT INTO dbo.ConstraintTest (C1) VALUES (1);
SELECT * FROM dbo.ConstraintTest;

INSERT INTO dbo.ConstraintTest (C1, C2) VALUES (2, 2);

Alternatively you could look at using a trigger to ensure that the value does not get set to something different.


text:
Q: Itunesconnect stuck on "This Field is Required" I've submitted a new app to itunesconnect - which got rejected because of a metadata issue. I fixed the metadata issue and replied to them in the resolution centre. However, I was not sure whether I need to press "Submit for Review" again on the app page (since they do not really specify). So, I went to go press it just for in case. It does not want to trigger and gives an error "This field is required" - with NO indication of what it actually wants?
Please, does anyone have a suggestion on how to fix this. I have already set the age rating, privacy policy etc. It has screenshots and a binary file. As far as I can see, it should be good to go. At this stage, it looks like they are just trying to make life difficult.

A: OK, so after scrambling around and changing random fields, I inserted a value for "Copy Right" and that seemed to work. After I submitted though, it immediately cleared that field from the entry I had put in? So, not sure what that is all about. Hopefully this helps someone else too.


text:
Q: Join two tables by dates returning data grouped by date I have two tables tbl_live_links and tbl_total_links both have two colums  dateSubmitted, pid and linkSubmitted and they do not have any relation between them. But the requirement is to fetch sum of links submitted in each month.
I am using these queries::
    SELECT dateSubmitted
         , sum(`linkSubmitted`) as total
      FROM `tbl_total_links`
     where pid = 1
     group
        by `dateSubmitted`
     order
        by `dateSubmitted` DESC
     limit 0,6

Result of this query is::
dateSubmitted total
2015-08-10       20
2015-07-06       56

AND
SELECT dateSubmitted, sum(`linkSubmitted`) as live FROM `tbl_live_links` where pid = 1 group by `dateSubmitted` order by `dateSubmitted` DESC limit 0,6

Result of this query is::

dateSubmitted
  live
2015-08-10
  59
2015-07-06
  78

AND I want result like this

dateSubmitted
  total
  live
2015-08-10
  20 59
2015-07-06
  56 78

Both tables can have multiple submission for particular month but I want sum of all links submitted in a month from both the tables

A: try this
SELECT tbl_live_links.dateSubmitted, sum(tbl_live_links.`linkSubmitted`) as live ,sum(tbl_total_links.`linkSubmitted`) as total
     FROM `tbl_total_links`, `tbl_live_links`
     where pid = 1
     and tbl_live_links.dateSubmitted = tbl_total_links.dateSubmitted
     group
        by `tbl_live_links.dateSubmitted`
     order
    by `tbl_live_links.dateSubmitted` DESC
 limit 0,6

A: here you can try with the simple joins conditions, hope this can resolve your prob, the join condition i have took from your two statement,
select
    dateSubmitted,
    sum(tlink.linkSubmitted) as total,
    sum(llinks.linkSubmitted) as live
from
    tbl_total_links tlink
    inner join tbl_live_links llinks on llinks.pid = tlink.pid
where
  llinks.pid = 1
group by
    tlink.dateSubmitted,
    llinks.dateSubmitted
order by
    tlink.dateSubmitted,
    llinks.dateSubmitted
    desc
limit 0,6


text:
Q: Portlet superclass must be a valid portlet class I'm using liferay-portal-6.1.1-ce-ga2 with maven 2.2.1.. and I'd like to create a new portlet!!
when I click New>liferay-portlet... using eclipse. After creating the portlet I found 2 errors in portlet.xml and pom.xml!
portlet.xml:
...
        javax.portlet.faces.GenericFacesPortlet
...
 the error : The class javax.portlet.faces.GenericFacesPortlet was not found on the Java Build Path.
pom.xml:
    <plugins>
        <plugin>
            <groupId>com.liferay.maven.plugins</groupId>
            <artifactId>liferay-maven-plugin</artifactId>
            <version>${liferay.maven.plugin.version}</version>
            <executions>
                <execution><!-- the error is here -->
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>build-css</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <autoDeployDir>${liferay.auto.deploy.dir}</autoDeployDir>
                <appServerDeployDir>${liferay.app.server.deploy.dir}</appServerDeployDir>
                <appServerLibGlobalDir>${liferay.app.server.lib.global.dir}</appServerLibGlobalDir>
                <appServerPortalDir>${liferay.app.server.portal.dir}</appServerPortalDir>
                <liferayVersion>${liferay.version}</liferayVersion>
                <pluginType>portlet</pluginType>
            </configuration>
        </plugin>

 the error: Plugin execution not covered by lifecycle configuration: com.liferay.maven.plugins:liferay-maven-plugin:${liferay.maven.plugin.version}:build-css
 (execution: default, phase: generate-sources)
Any Idea?

A: Regarding the maven error, I'm not sure but it seems that the liferay.maven.plugin.version property is missing (I'd expect it would get replaced with an actual value in the error message if the value was resolvable by maven)
As for the The class javax.portlet.faces.GenericFacesPortlet was not found on the Java Build Path error: you said that you used some New>liferay-portlet, so I assume you are using Liferay Developer Studio. From my experience (and this is my subjective opinion), it seems that Liferay put much more emphasis on it's ant SDK and general ant integration so Liferay DS (at least – at the moment) may not work well with a maven-based portlet project. I guess it missed some dependency in pom.xml, so simply verify if jsf-portlet-bridge-api.jar is in dependencies in pom.xml


text:
Q: How do I perform a function using DateTime objects? I want my .pl to execute a function at the end of every day, week and month. What the function will do is grab an integer from an html at the end of the day and store it in a .txt to be used to create a graph.
I already know how to implement CGI and JS with a perl script, so that is no issue. I'm just not clear on whether or not DateTime objects can be used in this boolean-type way. This sounds simple, so I hope there is a simple answer.

A: It's unclear whether your solution MUST be all-perl or not.
If NOT all-perl, you can do something "at the end of every day" and "at teh end of every week" (the latter just means end of Sunday) using your system's scheduler (cron on Unix/Linux/MacOS, AT pr Windows Scheduler on Windows).
For end of month, you can run the script every day but at the beginning, quit if not end of month. The logic for both end of month (and end of week as a bonus) would be using something like:
use Time::Local qw ( timelocal_nocheck );
my @time_data = localtime() ;
my $current_dom = $time_data[3];
my $current_dow = $time_data[6];
$time_data[4]++;   # Next month.
$time_data[3] = 0; # Last day of previous month.
@time_data = localtime ( timelocal_nocheck ( @time_data ) );
if ($current_dom == $time_data[3]) {
    # Do end of month processing
}
if ($current_dow == 0) { # Sunday
    # Do end of week processing
}

Hat tip: http://www.perlmonks.org/?node_id=418897

A: Here is a simple example of how to use DateTime to trigger a function:
use 5.012;
use warnings;
use DateTime;

my $now = DateTime->now;

# example queue
my @jobs = (
    { after => $now->clone->subtract( hours => 1 ), sub => undef },  # done
    { after => $now->clone->subtract( hours => 1 ), sub => sub{ say "late"  }},
    { after => $now->clone,                         sub => sub{ say "now"  }},
    { after => $now->clone->add( hours => 1 ),      sub => sub{ say "not yet" }},
);

for my $job (@jobs) {
    if ($job->{after} <= $now && $job->{sub}) {
        $job->{sub}->();
        $job->{sub} = undef;   # ie. clear from queue
    }
}

The above will run late & now only.
There are a couple of DateTime modules on CPAN which may help further.

*

*DateTime::Event::Cron

*DateTime::Cron::Simple
Alternatively there is a complete cron clone called Schedule::Cron


text:
Q: Android autocomplete with SQLite LIKE works partially I have a Restaurants table in my SQLite DB that have the following records
| Name   | Latin_Name |
+--------+------------+
| Манаки | Manaki     |
+--------+------------+
| Енрико | Enriko     |
+---------------------+

Now I'm doing the search like this:
From my fragment:
String selection = DBHelper.COL_NAME + " LIKE ? OR " +
                    DBHelper.COL_LATIN_NAME + " LIKE ?";

String[] selectionArgs = {"%"+term+"%", "%"+term+"%"};

CursorLoader loader = new CursorLoader(getActivity(),
                               DatabaseContentProvider.REST_CONTENT_URI,
                               columns, selection, selectionArgs, null);

The content provider query method:
 public Cursor query(Uri uri, String[] projection, String selection,
                    String[] selectionArgs, String sortOrder) {

    db = dbHelper.getReadableDatabase();
    SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
    switch(URI_MATCHER.match(uri)){
        case REST_LIST:
            builder.setTables(DBHelper.REST_TABLE);
            break;
        case REST_ID:
            builder.appendWhere(DBHelper.COL_ID + " = "
                    + uri.getLastPathSegment());
            break;
        default:
            throw new IllegalArgumentException("Unsupported URI: " + uri);
    }
    Cursor cursor = builder.query(db, projection, selection, selectionArgs,
            null, null, sortOrder);

    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    return cursor;
}

So pretty basic right? Now here comes the problem:
If the term that comes in is en I can see the Enriko restaurants among the others.
If I pass enri I can't see the Enriko as a result anymore.
Same goes for the Manaki restaurant I can see it until mana and after that (for manak term for ex) I can't see it in the results list.
I was debugging my ContentProvider and I realized that the cursor was empty, so the problem have to be at the database level, I guess.
Please help.
UPDATE:
Having the @laalto comments in mind I decided to do some test on the database. In the onCreate() method of my SQLiteOpenHelperI inserted only those two records in the table by hand and it worked.
Now the problem is that I have to insert 1300 records onCreate() from a json file shipped in the assets folder. Right now I'm parsing the json file create an ArrayList<Restaurant> then loop trough it and insert one record per object for all 1300 items.
That kind of insertion won't work with the SQLite LIKE method.
Are there any gotchas about this kind of populating the database?
Maybe I need to change file encoding (it is UTF-8 now) or maybe database's collation, or maybe getString() from JSONObject can be tweaked for the database?

A: If it's urgent, here a quick and dirty solution.
2.600 strings (1.300 cyrillic + 1.300 latin) are really few values to handle in memory: you can simply load all values from the SQLite with
select name, latin_name from restaurants

and then you can loop the result set in Java while searching for the matching string with a String.contains method. Just remember that contains method is case sensitive, so you should use something like this:
string1.toLowerCase().contains(string2.toLowerCase())

A: sqlite documentation link
The LIKE operator does a pattern matching comparison. The operand to the right of the LIKE
operator contains the pattern and the left hand operand contains the string to
match against the pattern. A percent symbol ("%") in the LIKE pattern matches any
sequence of zero or more characters in the string. An underscore ("_") in the LIKE
pattern matches any single character in the string. Any other character matches
itself or its lower/upper case equivalent (i.e. case-insensitive matching).
(A bug: SQLite only understands upper/lower case for ASCII characters by default.
The LIKE operator is case sensitive by default for unicode characters that are
beyond the ASCII range. For example, the expression 'a' LIKE 'A' is TRUE but 'æ' LIKE 'Æ'
is FALSE.)


text:
Q: Git Permission Denied when checking out a branch I am having a git issue with a specific folder when trying to checkout to the master branch from my events-feature branch. Below is what is happening in the command line. No code is being changed during the command line inputs. At the end of my second git status the folder lib/partials has been deleted.
~/Desktop/climbingTheWeb/climbers-hub (events-feature)
$ git status
On branch events-feature
nothing to commit, working directory clean

~/Desktop/climbingTheWeb/climbers-hub (events-feature)
$ git checkout master
fatal: cannot create directory at 'lib/partials': Permission denied

~/Desktop/climbingTheWeb/climbers-hub (events-feature)
$ git status
lib/partials/createEvent.jade: Permission denied
lib/partials/event.jade: Permission denied
lib/partials/login.jade: Permission denied
lib/partials/navbar.jade: Permission denied
lib/partials/register.jade: Permission denied
lib/partials/search.jade: Permission denied
lib/partials/welcome.jade: Permission denied
On branch events-feature
Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   gulpfile.js
    modified:   lib/js/config.js
    deleted:    lib/js/createEventController.js
    modified:   lib/js/eventController.js
    deleted:    models/event.js
    deleted:    public/index.html
    deleted:    public/partials/createEvent.html
    deleted:    public/partials/createEventForm.html

    no changes added to commit (use "git add" and/or "git commit -a")


text:
Q: SqlDependency.OnChange keep firing from what i understood,SqlDependency.OnChange should only fire when the query result changes
here is a small application, i placed a counter inside the event, and displayed it, it seem like it continuously fire even if i didnt add new rows, i tried some examples from some blogs, and i get the same results, what am i doing wrong?
i checked "sys.transmission_queue" and "sys.dm_qn_subscriptions" both were empty
the SqlNotificationEventArgs properties value are "Info = Invalid,Source = Statement,Type = Subscribe"
    private void Runnn()
    {
        var query = from x in Entities.Contacts select x;
        qqq.ItemsSource = query.ToList();
        con = new SqlConnection(@"server=PC\sqlexpress08;
             database=test2db;Trusted_Connection=yes;");
        command = new SqlCommand("SELECT ID,Name FROM dbo.Contacts",con);
        BeginSqlDependency(con.ConnectionString);

    }
    private void BeginSqlDependency(string connection)
    {
        SqlDependency.Stop(connection);
        SqlDependency.Start(connection);
        RegisterSqlDependency();
    }
    private void RegisterSqlDependency()
    {

        command.Notification = null;
        dependency = new SqlDependency(command);
        dependency.OnChange += new OnChangeEventHandler(DependencyOnChange);
        RegisterSqlCommand();
    }
    private void RegisterSqlCommand()
    {
        con.Open();
        command.ExecuteNonQuery();
        con.Close();
    }
    private void DependencyOnChange(object sender, SqlNotificationEventArgs e)
    {
        SqlDependency dependency = (SqlDependency)sender;
        dependency.OnChange -= DependencyOnChange;
        var query = from x in Entities.Contacts select x;
        Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, _
             new Action(() => { qqq.ItemsSource = null; qqq.ItemsSource =
             query.ToList(); ee.Text = i.ToString(); }));
        RegisterSqlDependency();
        i++;
    }
    ##SQL server Express SP2 2008##
    ALTER DATABASE test2db SET ENABLE_BROKER;
    CREATE QUEUE ContactChangeMessages;
    CREATE SERVICE ContactChangeNotifications
    ON QUEUE ContactChangeMessages
    ([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]);

A: Today I had exactly the same issue and for me the problem was relating to set options, note that you can see what is the error by putting a break point in  your DependencyOnChange event handler and watching the SqlNotificationEventArgs info property (see here for more details)
Registering a query for Query Notification requires the database connection on which the subscription is made to have the correct SET OPTIONS enabled:
ANSI_NULLS ON
ANSI_PADDING ON
ANSI_WARNINGS ON
CONCAT_NULL_YIELDS_NULL ON
QUOTED_IDENTIFIER ON
NUMERIC_ROUNDABORT OFF
ARITHABORT ON

and you turn ARITHABORT on in Sql Studio Management's database property dialog (see here for more details).
Also, consider the following steps if you want to enable service broker (Northwind is database name)
ALTER DATABASE Northwind SET enable_broker WITH ROLLBACK IMMEDIATE
ALTER DATABASE Northwind SET TRUSTWORTHY ON
ALTER AUTHORIZATION ON DATABASE::Northwind TO [sa]

A: Other things to consider that would cause SqlDependency to continuously fire:

*

*Using a query that is not specific (i.e. No wildcards "*", or DISTINCT usage).

*Not using a fully qualified table name (ex: SELECT Person FROM PersonTable vs. SELECT Person FROM dbo.PersonTable).


text:
Q: Handling property does not exist when using JavaScript libraries in TypeScript I'm using TypeScript for a Vue.js app and I'm trying to use the drop event to trigger uploading an image like this:
handleDOMEvents: {
    drop(view, event) {
        const hasFiles = event.dataTransfer
            && event.dataTransfer.files
            && event.dataTransfer.files.length;
        if (hasFiles) {
            upload(event.dataTransfer.files);
        }
    }
}

(The full guide I'm follow is: https://gist.github.com/slava-vishnyakov/16076dff1a77ddaca93c4bccd4ec4521)
The code works, but TypeScript is giving a warning on the .dataTransfer lines:

Property 'dataTransfer' does not exist on type 'Event'

The reason is that the event argument of the drop function is expecting an Event object, which doesn't have the dataTransfer property.
However, I would expect that drop() should always expect a DragEvent, but this is set in the external library so I don't have control over it.
How can I correctly handle this in TypeScript? Is is as simple as adding something like if (typeof(event) !== DragEvent)? Or is there a better way to get TypeScript to recognise this as a DragEvent? Is this just a case where it's best to ignore the warning?
I'm trying to understand what the best practice approach to handle this would be.

A: You have the right idea with if (typeof(event) !== DragEvent), except for the fact that TS types don't exist at runtime, so you can't check for them like that.
The way to do this is to create a custom type guard on the field event.type:
function isDragEvent(e: Event): e is DragEvent {
  return e.type === "drag";
}

You can then use it as a condition:
drop(view, event) {
    if(isDragEvent(event)){
        // TS recognizes that event is a DragEvent and has a dataTransfer member
        const hasFiles = event.dataTransfer
            && event.dataTransfer.files
            && event.dataTransfer.files.length;
        if (hasFiles) {
            upload(event.dataTransfer.files);
        }

    } else {
        throw new Error("the passed event is not a DragEvent")
    }
}


text:
Q: How to change props of TextInput component in a FlatList? I'm a newbie in React Native.
What I'm trying to do is making a Google Maps-like app. At the MainMap.js screen, when we enter,the screen will immediately generate 2 search bars. The first one will have the text "Your location". The second one and so on will be empty for users to type in for searching location.
But, I'm having some problems with the FlatList component. In my PlaceInput component, I use the defaultValue, as a prop, for the text input. And then in the MainMap.js, I will have a state which initially be set as "Your Location", then I'll change it to null when the FlatList starts rendering from the 2nd PlaceInput component.
Here's the MainMap.js*
import React from 'react';
import {
    TouchableWithoutFeedback,
    StyleSheet,
    Keyboard,
    PermissionsAndroid,
    Platform,
    View,
    Button,
    FlatList,
    Dimensions
} from 'react-native';

import PlaceInput from '../components/PlaceInput';

import axios from 'axios';
import PolyLine from '@mapbox/polyline';
import MapView, {Polyline, Marker} from 'react-native-maps';
import Geolocation from 'react-native-geolocation-service';

const INCREMENT = 1;
const HEIGHT = Dimensions.get('window').height;
const WIDTH = Dimensions.get('window').width;

class MainMap extends React.Component{

    constructor(props){
        super(props);

        this.state={

            _userLocationDisplayed: null,
            userLatitude: 0,
            userLongitude: 0,

            numOfInput:[0,1],
            counter: 1,
        };
    };
    componentDidMount(){
        this._requestUserLocation();
    };

    // Get user current location

    // Ask user permission for current location
    // Request the Directions API from Google
    // Get the formatted_address & name from Google Places API
    // Adding a search bar
    onAddSearch(){
        this.setState((state) => ({
            counter: state.counter + INCREMENT,
            numOfInput: [...state.numOfInput, state.counter],
        }));
    };

    onChangeSearchDisplay(){
        this.setState({
            _userLocationDisplayed: null
        })
    };

    render(){

            return(
                <TouchableWithoutFeedback onPress={this.hideKeyboard} >
                    <View style={styles.container} >
                        <View style={{height: HEIGHT/2.5 }}>
                            <FlatList
                                data={this.state.numOfInput}
                                keyExtractor={(item, index) => item}
                                renderItem={itemData => {
                                    return(
                                        <PlaceInput
                                            id={itemData.item}
                                            onDelete={this.onDeleteSearch}
                                            showDirectionOnMap={this.showDirectionOnMap}
                                            userLatitude={userLatitude}
                                            userLongitude={userLongitude}
                                            userLocationDisplayed={this.state._userLocationDisplayed}
                                        />
                                    )
                                }}
                            />
                        </View>
                    </View>
                </TouchableWithoutFeedback>
            )
        }

    }

//}

export default MainMap;

const styles = StyleSheet.create({
    container:{
        flex: 1
    },
    map:{
        ...StyleSheet.absoluteFillObject
    },
});

Here's the PlaceInput component
import React from 'react';
import {
    View,
    TextInput,
    StyleSheet,
    Text,
    Dimensions,
    TouchableOpacity,
    Keyboard,
} from 'react-native';
import axios from 'axios';
import _ from 'lodash'
import Icon from 'react-native-vector-icons/MaterialCommunityIcons'

const WIDTH = Dimensions.get('window').width;
const HEIGHT = Dimensions.get('window').height;

class PlaceInput extends React.Component{

    constructor(props){
        super(props);
        this.state={
            ...
        }
        ...
    }

    render() {
        // console.log(this.state);
        // Code for displaying the suggestions from the Google Place API
        // Don't care about it too much :)))
        const predictions = this.state.predictions.map(prediction => {
            const { id, structured_formatting, place_id } = prediction;
            return(
                <TouchableOpacity
                    key={id}
                    onPress={() => this.setDestination(structured_formatting.main_text, place_id)}
                >
                    <View style={styles.suggestion}>
                        <Text style={styles.mainText}>{structured_formatting.main_text}</Text>
                        <Text style={styles.secText}>{structured_formatting.secondary_text}</Text>
                    </View>
                </TouchableOpacity>
            );
        } )

        return (
            <View style={{flex: 1, flexDirection: 'column'}} key={this.props.id}>
                <View style={styles.buttonContainer}>
                    <View style={{flex: 1, alignItems: 'center'}}>
                            <Text style={{fontSize: 8}}>{'\u25A0'}</Text>
                    </View>
                    <View style={{flex: 4}}>
                        <TextInput
                            key={this.id}
                            autoCorrect={false}
                            autoCapitalize='none'
                            style={styles.inputStyle}
                            placeholder='Search your places'
                            onChangeText={(input) => {
                                this.setState({destinationInput: input});
                                this.getPlacesDebounced(input);
                            }}
                            value={this.state.destinationInput}

                            {/*What I'm trying here as mentioned*/}
                            defaultValue={this.props.userLocationDisplayed}

                        />
                    </View>
                    <View style={styles.rightCol}>
                            <TouchableOpacity onPress={() => this.props.onDelete(this.props.id)}>
                                <Icon name='delete' size={25} style={{alignSelf: 'center'}} />
                            </TouchableOpacity>
                    </View>

                </View>
                {predictions}
            </View>
        )
    }
}

const styles = StyleSheet.create({
    buttonContainer:{
        flexDirection: 'row',
        height: (HEIGHT - 690),
        width: (WIDTH-48),
        marginTop: 55,
        padding: 5,
        backgroundColor: 'white',
        shadowColor: '#000000',
        elevation: 7,
        shadowRadius: 5,
        shadowOpacity: 1,
        borderRadius: 5,
        alignItems: 'center',
        alignSelf:'center'
    },
    inputStyle:{
        fontFamily: 'sans-serif-thin',
        fontSize: 16,
        color: 'black',
        fontWeight: 'bold'
    },
    suggestion:{
        backgroundColor: 'white',
        padding: 10,
        borderWidth: 0.5,
        width: (WIDTH-48),
        alignSelf: 'center'
    },
    secText:{
        color: '#777'
    },
    mainText:{
        color: '#000'
    },
    rightCol:{
        flex: 1,
        borderLeftWidth: 1,
        borderColor: '#ededed',
    },
})

export default PlaceInput;

I'd love to hear your comments for helping me.
Also, feel free to give out other ways too since I think my way isn't optimized enough. And I'm building this for production too.

A: If I understand your question correctly, you're asking how to conditionally set a prop value based upon where it is in the flatlist data. Basically you want the first PlaceInput component to have a displayed "entered" text value of "Your Location" and the rest to have nothing.
Update API of PlaceInput to take in another prop to indicate displaying a default value or not.
PlaceInput.js
...
<TextInput
  key={this.id}
  autoCorrect={false}
  autoCapitalize='none'
  style={styles.inputStyle}
  placeholder='Search your places'
  onChangeText={(input) => {
    this.setState({destinationInput: input});
    this.getPlacesDebounced(input);
  }}
  value={this.state.destinationInput}
  defaultValue={this.props.displayDefaultValue ? this.props.defaultValue : null}
/>
...

And pass in whether or not any specific PlaceInput should display it or not. Since you want only the first to display and the rest to not, using the array index is a good place to start. Here we can leverage the fact that in javascript 0 is a falsey value, while all other numbers are truthy. Using !index then !0 is true  while !1, !2, etc, are all false.
MainMap.js
<FlatList
  data={this.state.numOfInput}
  keyExtractor={(item, index) => item}
  renderItem={({ index, item }) => {
    return(
      <PlaceInput
        id={item}
        defaultValue="Your Location"
        displayDefaultValue={!index} // index 0 is falsey, all others truthy
        onDelete={this.onDeleteSearch}
        showDirectionOnMap={this.showDirectionOnMap}
        userLatitude={userLatitude}
        userLongitude={userLongitude}
        userLocationDisplayed={this.state._userLocationDisplayed}
      />
    )
  }}
/>

A: I take advantage of Drew Reese's answer but It doesn't work
I found out why it doesn't work because of the value prop, whose value is set by this.state.destinationInput which is " " in the state in the constructor. I again use Drew's way in the value prop instead, and it works
                     <TextInput
                        key={this.id}
                        autoCorrect={false}
                        autoCapitalize='none'
                        style={styles.inputStyle}
                        placeholder='Search your places'
                        onChangeText={(input) => {
                            this.setState({destinationInput: input});
                            this.getPlacesDebounced(input);
                        }}
                        value={this.props.displayDefaultValue ? this.props.defaultValue : this.state.destinationInput}
                    />

BIG thanks to Drew Reese


text:
Q: Using Filter Method to Remove Item from Array I am new to React and I am trying to build a very basic timesheet tool, where users can add tasks into the application and save. I am using React as well as Typescript.
So far I have my main component that includes an empty array of tasks and the table. Then inside the table body I have mapped to pull the table rows and a separate component that includes the tags.
I am trying to add in a button to delete tasks using the filter method on the array to remove the index for the individual item, however nothing happens when I click, or I get an undefined error. Can someone please help? I am using the delete button and handle delete function below to achieve this
Main Component
import * as React from 'react';
import { ITimesheetToolProps } from './ITimesheetToolProps';
import { escape } from '@microsoft/sp-lodash-subset';
import TableRow from './TableRow';
import styles from './TimesheetTool.module.scss';

export default class TimesheetTool extends React.Component<ITimesheetToolProps, any> {
  state = {
    tasks: []
  }

  addTask = (task) => {
    const tasks = [...this.state.tasks];
    this.setState({tasks: this.state.tasks.concat(task)});
  }

  handleDelete = (index) => {
    const tasks = this.state.tasks.filter(t => t.index !== index);
    this.setState({ tasks });
  }

  public render(): React.ReactElement<ITimesheetToolProps, any> {
    return (

        <button onClick={(task) => this.addTask(task)}>Add Task</button>

              Project
              Task
              Monday
              Tuesday
              Wednesday
              Thursday
              Friday
              Saaturday
              Sunday

            {this.state.tasks.map((task, index) =>
<TableRow /><button onClick={() => this.handleDelete(index)}>Delete</button>
)}

    );
  }
}

A: Its hard to help without knowing the shape of the data, but i think this is what you're looking for, help me know if this helps
const tasks = this.state.tasks.filter((_, i) => i !== index);

The code works, why it is removing the last item in the array i don't know, you'll have to
//change <button onClick..../>
// to this.
<button onClick={handleDelete(index)}/>

//change handleDelete to this..
const handleDelete = (index) => () => this.setState({tasks: this.state.tasks.filter((_, i) => i !== index)

A: Use Splice.
 handleDelete = (index) => {
    this.setState({ tasks: this.state.tasks.splice(index,1);
 });
  }


text:
Q: Quality of bluetooth headsets as microphone I'm thinking about getting a bluetooth headset to use primarily as computer microphone. Question is: do they typically have good quality compared to traditional wireless microphones (or classic wired mics)? Are they good enough for speech recognition software? I don't need top quality, just something decent.
Also: can the battery hold a 2-hour recording session?

A: I have a Plantronics Calisto B70 Bluetooth headset that came with Dragon Naturally Speaking (Amazon.com: Dragon NaturallySpeaking Premium 11 Bluetooth).
If I try using sound recorder, I can hear some crackling noise as well as my voice, so I don't think the quality is great.
One time, I was able to get it working 99% accurately with DNS, but since then I haven't been able to repeat that accuracy.
The headset is worse in Windows Speech Recognition, perhaps because it isn't tuned for Bluetooth like DNS is.
For what it's worth, I tried doing a sound recording using a couple other pairs of analog wired headphones, and there was noise present on those too, so I'm thinking wired USB headphones would be the best, but can't confirm that.
UPDATE
I just bought the Plantronics 625 USB headset.
Training Dragon Naturally Speaking seems to be working better than with the B70 Bluetooth.
I also tried recording my voice as a way to compare them.  The B70 sounds OK, but has a small amount of hiss in the background and has a lower range of frequencies.  The 625 sounds much clearer and more natural.
Here's the recordings if you'd like to compare for yourself.

*

*USB

*Bluetooth
You could also have a look at the Dragon Naturally Speaking Hardware Compatibility List.

A: They won't have as good quality as normal mics since the audio data is compressed before transmission. They are, however, generally good enough for speech recognition. Two hours might be a bit too long for the cheaper ones, but it certainly is doable.


text:
Q: why ip address differs when wireless is off? public class Main {

    public static void main(String[] args) throws IOException {
        InetAddress myIp = null;

        try {
            myIp = InetAddress.getLocalHost();
        } catch (UnknownHostException ex) {
            System.out.println("Exception cought.");
            System.exit(0);
        }

        System.out.println(myIp);
    }

}

I have this simple question that why my ip address is different when my wireless is off?
it's still the same computer, so why does it change? (isn't this a unique number?)

A: The IP address of the computer depends on the network it's connected to (and indeed, the same machine may have more than one, if it has multiple adapers).
So if I connect my machine to one of my networks, it may have the address 192.168.10.7 whereas on another of my networks, it may be 192.168.17.12. It can vary between connections as well, although in practice they tend to be a bit sticky. (It depends on how the DHCP server is configured.)
Your adapter can be configured with a fixed address, but if you do that, it has to be an address the network it's connecting to has reserved for it. Otherwise it may not work at all ("No route to host") or may conflict with another machine using the network.

A: .An IP address is the address of a network adapter within a specific local network.
It will be different when connected to different networks.
When not connected to any network, it will either be a link-local address or an auto-configuration address.
You might want the MAC address, which is the hardware address of a single network adapter and is not very likely to change.

A: The provided code returns HOSTNAME/IP-Address(xx.xx.xx.xx).
Hostname is your computer name ex: MY-PC and then you get the IP corresponding to it.
When you are connected to a network, InetAddress.getLocalHost() asks the DHCP server in the network "what is the address of MY-PC (the name of your computer)", the DHCP replies -> 33.44.55.66
Try the following CMD commands when both connected and disconnected.
\>hostname
MY-PC
\>nslookup MY-PC
44.55.66.77

When you are not connected to a network there are two possibilities:

*

*You do not get a hostname (default is localhost)

*You do get a hostname, but there is no DHCP server on the network to return an IPaddress,
so you get loopback - 127.0.0.1

If you want to "call" your computer on the network locally, use the loopback http://www.pcmag.com/encyclopedia/term/57812/loopback-address
Hope this helps

A: No. You're confusing IP and MAC addresses. The MAC address is a serial number of hardware(but may be programatically changed on certain chipsets).
The IP address is either software-determined or determined by the network. It can differ between networks or even with time.

A: IP addresses are (usually) interface specific, not machine specific.
If your machine only has one interface the difference is moot, but it matters if (for example) you have both wired and wireless ethernet.
Also note that if you do have both and attempt to use them both at the same time on the same subnet that things will likely get very confused!


text:
Q: Broken page redirect I tried one plugin. It had settings page where I need to select page where I want to present plugin's content. I selected one of my pages - mywebsite.com/page1/ and tested how plugin works.
Then I decided to delete this plugin. And now if i open url mywebsite.com/page1/ - I got redirect to main page.
I tried manually change URL of this page and it works fine. But how can I get mywebsite.com/page1/ to use?

A: I found solution - I needed to run flush_rules() method at least once to clean cache.
//Ensure the $wp_rewrite global is loaded
global $wp_rewrite;
//Call flush_rules() as a method of the $wp_rewrite object
$wp_rewrite->flush_rules( false );