text:
Q: change or move the position of the popup react-leaflet My popup from the marker is overlapping, making it partially visible. I need to move the popup above.

Code:
<Marker
  draggable={draggable}
  eventHandlers={eventHandlers}
  position={position}
  ref={markerRef}
>
  <Popup>
    <span onClick={toggleDraggable}>
      {draggable && <Button>Click Here</Button>}
    </span>
  </Popup>
</Marker>

I also tried access the popup component, but that breaks the popup.
.leaflet-popup-content-wrapper {
    padding: 1px;
    text-align: left;
    border-radius: 12px;
    margin-bottom: 30px;
}

A: A hack to get around it:
.leaflet-popup {
    padding-bottom: 30px; /* adjust as you see fit */
}


text:
Q: How to replace UTF-8 to similar Latin letters in a String? I am having a String
s = M\\c3\\a4nager

I want to replace \\c3\\a4 with its equivalent Latin character ä
So the String should be
s = Mänager

I searched a lot how to do it in java please help me with the same
I want to handle all such UTF-8 characters in my code.

A: To unescape the LDAP string you could use following snippet
// import javax.naming.ldap.Rdn;
String escapedValue = "M\\c3\\a4nager";
Object unescapedValue = Rdn.unescapeValue(escapedValue);
System.out.println("escapedValue   = " + escapedValue);
System.out.println("unescapedValue = " + unescapedValue);

output
escapedValue   = M\c3\a4nager
unescapedValue = Mänager

unescapedValue contains the String as UTF-8. If you need another encoding you need to handle it properly.
Simple example to show the difference in bytes for different encodings.
byte[] latinBytes = ((String)unescapedValue).getBytes(StandardCharsets.ISO_8859_1);
byte[] utf8Bytes = ((String)unescapedValue).getBytes(StandardCharsets.UTF_8);

System.out.println("latin1: " + Arrays.toString(latinBytes));
System.out.println("utf8  : " + Arrays.toString(utf8Bytes));

output
latin1: [77, -28, 110, 97, 103, 101, 114]
utf8  : [77, -61, -92, 110, 97, 103, 101, 114]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Would Python make a good substitute for the Windows command-line/batch scripts? I've got some experience with Bash, which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using
the Windows command-line language. For some reason said language really irritates me, so I was considering learning Python and using that instead.
Is Python suitable for such things? Moving files around, creating scripts to do things like unzipping a backup and restoring a SQL database, etc.

A: Sure, python is a pretty good choice for those tasks (I'm sure many will recommend PowerShell instead).
Here is a fine introduction from that point of view:
http://www.redhatmagazine.com/2008/02/07/python-for-bash-scripters-a-well-kept-secret/
EDIT: About gnud's concern: http://www.portablepython.com/

A: Are you aware of PowerShell?

A: Anything is a good replacement for the Batch file system in windows.  Perl, Python, Powershell are all good choices.

A: @BKB definitely has a valid concern. Here's a couple links you'll want to check if you run into any issues that can't be solved with the standard library:

*

*Pywin32 is a package for working with low-level win32 APIs (advanced file system modifications, COM interfaces, etc.)

*Tim Golden's Python page: he maintains a WMI wrapper package that builds off of Pywin32, but be sure to also check out his "Win32 How Do I" page for details on how to accomplish typical Windows tasks in Python.

A: Python is certainly well suited to that. If you're going down that road, you might also want to investigate SCons which is a build system itself built with Python. The cool thing is the build scripts are actually full-blown Python scripts themselves, so you can do anything in the build script that you could otherwise do in Python. It makes make look pretty anemic in comparison.
Upon rereading your question, I should note that SCons is more suited to building software projects than to writing system maintenance scripts. But I wouldn't hesitate to recommend Python to you in any case.

A: Python is well suited for these tasks, and I would guess much easier to develop in and debug than Windows batch files.
The question is, I think, how easy and painless it is to ensure that all the computers that you have to run these scripts on, have Python installed.

A: As a follow up, after some experimentation the thing I've found Python most useful for is any situation involving text manipulation (yourStringHere.replace(), regexes for more complex stuff) or testing some basic concept really quickly, which it is excellent for.
For stuff like SQL DB restore scripts I find I still usually just resort to batch files, as it's usually either something short enough that it actually takes more Python code to make the appropriate system calls or I can reuse snippets of code from other people reducing the writing time to just enough to tweak existing code to fit my needs.
As an addendum I would highly recommend IPython as a great interactive shell complete with tab completion and easy docstring access.

A: Summary
Windows: no need to think, use Python.
Unix: quick or run-it-once scripts are for Bash, serious and/or long life time scripts are for Python.
The big talk
In a Windows environment, Python is definitely the best choice since cmd is crappy and PowerShell has not really settled yet. What's more Python can run on several platform so it's a better investment. Finally, Python has a huge set of library so you will almost never hit the "god-I-can't-do-that" wall. This is not true for cmd and PowerShell.
In a Linux environment, this is a bit different. A lot of one liners are shorter, faster, more efficient and often more readable in pure Bash. But if you know your quick and dirty script is going to stay around for a while or will need to be improved, go for Python since it's far easier to maintain and extend and you will be able to do most of the task you can do with GNU tools with the standard library. And if you can't, you can still call the command-line from a Python script.
And of course you can call Python from the shell using -c option:
python -c  "for line in open('/etc/fstab') : print line"

Some more literature about Python used for system administration tasks:

*

*The IBM lab point of view.

*A nice example to compare bash and python to script report.

*The basics.

*The must-have book.

A: Python, along with Pywin32, would be fine for Windows automation.  However, VBScript or JScript used with the Windows Scripting Host works just as well, and requires nothing additional to install.

A: I've done a decent amount of scripting in both Linux/Unix and Windows environments, in Python, Perl, batch files, Bash, etc. My advice is that if it's possible, install Cygwin and use Bash (it sounds from your description like installing a scripting language or env isn't a problem?). You'll be more comfortable with that since the transition is minimal.
If that's not an option, then here's my take. Batch files are very kludgy and limited, but make a lot of sense for simple tasks like 'copy some files' or 'restart this service'. Python will be cleaner, easier to maintain, and much more powerful. However, the downside is that either you end up calling external applications from Python with subprocess, popen or similar. Otherwise, you end up writing a bunch more code to do things that are comparatively simple in batch files, like copying a folder full of files. A lot of this depends on what your scripts are doing. Text/string processing is going to be much cleaner in Python, for example.
Lastly, it's probably not an attractive alternative, but you might also  consider VBScript as an alternative. I don't enjoy working with it as a language personally, but if portability is any kind of concern then it wins out by virtue of being available out of the box in any copy of Windows. Because of this I've found myself writing scripts that were unwieldy as batch files in VBScript instead, since I can't usually depend on Python or Perl or Bash being available on Windows.

A: I've been using a lot of Windows Script Files lately. More powerful than batch scripts, and since it uses Windows scripting, there's nothing to install.

A: As much as I love python, I don't think it a good choice to replace basic windows batch scripts.
I can't see see someone having to import modules like sys, os or getopt to do basic things you can do with shell like call a program, check environment variable or an argument.
Also, in my experience, goto is much easier to understand to most sysadmins than a function call.


text:
Q: Runing a "child" python file as regular user when main python file needs to be run as root I'm doing a python program (and using PyQt5 for GUI) that needs to be run as root (because I'm programming sockets on it). It has a button,when I click on it, it opens another python file (the "child" file: chrometest.py, it's based on this library, eel: https://www.youtube.com/watch?v=2kbeBzEQfXE, it lets me open a js file). The problem is that eel won't work when it's run as root, so I don't know how I could switch users to run only this function as regular user.
Main python program (sample, the one runing as root)
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class Window(QtWidgets.QMainWindow):
    def __init__(self, *args):
        super(Window, self).__init__()
        self.img = QtWidgets.QLabel()
        self.open_js= QtWidgets.QPushButton('Load')
        self.width = 400
        self.height = 150
        self.init_ui()

    def init_ui(self):
        self.img.setPixmap(QtGui.QPixmap("someimage.png"))
        self.open_js.clicked.connect(self.openjs)
        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)
        h_layout = QtWidgets.QHBoxLayout(central_widget)
        h_layout.addWidget(self.img)
        h_layout.addWidget(self.open_js)
        self.setWindowTitle('Main Window')
        self.setGeometry(600,150,self.width,self.height)

    def openjs(self):
        #here is where I think I need to switch to regular user
        exec(open("chrometest.py").read())

def main():
    app = QtWidgets.QApplication(sys.argv)
    main = Window()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

chrometest.py (program that needs to be run as regular user)
import eel
eel.init('webfiles')
eel.start('index.html')

I tried to use this tutorial https://www.tutorialspoint.com/python/os_chown.htm in the line commented but it didn't work

A: It is common in Unix-like systems to have a process that needs to be root at a time, for example to listen on ports below 1024, but then executes  as a regular non priviledges user for security reasons. Whatever the language the design is as follow:

*

*priviledged part (extensively tested for security flaws) executes only code requiring root privileges

*as soon as code that does not require root has to be executed it forks and

*

*parent remains priviledged and continue to run priviledged code

*child switch to a regular user (allowed because it is still at priviledged-root level) and executes normal code

That is what you should do here:
def openjs(self):
    pid = os.fork()
    if 0 == pid:
        os.setuid(uid_of_non_priviledged_user)
        # you can now safely execute code from chrometest.
    else:
        # optionaly wait for child:
        os.waitpid(pid, os.WEXITED)

A: oh yes!!.. you can able to run a child python file as a regular python file.but u need to add this line in your parent python file.
import os
os.system("python  chrometest.py")

by this line your parent python file can run your child python file.

A: Like Mani Kandan said, you can run process by os.system, but if you already working under root, it will be executed with same privileges.
You can run program under specified user using sudo -u or sudo --user argument like
sudo -u regular_user "python3 chrometest.py"
So, in Python it will look like:
import os
os.system('sudo -u regular_user python3 chrometest.py')

and about your TabError: inconsistent use of tabs and spaces in indentation error: change all tabs in your script to spaces or vice versa.


text:
Q: How correctly write Jest test for avoid act() warning? useEffect usually use Promises for update state.
This updates cause long warning in jest: Warning: An update to null inside a test was not wrapped in act(...).
How correctly write Jest Test for such case?
live example, Reproducible Example:
https://codesandbox.io/s/jest-test-for-useeffect-with-promises-spieq?file=/index.test.js
index.test.js
import React from "react";
import Hello from "./Hello";
import { create, act } from "react-test-renderer";

it("works", () => {
  let root;
  act(() => {
    root = create(<Hello />);
  });

  // console.log("From test:", );
  let repr = JSON.stringify(root.toJSON());
  expect(repr).toBe('{"type":"span","props":{},"children":["Hello! "]}');
});

Hello.js
import React, { useState, useEffect } from "react";

export default () => {
  const [count, setCount] = useState();

  useEffect(() => {
    Promise.resolve({}).then(() => setCount(4));
  }, []);

  return Hello! {count};
};

Upd 1:
the same result for one of propasal:

A: I would like to suggest you to use testing-library/react which could be use smoothly with jest and provide async methods
Your test would become something like:
import React from "react";
import Hello from "./Hello";
import { render } from '@testing-library/react';

it("works", () => {
   const { baseElement } = render(<Hello />);
   expect(baseElement).toBeTruthy();
});

EDIT: For sake of completeness, in your example you're trying to test whether or not an update in your component happened after an effect which is using a promise.
In order to waitFor something async you can use the method findBy (findBy methods are a combination of getBy queries and waitFor.)
import React from "react";
import Hello from "./Hello";
import { render, findByText } from "@testing-library/react";
import "@testing-library/jest-dom";

it("works", async () => {
  const { baseElement } = render(<Hello />);
  expect(await findByText(baseElement, "Hello! 4")).toBeVisible();
});

Let's me explain, import "@testing-library/jest-dom" allows you to use the the method toBeVisible
So, this test is rendering a component Hello and then it's waiting (with default value, 1000ms) inside the baseElement (which is the component itself) looking for the text "Hello! 4", then if found it will return the found element, which we are going to test whether is it visibile or not.

A: Looks like this sample works correct
import React from "react";
import Hello from "./Hello";
import { render, screen, waitFor } from "@testing-library/react";
import "@testing-library/jest-dom";

it("works", () => {
  render(<Hello />);
  return waitFor(() => screen.getByText("Hello! 4"));
  // expect(baseElement.toBeTruthy();
});


text:
Q: Ubuntu 18.04: List View for Icons on the Desktop I have a number of files cluttering my Desktop. I would like to view the files as a list (e.g., "delete" folder on right vs. grid layout of the same folder on the left). I prefer list view because it is much more compact, especially when file names are long. I have tried various gsettings (e.g., using folder manager to draw Desktop and making list view default), but these changes only affect nautilus, rather than icons on the Desktop. How do I get list view on the Desktop itself?

A: It appears support for this feature has/is being stripped away by Nautilus.
https://www.omgubuntu.co.uk/2018/01/gnome-desktop-icons-removed-3-28
Also tried the work-around by using Nemo to manage the desktop.
https://www.linuxuprising.com/2018/07/how-to-replace-nautilus-with-nemo-file.html
Was not successful in getting Nemo to manage the desktop, perhaps due to the following bug: https://bugs.launchpad.net/ubuntu/+source/nemo/+bug/1742193


text:
Q: Can we run flutter app wirelessly on iOS device? In Xcode I'm able to connect iOS device wirelessly but not in android studio. Can anyone know how to do in android studio if it is possible?

A: Not yet, but it will be implemented soon.
Take a look at this issue.


text:
Q: "org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration" Problem - AndroidStudio I get this error while running android studio.
I know it's a Gradle problem, and after a lot of Googling, I haven't found anything other than a solution to turn off Toggle Offline Mode.
Android Gradle Version is 7.1.3 and Gradle Version is 7.2.
org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
Help me, Please
Build.gradle(Module)
plugins {
    id 'com.android.application'
}

android {
    compileSdk 32

    defaultConfig {
        applicationId "com.example.graduationproject"
        minSdk 32
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

        configurations.all {
            resolutionStrategy { force 'androidx.work:work-runtime:2.6.0' }
        }
        multiDexEnabled true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8

    }

}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    implementation 'de.hdodenhof:circleimageview:3.1.0'
    implementation files('lib\\com.skt.Tmap_1.71.jar')
    implementation 'com.google.android.gms:play-services-maps:17.0.1'
    implementation 'com.google.android.libraries.places:places:1.0.0'
    implementation 'com.androidx.support:multidex:2.0.1'
    implementation 'com.getbase:floatingactionbutton:1.10.1'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
//    androidTestImplementation 'com.android.support.test:runner:1.0.1'
//    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

Build.gradle(Project)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.1.3' apply false
    id 'com.android.library' version '7.1.3' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


text:
Q: Comparing and printing elements in nested loops The program identifies if one of the elements in the string word is a consonant by looping though the word string, and then for each iteration though the word string, iterating though the consonants list and comparing if the current element in word string equals to the current element of consonant list.
If yes, the current element of the word string is a consonant and the consonant gets printed (not the index of the consonant, but the actual consonant, for e.g. "d".)
The problem is, I get this instead:
1
1

What am I doing wrong? Shouldn't the nested loops work so that the below loop iterates every element for each element in the above loop? That is, each index above makes the below loop iterate though each index?
That's the program:
word = "Hello"

consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z']

for character in range(len(word)):
    for char in range(len(consonants)):
        if consonants[char] == word[character]:
            consonant = word[character]
            print consonant

A: You are misreading the output. The character is the letter L lowercase, not the number 1.
In other words, your code is working as designed. The captital letter H is not in your consonants list, but the two lowercase letters l in Hello are.
Note that it'd be much more efficient to use a set for consonants here; you'd not have to loop over that whole list and just use in to test for membership. That works with lists too, but is much more efficient with a set. If you lowercase the word value you'd also be able to match the H.
Last but not least, you can loop over the word string directly rather than use range(len(word)) then use the generated index:
word = "Hello"
consonants = set('bcdfghjklmnpqrstvwxz')

for character in word.lower():
    if character in consonants:
        print character

Demo:
>>> word = "Hello"
>>> consonants = set('bcdfghjklmnpqrstvwxz')
>>> for character in word.lower():
...     if character in consonants:
...         print character
...
h
l
l


text:
Q: Try to modify the XML attribute value using XSLT. If there is similar type of elements In XML if there is similar type of elements present and I want to modify the one of the elements attribute value using XSLT.
These is the problem
<caption>
  <captionStrings>
    <add name="lion" providerName="xyx"/>
    <add name="tiger" providerName="yxy"/>
    <add name="dog" providerName="yxy"/>
  </captionStrings>
</caption>

The expected result will be
<caption>
  <captionStrings>
    <add name="lion" providerName="xyx"/>
    <add name="cat" providerName="yxy"/>
    <add name="dog" providerName="yxy"/>
  </captionStrings>
</caption>

And I try these approach.
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

<xsl:template match="caption/captionStrings/add/@name">
      <xsl:attribute name="{name()}">cat</xsl:attribute>
</xsl:template>

</xsl:stylesheet>

please help me with these

A: It is still not clear how to determine which attribute should be modified. Perhaps you are looking for:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="@name[.='tiger']">
    <xsl:attribute name="name">cat</xsl:attribute>
</xsl:template>

</xsl:stylesheet>

Or maybe it needs to be:
<xsl:template match="add[2]/@name">
    <xsl:attribute name="name">cat</xsl:attribute>
</xsl:template>

I don't think there are any other options that would produce the result you show (at least not reasonable ones).


text:
Q: Arduino WiFi101 ConnectSSL fails to connect Help!  I am trying to use the Arduino WiFi101 library to connect to an existing SSL server. For troubleshooting - I'm actually connecting to www.howsmyssl.com.  Whether I use the IP address or the host name, the connection fails every time.  The board I am using is the Adafruit Feather M0 Wifi. I used the Firmware Updater to upload the certificate for www.howsmyssl.com to the board. Here is the code:
#include <stdint.h>
#include <WiFi101.h>
#include <stdlib.h>

WiFiSSLClient client;

char ssid[] = "SciAv";
char pass[] = "FlyAcclaim";

void setup() {
    WiFi.setPins(8,7,4,2);
    while ( WiFi.begin(ssid, pass) != WL_CONNECTED) {
      Serial.println("Connecting to SciAv");
      delay(10000);
    }
    Serial.println("WiFi Connected");
    if (!client.connectSSL("www.howsmyssl.com",443)) {
      Serial.println("Connection Failed");
    }
    else {
      Serial.println("Connected");
    }
}

void loop() {
    if (client.connected()) {
      Serial.println("Connect to host");
    }
}

A: You verificate if the certificate upload succefully on the board? Because to connect a ssl connection the shield needs be loaded with the ssl certificate. You can try add this verification before the Wifi network connection:
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
}

Alternatively, you can try using method 'connect("www.howsmyssl.com",443)' instead of 'connectSSL..'. This is useful If you have a library that accepts only plain Client, but you want to force it to use SSL, keeping the same method names of the non SSL client.

A: I have the same problem with the NANO33 IoT board. I found that an SSL connect failed on a board with the latest microcode (revision 1.4.8), but worked on a board with back-level microcode (revision 1.2.3). Just swapping out the NANO33 board makes the problem show up or go away. Reflash the microcode to a working back-level version if you need an SSL internet connection, or wait for Arduino to fix their bug in the next microcode release. Arduino WiFiNINA library used was version 1.8.13.


text:
Q: Boundary and limit points Suppose that $\Omega \in \mathbb{R}^n$. Prove that if $\vec{x} \notin \Omega$ and $\vec{x}$ is a boundary point of $\Omega$, then $\vec{x}
$ is a limit point of $\Omega$.
My try:
$\vec{x}$ is a boundary point so there is a ball around it such that there are points in $\Omega$ and $\Omega^c$. We construct a sequence $\{\vec{x}_i\} \in $ the ball around $\vec{x}$ and it converges to $\vec{x}$ since the sequence is within the ball.
I can't think of a technical proof and I'm notconfidence on my answer since the logic seems wrong
ANy help thanks

A: Let $\{B_i\}$ be a sequence of shrinking open balls around $x$.
Since $x$ is a boundary point, every open ball around it contains a point in $\Omega$ (and a point in $\Omega^c$), in particular for each $i$ there is $x_i \in B_i$ such that $x_i \in \Omega$. Each $x_i$ is distinct from $x$ since $x$ is not in $\Omega$, hence $\{x_i\} \subset \Omega$ is a sequence in $\Omega$ converging to $x$ and distinct from $x$, i.e. $x$ is a limit point of $\Omega$.


text:
Q: parsing a file using fgets() There is probably more issues at hand, but for now my problem is that when I compile and run this like so:
cc -o parser parser.c
./parser

I expect it to open a particular file, read from it, and parse it. However, it seems to expect me to provide input and I have to Ctrl-C to kill it. Am I using fgets wrong? I tried getline() with the same results. I added the puts() to make sure it was reading what I expected and it does. Any help is appreciated.
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <limits.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {

    FILE    *fp;
    char    buf[1024];
    char    *tmp, *pattern, *dir;
    char    *skip, *p;
    char    *tok[5];
    char    **ap;
    size_t  sz = 0;
    ssize_t len;
    int i;
    int action = 0; // placeholder
    int fileinto = 1; // placeholder
    char    path[PATH_MAX] = "/home/edgar/.patfile";

    fp = fopen(path, "r");
    if (fp == NULL)
        fprintf(stderr, "fopen failed");
    while (fgets(buf, sizeof(buf), fp) != NULL) {
        buf[strcspn(buf, "\n")] = '\0';

        // skip comments
        for (skip = buf; *skip; ++skip) {
            if (*skip == '#') {
                *skip = '\0';
                break;
            }
        }
        // skip empty lines
        if (strlen(buf) == 0)
            continue;
        puts(buf); // debug only
        // make a copy
        tmp = strdup(buf);

        for (i = 0, ap = tok; ap < &tok[4] && (*ap = strsep(&tmp, " ")) != NULL; i++) {
            if (**ap != '\0')
                ap++;
        }

        while (i >= 0) {
           if(tok[i] == "match")
                pattern = tok[i + 1];
           if(tok[i] == "fileinto") {
                action = fileinto;
                dir = tok[i + 1];
           }
        }
   }
   free(tmp);
   fclose(fp);
   exit(0);
}


text:
Q: Core Data ordeal A few weeks ago, I decided to learn Core Data for my new project and apply it to my entire model. There was a steep learning curve, but eventually I got familiar with the stack and I'm now rather comfortable with at least the basic concepts and the few common pitfalls such as thread concurrency.
I have to say, the first few weeks after getting comfortable where pretty amazing. NSFetchedResultsController give you a good way to communicate between my model and my controllers. However the more I use Core Data, the more annoying it gets.
As a concrete example, my app fetches a few pieces of data from my server (the posts) which appear in a feed. Each post has an owner, of class User, which I also fetch from the server. Now, Core Data has been great for managing the realtionship between a post and a user. The relationship is updated automatically and getting the post's origin is as simple as calling post.owner. However, there are also inconveniences:
1.Core Data forces objects to the disk that I do not want forced to the disk. This is probably the main issue. With the posts, I do not want them to be forced to disk, and would rather make calls to the server again. Why? Because the more posts I store persistently, the more housekeeping there is to do. A post can be edited, deleted, flagged, etc... and keeping those posts locally means having to plan updates.
2.Having to constantly worry about concurrency of contexts, objects and the likes. I wrote an object factory that always returns objects on the right thread and the right context, but even then bugs occur here and there, which quickly becomes frustrating.
3.Decreased performance. Perhaps the least important one at this point, going from cached objects to Core Data has taken a (barely noticeable) toll on the performance of my application (most notably the feed).
So what are your recommendations regarding Core Data? Would you suggest a different approach to Core Data?
I was thinking of a hybrid caching + Core Data where I store the information I will actually use many times (such as users) persistently and then use the RAM for things like posts, or simply creating posts without an NSManagedContext. Input welcome!

A:
Core Data forces objects to the disk that I do not want forced to the disk.

It does no such thing. If you don't want to save your Post objects to the persistent store, don't put them in Core Data and don't make them managed objects. Your User object can have a posts property even if the Post object is not managed by Core Data. Managed objects can have properties of any type, not only to other managed objects.

Having to constantly worry about concurrency of contexts, objects and the likes.

Concurrency is complex no matter how you model your data. It's a fundamentally complex problem. You're encountering it with Core Data because you're using Core Data. If you use something else, you'll deal with it there.

Decreased performance.

"Product" menu --> "Analyze" and run Instruments to find out why. There's no reason this should happen, and you have the tools to discover what's actually going on.


text:
Q: Get day from date Laravel I got a date with format 'Y-m-d', and want to get the day from it. Like if I have 2021.01.01, I want for example Friday, or Thursday depending on what day it actually is. I already got the date stored as $date and I want the day stored as $day.
I've already tried this, without any error, and without anything happening:
$day = Carbon::createFromFormat('Y-m-d', $date)->format('1');
var_dump($day);

A: You can try this ,
$d=unixtojd(mktime(0,0,0,6,20,2007));
var_dump(cal_from_jd($d,CAL_GREGORIAN));

output :
    array (size=9)
  'date' => string '6/20/2007' (length=9)
  'month' => int 6
  'day' => int 20
  'year' => int 2007
  'dow' => int 3
  'abbrevdayname' => string 'Wed' (length=3)
  'dayname' => string 'Wednesday' (length=9)
  'abbrevmonth' => string 'Jun' (length=3)
  'monthname' => string 'June' (length=4)

And for your code , you just need to add your date like this
$d=unixtojd(mktime(0,0,0,month,days,year));
$calendar  = cal_from_jd($d,CAL_GREGORIAN);
var_dump($calendar['dayname']);

A: I've found another solution for you :
$timestamp = strtotime('2009-10-22');
$day = date('l', $timestamp);
echo $days;

output:
Thursday

A: It seems like you used a 1 (one) instead of an l (lowercase L). If you change that, it works fine.
$day = Carbon::createFromFormat('Y-m-d', $date)->format('l');
var_dump($day);

A: This works, you seem to be using 1 instead of l
$today = Carbon::now();
$dayName = $today->format('l');

A: When using Carbon, ->dayName is the obvious and more explicit way:
Carbon::createFromFormat('Y-m-d', $date)->dayName

It also allow you to have it in any language:
Carbon::createFromFormat('Y-m-d', $date)->locale('fr_FR')->dayName


text:
Q: Haskell print a return value (Yet Another Haskell Tutorial, askForWords) So I'm trying to print out a line of text to the terminal window using a returned value in a compiled code. The program looks like this:
module Main
    where

import System.IO

main = do
  askForWords

askForWords = do
  putStrLn "Pleas enter a word:"
  word <- getLine
  if word == ""
    then return []
    else do
      rest <- askForWords
      return (word ++ " " ++ rest)

When I run it in the GHCi it works fine
*Main> main
Pleas enter a word:
Hello
Pleas enter a word:
World
Pleas enter a word:

"Hello World "
*Main>

When I try to run the Unix executable file the program don't print the last string
% /Users/tobyone/Workspace/Haskell/yaht/Yaht ; exit;
Pleas enter a word:
Hello
Pleas enter a word:
World
Pleas enter a word:

[Process completed]

I have tried printing out askForWords in main with putStrLn but get the error
<interactive>:2:10: error:
    Couldn't match type 'IO [Char]' with '[Char]'
    ...
    ...

A: You aren't printing the output, you are only returning it. Your executable effectively ignores the return value of the main, which conventionally has type IO () to emphasize this.
module Main
    where

import System.IO

main = do
  result <- askForWords
  putStrLn result

askForWords = do
  putStrLn "Pleas enter a word:"
  word <- getLine
  if word == ""
    then return []
    else do
      rest <- askForWords
      return (word ++ " " ++ rest)
In GHCi (like REPLs in most languages), the value of an expression is printed to the terminal.
main could also be defined more simply as
main = askForWords >>= putStrLn


text:
Q: Using xfce4 with kwin on Ubuntu 16.04 I am running Ubuntu 16.04 on my laptop.  I recently installed xfce4 on it and have been using it for a while with everything working.  The other day i tried installing the kde window manager with the command sudo apt-get install kwin.  This installed the window manager in working order but i can't open the window manager settings when I right click the title bar of a window.  Every time I click it nothing happens.  I have looked on-line but haven't seen a solution.  Any advice would be appreciated, thank you.

A: You need to install kde-cli-tools:
sudo apt-get install kde-cli-tools


text:
Q: jQuery: Nested hover and click function to show and hide text For a project, I need the following:

*

*If you hover the first part of the text, the second part of the text should be visible. (Works so far.)

*If you unhover the first part of the text, the second part of the
text should be hidden. (Works so far.)

*If you click the first part of the text, the second part of the text should be visible, and should be still visible after unhovering. (Doesn't work.)

*If you click the first part of the text again, it should be like
before, with a hover-sensitive state. (Doesn't work.)
Here is my try:

// Works generally

$("div").mouseover(function() {
  $("p:nth-child(2)").css("display", "block");
});

$("div").mouseout(function() {
  $("p:nth-child(2)").css("display", "none");
});

// Doesn't work

$("div").click(function() {
  $("p:nth-child(2)").css("display", "block");
});

$("p:nth-child(1)").click(function() {
  $("p:nth-child(2)").css("display", "none");
});
p:nth-child(2) {
  display: none;
}

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.

Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos
    et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

I would be very, very thankful for help!

A: When you click the element (first part of the text), you should add a class like "locked" so when you hover out of the element you check that first (and not make it display: none if that's the case, otherwise you're setting display: none anyways, on mouseout.
Also, the description says you should "unlock" it when you click in the first part again, not the second one, if you do
$("p:nth-child(1)").click(function() {
  $("p:nth-child(2)").css("display", "none");
});

You are doing it when clicking in the second part instead.

A: This works:

$("div").mouseover(function() {
  $("p:nth-child(2)").toggleClass("hover");
});

$("div").mouseout(function() {
  $("p:nth-child(2)").toggleClass("hover");
});

$("p:nth-child(1)").click(function() {
  $("p:nth-child(2)").toggleClass("clicked");
});
p:nth-child(2) {
  display: none;
}

.hover {
  display: block !important;
}

.clicked {
  display: block !important;
}

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.

Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos
    et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

A: Hope that this is what you want.

// Works generally
var trackMouseClickDivTag = false;

$("div").mouseover(function() {
  $("p:nth-child(2)").css("display", "block");
});

$("div").mouseout(function() {
  if(trackMouseClickDivTag == false)
    $("p:nth-child(2)").css("display", "none");
  else
  $("p:nth-child(2)").css("display", "block");
});

$("div").click(function() {
  $("p:nth-child(2)").css("display", "block");
  trackMouseClickDivTag = (trackMouseClickDivTag == false) ? true : false;
});

$("p:nth-child(1)").click(function() {
  $("p:nth-child(2)").css("display", "none");
});
p:nth-child(2) {
  display: none;
}

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.

Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos
    et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.


text:
Q: If condition check in linq Below are the linq query. Here I want to add one condition .
Condition : If : Firstname is not empty then select list
                 where  (d=>d.firstname=="Firstname")
            else: select all list without condition
function Ponits(string Firstname)
{

     pointsCore.Categories.SelectMany(c => c.Events).Select(e => new
     {
            e.Firstname,
            e.Surname,
            e.EntityNumber,
            e.Eventdate
     }).ToList()
}

A: Two options:
First, optionally use Where:
var events = pointsCore.Categories.SelectMany(c => c.Events);
if (!string.IsNullOrEmpty(firstName))
{
    events = events.Where(e => e.Firstname == firstName);
}
var result = events.Select(e => new { ... });

Second: make your Where clause check firstName:
var events = pointsCore.Categories.SelectMany(c => c.Events);
                       .Where(e => string.IsNullOrEmpty(firstName) ||
                                   e.Firstname == firstName)
                       .Select(e => new { ... });

Note that due to the lazy evaluation in LINQ, the first option won't involve fetching all the values and then querying; you're still just building up a query.

A: .Where(d => string.IsNullOrEmpty(Firstname) || d.firstname==Firstname)


text:
Q: I am Getting this error on an online judge~ I am getting this error on an online judge:
no matching function for call to 'find(std::vector<char>::iterator, std::vector<char>::iterator, __gnu_cxx::__alloc_traits<std::allocator<char> >::value_type&)'
      it=find(s.begin(),s.end(),words[i]);

What is my mistake?
This is my code-
  #include<iostream>
  using namespace std;
  #include<vector>

  int main()
  {
      string guest,host,words;
      cin>>guest>>host>>words;
      vector<char>s;
      vector<char>::iterator it;
      for(int i=0;i<guest.length();i++)
      {
        s.push_back(guest[i]);
      }
      for(int i=0;i<host.length();i++)
      {
        s.push_back(host[i]);
      }

      for(int i=0;i<words.length();i++)
      {
        it=find(s.begin(),s.end(),words[i]);

        if(it!=s.end())
        {
          s.erase(it);
        }
        else{

           cout<<"NO";
           return 0;
        }
      }
      cout<<"YES";
      return 0;
  }


text:
Q: Time is come or Time has come I was reading an article in The Economist and came across the phrase "Perhaps their time is come at last."

The founder of the first vegan society said in 1944 that "in time [people] will view with abhorrence the idea that men once fed on the products of animals' bodies." Many since have shared his hope. Perhaps their time is come at last.

I googled it but couldn't find any satisfactory reason as to why the author should use "Time is come" instead of "Time has come". Any ideas?

A: It's an archaic expression, probably sourced from 1 Peter 4:17:

For the time is come that judgment must begin at the house of God: and
  if it first begin at us, what shall the end be of them that obey not
  the gospel of God?

At least one source claims that the difference between "time is come" and "time has come" is that the former always means that someone is about to die, while the latter can mean other things too.


text:
Q: $((x+2)^2 - (x+1)^2) - ((x+1)^2-x^2) = 2$ Is this proof valid for this identity? Claim:
$$((x+2)^2 - (x+1)^2) - ((x+1)^2-x^2) = 2$$
Proof:
$$x \times x = x^2$$
$$(x+1) \times x = x^2 +x$$
$$(x+1) \times (x+1) = x^2 + x + (x+1)$$
$$(x+1)^2 = x^2 + 2x + 1$$
As we know, $2x+1$, is the definition of an odd number, since an odd number is always one more than a multiple of $2$.
$$(x+1)^2 - x^2 = 2x+1$$
The difference between two consecutive odd numbers will always be $2$, like e.g. $3-1 =2$, $5-3 = 2$, $7-5 = 2$, and so on.
Therefore:
$$((x+2)^2 - (x+1)^2) - ((x+1)^2-x^2) = 2$$
Is this proof valid? Also, have you ever seen this proof before? Has the same identity been proven in a different, better way?

A: Let's evaulate
$$((x+2)^2 - (x+1)^2) - ((x+1)^2-x^2) $$
using the difference of $2$ squares factorisation:
$$((x+2)^2 - (x+1)^2) - ((x+1)^2-x^2) =(x+2+x+1)(x+2-x-1)-(x+1+x)(x+1-x)$$
$$=(2x+3)-(2x+1)=3-1=2$$
as required.


text:
Q: python login form vulnerability?
<TITLE>Login Page</TITLE>

<FORM method="POST" action="http://yourserver/cgi-bin/login.py">
<paragraph> Enter your login name: <input type="text" name="login">
<paragraph> Enter your password: <input type=password name="password">
<paragraph> <input type="submit" value="Connect">
</FORM>

</form>

login.py:
#!/usr/local/bin/python
import cgi

def header(title):
   print "Content-type: text/html\n"
   print "\n\n<TITLE>%s</TITLE>\n\n\n" % (title)

def footer():
   print ""

form = cgi.FieldStorage()
password = "python"

if not form:
   header("Login Response")
elif form.has_key("login") and form["login"].value != "" and form.has_key("password")       and form["password"].value == password:
header("Connected ..." )
   print "

Welcome back," , form["login"].value, ".

"
   print r"""<form><input type="hidden" name="session" value="%s"></form>""" % (form["login"].value)
   print "
Click here to start browsing
"

else:
   header("No success!")
   print "
Please go back and enter a valid login.
"

footer()

I would like to make this login form vulnerable to RCE (remote code execution), is this possible with the function eval() or exec().
I am looking for functions that introduce a vulnerability within the login form. Are there whole classes/modules that contain dangerous functionally? Also would it be possible to make this login form vulnerable to remote code execution?

A:
I would like to make this login form vulnerable to RCE ( remote code execution), is this possible with the function eval() or exec()?

Yes. If you pass unchecked user input to either of those functions then you are allowing remote code execution.

I am looking for functions that introduce a vulnerability within the login form.I am particularly interested in Remote Code Execution vulnerabilities. Are there whole classes/modules that contain dangerous functionally?

Yes. Python can open files/delete files/connect to databases/etc. So yes there is plenty of bad things that could happen if you can execute arbitrary code.

Also would it be possible to make this login form vulnerable to remote code execution?

Yes. See above.


text:
Q: Improving text drawing performance through caching I am currently developing a 2d graphic engine for a game using the canvas element. In this engine, various sprites have text labels which follow them around. I did some profiling to improve performance and noticed that the largest FPS-eater in this engine are my calls to context.fillText and contex.drawText for drawing these text labels on every frame. I can understand that this is a performance-hook, because rasterizing vector-based TTF fonts isn't a trivial task. So I am searching for a way to improve this through caching the rendered texts.
What I tried
I though that to speed this up I could draw each text labels once, cache the result, and draw these cached results instead. So I tried to draw each text label to an invisible canvas the first time it is needed. But in order to do so I need to know the width and height of the rendered text so that I can create a background canvas with the appropriate size. I tried to get this with context.measureText, but unfortunately many browsers don't implement it fully (Firefox returns only the width, not the height or anything else).
Another thing I tried was to let the browsers HTML rendering engine handle the text caching. So instead of drawing the text labels with the canvas, I created HTML <span> elements with position:absolute, added them to the <div> the canvas is in, and moved these around every frame so that they were always where they needed to be. This sort of worked performance-wise, but it cause a whole bunch of other problems. Some can be worked around (text labels catching click events, text being drawn outside of the canvas) but others aren't fixable that easily (canvas being unable to draw over text). So I discarded this solution.
Do you have any ideas what else I could do?

A: For caching the text, you can use a HTML element with visibility: hidden but not display: none (so that it sizes out to accommodate the contents) - measure out its computed width and height and use that to size your cache-source canvas. For your HTML element, specify the same font (using @font-face) and size etc.
You may want to do this after ensuring that the font specified in your @font-face declaration has loaded completely. $(document).ready(..) will not work reliably. It should be safe to do this inside $(window).load(..) which is fired only after everything including content and resources are loaded.

A: You should be able to offline the text rendering inside a setTimeout(...) effectively letting the rest of the rendering continue smoothly.


text:
Q: Accessing python classes not imported in __init__ I'm aiming to patch the python multiprocessing library to use their undocumented class ThreadPool instead of Pool.  My current solution is just to
from multiprocessing.pool import ThreadPool
import multiprocessing
multiprocessing.Pool = ThreadPool

this works fine, but the import statement I have to use to get the ThreadPool class is a bit weird, since it's defined in pool.py and never imported in __init__.py.
Say I had access to the multiprocessing module object. How would I access anything in multiprocessing.pool? I'm not certain it's possible without using __file__ and importing the path.


text:
Q: javascript/typescript - es-lint import/no-unresolved is not working for ts files I'm working on a project that uses the same code base for various brands. Some imports are done dynamically and are managed by webpack.
We use javascript in one part of the code and typescript in another part.
So we use something like the code below to do the dynamic imports:
import { comp } ../brand/../..

As this import is not found, the es-lint shows the error: Unable to resolve path to module ...
To solve this problem we can do something as simple as 'import/no-unresolved': [2, { ignore: ['brand'] }] on eslintrc file.
This solves the issue for JS files but it doesn't solve for TS files.
We have already installed
    "eslint": "7.16.0",
    "eslint-plugin-import": "2.22.1",
    "@types/react": "17.0.14",
    "@typescript-eslint/eslint-plugin": "4.28.4",
    "@typescript-eslint/parser": "4.28.4",
    "babel-eslint": "10.1.0",
    "eslint-plugin-jsx-a11y": "6.4.1",
    "eslint-plugin-react": "7.24.0",
    "eslint-plugin-react-hooks": "4.2.0"

Any idea how to solve that for TS files ?


text:
Q: Can I upgrade my laptop to 8GB of RAM? I have an old laptop which I'm trying to upgrade. It's an Acer Aspire 5253 with 32-bit architecture. I am a little confused about how much RAM I can add.
On one side, I've read that 32 bit systems will only support up to 4GB of RAM. But on the other side, if a tipe my motherboard model on Crucial, which is P5wx6, it says that it's compatible with up to 8GB of RAM.
So, what's the catch here? Can I upgrade it to 8GB RAM or not?
Thanks in advance!

A: The memory is expandable to 8 GB.  Please see this Acer post below:
https://us.answers.acer.com/app/answers/detail/a_id/15801/~/how-do-i-replace-the-ram-memory-on-my-acer-aspire-5253-series-notebook%3F
Your 32-bit OS only uses 3GB  (32-bit limit), so adding memory will not be used or help. You would need to freshly install a 64-bit operating system


text:
Q: I need a library and some tips to process a few DXF files I need to help a friend with automating a task and find myself in need of some information.
Basically there are a bunch of DWG files i need to process and i would rather do it by coding than by hand.
All the files contain are shapes that are to be fed into a kind of plotter but the problem is that the lines come out interrupted at intervals and the plotter can't do it's job.
I need to know if there are any ways to hack the image files to make the lines continuous.
I have experience in Python, C# , C and some knowledge of a sum of other programming languages but i have almost no knowledge at all about image processing. I would really appreciate any help you guys can provide.
Thanks in advance

A: There are a few libraries for reading/writing DXF/DWG files, one of them is CadLib, feel free to try it out. The Open Design Alliance also has libraries (in C++, they also have .NET wrappers).


text:
Q: Cargar enlace en un div al presionar botón Necesito que al presionar el botón "Generar" me cargue un enlace en el div "Certificado".

Generar Certificado

    <form action="#">

          Dirigido a:
          <input type="text" class="form-control" name="dirigido" id="dirigido" placeholder="Ingrese un valor">

          Cedula:
          <input type="password" class="form-control" name="cc" id="cc" placeholder="Ingrese Cedula">

        <input type="submit" value="Generar" name="Generar" class="btn btn-sm" style="color: white; background: #006050;">
    </form>

A: Por lo que dices en la pregunta y en los comentarios, la URL a la cual consultar se genera por medio de la cédula (cc) tomando como base una URL cualquiera que, supongo por motivos de seguridad, no puede ser mostrada aquí.

Se asume que el contenido a obtener está en el mismo dominio. En caso contrario, se debe verificar las reglas CORS en el servidor destino.

Sabiendo esto, lo único que debes hacer es hacer una petición AJAX a dicha URL para descargar el HTML:
$('form').on('submit', function (e) {
  e.preventDefault();

  let cc = $(this).find('#cc').val();
  $('.container').load(BASE_URL + '?cc=' + cc);
});

Si dicha petición te devuelce contenido dinámico, es mejor usar un object o iframe para cargar dicha URL directamente en el documento. Por ejemplo:
HTML
<obejct data="" type="text/html" id="certificado"></object>

JavaScript
$('form').on('submit', function (e) {
  e.preventDefault();

  let cc = $(this).find('#cc').val();
  $('certfificado').attr('data', BASE_URL + '?cc=' + cc);
});

La URL es externa y no puedo consumirla desde el cliente. ¿Qué puedo hacer?

En ese caso, te basta descargar el HTML en el servidor en lugar del cliente:
// archivo get_external_html.php
<?php echo file_get_contents($_GET['url']); ?>

Y la petición AJAX debe hacerse a este archivo.
$('.container').load('//get_external_html.php?url=http://externo.com?cc=' + cc);

O embebido:
<object data="'//get_external_html.php?url=http://externo.com?cc=af7s5f5w" type="text/html"></object>

A: Primero modificaría unas cuantas cosa a tu formulario

*

*Quite el action="#" solo para evitar refrescar la pagina al enviar el form.

*Cambie el input por un button y quite el tipo submit ya que no vamos a actualizar la pagina ni refrescarla.

<form name="Certificado">

    Dirigido a:
    <input type="text" class="form-control" name="dirigido" id="dirigido" placeholder="Ingrese un valor">

    Cedula:
    <input type="password" class="form-control" name="cc" id="cc" placeholder="Ingrese Cedula">

  <button name="Generar" class="btn btn-sm" style="color: white; background: #006050;">Generar</button>
</form>

yo haria el submit com la función click con jQuery
$('button[name="Generar"]').on('click', function(){
  //serializamos el formulario el cual el formato a serializar seria
  //dirigido=embajada&cc=123456
  var datos = $('form[name="Certificado"]').serialize();
  //hacemos la peticion ajax para enviar la informacion del formulario y mostrar los datos en el div
  $.ajax({
    type: 'POST',
    url: 'url/destino',
    data: datos,
    success: function (data) {
      //mostrando que recibe data
      console.log(data)
      //mostrando los datos en el div si recibe un html
      $('.container').html(data);
    },
    error: function(objXMLHttpRequest){
      //mostrando el error
      alert("error" );
    }
  });
});

A: Crea una funcion 'Onclick' y llena el registro que necesitas o crea una función en JQuery que verifique cuando sea un evento de submit en ese momento realiza la función que necesitas

A: Utilizando la función .load() vas a poder cargar lo que este en otra página y ponerla donde desees
function cargaContenido() {
  $('#container').load('documento.php');
}

<input type="submit" value="Generar" name="Generar" ... onclick='cargaContenido()'>


text:
Q: Android Layout transparent layout background with underline I am trying to have a layout background drawable, which will be only gradient underline with 1-2 dp height and rest is transparent, so the upper part will have the parent's background.
Here is what I have.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android>

<!-- underline color -->
<item>
    <shape>
        <gradient
            android:startColor="@color/colorPrimaryDark"
            android:endColor="#FFFFFFFF"
            android:centerY="0.5"
            android:angle="0"/>

    </shape>
</item>

<!-- main color -->
<item android:bottom="2.5dp">
    <shape android:shape="rectangle">
        <solid android:color="@color/white" />
        <padding
            android:top="4dp"
            android:bottom="4dp" />
    </shape>
</item>

If I change the solid color in "main color" to transparent, whole background will be using "underline color" settings.

A: The technique you use to create a line on the bottom of the view works if the color of the layer overlaying the gradient layer is opaque. What you are trying to do is to apply a transparent layer that replaces (erases) the underlying gradient. That is not how it works: A transparent overlay leaves the underlying color, here a gradient, untouched.
Here is an alternate layer-list drawable that you can use for API 23+:
underline_drawable.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:gravity="bottom">
        <shape>
            <size android:height="2dp" />
            <gradient
                android:angle="0"
                android:centerY="0.5"
                android:endColor="#FFFFFFFF"
                android:startColor="@color/colorPrimaryDark" />
        </shape>
    </item>
</layer-list>

Here is what it looks like:

Prior to API 23, you can use the following custom drawable, but it must be set in code.
GradientUnderline.java
public class GradientUnderline extends Drawable {
    private Shader mShader;
    private final Paint mPaint;
    private int mHeight = -1;
    private int mStartColor = Color.BLACK;
    private int mEndColor = Color.WHITE;
    private int mLastWidth;

    public GradientUnderline() {
        mPaint = new Paint();
    }

    public GradientUnderline(int lineHeight, int startColor, int endColor) {
        mPaint = new Paint();
        mHeight = lineHeight;
        mStartColor = startColor;
        mEndColor = endColor;
    }

    @Override
    public void draw(@NonNull Canvas canvas) {
        if (mShader == null || getBounds().width() != mLastWidth) {
            mLastWidth = getBounds().width();
            mShader = new LinearGradient(0, 0, getBounds().width(), mHeight, mStartColor,
                                         mEndColor, Shader.TileMode.CLAMP);
            mPaint.setShader(mShader);
        }
        canvas.drawRect(0, getBounds().height() - mHeight, getBounds().width(),
                        getBounds().height(), mPaint);
    }

    @Override
    public void setAlpha(int alpha) {

    }

    @Override
    public void setColorFilter(@Nullable ColorFilter colorFilter) {

    }

    @Override
    public int getOpacity() {
        return PixelFormat.OPAQUE;
    }
}

I missed the availability of android:gravity initially because it is not mentioned on the "Drawable Resources" page. It is mentioned, however, in the LayerDrawable documentation.

A:
Why problem occurs: Shape at first item will draw the gradient in entire region. After setting colour to second item will hide the top item region except ay 2.5dp at bottom. So whenever you set transparent colour to second item it automatically show the top level item that is gradient region..

Here i suggest the way to use but you can set to fixed height in view.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="47dp">
<shape>
<gradient
    android:startColor="@color/colorPrimaryDark"
    android:endColor="#FFFFFFFF"
    android:centerY="0.5"
    android:angle="0"/>

</shape>
</item>

</layer-list>

View.xml
 <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="@drawable/bottom_line">

</RelativeLayout>

Change size according to your needs..!
OUTPUT


text:
Q: Locate encfs rootdir If a rootdir is mounted by encfs to a mount point, I can see the mount point by "mount" command or from the /proc/mounts.
However, if I can get the mount point, but I don't know which rootdir I have mounted, how do I locate that encrypted directory?

A: You can check the running encfs commands to match mount points with underlying directories. Using Linux's ps syntax:
ps ww -C encfs -o cmd=

Using POSIX ps syntax:
COLUMNS=999999999 ps -o args= | grep -E '^([^ ]*/)?encfs'

This is somewhat awkward to parse automatically. If you keep your directory names free of whitespace and put options before operands, you can use (with Linux syntax):
ps ww -C encfs -o cmd= | awk -v m='/path/to/mount/point' '$NF == m {print $(NF-1)}'


text:
Q: i am getting error while using nodemailer here's my UserController.js where i am receiving user email and password as a post request

const User = require('../models/User');
const nodemailer = require('nodemailer');

module.exports.User = (req, res) => {
     if(req.body.password != req.body.confirm_password){
            res.redirect('back')
        }

    User.findOne({email: req.body.email}, function(err, user){
        //error in creating the user
        if(err){console.log('error in creating the user');}

        //if user doesnot initially exist in the daatbase
        if(!user){
            User.create(req.body, function(err, user){
                if(err){console.log('error');}
                console.log('User created');
            })
            return res.send('<script>alert("User created")</script>');
        }
        else{
            console.log('User already present in the database');
            let mailTransporter = nodemailer.createTransport({
                service: 'gmail',
                host: 'smtp.gmail.com',
                auth: {
                    email: 'my_email',
                    pass: 'my_email_password'
                }
            });

            let mailDetails = {
                from: 'my_email',
                to: req.body.email,
                subject: 'from dhruv singhal as a project',
                text: 'your data is successfully stored on our database'
            };

            mailTransporter.sendMail(mailDetails, function(err, data) {
                if(err) {
                    console.log(err);
                } else {
                    console.log('Email sent successfully');
                }
            });
            res.send('<script>alert("your have already got mail from our side")</script>')
        }
    })
}

i am getting error as :-

/* Error: Missing credentials for "PLAIN"
at SMTPConnection._formatError (C:\Users\dhruv singhal\Desktop\web_development_project\node_modules\nodemailer\lib\smtp-connection\index.js:774:19)
at SMTPConnection.login (C:\Users\dhruv singhal\Desktop\web_development_project\node_modules\nodemailer\lib\smtp-connection\index.js:438:38)
at C:\Users\dhruv singhal\Desktop\web_development_project\node_modules\nodemailer\lib\smtp-transport\index.js:271:32
at SMTPConnection. (C:\Users\dhruv singhal\Desktop\web_development_project\node_modules\nodemailer\lib\smtp-connection\index.js:209:17)
at Object.onceWrapper (events.js:421:28)
at SMTPConnection.emit (events.js:315:20)
at SMTPConnection._actionEHLO (C:\Usenter code hereers\dhruv singhal\Desktop\web_development_project\node_modules\nodemailer\lib\smtp-connection\index.js:1303:14)
at SMTPConnection._processResponse (C:\Users\dhruv singhal\Desktop\web_development_project\node_modules\nodemailer\lib\smtp-connection\index.js:932:20)
at SMTPConnection._onData (C:\Users\dhruv singhal\Desktop\web_development_project\node_modules\nodemailer\lib\smtp-connection\index.js:739:14)
at TLSSocket.SMTPConnection._onSocketData (C:\Users\dhruv singhal\Desktop\web_development_project\node_modules\nodemailer\lib\smtp-connection\index.js:189:44)
at TLSSocket.emit (events.js:315:20)
at addChunk (_stream_readable.js:295:12)
at readableAddChunk (_stream_readable.js:271:9)
at TLSSocket.Readable.push (_stream_readable.js:212:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:186:23) {
code: 'EAUTH',
command: 'API'
}
i have enabled less secure apps on google please help

complete github code :-https://github.com/dhruv354/form.git*/

A: Have you done the "Captcha Challenge" on top of enabling the less secure app?
https://accounts.google.com/b/0/displayunlockcaptcha

A: Instead of email: 'my_email' I believe you need user: 'my_email'. See this nodemailer example.
As mentioned in the other answer: before sending from your app for the first time, click this from the relevant Google account: https://accounts.google.com/DisplayUnlockCaptcha


text:
Q: decode base64 utf-8 string java I have this string
"=?UTF-8?B?VGLNBGNDQA==?="

to decode in a standard java String.
I wrote this quick and dirty main to get the String, but I'm having troubles
String s = "=?UTF-8?B?VGLNBGNDQA==?=";
s = s.split("=\\?UTF-8\\?B\\?")[1].split("\\?=")[0];
System.out.println(s);
byte[] decoded = Base64.getDecoder().decode(s);
String x = new String(decoded, "UTF8");
System.out.println(decoded);
System.out.println(x);

It is actually printing a strange string
"Tb�cC@"

I do not know what is the text behind the encoded string, but I can assume my program works, since I can convert without problems any other encoded string, for example
"=?UTF-8?B?SGlfR3V5cyE="

That is "Hi_Guys!".
Should I assume that string is malformed?


text:
Q: Share info Between Discord.py Commands I'm making a Discord Bot that will kick and ban users, then log the information to a #mod-log channel automatically. This is working fine as I have specified the #mod-log channel ID for my testing server. But if my bot is in a different server, I want the moderators of that server to set their own #mod-log channel. I've written the following command:

@commands.command(pass_context=True)
@commands.has_permissions(kick_members=True)
async def setmodlog(self,ctx,mlog:discord.Channel):
    """Sets mod-log channel"""
    await self.bot.say("Mod Log channel set")

I want that "mlog" variable to carry over to my kick/ban commands so it will log to the channel specified by the moderator. However, that is not working. The "mlog" variable doesn't carry over. Is there a way to do this?

A: You should keep a dictionary of server IDs to channel IDs.  Update that dictionary when setmodlog is called and check it for your other commands
modlog = {}

async def on_ready(self):
    global modlog
    try:
        with open('modlog.json') as f:
            modlog = json.load(f)
    except:
        modlog = {}

@commands.command(pass_context=True)
@commands.has_permissions(kick_members=True)
async def setmodlog(self,ctx,mlog:discord.Channel):
    """Sets mod-log channel"""
    modlog[ctx.message.server.id] = mlog.id
    await self.bot.say("Mod Log channel set")
    with open('modlog.json', 'w+') as f:
        json.dump(modlog, f)

@commands.command(pass_context=True)
@commands.has_permissions(kick_members=True)
async def kick(self, ctx, member: discord.Member):
    server = ctx.message.server
    author = ctx.message.author
    message = "{} kicked {}".format(author.name, member.name)
    await bot.kick(member)
    channel = modlog[server.id]
    await bot.send_message(server.get_channel(channel), message)


text:
Q: How can I debug a port/connectivity issue? I am running a simple WebSocket server on Amazon EC2 (Fedora Core). I've opened the relevant port using ec2-authorize, and checked that it's opened. Iptables is definitely not running. However I can't connect to the port from outside EC2.
I've tried the following (my server is running on port 7000):
telnet ec2-public-dns.xx.xx.xx.amazon.com 7000

(from within EC2: connects fine)
nmap localhost

(output includes line: 7000/tcp open  afs3-fileserver)
telnet ec2-public-dns.xx.xx.xx.amazon.com 7000

(this time from my local machine: I get "connection refused: Unable to connect to remote host")
The strange thing is this: if I start Nginx on port 7000 then it works and I can connect from outside EC2! And the WebSocket server fails on port 80, where Nginx works fine.
To me this suggests a problem with the WebSocket server, BUT I can connect to it successfully from within EC2. (And it works fine on a different VPS account).
How can I debug this further? If anybody can stop me tearing my hair out, I'd be very grateful indeed :)

A: is it possible that your service listens only on loopback interface?
on your amazon box run
netstat -lanp|grep LISTEN|grep 7000

you expect to have something like:
tcp        0      0 0.0.0.0:7000              0.0.0.0:*               LISTEN      2216/abc

rather than
tcp        0      0 127.0.0.1:7000          0.0.0.0:*               LISTEN      13798/abc


text:
Q: scrbook: Roman page numbers in TOC are wider than textwidth? Consider the following Minimum Working Example (MWE):
\documentclass{scrbook}

\begin{document}

\pagenumbering{Roman}%
\tableofcontents

\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}

\pagenumbering{arabic}%

\chapter{Arabic Chapter}
\chapter{Arabic Chapter}
\chapter{Arabic Chapter}

\end{document}

Screenshot of the result:

Description of the issue:
As you can see, the Roman letters are wider than the \textwidth what looks really ugly. How can I right align the Roman numbers below each other in one row?

Update: While playing around with \documentclass{book}, suddenly the TOC does appear like expected. Now I am curious - what could be the issue in scrbook?

A: By the default the pagenumbers are right aligned in box of \@pnumwidth (default is 1.55em). This box is to small for the Roman numbers.
Assuming there are only chapters with Roman page numbers:
\RedeclareSectionCommand[
  tocpagenumberbox=\mbox
]{chapter}

or
\RedeclareSectionCommand[
  tocpagenumberbox={\makebox[3em][r]}% adjust the width to your needs
]{chapter}

Example:
\documentclass{scrbook}

\RedeclareSectionCommand[
  tocpagenumberbox=\mbox
]{chapter}

\begin{document}
\pagenumbering{Roman}
\tableofcontents
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
\chapter{Roman Chapter}
%\section{Roman Section}
\chapter{Roman Chapter}

\cleardoubleoddpage
\pagenumbering{arabic}%
\chapter{Arabic Chapter}
\chapter{Arabic Chapter}
\chapter{Arabic Chapter}
\end{document}

Result:

If there are also sections etc. with Roman pagenumbers, then you could change \@pnumwidth (works for standard classes too):
\makeatletter
  \renewcommand\@pnumwidth{3em}
\makeatother

or you could use \RedeclareSectionCommands:
\RedeclareSectionCommands[
  tocpagenumberbox={\makebox[3em][r]}% adjust the width to your needs
]{chapter,section,subsection}

The next KOMA-Script version 3.27 will provide an option pagenumberwidth for the TOC entry style tocline. With prefix toc (topagenumberwidth) this option can be used in \RedeclareSectionCommand or \RedeclareSectionCommands.
\RedeclareSectionCommands[
  tocpagenumberwidth=3em% needs at least version 3.27.3161
]{chapter,section,subsection}

If you want to test this new option you can install the prerelease from the KOMA-Script website.


text:
Q: Get background variable value in content scripts I have a var in background page (for example var x = 23). How I can get this variable in my content script? I tried this in content.js:
chrome.extension.getBackgroundPage().x;

But it doesn't work.

A: Send your data with messages, and listen on the receiving side.
Messages

Since content scripts run in the context of a web page and not the extension, they often need some way of communicating with the rest of the extension. For example, an RSS reader extension might use content scripts to detect the presence of an RSS feed on a page, then notify the background page in order to display a page action icon for that page.

A: You can not use chrome.extension.getBackgroundPage() in content scripts, it is not supported, as an alternative use epoch answer for message communication.
References:

*

*Support for Content Scripts


text:
Q: Google Apps Script: Display single column based on user email I am trying to develop a gradebook with Google Spreadhseets, but I only want to display individual grades based on user email. Is there a Google Apps Script function that looks at a logged in user's email, searches the spreadhseet for it (it would be at the top of a column) and then displays that column back to the user?

A: I think the best solution would probably be to create a small webapp Ui that shows only the relevant column in a html table. Depending on your programming skills it can be quite easy to setup.  I could have suggested an example but you gave too few information about the type of data that are in the spreadsheet... User's data are in a single column but I suppose there is also some kind of headers or row identifiers that must be shown to understand what is shown ?
Users will have to authorize the webapp in order to let you identify them when they are logged in.

Edit : here is a simple example of a possible solution that you can start from.
I assumed mails are in row 1, descriptions in column A.
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheet/ccc?key=0AnqSFd3iikE3dGdQOXZpRmJnT0xjQklkdEZING5YREE#gid=0');
var sh1 = ss.getSheetByName('sheet1');
var logsheet = ss.getSheetByName('logsheet');
var data = sh1.getDataRange().getValues();
var user = Session.getEffectiveUser()

function doGet() {
       var app = UiApp.createApplication();
       if(!getcol(user)){
          var warn = app.createTextBox().setWidth('500').setValue("Your results are not available or you don't have permission to view these data");// if user is not in the list, warning + return
app.add(warn)
return app
          }
       var grid = app.createGrid(data.length, 2).setBorderWidth(1).setCellPadding(2);
       var text = app.createTextBox().setName('text').setId('text').setValue(user+'  | idx'+getcol(user) ).setWidth('300px');
       var btn = app.createButton('press here to confirm you have view these results');
       var handler = app.createServerHandler('log').addCallbackElement(grid);
       btn.addClickHandler(handler);
       var col = getcol(user)
       grid.setWidget(0,1,text).setText(0, 0, 'Results for');
       grid.setStyleAttribute('textAlign','center')
       for(n=1;n<data.length;++n){
         grid.setText(n, 0, data[n][0])
         grid.setText(n, 1, data[n][col])
         }
       app.add(grid).add(btn)
       return app
    }

function log(e){
      var text = e.parameter.text
      var app = UiApp.getActiveApplication();
    // add user name to the log sheet + timestamp + eventually send a mail etc...
    return app
    }

function getcol(mail){
  if(data[0].toString().indexOf(mail.toString())!=-1){
  for(zz=1;zz<data[0].length;++zz){
    if(data[0][zz] == mail){var colindex=zz;break}
  }
   return colindex
  }
  return false
}

EDIT2 :
To print numbers with the desired number of decimals you can use the recently implemented printf function like this :
grid.setText(n, 1, Utilities.formatString('%.2f',data[n][col]));// 2 decimals, no leading 0

to show dates like you want use formatDate()
Utilities.formatDate(date, Session.getTimeZone(), "MM-dd")

EDIT3 :
here is a version that handles the different types of data :
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheet/ccc?key=0AnqSFd3iikE3dGdQOXZpRmJnT0xjQklkdEZING5YREE#gid=0');
var sh1 = ss.getSheetByName('sheet1');
var logsheet = ss.getSheetByName('logsheet');
var data = sh1.getDataRange().getValues();
var user = Session.getEffectiveUser()
Logger.log(user)

function doGet() {
       var app = UiApp.createApplication();
       if(!getcol(user)){
          var warn = app.createTextBox().setWidth('500').setValue("Your results are not available or you don't have permission to view these data");// if user is not in the list, warning + return
app.add(warn)
return app
          }
       var grid = app.createGrid(data.length, 2).setBorderWidth(1).setCellPadding(2).setStyleAttribute('background','#ffeeaa').setId('grid');
       var text = app.createTextBox().setName('text').setId('text').setValue(user+'  | idx'+getcol(user) ).setWidth('300px');
       var btn = app.createButton('press here to confirm you have view these results');
       var handler = app.createServerHandler('log').addCallbackElement(grid);
       btn.addClickHandler(handler);
       var col = getcol(user)
       grid.setWidget(0,1,text).setText(0, 0, 'Results for');
       grid.setStyleAttribute('textAlign','center')
       for(n=1;n<data.length;++n){
         grid.setText(n, 0, string(data[n][0]));
         grid.setText(n, 1, string(data[n][col]));
         }
       grid.setStyleAttributes(n-1, 0, {'fontWeight':'bold','background':'#ffff99'})
       grid.setStyleAttributes(n-1, 1, {'fontWeight':'bold','background':'#ffff99'})
       app.add(grid).add(btn)
       return app
    }

function log(e){
      var text = e.parameter.text
      var app = UiApp.getActiveApplication();
      app.getElementById('grid').setStyleAttribute('background','#bbffbb')
    // add user name to the log sheet + timestamp + eventually send a mail etc...
    return app
    }

function string(value){
Logger.log(typeof(value))
if (typeof(value)=='string'){return value};// if string then don't do anything
if (typeof(value)=='number'){return Utilities.formatString('%.1f / 20',value)};// if number ther format with 1 decimal
if (typeof(value)=='object'){return Utilities.formatDate(value, Session.getTimeZone(), "MM-dd")};//object >> date in this case, format month/day
return 'error'
}

function getcol(mail){
  if(data[0].toString().indexOf(mail.toString())!=-1){
  for(zz=1;zz<data[0].length;++zz){
    if(data[0][zz] == mail){var colindex=zz;break}
  }
   return colindex
  }
  return false
}


text:
Q: Can't use some AMS binary operators I'm using the amsmath package, and I want to put in a sentence, the not similar binary operator. I tried this:
... bla bla $ a \nsim b $ bla bla ...

I get the error:

"Undefined control sequence".

By the way, if I put \sim it works, but I want negate it.

A: The command \nsim is listed in table 69 of the Comprehensive LaTeX Symbol List, under the caption

AMS Negated Binary Relations

In section 1.1 of the document, we find

"AMS" means to use the AMS packages, viz. amssymb and/or amsmath.

Actually most of the symbols with that tag require amssymb and this is the case for \nsim.

Note that the result of \not\sim is rather different, so the final answer is
\documentclass{article}
\usepackage{amssymb}

\begin{document}
... bla bla bla $a \nsim b$ bla bls ...

\end{document}


text:
Q: MKLocalSearch (search.start)always goes in the error flow. (SWIFT) I've been trying to learn swift for the past few days and just started my own project! As part of the project I wanted to show nearby cocktail bars on a map, I was able to find some nice info online and have been able to show a map with my current location. I also found info on how to find nearby locations: https://developer.apple.com/documentation/mapkit/mklocalsearch/request
Unfortunately this last one never seems to work, it just goes out of the function and does not return any locations, could anyone help me further? Below is the code of my viewcontroller with the function getNearbyLandmarks which doesn't work as intended.
class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet var mapView: MKMapView!
let manager = CLLocationManager()
private var landmarks: [Landmark] = [Landmark]()

override func viewDidLoad() {
    super.viewDidLoad()

}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    manager.desiredAccuracy = kCLLocationAccuracyBest
    manager.delegate = self
    manager.requestWhenInUseAuthorization()
    manager.startUpdatingLocation()

}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.first {
        manager.stopUpdatingLocation()
        render(location)
    }
}

func render(_ location: CLLocation){

    let coordinate = CLLocationCoordinate2D(latitude: location.coordinate.latitude,
                                            longitude: location.coordinate.longitude)

    let span = MKCoordinateSpan(latitudeDelta: 0.01,
                                longitudeDelta: 0.01)

    let region = MKCoordinateRegion(center: coordinate,
                                    span: span)
    mapView.delegate = self
    mapView.setRegion(region,
                      animated: true)

    let pin = MKPointAnnotation()
    pin.coordinate = coordinate
    pin.title = "Current location"
    mapView.addAnnotation(pin)
    self.getNearByLandmarks()
    updateAnnotations(from: mapView)
}

func mapView(_ mapViewIcon: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    var annotationView = mapViewIcon.dequeueReusableAnnotationView(withIdentifier: "custom")

    if annotationView == nil {
        annotationView = MKAnnotationView(annotation: annotation,
                                          reuseIdentifier: "custom")
        annotationView?.canShowCallout = true
    }else{
        annotationView?.annotation = annotation
    }

    annotationView?.image = UIImage(named: "User")

    return annotationView
}

private func getNearByLandmarks(){
        let request = MKLocalSearch.Request()
        request.naturalLanguageQuery = "coffee"
    request.region = mapView.region

        let search = MKLocalSearch(request: request)
        search.start{(response, error) in
            if let response = response {
                let mapItems = response.mapItems
                self.landmarks = mapItems.map{
                    Landmark(placemark: $0.placemark)
                }
            }

        }
    }

private func updateAnnotations(from mapView: MKMapView){
    let annotations = self.landmarks.map(LandmarkAnnotation.init)
    mapView.addAnnotations(annotations)
}

}

A: You call getNearByLandmarks, and then immediately try to update the annotations:
self.getNearByLandmarks()
updateAnnotations(from: mapView)

but getNearByLandmarks is asynchronous, and takes some time to complete. You need to update the annotations whenever private var landmarks changes, one way is to update it in all the places that set that, like where you say
   self.landmarks = mapItems.map{
            Landmark(placemark: $0.placemark)
        }

note you don't call updateAnnotations(from: mapView) there.
Or you could add a didSet property observer to landmarks itself so that updateAnnotations is called whenever it changes.


text:
Q: Dynamically Writing Javascript to a new HTML Page I have the following code below in which I am using to attempt to dynamically write some javascript into a new html page at the click of a button.
I am however getting an error when attempting to do so I get "unterminated string constamnt"
in theory, this should work:
var html     =  '<!DOCTYPE html>\n'
html    +=  '\n'
html    +=  '\n'
html    +=  '\n'
html    +=  '\n'
html    +=  '\n'
html    +=  '\n'
html    +=  ' on the last line
html    +=  '</html\n'  <-- Missing a greater than

should be
html    +=  '\n'

If the code is inline and not in an external script, you will need to break up the closing script tag.
html    +=  '</scr' + + 'ipt>\n';

also, use semicolons.
Now the window.open, document.write line looks strange. Most developers would write it as
var winPop = window.open('','');
winPop.document.open();
winPop.document.write(html);
winPop.document.close();

A: Just a tip you can use multiple lines instead of putting html += on every line just add a backslash at the end of a line so:
html = '\n  \
        \n \
        \n \
        \n \
        \n \
        \n \
        \n  ';

However you there were some flaws in your code you forgot the > for the
And just like epascarello said break up the script tag.
However you might want to take a look at if you want to open a different html document with your popup, or even a php file since then you could just pickup the $_GET values and fill your custom values in with that. what would be more reliable.
Check out the w3c about $_GET


text:
Q: How do I use Project Oxford's Speech API to implement solution into a WPF application? I have been unable to find relevant documentation whose link has not been broken.
I want to implement all the API features of Project Oxford's Speech API into my WPF application. The features include adding, editing and deleting of Intent, Entities, Prebuilt Entities, Phrase Lists.
So how do I bring all these controls into my WPF application and be able to use the Speech API in real time?
Any help is greatly appreciated and thank you for reading my question.

A: We just renamed Project Oxford to Microsoft Cognitive Services; I wonder if that broke some links.  (Apologies if so!)  All of the APIs are listed at https://www.microsoft.com/cognitive-services/en-us/apis.
The Speech API specifically is at https://www.microsoft.com/cognitive-services/en-us/speech-api.  I clicked through on that and found detailed documentation on individual classes at https://staging.www.projectoxford.ai/Files/Doc/Speech/Windows/html/2f2b6f71-0a81-b331-fe50-dc681063bbf8.htm.  Does that help?


text:
Q: Cannot have two renders using Node.js So I am trying to set the title of the index page to be "Sign In" and at the same time retrieving data from mongodb. I learned this technique from this page - http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/
It seems that I cannot have two renders because if I do I get the cannot read from undefined error. If I just keep the one that help me retrieving data, I cannot have the title set properly. Any idea what I should do?
Here are the two related pieces of codes.
This one is from the index.js in routes folder.
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
    next();
});

router.get('/', function(req, res, next) {
    var db = req.db;
    var accounts = db.get('accountInfo');
    accounts.find({}, {}, function(err, docs) {
        res.render('index', {
            "accounts" : docs
        });
    });
});

router.get('/signup', function(req, res) {
    res.render('signup', { title: 'Create New Account' });
});

module.exports = router;

And this is from the index.jade
ul
    each account, i in accounts
        li
            p= account.username

Thanks for the help!

A: It turns out that I should combine the two into one. Otherwise the server will try to put two windows' information on one single screen.


text:
Q: Check whether a Kafka topic exists in Python I want to create a Kafka topic if it does not already exist. I know how to create a topic via the bash, but I don't know how to check whether it exists.
topic_exists = ??????
if not topic_exists:
    subprocess.call([os.path.join(KAFKABIN, 'kafka-topics.sh'),
        '--create',
        '--zookeeper', '{}:2181'.format(KAFKAHOST),
        '--topic', str(self.topic),
        '--partitions', str(self.partitions),
        '--replication-factor', str(self.replication_factor)])

A: Another nice way is with python kafka module:
kafka_client = kafka.KafkaClient(kafka_server_name)
server_topics = kafka_client.topic_partitions

if topic_name in server_topics:
   your code....

kafka_client.topic_partitions returns list of topics.

A: You can use the --list (List all available topics) option for kafka-topics.sh and see if self.topic exists in the topics array, as shown below.
Depending on the number of topics you have this approach might be a bit heavy. If this is the case, you might be able to get away with using --describe (List details for the given topics) which will likely return empty if the topic doesn't exist. I haven't thoroughly tested this, so I can't say for sure how solid this solution (--describe) is, but it might be worth it for you to investigate a bit further.
wanted_topics = ['host_updates_queue', 'foo_bar']

topics = subprocess.check_output([os.path.join(KAFKABIN, 'kafka-topics.sh'),
        '--list',
        '--zookeeper', '{}:2181'.format(KAFKAHOST)])

for wanted in wanted_topics:
    if wanted in topics:
        print '\'{}\' topic exists!'.format(wanted)
    else:
        print '\'{}\' topic does NOT exist!'.format(wanted)

    topic_desc = subprocess.check_output([os.path.join(KAFKABIN, 'kafka-topics.sh'),
        '--describe',
        '--topic', wanted,
        '--zookeeper', '{}:2181'.format(KAFKAHOST)])

    if not topic_desc:
        print 'No description found for the topic \'{}\''.format(wanted)

OUTPUT:
root@dev:/opt/kafka/kafka_2.10-0.8.2.1# ./t.py
'host_updates_queue' topic exists!
'foo_bar' topic does NOT exist!
No description found for the topic 'foo_bar'

There is also a Broker Configuration available so you don't have to take any of these steps:

auto.create.topics.enable | true  | Enable auto creation of topic on the server. If this is set to true then attempts to produce data or fetch metadata for a non-existent topic will automatically create it with the default replication factor and number of partitions.

I would take this approach if possible.
Note that you should set topic configs (server.properties) on your broker for num.partitions and default.replication.factor to match your settings in your code snippet.

A: Use kafka-python consumer api for this.
import kafka
consumer = kafka.KafkaConsumer(group_id='test', bootstrap_servers=your_server_list)
new_topics = set(wanted_topics)-set(consumer.topics())
for topic in new_topics:
    create(topic)

A: Use KafkaAdminClient from kafka api. Not docummented but a method list_topics exists !


text:
Q: Alguém sabe me explicar o motivo do código ter dado um erro completo, desde já agradeço. Lembrando que a linguagem é C++, a do arduino #define bombA 44  // pino bomba de água 1 (presente no galão 1)
#define bombB 45  // pino bomba de água 2 (presente no galão 2)
#define pSA A2  //  pino para o valor analógico do sensor de  umidade da terra
#define pLvm 40 // pino Led Vermelho
#define pLa 41 // pino Led Amarelo
#define pLvd 42 // pino Led Verde
#define pino_sinal_analogico A3 // pino analógico do sensor de humidade da terra
int valor_analogico;
const int LNdA = 46; // pino Led Nível d'água
const int SNdA1 = A6; // pino analógico Sensor Nível d'água 1
const int SNdA2 = A7; // pino analógico Sensor Nível d'água 2
#include <LiquidCrystal.h> //Carrega a biblioteca LCD
#include <dht.h>     //Carrega a biblioteca DHT
#define DHTPIN A4       // Pino analog 4 para o DHT
dht DHT;
#define DHT11_PIN 7
LiquidCrystal lcd(30, 31, 32, 33, 34, 35); // pinos ligados ao lcd
byte grau[8] = { B00001100,
B00010010,
B00010010,
B00001100,
B00000000,
B00000000,
B00000000,
B00000000,
};
#include <Wire.h>   //sensor de luminosidade
#include <BH1750.h>
BH1750 lightMeter; // Cria uma instância
void setup() {
Serial.begin(9600); //Inicia uma serial
lcd.begin(16, 2); // Inicia o LCD
lcd.clear(); // Limpa o LCD
lcd.createChar(0, grau); //Cria o caractere customizado com o simbolo do grau
dht begin();
Wire.begin();
lightMeter.begin(); //Inicia a medição de luminosidade
pinMode(pSA, INPUT);
pinMode(pLvm, OUTPUT);
pinMode(pLa, OUTPUT);
pinMode(pLvd, OUTPUT);
pinMode(bombA, OUTPUT);
pinMode(bombB, OUTPUT);
pinMode(LNdA, OUTPUT);
pinMode(SNdA1, INPUT);
pinMode(SNdA2, INPUT);
}
void loop() {
if (analogRead(SNdA1) < 550) {
digitalWrite(LNdA, HIGH); // Led de nível d'água baixo aceso 1
} else {
digitalWrite(LNdA, LOW); // Caso nível d'água alto/moderado, Led 1 não acende
}
if (analogRead(SNdA2) < 550) {
digitalWrite(LNdA, HIGH); // Led de nível d'água baixo aceso 2
} else {
digitalWrite(LNdA, LOW); // Caso nível d'água alto/moderado, Led 2 não acende
}
lcd.write((byte)0);
int chk = DHT.read11(DHT11_PIN);
Serial.print("Umidade = ");
Serial.println(DHT.humidity);
float lux = lightMeter.readLightLevel();
Serial.print("Luminosidade: ");
Serial.print(lux); // Imprime o valor de luminosidade no lcd
Serial.println(" lux");
valor_analogico = analogRead(pino_sinal_analogico);
if (valor_analogico > 0 && valor_analogico < 400) { // Status de solo úmido, led Verde aceso
digitalWrite(pLvd, HIGH);
digitalWrite(pLa, LOW);
digitalWrite(pLvm, LOW);
}
if (valor_analogico > 400 && valor_analogico < 800) { // status de solo moderado, led Amarelo aceso
digitalWrite(pLvd, LOW);
digitalWrite(pLa, HIGH);
digitalWrite(pLvd, LOW);
delay(150);
digitalWrite(bombA, HIGH);
delay(3500);
}
if (valor_analogico > 800 && valor_analogico < 1024) { // status de solo seco, led Vermelho aceso
digitalWrite(pLvd, LOW);
digitalWrite(pLa, LOW);
digitalWrite(pLvd, HIGH);
delay(150);
digitalWrite(bombA, HIGH);
digitalWrite(bombB, HIGH);
delay(5000);
}
}


text:
Q: Understand vector table definition assembly in stm32cubeIDE startup The code to initialize vector table is placed in startup code of STM32cubeIDE:
  .global  g_pfnVectors
  .section  .isr_vector,"a",%progbits
  .type  g_pfnVectors, %object
  .size  g_pfnVectors, .-g_pfnVectors

g_pfnVectors:
  .word  _estack
  .word  Reset_Handler

  .word  NMI_Handler
  .word  HardFault_Handler
  .
  .
  .
  .word  DMA1_Stream0_IRQHandler           /* DMA1 Stream 0                */
  .
  .
  .

I want to understand it, Then I have some questsion if anyone could help:

*

*g_pfnVectors have declared two time one with .global other with .word. It first declared as global then declared it's size in hardware?

*line 2,3,4 have all something comma separated, what are they?

*Is there any reference to understand them?
Note: I know line 6 is array defenition of g_pfnVectord.

*It seem the startup have to holds the IRQhandlers function pointer, since we have defined them on *_it.c ,these will link to them, am I right?

*In arm interupt vector relocation usage and description they've reassigne SysTick_Handler after table reallocation. If we use linker to move this function to RAM then we don't need this re allocate this function, am I right? (Since this function executes every 1mS by default on cubeIDE apps and have be fast)

A: Can't exactly cover the assembly syntax well, but I think some explanation of vector table and interrupt entry would be helpful. In fact, it's very easy to have zero assembly code in startup, you can totally make a vector table in C as an array that you place in its own section. Also, I'm not super verse in assembly myself. Anyway, regarding the vector table, what it is, how it works and what you can do with it.
In the beginning of Flash, before any executable code, you have a vector table. It's just a list of pointers to void (void) functions. (The first word of the vector table is loaded into main stack pointer on power on, the others are pointers). Since Flash is not intended to be dynamically changed at runtime, we can safely assume that in practice those pointers are fixed.
When interrupt occurs, the CPU reads the corresponding interrupt handler address from the vector table and then jumps to whatever address it read. Thus, if you move vector table, you also need to make sure that all interrupts have handler addresses in the correct places in new vector table. Basically, you want to copy the old vector table into the new place.
Small addition: in Cortex M, vector table entries' least significant bit is always set to 1 (like all function pointers). Architecture requirement (indicates Thumb instruction set and not 32-bit ARM instruction set). Otherwise usage fault exception. (so for interrupt handler at 0x20040000, the vector table entry is 0x20040001).
Let's consider a basic example.
Your vector table is in Flash and it's fixed (unchangeable). Imagine you have interrupt number 20. Imagine you have void IRQ20_Handler (void) handler for that interrupt, located also in Flash, where your executable code typically resides. Let's imagine the address of the handler is 0x08004000 (any address in Flash that's not overlapping with vector table, just an example).
In your Flash, 32-bit word number 36 of the memory is going to contain 0x08004001. 36 because MSP+Exceptions (hardfault, memmanage fault, busfault, systick, etc) take the first 16 words, and IRQs start only after that. Vector table is in the STM MCU's reference manual.
So right now, your vector table is at location 0x08000000 (beginning of Flash), and word 36 of it has a pointer to IRQ20_Handler, which is also somewhere in Flash. So if IRQ20 interrupt happens, your MCU reads word number 36 from Flash - 0x08004001 - and jumps to 0x08004000 to the handler.
Imagine you want to have a function in SRAM as an interrupt handler located at 0x20040000. You will have to overwrite Flash so that vector table word number 36 has new handler's address - it's not recommended to rewrite flash just for 1 thing - so instead you move vector table to RAM, and then you can dynamically change vectors as much as you want at runtime.
Thus, you first move IRQ handler to RAM (say, 0x20040000), then you move vector table to RAM and make sure that all handler addresses are copied over to there so that all interrupts work just like before, then in the new vector table you overwrite the IRQ20_Handler (word 36 of vector table) with the address of the SRAM function (+1). In this case, with 0x20040001.
Unfortunately, can't provide more details about assembly, since I use it only a bit and mainly as inline assembly blocks for context switching or special instructions not natively supported through C. It looks like it declares a section (and makes it globally visible) and gives it a pair of attributes.


text: Q: Built in JSON parser in .NET framework For reasons I don't want to get into I find I cannot make use of the JSON.NET JSON parser from Newtonsoft. Does .NET have it's own JSON parser available in the framework?


text:
Q: HDMI through USB-C I am trying to connect an HDMI monitor to USB-C port on my computer so that I can have dual screens.
The port is SuperSpeed USB Type-C and the HDMI monitor standard is HDMI 1.4.  I am using a dock.
No picture shows.  Wondering if it is even possible to do this -- however it works on my laptop that has a thunderbolt connection.