text:
Q: Расположить элемент справа на десктопе и слева на мобильном Bootstrap4 В проекте используется bootstrap4. Имеется навигация navbar в которой есть логотип и пункты меню. По умолчанию в bootstrap логотип navbar-brand всегда слева.
За основу взяла navbar-light отсюда.

    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#containerNavbar" aria-controls="containerNavbar" aria-expanded="false" aria-label="Toggle navigation">

    </button>
    Navbar

          Home (current)

          Link

          Disabled

          Dropdown

            Action
            Another action
            Something else here

Как расположить navbar-brand справа для десктопа и слева для мобильных?
UPD
Суть вопроса: как расположить navbar-brand (логотип) по правому краю для десктопа (для ширины md и больше), и по левому для мобильных?

A: Управлять расположением бренда(логотипа) можно с помощью классов flex-first, flex-last, др . Для отображения на необходимых разрешениях можно использовать все те же приставки -lg, -md, -sm, -xs.
Ресурс
Пример:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#containerNavbar" aria-controls="containerNavbar" aria-expanded="false" aria-label="Toggle navigation">

  </button>
  Navbar

        Home (current)

        Link

        Disabled

        Dropdown

          Action
          Another action
          Something else here


text:
Q: Angular 2 animations Is it possible to animate elements on Angular 2 like on jQuery? For example, I want div containing sub-elements to expand/shrink when clicked. Does Angular 2 provide directives for this, or do I have to call jQuery inside Angular event handlers ?

A: Check out https://angular.io/docs/ts/latest/guide/animations.html
Remember to use the polyfills for older browsers.

A: Just use bootstrap accordion . Here is a link to it
https://getbootstrap.com/docs/4.3/components/collapse/

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I passively monitor the Windows Event Log? How can I monitor the Windows Event Log remotely such that I will be informed automatically when certain events occur?
There are plenty of active monitoring solutions, but they require human attention or constant polling.  I need a passive solution that will simply generate a notification when a particular event occurs.

A: You could use Event Sentry which has notifications:

Real-time Event Log monitoring is the
  core feature of EventSentry and allows
  you to monitor all standard
  (Application, Security, System, DNS
  Server, File Replication Service,
  Directory Service) and custom event
  logs. Event Log entries can be
  forwarded to a variety of immediate
  notifications (e.g. email, pager, SNMP
  etc.) or notifications designed for
  consolidation (e.g. database, files,
  etc.).

If you have time and are familiar with scripting, you could build a DIY solution, using existing code and tools like SysInternal's PsLogList, a script to monitor the event log from Microsoft's ScriptCenter, LogParser and a free SMTP commandline tool like Blat or bmail.
http://www.blat.net/

A: Windows Server has a built in SNMP trap generator for the Windows Event Log/Viewer, which can send traps on the occurrence of arbitrary events.
Trap Form (OID)
These traps will conform to the Microsoft private enterprise MIB branch in the following form:
1.3.6.1.4.1.311.1.13.X.n.n.n.n.n.n.n.n.n...

Each "n" is a decimal encoding of an ASCII character octet from the Event Log source name, and the X designates the number of characters to follow.
So, for example, a trap generated by source "Prefect" (as seen in Event Viewer) would appear as:
1.3.6.1.4.1.311.1.13.7.80.114.101.102.101.99.116

Windows 2000 Server does not support this fully, and will generate traps of a slightly different format, but the procedure is otherwise identical.  All newer versions of Windows server support this properly
Configuring Trap Sending
There are two built-in tools that you will use to set up trap generation.
evntwin: Create mapping of Event Log messages to SNMP traps
evntcmd: Load mapping created by evntwin so that traps are generated
Run evntwin from a command prompt: this will spawn a GUI.  Select "Custom" under Configuration type, and then "Edit."  You will now see a list of all possible event sources.  Under the source in which you are interested, select the particular event ID on which you wish to generate traps.  Then, click "Add."
Now, you will see the actual OID of the trap, the specific ID, and an option to set a time-based threshold of event occurrences before the trap would be sent.
Repeat until you have created a mapping for each particular trap/event combination you care about.  Then, click "Apply," highlight all of the mappings, and then "Export..."  Save the file, and exit the application.
Now, again from the command line, run evntcmd, specifying the name of the file you just created:
evntcmd myeventfile.cnf

From this point forward, the events you specified will generate SNMP traps, which will be sent to all trap receiver destinations you have configured in your SNMP service settings.  Process them as you would any normal SNMP trap.

A: For 2008, Vista, XP and 2003 you could use the Windows remote event log subscription service. This is a native function of Vista and 2008. For 2003 and XPs you need specific service packs. Windows use RMI to collect event logs from remote systems much similar to syslogs but in a more secure fashion. You could also use group policy to make all servers forward events to a single 2K8,Vista or 2003 server. You can also setup notifications/alerts within event viewer.

A: If you enjoy scripting, you can write a WMI event sink that can receive notifications when new events are appended to the event log. I've run a VBScript version of such a script as a service, and upon receiving events it considers "interesting" (by way of a regexp match from a configuration file), it generates SMTP email. It's a fairly trivial script, but I can't post it since it "belongs" to the Customer I wrote it for.

A: Perhaps eventtriggers can help you (http://technet.microsoft.com/en-us/library/cc773308(WS.10).aspx). Look for eventquery.vbs as well.

A: I think eTrap is the perfect solution form monitoring Windows events.


text:
Q: MUI : Out-of-range value `X` for the select component I'm making a glossary where each of the definitions are a cards that can be flipped (CardFlip) I build an array where I send for each card, the data via props to my component "CardFlip" dealing with the actual construction of cards with my data
This is my first component sending everything :

{glossaire.map((carte, index) => (
  <Fragment key={carte.dat_id}>
    <CardFlip item={carte} tags={tags} />
  </Fragment>
))}

*

*First prop ,"item", contains information such as: a title, a definition, a search tag

*Second prop, "tags", is the list of tags that a definition can have, a definition can have only one tag, right now only those tags are available : "Application", "Entreprise", "Technique" and "Télécom"

And here is the code for my second component (only the interesting part):
    export default function CardFlip = ({ item, user, tags }) => {
  // -- [Variables] --
  // Flip front / back
  const [isFlipped, setIsFlipped] = useState(false);

  // Storage
  const [titreDef, setTitreDef] = useState("");
  const [definitionDef, setDefinitionDef] = useState("");
  const [tagSelected, setTagSelected] = useState("");

  // Flag for error
  const [errorTitre, setErrorTitre] = useState(false);
  const [errorDefinition, setErrorDefinition] = useState(false);
  const [errorSelect, setErrorSelect] = useState(false);
  console.log(item.dat_tag);
  console.log(tags);

  // -- [Handlers] --
  // UPDATE
  const handleTitre = (data) => {
setTitreDef(data);
setErrorTitre(false);
  };

  const handleDefinition = (data) => {
setDefinitionDef(data);
setErrorDefinition(false);
  };

  const handleSelect = (event) => {
const {
  target: { value },
} = event;
setTagSelected(value);
setErrorSelect(false);
  }

  return (
<Grow in style={{ transformOrigin: "0 0 0" }} {...{ timeout: 1000 }}>

    <ReactCardFlip
      isFlipped={isFlipped}
      flipDirection="horizontal"
      style={{ height: "100%" }}
    >

        <Card className={style.mainCard}>
          <CardActions className={style.buttonFlipCard}>
            <Tooltip title="Retour">
              <IconButton
                className={style.iconFlipCard}
                disableRipple
                onClick={() => setIsFlipped((prev) => !prev)}
              >
                <ChevronLeftIcon />
              </IconButton>
            </Tooltip>
          </CardActions>

          <CardContent>

              <FormControl
              sx={{width: "90%"}}
              >
                <InputLabel
                  id="SelectLabel"
                  sx={{display: "flex"}}
                >
                  {<TagIcon />}
                  {" Tag"}
                </InputLabel>
                <Select
                  labelId="SelectLabel"
                  label={<TagIcon /> + " Tag"}
                  renderValue={(selected) => (
                    <Chip
                      onMouseDown={(event) => {
                        event.stopPropagation();
                      }}
                      key={selected}
                      label={selected}
                      icon={<TagIcon />}
                    />
                  )}
                  defaultValue={item.dat_tag}
                  onChange={handleSelect}
                >
                  {tags && tags.map((tag) => (
                    <MenuItem key={tag.dat_tag} value={tag.dat_tag}>
                      {tag.dat_tag}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>

          </CardContent>
        </Card>

    </ReactCardFlip>

</Grow>
  );
};

When the user returns the card, he can change the title, description and tag of the chosen card.
My problem is with the Select.
In order to display the selected tag before any modification, I display the tag in defaultValue={item.dat_tag}
(Also tried with value and not defaultValue)
Then with my second prop, I build the list of my menu.
This is where I get my warning (which seems to extend the rendering time of the page considerably (Since it load / render like +100 definitions, getting a warning for every definition)

MUI: You have provided an out-of-range value Entreprise for the select component.
Consider providing a value that matches one of the available options or ''. The available values are "".

This is an example of what a console.logs told me about my props :
item.dat_tag

Entreprise

tags

0: {dat_tag: "Applicatif"}
1: {dat_tag: "Entreprise"}
2: {dat_tag: "Technique"}
3: {dat_tag: "Télécom"}

I already looked at several posts saying to put in a string variable my tag data (item.dat_tag) or to display my menu when it is not empty. No change.


text:
Q: JavaFX ScrollPane styling I'm trying to create a black and white ScrollPane in JavaFX. I already created a CSS file, which works pretty fine. Except for this little square:

Whatever I try, I'm not able to turn it black.
Here is my CSS file:
.scroll-pane {
    -fx-background-color: black;
}

.scroll-bar:horizontal, .scroll-bar:vertical{
    -fx-background-color:transparent;
}

.increment-button, .decrement-button {
    -fx-background-color: transparent;
    -fx-border-color: transparent;
}

.scroll-bar:horizontal .track,
.scroll-bar:vertical .track{
    -fx-background-color: transparent;
    -fx-border-color: transparent;
    -fx-background-radius: 0em;
}

.scroll-bar:horizontal .thumb,
.scroll-bar:vertical .thumb {
    -fx-background-color: white;
    -fx-background-radius: 5em;
}

Is there a way to change the color of this square?

A: Use "corner" class.
.scroll-pane > .corner {
      -fx-background-color: black;
}

A: Simply add the following selector using the needed color:
.scroll-pane > .corner {
    -fx-background-color: black;
}


text:
Q: Coldfusion cfpdfform with LiveCycle I am using <cfpdfform> to populate a LiveCycle Designer developed pdf form.  I've excluded the destination attribute and the pdf shows in the browser exactly as I wish.  However, it provides a filename of a series of numbers followed by=temp.pdf.
Is there any way to provide a variable name for the displayed file?
For example, if I provide a #URL.name# in my form submission, I would like the filename displayed in the browser to be smith.pdf or whatever name I place in the #URL.name#

A: I think this is what you need below. I once had to create a pdf document using cfdocument and I used the below to specify the filename to render as. The caveat is that i had to save the file on the file system first which i achieved with same cfdocument.
note path_to_pdf_file_on_server and name_to_render_as.pdf in the code below
<cfheader name="Content-Disposition" value="attachment;filename=name_to_render_as.pdf">
<cfcontent type="application/pdf" file="path_to_pdf_file_on_server" deletefile="Yes">


text:
Q: Why getsockopt() does not return the expected value for TCP_MAXSEG? I'm trying configuring programmatically the MSS of my TCP connection on a GNU/Linux system, specifically Ubuntu 12.04, kernel 3.2.0-68-generic
According to man 7 tcp

TCP_MAXSEG The maximum segment size for outgoing TCP packets.  If this
  option is  set  before  connection establishment, it also changes the
  MSS value announced to the other end in the initial packet.Values
  greater than the (eventual) interface MTU have no effect.  TCP  will
  also  impose  its minimum and maximum bounds over the value provided.

this let me think I can configure the value before I connect the TCP socket.
I wrote a small chunk of code to create a socket and I used setsockopt() to configure the MSS.
In my test I'm setting the mss to 1000B.
The code calls setsockopt() followed by getsockopt() to double check the value has been properly configured. Both syscalls return 0 (no error). After that I connect to a remote host to verify via tcpdump the used mss is correct. Here what I see:

*

*returned MSS value from getsockopt() is always 536 Byte

*tcpdump shows the configured MSS in the syn packet

Modified my code to configure the MSS after I connect the socket.

*

*returned MSS value from getsockopt() is 1448 Bye

Is there a correct way to explain such behavior?
A couple of notes:

*

*according to wikipedia 536 B = MaxIPDatagramSize - IPHeaderSize - TcpHeaderSize
this is to avoid IP packet fragmentation.

*creating a socket and connecting it (no setsockopt() call), displays an mss of 536 B returned by getsockopt() but tcpdump shows an announced mss of 1460 B in the SYN packet, that makes sense being 1500 - IpHeader - TcpHeader

Below, if you are interested, is my code:
int setSocketMss( int i_sd, int i_mss )
{
    int res = 0;
    int mss = i_mss;
    socklen_t len = sizeof( mss );

    res = ::setsockopt( i_sd, IPPROTO_TCP, TCP_MAXSEG, &mss, len );
    if ( res < 0 )
    {
        qDebug() << "error: cannot configure mss for socket" << i_sd;
        return -1;
    }
    res = ::getsockopt( i_sd, IPPROTO_TCP, TCP_MAXSEG, &mss, &len );
    if ( mss != i_mss )
    {
        qDebug() << "MSS set to" << i_mss << "but read value is" << mss;
    }
    else
    {
        qDebug() << "MSS for socket" << i_sd << " has been set to" << mss;
    }
    return mss;
}

void configureAddrStruct( const QString & i_ipAddress,
                          quint16 i_port,
                          struct sockaddr_in & o_sockaddr )
{
    o_sockaddr.sin_addr.s_addr = htonl( QHostAddress(i_ipAddress).toIPv4Address() );
    o_sockaddr.sin_port = htons( i_port );
    o_sockaddr.sin_family = PF_INET;
    memset( o_sockaddr.sin_zero, 0, sizeof(o_sockaddr.sin_zero) );
}

int main(int argc, char *argv[])
{
    int sd = ::socket( PF_INET, SOCK_STREAM, getprotobyname("tcp")->p_proto );
    if ( -1 == sd )
    {
        qDebug() << "erro creating socket";
        exit (1);
    }
    else
    {
        qDebug() << "created socket:" << sd;
    }

    setSocketMss( sd, 1000 );

    struct sockaddr_in localAddress;
    struct sockaddr_in remoteAddress;

    configureAddrStruct( "192.168.23.7", 0, localAddress );
    configureAddrStruct( "192.168.23.176", 9999, remoteAddress );

    int res = ::bind( sd,
                      reinterpret_cast<const sockaddr *>( &localAddress ),
                      sizeof(localAddress) );
    if ( -1 == res )
    {
        qDebug() << "error binding socket to local address";
        exit(2);
    }

    //setSocketMss( sd, 1000 );

    res = ::connect( sd,
                     reinterpret_cast<const sockaddr*>( &remoteAddress ),
                     sizeof(remoteAddress) );
    if ( -1 == res )
    {
        qDebug() << "error connecting to remote host";
        ::perror( "connect()" );
        exit(2);
    }

    //setSocketMss( sd, 1000 );

    return 0;
}

A: You're doing the wrong thing. You should send the socket receive buffer size, at the receiver.


text:
Q: Google Play downloaded Ionic application $http not working My Ionic based app works correctly when deploying it using ionic run android on my real device. However, when I download the exact same version from Google Play, all $http requests fail:
09-15 18:59:02.901: I/chromium(22744): [INFO:CONSOLE(26799)] "Failed to log in user [...]:
{"data":null,
    "status":-1,
    "config": {
       "method":"GET",
       "transformRequest":[null],
       "transformResponse":[null],
       "url":"https://example.com/something",
       "headers":{
          "Accept":"application/json, text/plain, */*",
          "Authorization":"Basic c2ltb2324Ghlbmlu5322Ng=="}
       },
       "statusText":""}",
       source: file:///android_asset/www/lib/ionic/js/ionic.bundle.js (26799)

This is what I use for my request
 $http.get(config.apiUrl + "/user/").then(function (response) {
      }
      callback && callback($rootScope.authenticated, response.data);
    }, function (err) {
      $log.info("Failed to log in user [...]: " + JSON.stringify(err));
    });

The app worked for a year now, but since the last uploaded version I have this issue. I did not update ionic or anything, my build environment should not have changed at all. And it really works on the same device if I use the APK I have locally, but doesn't with the Google Play one....

A: Oh my god, I finally figured this out thanks to this thread: https://stackoverflow.com/a/32030346/606513
Esentially - the production version has certificate checks enabled whereas the debug version does not. The certificate for my web server was outdated (for some reason the letsencrypt renewal was not working). Updating the certificate solved all my problems!


text:
Q: How to signal all consumers after finishing to produce? (Producer-Consumers Multithread Programming C CONDITION VARIABLES) I have an assignment to complete and got stucked at one point . Is the classical producer-consumers problem with 1  producer, n multiple consumers and a MAX number of items produced.
I have to use Condition Variables. I have 2 big doubts:
1- How to stop the consumers when all the items are created by the producer? I mustn't use global variables to solve this.
My problem is that all the consumers remain waiting for the producer that has just finished its execution because he produced all the items.
2-Each item has a random id that represents the id of the consumer that is supposed to consume it. So a consumer can only consume its own item (marked by the producer randomly at the beginning). How to implement this with condition variables.
My code works with 1 prod and 1 cons. When I have more than 1 consumer I don't know how to terminate the consumers thread when all the items are produced.
This is my code now:
static void * producer (void * arg)
{
   ITEM    item;

   int j = 1;
   while (j <=  NROF_ITEMS)
   {
       rsleep (PRODUCER_SLEEP_FACTOR);

          item = create_item(j);

           pthread_mutex_lock (&mutex);
           while(item_counter == BUFFER_SIZE)
              pthread_cond_wait(&not_full_condition, &mutex);

        put(item);
        printf("%04x\n", item); // write info to stdout

        pthread_cond_signal (&not_empty_condition);

        pthread_mutex_unlock (&mutex);
        j++;

    }

    pthread_exit(0);

   // TODO:
   // * inform consumers that we're ready

    //HERE I NEED TO STOP THE CONSUMER THREAD
}

static void * consumer (void * arg)
{
    ITEM    item;   // a consumed item
    int     id;

    int * argid;
    argid = (int*) arg;
    id = *argid;
    free(arg);

     while (i < NROF_ITEMS)
    {
        rsleep (100 * NROF_CONSUMERS);

         pthread_mutex_lock (&mutex);

              while(item_counter == 0)
                pthread_cond_wait(&not_empty_condition, &mutex);

              printf("\n C%d signalled by the producer",id);

              item = get_after_check();
              printf("%*s    C%d:%04x\n", 7*id, "", id, item);

              pthread_cond_signal (&not_full_condition);

            pthread_mutex_unlock (&mutex);
            i++;

 }

   pthread_exit(0);
}


text:
Q: dynamically set the level based on the application is run on the server I want to change the log level dynamically based on TEST/PROD server accessing the application.
Our web app has a lot of DEBUG and INFO,error log statements. Once we deploy the .war file to the test / production servers,
the log4j.xml also gets deployed which results in a lot of DEBUG and INFO statements in the log files.
How to show only error logs in PROD server and debug and error logs in DEV/TEST server. Apache Tomcat is the server we are using to deploy the application.
log4j.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration>
    <!-- This appender logs to the console -->
    <appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%-5p] [%c{1}] [%M:%L] - %m%n"/>
        </layout>
    </appender>

<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
        <param name="file" value="${catalina.home}/logs/myProject.log"/>
        <param name="append" value="true" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L %m %n" />
        </layout>
    </appender>

    <!-- Set "debug" log level for project code  -->
    <logger name="com.choonchernlim.myproject">
        <level value="info"/>
    </logger>

    <!-- Set "info" log level for Spring framework  -->
    <logger name="org.springframework">
        <level value="info"/>
    </logger>

    <!-- Set "debug" log level for Hibernate framework  -->
    <logger name="org.hibernate">
        <level value="debug"/>
    </logger>

    <root>
        <!-- The default log level is "warn" -->
        <priority value="warn"/>
        <appender-ref ref="consoleAppender"/>
    </root>
</log4j:configuration>

Included below tags in web.xml:
<context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/log4j.xml</param-value>
</context-param>

One approach i could think of is to edit setenv.bat from apachetomcatserver\bin and add loglevel. But how to set loglevels dynamically in the log4j.xml file???
in tomcatserver : catalinahome\bin\setenv.bat
set loglevel=error

How to dynamically set the loglevel so that when application is deployed in TEST all logs are shown and when deployed in PROD only error log messages are shown in the log file.
I am using log4j1.2,spring,java.

A: You would have to create different log4j.xml-files for the corresponding environments. And then during startUp, you can simply provide the path to the log4j.xml configuration it should use.
Application parameter:
-Dlog4j.configuration=path/to/env/folder/log4j.xml

A: If you are using spring framework, you can use logback for logging configuration and then you can control log level based on your active spring profile.
You can get some help form following examples-
http://www.baeldung.com/spring-profiles
https://springframework.guru/using-logback-spring-boot/


text:
Q: How To Import External Library to OpenCV I would like to extract features of images using opencv 3.0 with Visual Studio 2013.
My code:
#include <stdio.h>
#include <iostream>
#include "opencv2\core.hpp"
#include "opencv2\features2d.hpp"
#include <opencv2\xfeatures2d.hpp>
#include <opencv2\highgui.hpp>

using namespace cv;
using namespace cv::xfeatures2d;

void readme();

/** @function main */
int main(int argc, char** argv)
{
    if (argc != 3)
    {
        readme(); return -1;
    }

    Mat img_1 = imread(argv[1], IMREAD_GRAYSCALE);
    Mat img_2 = imread(argv[2], IMREAD_GRAYSCALE);

    if (!img_1.data || !img_2.data)
    {
        std::cout << " --(!) Error reading images " << std::endl; return -1;
    }

    //-- Step 1: Detect the keypoints using SURF Detector
    int minHessian = 400;

    Ptr<SURF> detector = SURF::create(minHessian);

    std::vector<KeyPoint> keypoints_1, keypoints_2;

    detector->detect(img_1, keypoints_1);
    detector->detect(img_2, keypoints_2);

    //-- Draw keypoints
    Mat img_keypoints_1; Mat img_keypoints_2;

    drawKeypoints(img_1, keypoints_1, img_keypoints_1, Scalar::all(-1), DrawMatchesFlags::DEFAULT);
    drawKeypoints(img_2, keypoints_2, img_keypoints_2, Scalar::all(-1), DrawMatchesFlags::DEFAULT);

    //-- Show detected (drawn) keypoints
    imshow("Keypoints 1", img_keypoints_1);
    imshow("Keypoints 2", img_keypoints_2);

    waitKey(0);

    return 0;
}

/** @function readme */
void readme()
{
    std::cout << " Usage: ./SURF_detector <img1> <img2>" << std::endl;
}

Error:
Cannot open include file: 'opencv2\xfeatures2d.hpp': No such file or directory

In  C:\OpenCV3.0.0\opencv\build\include\opencv2
directory, there is no xfeatures2d.hpp file. Thus, I should import this library externally. How to fix it?


text:
Q: For loop through array.length only executes once The code below only executes through the first for loop once, yet all the other for loops perform as expected. Does anyone know why this is the case? I'm not sure how relevant the bulk of the (inefficient, poorly formatted) code within the loop is but I include it nonetheless.
var numbers = [9795526789839145, 2861747566959730, 4498854833783559, 6301982162016598, 1131197164065322];
for (i = 0; i < numbers.length; i++) {
    var current = numbers[i];
    var currentStr = current.toString();
    var reverseStr = currentStr.split('').reverse().join('');
    var reverseArr = [];

    for (i = 0; i < reverseStr.length; i++) {
        reverseArr.push(reverseStr[i]);
    }

    var A = 0;
    for (i = 0; i < reverseArr.length; i += 2) {
        A += Math.round((reverseArr[i]));
    }

    var evenDigits = [];
    for (i = 1; i < reverseArr.length; i += 2) {
        evenDigits.push(reverseArr[i]);
    }

    for (i = 0; i < evenDigits.length; i++) {
        evenDigits[i] = evenDigits[i] * 2;
        if (evenDigits[i] > 9) {
            var temp = evenDigits[i].toString();
            var firstInt = Math.round(temp[0]);
            var secondInt = Math.round(temp[1]);
            evenDigits[i] = firstInt + secondInt;
        }
    }

    var B = 0;
    for (i = 0; i < evenDigits.length; i++) {
        B += evenDigits[i];
    }

    var sum = A + B;

    if (sum % 10 == 0) {
        console.log('Yes');
    } else console.log('No');
}

A: In your code you are using same instance of 'i' variable to iterate all loops.
Solution is to use different index variables to iterate external and internal loops
var numbers = [9795526789839145, 2861747566959730, 4498854833783559, 6301982162016598, 1131197164065322];
var i = 0;
var j = 0;
for (j=0; j < numbers.length; j++) {
    var current = numbers[j];
    /...
}

JavaScript behaves like this because 'i' is not scoped to block (like in Java od C#). In ES2015 you can use let or const to bind variable to block scope (in this sample to for loop)


text:
Q: How do you drop a weapon in Borderlands 2 without accessing the menu? I've seen people quick drop their currently holding weapon in Borderlands 2 without accessing the menu, but I can't figure out what key combination I have to press! I'm playing on my PC with an xbox controller.

A: Actually, you can.
In the PC version there is a keyboard mapping for that in the controls menu. It's by the lower end of the list, so it's easy to miss. By default it is '-' or something. Not sure about xbox controllers though.
P.S:
I didn't even know about that until I got a crappy loot spree once and the first time I came across a decent gun after that I thought "Hmm, I don't even want to keep this thing, there should be a more expressive way to get rid of stuff!" After I found that option, I had tons of fun tossing things over the ledge above the vending machines in Frostburn Canyon, as there were too many loot-dropping spiderants and my backpack was too small, so I needed several trips before everything was piled up and ready to be sold.

A: If you have a full backpack, and you hold E while looking at another weapon with a weapon in your hands, you will equip the one you are looking at and toss out the other one.
This only works if you have a full backpack. You cannot throw out items without going to the menu if you do not have a full backpack.


text:
Q: Raspberry serial port automatically stops after some time I am using neo 6m gps module with raspberry pi 3 , i have attached it on serial port ttyAMA0 , but it reads data for only small time and then port closes automatically , and sometime the data is also corrupt which causes gps.js module to throw an error.
Execution Demo screenshot.
Below is my node js script:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var file = '/dev/ttyAMA0';

const SerialPort = require('serialport');
const parsers = SerialPort.parsers;

const parser = new parsers.Readline({
  delimiter: '\r\n'
});

const port = new SerialPort(file, {
  baudRate: 9600
});

port.pipe(parser);

var GPS = require('../../gps.js');
var gps = new GPS;

gps.on('GGA', function(data) {
  io.emit('position', data);
  console.log("Latitiude :", data.lat);
  console.log("Longitude :", data.lon);
});

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/maps.html');
});

http.listen(3000, function() {

  console.log('listening on *:3000');
});

port.on('data', function(data) {
  gps.updatePartial(data);
});

process.on('unhandledRejection', function (reason, p) {
  //I just caught an unhandled promise rejection, since we already have fallback handler for unhandled errors (see below), let throw and let him handle that
  console.log("=============");
  console.log(reason);
  console.log("=============");
  return;
});

process.on('rejectionHandled', () => {});

process.on('uncaughtException', function (error) {
    console.log(error);
});

port.on('close', function(data) {

  console.log("Port closed");
  console.log(port.binding);

    });

Output screenshot

A: I solved the problem by reinstalling the raspbian, OS was closing the port for some reason


text:
Q: Read html and style tags content inside an html like php file? I am trying to read all the css 'class' names and 'id' names used inside  tag in a php file which has  and  tags. I want to read all the class names and id names into an array. I am reading the file with 'fopen', file_get_contents and file methods but they are all not working properly. All I am getting the data as a webpage that is file content is showing as a webpage.
I am trying to read the below file
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
<head>
<!-- Tekion related css -->
<style type="text/css">
    div.formThirdParty{
        width: 960px;
        min-height: 760px;
        overflow-x: hidden;
        overflow-y: auto;
        display: block;
        background: #ffffff;
    }
</style>
<script type="text/javascript" async="" src="https://static.ed.edmunds-media.com/unversioned/libs/edw/edw-lib-0.0.2-min.js"></script><script type="text/javascript" async="" src="https://www.google-analytics.com/plugins/ua/linkid.js"></script><script type="text/javascript" async="" src="https://www.google-analytics.com/analytics.js"></script><script async="" src="https://www.googletagmanager.com/gtm.js?id=GTM-PQJ2GJZ&l=CarCodeDataLayer"></script><script type="text/javascript">
    var tekion = {
      DEALER_ID: 5,
      TENANT_NAME: 'cacargroup'
    }
</script>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css" />
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap-theme.min.css" />

<link rel="stylesheet" href="https://s3-us-west-1.amazonaws.com/scheduling-buildfiles/tst/style.css" />

<title>INFINITI Service Dublin | Pleasanton</title>
<meta name="description" content="Schedule an oil change, tire rotation, brake replacement, or service inspection in Dublin for your INFINITI car or SUV. Get in touch with us at Dublin INFINITI." />
<link rel="stylesheet" type="text/css" href="./infiniti_files/bundle_f7q.css" />
<style type="text/css">
    .bg-color {
        background-color: ;
    }
    .hide-page-background
    {
        background: none repeat scroll 0 0 transparent !important;
    }

    .clickMapBlockTitle:after {
        background-image: url("http://media-dmg.assets-cdk.com/websites/5.0-353/websitesEar/websitesWebApp/common/images/spriteClickMap.png");
    }

My code is below:
$file_path = "/path/to/file/file_name.php";
$myfile = fopen($file_path, "r") or die("Unable to open file!");

Trial-1:
while(!feof($myfile)) {
  echo fgets($myfile) . "<br>";
}

Trial-2:
$file_data = fread($myfile,filesize($file_path));
echo strip_tags($file_data,'<html><style>');

Trial-3:
$lines = file($file_path, FILE_IGNORE_NEW_LINES);
print_r($lines);

All the output I am getting is a webpage but not the content. My expected result is only the content(like only class names and id names) inside 'style' tags after reading the total file. The result I am getting is if I try to echo the content after reading the data from the file is a webpage since the file has 'style' tags inside. Any help Please? Thanks.

A: I used a preg_match_all to get all the style tags' contents:
$contents = file_get_contents($file_path);

preg_match_all('/[<]style[^>]*[>]([^<]+)[<]\/style[>]/', $contents, $matches, PREG_OFFSET_CAPTURE);

for($i = 0; $i < count($matches[1]); $i++) {
    var_dump($matches[1][$i][0]);
}


text:
Q: 'use strict' in angularjs and window.x undefined but still runs the file without error I am trying to write AngularJS and JavaScript function but I have a question about the keyword 'use strict'. Say the code is something like below kept in a html file within script tag. Now remember we are using 'use strict' keywords. And window.x is not defined anywhere within the html. When I load the HTML file on Google Chrome why does it not complain about window.x? Isn't it undefined? It outputs as window.x: undefined. So shouldn't any variable that is not defined be detected by AngularJS and spew out as an error in the Google Chrome Console or something? Why doesn't Chrome complain about the undefined variable?

(
  function() {
    'use strict';
    var x = "hello";

    console.log("window.x:", window.x); //undefined
    console.log("x:", x); //hello
    angular.module('myFirstApp', [])
      .controller('MyFirstController', function() {

      });
  })();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

A: 'use strict' does not check for property existence/access (which window.x is trying to find a property x on window) - that would be way too costly. Instead, it ensures that variables are declared.


text:
Q: ByRef vs ByVal performance when passing strings Reading Which is faster? ByVal or ByRef? made me wonder whether the comments in there did apply to Strings in terms of performance. Since strings are copied before being passed, isn't it much more efficient (if the callee doesn't need a copy of string course) to pass strings ByRef?
Thanks,
CFP.
Edit: Consider this code, which made me think there was some kind of copy going on:
Sub Main()
    Dim ByValStr As String = "Hello World (ByVal)!"
    Dim ByRefStr As String = "Hello World (ByRef)!"

    fooval(ByValStr)
    fooref(ByRefStr)

    Console.WriteLine("ByVal: " & ByValStr)
    Console.WriteLine("ByRef: " & ByRefStr)

    Console.ReadLine()
End Sub

Sub fooval(ByVal Str As String)
    Str = "foobar"
End Sub

Sub fooref(ByRef Str As String)
    Str = "foobar"
End Sub

It outputs:
ByVal: Hello World (ByVal)!
ByRef: foobar

A: I decided to check this for myself, to get a more "scientific" answer.  They are the same.  If I use the code below, ByVal is about 2% slower than ByRef.  If, however, I swap them around, so that I'm timing ByRef before ByVal, then ByRef is about 2% slower.  So, what actually matters more than ByRef or ByVal in this case is the order in which they run :)
Function CreateString()

    Dim i As Integer
    Dim str As String = ""

    For i = 1 To 10000
        str = str & "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Next i

    Return str
End Function

Sub fooval(ByVal Str As String)
    Str = Str & "foobar"
End Sub

Sub fooref(ByRef Str As String)
    Str = Str & "foobar"
End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim str As String = CreateString()
    Dim stopWatch As New Stopwatch
    Dim i As Integer

    stopWatch.Start()
    For i = 1 To 1000
        fooval(str)
    Next i
    stopWatch.Stop()
    Dim valtime As Long = stopWatch.ElapsedMilliseconds

    stopWatch.Restart()
    For i = 1 To 1000
        fooref(str)
    Next i
    stopWatch.Stop()
    Dim reftime As Long = stopWatch.ElapsedMilliseconds

    MsgBox("Val took " & valtime & " milliseconds and Ref took " & reftime & " milliseconds")
End Sub

A: Strings are not copied before being passed. Strings are reference types, even though they behave somewhat like value types.
You should use whatever makes the most sense in the context of your requirements. (And if your requirements happen to be something like "must squeeze every last nanosecond of performance at the expense of all other considerations" then you should probably crack out the profiler rather than asking on stackoverflow!)
This is almost certainly something that you don't need to worry about, and I doubt if there's ever a significant performance difference. The only situation where I can see any chance of a difference would be when passing big value types.

A: To understand the behavior of class-types, including strings, regard all class-type parameters, variables, fields, and array elements, etc. as holding "object ids".  If Foo is a variable of type string, the statement Foo = 12345.ToString(); will create a new object id (hypothetically, Object ID#197), and create a new object of type string with that id, holding the five characters "12345".  It will then store Object ID#197 into the variable Foo.  If one calls a routine with a non-ref parameter param, and passes Foo to it, then param will be a local variable holding Object ID #197.  The statement param += "6"; would create a new object (e.g. Object ID #521), of type string, holding the six characters "123456" and store Object ID #521 into param.  Note that Foo still holds Object ID#197, and that object still holds the five-character string "12345".
If param had been passed by ref, then the statement param += "6" would have stored Object ID #521 into Foo.  It still would not have caused any observable change to Object #197, except perhaps to make it eligible for garbage collection (if Foo had been the only reference to Object #197, overwriting it would mean that there would no longer exist any reference to that object anywhere in the universe).
Note that it's generally pretty easy to reason about immutable class types like string, even without thinking in terms of Object IDs, since the only way to change the sequence of characters represented by a string variable is to store a different Object ID there.  Thinking in terms of Object IDs becomes essential, however, when dealing with mutable class types.  Passing a variable of class type Car, not by ref, would be equivalent to copying a VIN from one slip of paper to another, and handing the latter slip of paper to some shop workers, and asking them to do something with it.  If the first paper originally identified a red car with VIN#15934, then when the workers were done the first paper might identify a blue car with VIN#15934, but it would be the same car.  Nothing the workers could do with the slip of paper they were given, nor anything they could do with the car, would change which car the first paper referred to.  On the other hand, passing the parameter by reference would be more like the shop workers a piece of paper with the VIN written on it, and getting the paper back from them when they were done.  If the workers could cross out the VIN and write another, then when they returned the slip of paper it might refer to the same car or a different car; if it refers to a different car, the car to which it originally referred may or may not have been modified, and the car to which the paper ends up referring may or may not bear any resemblance to the original.


text:
Q: Camera Overlay View on Just Capture Section I am trying to add a cameraOverlayView on a UIImagePickerController, but I want the overlay to cover just the part of the screen that shows what will be captured by the camera, not the "Cancel" button, take photo button, flash settings, or anything like that. How can I dynamically determine what the frame of the UIImageView of my overlay should be?
I've attached an image to illustrate exactly the section I'm talking about.

A: you can use AVCamCaptureManager to get overlay  which cover just the part of the screen that shows what will be captured by the camera only , not buttons

A: i had same situation, what i did, i created an UIImageView like follow:
    myview                 = [[UIImageView alloc]init];
    myview.frame            =  CGRectMake(0, 68, 320, 430);
// note that these frames were as per my needs, you can manipulate them as per yours.

then add this image view as
myImagePicker.cameraOverlayView   = myview;

try this with setting some background color and check whether its covering entire camera part or not, you would just need to set frames, thats all!!!
And yes it does work!


text:
Q: Running a batch file on Kid3 ID3 MP3 tagger I finally gave up after 120 hours of not finding a .NET or javascript/jquery plugin that can read and write to a COMPRESSED custom user frame (TXXX) in ID3v2 MP3 audio file.
UltraID3Lib: cannot read or write COMPRESSED Frames (last updated 2009, author Mitchell S. Honnert fell off face of the earth).
ID3Lib-sharp: cannot read or write COMPRESSED Frames (last updated 2012)
JavaScript-ID3-Reader: can return bytes but it's mostly the wrong bytes. Cannot write anything.
I cannot use the multitudes of Node.js or PHP scripts for my project so they are out of the question.
The only code I found that can read and write compress frames is Kid3.
http://sourceforge.net/projects/kid3/
However, it is written in C (I don't know that) and uses third party frameworks since it was not built in windows. The Command  program required 13MB of support dlls, QMs, and whatevers.
I have no choice at his point but to try and use it's separate command program kid3-cli.exe
So here's my question:
Here is the way to read a TXXX frame using the program at the command prompt.
"71F3-15-FOO58A77" is the name of the TXXX frame and the "2" gets the text value it holds:
cd "C:\mp3folder"
select "test.mp3"
get "71F3-15-FOO58A77" "2"
export "clipboard" "CSV unquoted" "2"

QUESTION: HOW DO I use a Batch file to run these commands?
According to kid3 documents. It shows using -c as grouped commands. Windows cmd (or the program) on windows does know what -c is.
Example: I double click the batch file and it should:

*

*start the program

*sent the program (not cmd) the above 4 lines

*each must be executed separately.

Sounds simple, but I can't get it to even execute one of the programs code after starting.
Any ideas? and and can someone write a ID3 tag program that can read and write COMPRESSED TXXX tags without using node.js, PHP or a server in Windows.
I will buy them a beer because I'm really a (cheap) designer by trade and a pert-time programmer only when I have too.
  Here is a zip file of a COMPRESSED TXXX Frame in test.mp3 to test:
  [http://robbiestewart.ca/test.zip][1]

*

*Download Kid3 and use its windows GUI (kid3.exe) to view the custom user frame (TXXX).

*Run the included kid3-cli.exe to do the same at the command prompt.

*Try to do the same in a batch file.

A: According to the help file, you should be able to use the command
kid3-cli -c 'cd "C:\mp3folder"' -c 'select "test.mp3"' -c 'get "71F3-15-F0058A77" "2"' -c 'export "clipboard" "CSV unquoted" "2"'
I ran it on the file you provided and seven tabs followed by 0:00.00 were put on my clipboard, but the value of the TXXX field indicated by the GUI was output to my command prompt.


text:
Q: Django website giving trouble serving static files I am working on a multi-app website. And I have bunch of noob questions.
My dir structure looks like as below:
/var/www/html/portal
    src/
        manage.py
        portal/
        static/
            admin/
            css/
            img/
            js/
            fonts/
        templates/
            base.html
            homepage.html
    venv/

*

*Is my dir structure as per as Django standards?

*Are my STATIC files settings correct?
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
Or should it be
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')

*Should I collectstatic after copying all my static files such as css,js etc or I can do it before copying files in those dirs?

*If I do collectstatic without mentioning STATIC_ROOT I get an exception
django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.
But when I replace STATICFILES_DIRS with the following, my .css files stop serving. What am I doing wrong?
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')

A: You don't need to run staticfiles when you're running a development server and DEBUG is set to True.
Static and media files can be then served directly via the web process (Docs) with adding these lines to your main urls.py:
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

As to the whole STATIC_URL, STATIC_ROOT, MEDIA_URL and MEDIA_ROOT, they're all related to how you'll serve your app in production, with a proper webserver.
What usually happens then is that the webserver (i.e. Nginx) handles serving files, not the Django app. But the Django app needs to know where are they. So:
STATIC_URL and MEDIA_URL need to be the same in your Django app settings and in your webserver config, for example with Nginx:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
...

location /static {
    alias /home/myusername/myproject/static/;
}
location /media {
    alias /home/myusername/myproject/media/;
}

STATIC_ROOT MEDIA_ROOT are 100% about how you want to structure your project on the server. Assuming the above, you need to work out how to point it to /home/myusername/myproject/static/.
Example of my settings:
BASE_DIR = Path(__file__).parent.parent.parent

MEDIA_URL = '/media/'
MEDIA_ROOT = str(BASE_DIR.joinpath('media'))

STATIC_URL = '/static/'
STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles'))

Media files will be directly uploaded to the MEDIA_ROOT, but notice that you need to somehow get the static files from your applications (which could be in a number of folders, a library you use can have some extra static files, Django Admin has then, etc.) to the folder that Nginx is pointed to (which should be the same as STATIC_ROOT). That's where collectstaticfiles comes in and copies all your static files to that directory.

A: In regards to directory structure, there are differences of opinion on how it should be set up. A quick google search can bring up some websites and discussions on Django project structures. I recommend reading some of the information to determine what is best for your and your project.
The Django documentation has a best practices page as well that is a good resource/reminder. Django Best Practices.
I mainly followed the Two Scoops of Django directory structure. The Two Scoops has helped me a lot in understanding this.  My own twist looks something like this.
src/
  app/
    templates/
       app_name/
         base.html
         other_pages.html
    tests/
       tests.py
    app_files.py
  static/
    images/
    css/
    etc..
  templates/
    global_includes/
        include_file.html
    base.html

The collectstatic should not effect the serving of your static files during development. From what I have learned, collectstatic is more for when you are serving your static files during deployment from a separate server, or aws, heroku, etc. More info can be found here in the docs: Managing Static Files, staticfiles app, Deploying static files
I have learned that if my CSS files are not serving, it usually has something to do with my path. Chrome developer tools inspect element/console helps me with any path errors.
Have you added
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

to your your main urlpattern/urls.py?
Here is more information on serving files during development: Serving static files during development.
Lastly check that your BASE_DIR is following the correct path for your project. You may have to change it.
I hope this helps.

A: Remember that if you have DEBUG set to 'False' it will ignore the staticfiles setting because it is expected that your webserver will be serving this directly. This caught me out a few times until I realized I hadn't updated the staticfiles folder (which I keep in a separate repository for reasons I can't remember now).

A: This seems to work in current django (2.2) :
from django.conf.urls.static import serve

urlpatterns += [
    path(settings.STATIC_URL[1:], serve, {'document_root': settings.STATIC_ROOT })
]


text:
Q: Cannot load a NSURL with spaces or hashtags in iPhone app Twitter has a nice feature that allows you to preload status messages using the following format:
http://twitter.com/?status=@HelloWorld Hello World

or alternatively:
http://twitter.com/?status=%40HelloWorld%20Hello%20World

I am trying to add a button to my iPhone app which will open Safari to the above pre-populated tweet.
However I am running into the problem where the percentage signs are being double escaped.
Here is the code that I have tried:
First an example of what does work
NSString* urlText = @"http://www.twitter.com/home?status=@HelloWorld";
NSURL *url = [NSURL URLWithString: urlText];
if (![[UIApplication sharedApplication] openURL:(NSURL*)url])
        NSLog(@"%@%@",@"Failed to open url:",[url description]);

This code works like a charm and outputs:
http://twitter.com/?status=%40HelloWorld

Code that doesn't work
NSString* urlText = @"http://www.twitter.com/home?status=@HelloWorld Hello World";
NSURL *url = [NSURL URLWithString: urlText];
if (![[UIApplication sharedApplication] openURL:(NSURL*)url])
        NSLog(@"%@%@",@"Failed to open url:",[url description]);

This creates a null NSURL. This I can only assume because URLWithString does not accept text with spaces in it.
So I tried this code:
NSString* urlText = @"http://www.twitter.com/home?status=@HelloWorld%20Hello%20World";
NSURL *url = [NSURL URLWithString: urlText];
if (![[UIApplication sharedApplication] openURL:(NSURL*)url])
   NSLog(@"%@%@",@"Failed to open url:",[url description]);

However that creates the URL:
http://twitter.com/?status=%40HelloWorld%2520Hello%2520World

So I have escaped my percentage sign %, which is of course not what I intended.
Of course people have been talking about using the function: stringByAddingPercentEscapesUsingEncoding
So I wrote this code:
NSString* urlText = @"http://www.twitter.com/home?status=@HelloWorld%20Hello%20World";
urlText = [urlText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *url = [NSURL URLWithString: urlText];
if (![[UIApplication sharedApplication] openURL:(NSURL*)url])
    NSLog(@"%@%@",@"Failed to open url:",[url description]);

However you again get the double escaping problem:
http://twitter.com/?status=%40HelloWorld%2520Hello%2520World

I'm hoping that someone might know some sort of work around. Ideally I would like to also include hashtags, but for now just getting spaces in would be a huge step forward.

A: So it turns out that the problem wasn't being caused by the NSURL object but twitter itself.
This is the correct code to use:
NSString* urlText = @"http://twitter.com/home?status=@HelloWorld Hello World";
urlText = [urlText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *url = [NSURL URLWithString: urlText];
if (![[UIApplication sharedApplication] openURL:(NSURL*)url])
    NSLog(@"%@%@",@"Failed to open url:",[url description]);

One thing I didn't realize about twitter is this using this twitter address:
http://www.twitter.com/home?status=

will auto-escape your status.
While:
http://twitter.com/home?status=

will not auto-escape.

A: Try this:
    NSString* urlText = @"http://www.twitter.com/home?status=@HelloWorld Hello World";
    NSString* newText = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)urlText,NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8);
    NSURL* url = [NSURL URLWithString: urlText];
    if (![[UIApplication sharedApplication] openURL:(NSURL*)url])
    NSLog(@"%@%@",@"Failed to open url:",[url description]);

A: I created this category on NSString for encoding strings as URLs:
@interface NSString (URLEncoding)
@property (readonly) NSString *URLEncodedString;
@end

@implementation NSString (URLEncoding)
- (NSString*)URLEncodedString
{
    NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, CFSTR("?=&+"), kCFStringEncodingUTF8);
    return [result autorelease];
}
@end

In your case, you would use it like this:
NSString *urlText = @"http://www.twitter.com/home?status=@HelloWorld Hello World";
NSURL *url = [NSURL URLWithString:[urlText URLEncodedString]];


text:
Q: Milo OPC UA Server push Values in Server Logic I'm a newbie to OPC UA.
My target is to create a OPC UA Server and as soon somebody changes any Value I want to receive a function call, so I can react on the Input.
To archive this, I created a server with MILO-Eclipse. In my Namespace I have some functions called onDataItemsModified() etc. But if I change a Value in my Server with UAExpert, the Server doesn't call the onDataItemsModified() Function. Is there another way to receive a notification as soon somebody changed a value on my Server? I saw the opportunity to add a client and register an observer, but I thought I can see the changes directly as Server and dosnt need to implement a client.

A: When a client writes to an attribute of a Node in your address space it comes in via the Write service, not any of the Monitored Item services.
You can override the write call in your address space, or simply add an AttributeObserver or an AttributeDelegate to the Nodes you create.


text:
Q: SonarScanner (C#) not honoring in-code StyleCop warning suppression I am trying to use SonarQube for static code analysis for my organization.
All our C# projects already have StyleCop enabled which has helped us a lot in terms of code readability. Now we want to utilize SonarQube for static code analysis.
I successfully hosted the SonarQube server locally following the guidelines provided here. I am able to run the analysis successfully and generate the sonarqube report when there are no warning-suppressions in the code.
ISSUE: Sonarqube does not consider in-code warning-suppressions and msbuild fails.
I created a sample C# console application project to demo the problem I am facing.
StyleCop is enabled (Installed nuget: StyleCop.Analyzers v1.1.118) and warnings are converted to errors.
Below is the snippet of the ruleset
...
...
...
<Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
...
...
<Rule Id="SA1307" Action="Error" />
...
...

The project has the below files:
1. Program.cs
// <copyright file="Program.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

namespace StyleCopSonarQubeIssue
{
    /// <summary>
    /// The program class.
    /// </summary>
    internal class Program
    {
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public static void Main(string[] args)
        {
            // Method intentionally left empty.
        }
    }
}

*SystemInfo.cs

// <copyright file="SystemInfo.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

namespace StyleCopSonarQubeIssue
{
    using System.Runtime.InteropServices;

    /// <summary>
    /// The sytem info enum.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public struct SystemInfo
    {
        /// <summary>
        /// Oem Id.
        /// </summary>
        public uint dwOemId;

        /// <summary>
        /// Page size.
        /// </summary>
        public uint dwPageSize;
    }
}

*packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="StyleCop.Analyzers" version="1.1.118" targetFramework="net452" developmentDependency="true" />
</packages>

*GlobalSuppressions.cs

[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:Accessible fields should begin with upper-case letter", Justification = "Native code.", Scope = "member", Target = "~F:StyleCopSonarQubeIssue.SystemInfo.dwPageSize")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:Accessible fields should begin with upper-case letter", Justification = "Native code.", Scope = "member", Target = "~F:StyleCopSonarQubeIssue.SystemInfo.dwOemId")]

*App.config (default - no changes)

Build the project - SUCCESS
Follow the guidelines by SonarQube to analyze the above project.

*

*SonarScanner.MSBuild.exe begin /k:"StyleCopSonarQubeIssue" /d:sonar.host.url="http://localhost:9000" /d:sonar.login=""

*MsBuild.exe /t:Rebuild
You will be below error after this statement:
Microsoft (R) Build Engine version 14.0.27530.0
Copyright (C) Microsoft Corporation. All rights reserved.

Build started 2019-07-22 11:17:25 AM.
The target "RazorCoreCompile" listed in a BeforeTargets attribute at "C:\Users\bshah\Documents\Visual Studio 2015\Projects\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue\.sonarqube\bin\targets\SonarQube.Integration.targets (453,49)" does not exist in the project, and will be ignored.
Project "C:\Users\bshah\Documents\Visual Studio 2015\Projects\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue.csproj" on node 1 (Rebuild target(s)).
CoreClean:
  Creating directory "obj\Debug\".
GenerateBindingRedirects:
  No suggested binding redirects from ResolveAssemblyReferences.
CreateProjectSpecificDirs:
  Creating directory "C:\Users\bshah\Documents\Visual Studio 2015\Projects\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue\.sonarqube\conf\0".
CoreCompile:
  C:\Program Files (x86)\MSBuild\14.0\bin\csc.exe /noconfig /nowarn:1701,1702 /nostdlib+ /platform:anycpu32bitpreferred /errorreport:prompt /warn:4 /define:DEBUG;TRACE /highentropyva+ /reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\Microsoft.CSharp.dll" /reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\mscorlib.dll" /reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\System.Core.dll" /reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\System.Data.DataSetExtensions.dll" /reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\System.Data.dll" /reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\System.dll" /reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\System.Net.Http.dll" /reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\System.Xml.dll" /reference:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\System.Xml.Linq.dll" /debug+ /debug:full /filealign:512 /optimize- /out:obj\Debug\StyleCopSonarQubeIssue.exe /ruleset:"C:\Users\bshah\Documents\Visual Studio 2015\Projects\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue\.sonarqube\conf\0\merged.ruleset" /errorlog:"C:\Users\bshah\Documents\Visual Studio 2015\Projects\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue\bin\Debug\StyleCopSonarQubeIssue.exe.RoslynCA.json" /subsystemversion:6.00 /target:exe /warnaserror- /utf8output /analyzer:C:\Users\bshah\AppData\Local\Temp\.sonarqube\resources\0\Google.Protobuf.dll /analyzer:C:\Users\bshah\AppData\Local\Temp\.sonarqube\resources\0\SonarAnalyzer.CSharp.dll /analyzer:C:\Users\bshah\AppData\Local\Temp\.sonarqube\resources\0\SonarAnalyzer.dll /analyzer:C:\Users\bshah\AppData\Local\Temp\.sonarqube\resources\1\Google.Protobuf.dll /analyzer:C:\Users\bshah\AppData\Local\Temp\.sonarqube\resources\1\SonarAnalyzer.dll /analyzer:C:\Users\bshah\AppData\Local\Temp\.sonarqube\resources\1\SonarAnalyzer.VisualBasic.dll /analyzer:..\packages\StyleCop.Analyzers.1.1.118\analyzers\dotnet\cs\StyleCop.Analyzers.CodeFixes.dll /analyzer:..\packages\StyleCop.Analyzers.1.1.118\analyzers\dotnet\cs\StyleCop.Analyzers.dll /additionalfile:"C:\Users\bshah\Documents\Visual Studio 2015\Projects\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue\.sonarqube\conf\cs\SonarLint.xml" /additionalfile:"C:\Users\bshah\Documents\Visual Studio 2015\Projects\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue\.sonarqube\conf\0\ProjectOutFolderPath.txt" GlobalSuppressions.cs Program.cs Properties\AssemblyInfo.cs SystemInfo.cs "C:\Users\bshah\AppData\Local\Temp\.NETFramework,Version=v4.5.2.AssemblyAttributes.cs"
  Using shared compilation with compiler from directory: C:\Program Files (x86)\MSBuild\14.0\bin
Program.cs(10,20): warning S1118: Add a 'protected' constructor or the 'static' keyword to the class declaration. [C:\Users\bshah\Documents\Visual Studio 2015\Projects\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue.csproj]
_CopyAppConfigFile:
  Copying file from "App.config" to "bin\Debug\StyleCopSonarQubeIssue.exe.config".
C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(3813,5): error MSB3030: Could not copy the file "obj\Debug\StyleCopSonarQubeIssue.exe" because it was not found. [C:\Users\bshah\Documents\Visual Studio 2015\Projects\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue.csproj]
Done Building Project "C:\Users\bshah\Documents\Visual Studio 2015\Projects\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue.csproj" (Rebuild target(s)) -- FAILED.

Build FAILED.

"C:\Users\bshah\Documents\Visual Studio 2015\Projects\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue.csproj" (Rebuild target) (1) ->
(CoreCompile target) ->
  Program.cs(10,20): warning S1118: Add a 'protected' constructor or the 'static' keyword to the class declaration. [C:\Users\bshah\Documents\Visual Studio 2015\Projects\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue.csproj]

"C:\Users\bshah\Documents\Visual Studio 2015\Projects\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue.csproj" (Rebuild target) (1) ->
(CopyFilesToOutputDirectory target) ->
  C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(3813,5): error MSB3030: Could not copy the file "obj\Debug\StyleCopSonarQubeIssue.exe" because it was not found. [C:\Users\bshah\Documents\Visual Studio 2015\Projects\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue\StyleCopSonarQubeIssue.csproj]

    1 Warning(s)
    1 Error(s)

Time Elapsed 00:00:00.96

Check the detailed errors \bin\Debug*.exe.RoslynCA.json file and you will see that the warnings that are suppressed in GlobalSuppression.cs are not considered. So the C# compiler does not generate the .exe and msbuild fails.
Any pointers???

A: It looks like this compiler bug.
The bug is that there are circumstances in which asking the compiler to write analysis issues to a file stops the compiler from generating the .dll/.exe file. However, the compiler doesn't emit any errors either. The build then fails in a later step when MSBuild tries to copy the non-existent file.
You can check if you're affected by this bug by doing the following:

*

*Disable the SonarQube/SonarCloud analysis steps.

*Execute the build and check that it completes successfully

*Now add the following MSBuild parameter in the MSBuild step: /p:ErrorLog=RoslynIssues.json then check that the build still completes successfully.

If (2) succeeds but (3) fails then you're affected by the compiler bug.
Workarounds/solutions: the bug has been fix in MSBuild 16.1 so the fix is to upgrade to the latest version of the compiler. If that isn't possible, then an option is to change the severities of the issues being raised from Error to Warning by editing the ruleset.
(note: answer copied from this external thread)


text:
Q: undefined method 'book_id' for nil:NilClass I'm trying to make a simple book ordering application in Ruby on Rails and have been running into some problems. I am trying to create a "place an order" page from a link from each product, so that on this second page the book information is there and then there's just a form to fill in the quantity the customer wants. However I keep running into the undefined method 'book_id' for nil:NilClass error specified above (and when I delete that line of code I run into the same error on the next one - i.e. undefined method 'order_id').
Here's my code for the view that I keep messing up on:
<%= @order_item.book_id %>
<%= @order_item.order_id %>
<%= @order_item.total_pricel %>
<%= form_for @order_item.quantity do |f| %>
<%= f.label :quantity %>:
<%= f.text_field :quantity %><br />
 <%= f.submit %>
<% end %>

My OrderItem model should have the foreign keys order_id and book_id.
Here's my OrderItem model:
class OrderItem < ActiveRecord::Base
belongs_to :order
belongs_to :book

validates :quantity, presence: true, numericality: {only_integer: true, greater_than: 0}
validate :book_present
validates :price, presence: true
validate :order_present

def unit_price
    if persisted?
        self[:unit_price]
    else
        book.price
    end
end

def total_price
    unit_price * quantity
end

private
    def book_present
        if book.nil?
            errors.add(:book, "is not valid.")
        end
    end

def order_present
    if order.nil?
        errors.add(:order, "is not a valid order.")
        end
    end

def finalize
    self[:unit_price] = unit_price
    self[:total_price] = quantity * self[:unit_price]
end
end

And here's the controller:
class OrderItemsController < ApplicationController

def create
    @order = current_order
    @order_item = @order.order_items.new(order_item_params)
    @order.save
    session[:order_id] = @order.id
end

def update
    @order = current_order
    @order_item = @order.order_items.find(params[:id])
    @order_item.update_attributes(order_item_params)
    @order_items = @order.order_items
end

def destroy
    @order = current_order
    @order_item = @order.order_items.find(params[:id])
    @order_item.destroy
    @order_item = @order.order_items
end

private
def order_item_params
    params.require(:order_item).permit(:quantity, :book_id)
end
end

In addition to this being my first Rails project, I'm generally very new to coding and would really appreciate some help!

A: Your view isn't getting the @order_item instance variable from the controller.  If it's on your 'show' view then in your OrderItem Controller you will need a defined action like this for example:
def show
  @order_item = OrderItem.find(params[:id])
end

I also see a potential issue with your form..you have form_for @item_order.quantity.  Take out the .quantity part so that's it's just form_for @item_order.  Your form is bound to the @item_order object and it will know to save the quantity attribute from the f.text_field :quantity part of the form

A: Ok...First of all,you must need a book,order present in the db before you make or create items.So you need to first check if there is a book created,order created and then use both of them to create item.
So i assume,you item.rb model will have something like :-
belongs_to :book
belongs_to :order

And book.rb
has_many :items,:dependent=>:destroy


text:
Q: Postgres - Calculate average monthly rows I have a table that represents user's deposits into a savings account. I'd like to find the average number of deposits that a user makes per month but I'm having trouble getting there.
I've tried
SELECT date_part('month', timestamp) as month FROM savings_account_deposit
WHERE user_id = :user_id
AND savings_account_id = :savings_account_id
GROUP BY date_part('month', timestamp)

but I'm actually looking for a single number that represents the average deposits per month across the lifetime of the savings account.

A: You would need another level of aggregation:
SELECT AVG(cnt) avg_deposit_per_month
FROM (
    SELECT COUNT(*) cnt
    FROM savings_account_deposit
    WHERE user_id = :user_id AND savings_account_id = :savings_account_id
    GROUP BY date_trunc('month', timestamp)
) t

The subquery counts the number of deposits per month, then the outer query just averages the counts.
Note that I changed date_part in your query to date_trunc: the former would aggregate together deposits of the same month in different years, which is probably not what you want.


text:
Q: Warning in install.packages lib is not writeable in R studio Extremely frustrated that I am not able to install the following package:
install.packages('tseries')
after I run this command I get the following message:

Would you like to use a personal library instead?

I click "yes"
Then it attempts to download a bunch of things from R URLs.
Then I get the following error where it mentions

Warning in install packages: lib = "My path" is not writable

I have read multiple things that mentioned that I need to set myself as administrator with full control/access.
I have done so and allowed full control to my personal account.
I then restart R and try to install the tseries package again but I get the same exact errors as mentioned above.
System windows 10
R version 3.6


text:
Q: Hive unable to perform queries other than SELECT * I am running hive on my system where I have successfully created a database and a table. I have loaded that table with a csv file which is located on my HDFS.
I am successfully able to describe the table in hive, seeing all of the columns that I intended to be created.
I am also successfully able to run the simple SELECT * FROM table; query which returns an enormous list of data.
My problem starts whenever I try to run a query that is any more complex than that. Specifically, when I try to run a query that is selecting a specific column name or selecting any aggregate of data. If I try anything else, I receive this error message after my map and reduce tasks have sat at 0% for a while.
Diagnostic Messages for this Task:
java.lang.RuntimeException: java.lang.NullPointerException
    at org.apache.hadoop.hive.ql.exec.Utilities.getMapRedWork(Utilities.java:230)
    at org.apache.hadoop.hive.ql.io.HiveInputFormat.init(HiveInputFormat.java:255)
    at org.apache.hadoop.hive.ql.io.HiveInputFormat.pushProjectionsAndFilters(HiveInputFormat.java:381)
    at org.apache.hadoop.hive.ql.io.HiveInputFormat.pushProjectionsAndFilters(HiveInputFormat.java:374)
    at org.apache.hadoop.hive.ql.io.CombineHiveInputFormat.getRecordReader(CombineHiveInputFormat.java:536)
    at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:394)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:332)
    at org.apache.hadoop.mapred.Child$4.run(Child.java:268)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1438)
    at org.apache.hadoop.mapred.Child.main(Child.java:262)
Caused by: java.lang.NullPointerException
    at org.ap

I have tried many different syntax techniques and performed numerous sanity checks to confirm that the table is actually there. What confuses me is that the SELECT * works while all other queries fail.
Any advice is appreciated.
Here is a query I ran with as many NULL checks as would allow: SELECT year FROM flights WHERE year != NULL AND length(year) > 0 AND year <> ''; This query still failed.

A: SELECT * doesn't invoke mapreduce jobs.
But any complex queries involve map reduce jobs.
Please check the MR job logs.
Also this can be a data issue, Data might be incompatible with the table schema.
Please check with fewer rows.

A: May be your input data consists any null values. Because,

*

*if you use select all command that job will not enter into mapreduce phase.

*if you select any specific column it will enter into mapreduce phase. so you may get this error.

A: What is happening here is that none of the queries involving mapreduce jobs are running.
The "select *" query doesn't invoke any mapreduce and just displays the data as it is. Please check your mapreduce logs and see if you can find something which is causing this.


text:
Q: Make Kik Bot listen on port 8080 without ngrok
Hello,
I am programming a Kik Bot in node.js and I'm using a VPS where my website (on an apache server) is located aswell. I used ngrok for the tunneling but I don't want to change the link every time I reload. So now I want to use the domain of my website instead.
But I am not sure how to do that. The last line of my index.js is
let server = http.createServer(bot.incoming()).listen(process.env.PORT || 8080);

and on the top I have
let Bot = require('@kikinteractive/kik');
let bot = new Bot({
    username: 'mybotname',
    apiKey: 'my-api-key-goes-here',
    baseUrl: 'http://example.com'
});

That doesn't quite work though. With ngrok the bot worked perfectly fine but I have no idea how to use the server without ngrok. I also tried to change the port in the last line from 8080 to 80. But that doesn't work because I get an exception telling me, the port is already in use (obviously by apache).
Thank you

A: Don't know if it is any help, but running a bot off a domain is a little tricky. You can use the port of the domains IP address, but you'd need to have a static address.
Try this link
You will need a static IP and then direct your program to the domain's IP that is setup.


text:
Q: Java Adding Numbers Together + Score? Hi I have made this to add to a score systems.
public int Cascore = 0;
public int Dascore = 0;
        public int dascore () {
        return Dscore = + 5;
    }
    public int cascore () {
        return Cscore = + 3;
    }
    public int ddascore () {
        return Dscore = + 1;
    }

I call these methods dascore() cascore() during points in the code that add to the score system but the overall Dascore and Cascore seem to just be 3 or 5.
 System.out.println("Bad Score: " + Dscore);
          System.out.println("Good Score: " + Cscore);

Just out puts 5 & 3.  When it should be something like 160/130...?

A: Let's try :

Dscore += 5

not =+

A: It looks like you wanted to this instead
public int Cascore = 0;
public int Dascore = 0;
    public int dascore () {
        return Dscore +=  5;
    }
public int cascore () {
        return Cscore +=  3;
    }
public int ddascore () {
        return Dscore +=  1;
    }

A: This isn't working because you aren't writing the correct code. Well, your IDE should generate an error...
There is nothing like the following in java!
= +

Java, as other language do, supports +=
Even + = is wrong too in java. Because there can't be a space between these two operators.
public int Cascore = 0;
public int Dascore = 0;
    public int dascore () {
    return Dscore += 5;
}
public int cascore () {
    return Cscore += 3;
}
public int ddascore () {
    return Dscore += 1;
}

For better understandability, Until you are using a Constant, don't start your variable name with an upper case letter.


text:
Q: Reset the Sheikah Scanner+ Target If you go to the Hateno village lab early. You will find out about the upgrades to your Sheikah slate's functions.
You can upgrade your scanner to scan for other things than Shrines by proximity.
I used the feature to scan for some nearly worthless weapon (rusty broadsword). I scanned for other things earlier but I used this one to not make it ping everywhere like it would have with Hylian Mushroom.
I don't see a way to "clear" the targeted item from scanner+ so it can scan only for shrines.
Is there a way to clear your scanner+ targeted item?
To be clear I am NOT asking to turn off the indicator only change it back to search only for shrine and nothing else. Which is not a duplicate of the other question.

A: Same as with the initial shrine alert:
Open the map and press Y to open the scanner menu. There's now a third option to pick some library target. Just disable it once again.


text:
Q: Is it still possible to render full-bleed previews with descriptions in Google+? I'm trying to get a full-bleed link preview as described in https://developers.google.com/+/web/snippet/article-rendering, so that my preview can display a description. I haven't been able to do so, and I haven't found any other posts that have descriptions present (besides interactive previews).
Does Google+ still support full-bleed previews with descriptions in them?


text:
Q: Trying to do a flexible/generic minimum distance level of detail distance ranges system Well, I'll like to create a level of detail system for my game to load the terrain.
The point here is that I'll like to use the minimum expression for distances, so all the chunks that I load match at the corners but there are no redundant parts, like here:

So, more something like this:

The purpose here is to have the maximum render distance with the minimum count of gameobjects to load.
I have two main concerns the system is not flexible for initial minimum distances that are non-base of 2.
As something like this is browsed:

Another thing is that distance must be patched:
                    //// If the number is even, then we must do this patch
                    if (currentDistanceLevel == 128)
                        sum += currentDistanceLevel / 2; // TODO, why?

I don't understand why...
This is what happens:

This is my code:
        /// <summary>
        /// Calculate the the minimum distances between level of detail chunks.
        /// </summary>
        /// <param name="lodLevels">The number of lod levels to go into.</param>
        /// <param name="numberOfChunks">The number of chunks after the view distance from the ChunkGenerator system finishes.</param>
        /// <returns>A list of distances to use on a grid of level of detail. (See https://i.gyazo.com/0ceb8ff3a4ebab8391532892fc8b6f82.png)</returns>
        public static IEnumerable<float> CalculateOptimumLoDValues(int lodLevels, int numberOfChunks, int chunkSize)
        {
            var back = false;
            var sum = 0;
            var currentDistanceLevel = chunkSize;
            for (var l = 1; l < lodLevels; l++)
            {
                // The last step is give the previous sum
                yield return sum;

                // At the second step, if we didn't went to the previous level
                if (!back)
                {
                    // We half the number of chunks of the previous level
                    numberOfChunks /= 2;

                    // And we double distance for the next level
                    currentDistanceLevel *= 2;
                }
                else
                    back = false;

                numberOfChunks += 2;

                // First, if we want to avoid this effect, we must do the following step.
                // https://i.stack.imgur.com/1nfgd.png
                // at https://stackoverflow.com/questions/72636128/trying-to-position-all-chunks-for-distinct-lod-levels
                // ----------------
                // If the following distance level has an odd number of elements then I try to match the current row/column by doubling it, in that way non of the following corner will be half of the previous one.
                // The number of chunk on the rows goes, 16-10(8+2)-12(10+2)-8(12/2+2)-6(8/2+2)-8(12/2+2)-6(12/2+2)....
                if (numberOfChunks / 2 % 2 != 0)
                {
                    // Then, if the number is odd after summing the two corners and dividing it,
                    // we must go into he back level, set the flag to true and sum the distance
                    l--;
                    back = true;

                    sum += currentDistanceLevel * 3 / 4;
                }
                else
                {
                    //// If the number is even, then we must do this patch
                    if (currentDistanceLevel == 128)
                        sum += currentDistanceLevel / 2; // TODO, why?
                    else
                        sum += currentDistanceLevel; // For the rest of the levels we sum it
                }
            }
        }


text:
Q: NSOSStatusErrorDomain, code: -67068 in sandbox related item NSFileSandboxingRequestRelatedItemExtension: an error was received from pboxd instead of a token. Domain: NSOSStatusErrorDomain, code: -67068
This appear when I was playing with sandbox related item. I have tried the code in individial project. It works. But in my main project, it not works.
What is this meaning? Anyone know how to solve? Thanks.


text:
Q: Rails - Elasticsearch - search by coordinates with Chewy I'm using Elasticsearch on my Rails APP trhough gem 'chewy'.
I have two models: Products and Tags [many to many relationship, managed through ProductTag model].
I defined ProductsIndex as follow:
class ProductsIndex < Chewy::Index
  define_type Product do
    field :name
    field :tags, value: -> { tags.map(&:name)}
    field :coordinates, type: 'geo_point', value: ->{ {lat: lat, lon: lon} }
  end
end

I can successfully query ProductsIndex in my controller with:
q = params[:q]
@products = ProductsIndex.filter { tags(:and) == [q] }.load

which returns me all the Product objects with the specified tag.
My question is: How can I query ProductIndex to return all the Product objects within a radius of 100Km from a given pair of coordinates (lat/lon)?
I do not strictly need sorting by distance, but if you include it in your answer it will be greatly appreciated :)
edit
I'm trying something like this but it doesn't work:
ProductsIndex.filter {
  geo_distance: {
    distance: '100km',
    location: {
      lat: 60.0951482712848,
      lon: -86.4810766234584
    }
  }
}

I got the following syntax error
 SyntaxError: (irb):10: syntax error, unexpected ':', expecting '}'
...uctsIndex.filter {geo_distance: {    distance: '100km',    l...
...                               ^

A: It's been a wild hunt, and a long afternoon, but eventually the errors were pretty silly:

*

*I was using location in the query while I defined coordinates as field type;

*wrong brackets after .filter.

The correct syntax is as follow:
ProductsIndex.filter(geo_distance: {
  distance: "100km",
  coordinates: {
    lat: <latitude>,
    lon:<longitude>
  }
})

Hope it might help.


text:
Q: variation on an exact sequence of logarithmic differentials Let $X$ be a smooth projective complex variety and $D$ a divisor with simple normal crossings on $X$, with irreducible components $D_i$. If $D_1$ is one of these (smooth) irreducible components, then one has an exact sequence of sheaves
$$
0 \to \Omega^p_X(\log D)(-D_1) \to \Omega^p_X(\log(D-D_1)) \to \Omega^p_{D_1}(\log (D-D_1)_{|D_1}) \to 0
$$ (This is explained e.g. in section 2 of the book by Esnault and Viehweg).
I'm wondering what happens if you remove several irreducible components at the same time. That is, let $H$ a reduced divisor with irreducible components some of the $D_i$. Is there a similar exact sequence relating $\Omega^p_X(\log D)(-H)$ and $\Omega^p_X(\log(D-H))$? Of course the problem is that $H$ is not smooth anymore, so I don't know how to make sense of the last term... Thanks for your help!

A: For simplicity let's say $X = \mathbb C^2$ and $D = D_1 + D_2$ with $D_1 = \{ x = 0 \}$ and $D_2 = \{ y = 0 \}$. Then you have a short exact sequence
$$ 0 \to \Omega_X^1(\log D)(-D) \to \Omega_X^1 \to \Omega_{D_1}^1 \oplus \Omega_{D_2}^1 \to 0. $$
Exactness can be checked by a local computation. The sheaves are freely generated by $\{ y \,\mathrm dx, x \,\mathrm dy \}$, $\{ \mathrm dx, \mathrm dy \}$, and $\{ (\mathrm dy, 0), (0, \mathrm dx) \}$, respectively. The second map is given by $\mathrm dx \mapsto (0, \mathrm dx)$ and $\mathrm dy \mapsto (\mathrm dy, 0)$.
This should work the same in general.


text:
Q: Maven dependency not found but present in mvnrepository I created a simple web scraper with Java and Selenium. It just reads a single piece of information and writes that to a CSV file.
I'm trying to run it daily using some scheduler on Heroku. The official Heroku documentation says I need to add this to the pom.xml:
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>3.0.1</version>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>package</phase>
                    <goals><goal>copy-dependencies</goal></goals>
                </execution>
            </executions>
        </plugin>

But when I add it to the pom.xml, I'll get

Plugin 'org.apache.maven.plugins:maven-dependency-plugin:3.0.1' not found

even though it found in mvnrepository.com. What is happening here?

A: First of all, run the build again (with something like mvn clean verify) and see if you get the error again.
If so, you probably have a network/firewall issue, or you misconfigured your settings.xml (if you have one).


text:
Q: Error iterating over a list 'TypeError: cannot unpack non-iterable object' I'm writing a Python script to solve a certain differential equation with SciPy's odeint. I just copied the example on the doc page:
def pend(y,t,b,c):
    theta, omega = y
    dydt = [omega, -b*omega -c*np.sin(theta)]
    return dydt
b = 0.25
c = 5.0

y0 = [np.pi-0.1,0.0]
t = np.linspace(0,10,101)
sol = odeint(pend, y0, t, args = (b,c))
plt.plot(t,sol[:,1])
plt.plot(t,sol[:,0])

This works fine and everything but when I try with the Lotka-Volterra system the code breaks down:
def F(t,n,a,b,c,d):
    x, y = n
    deriv = [a*x-b*x*y,c*x*y-d*y]
    return deriv

t = np.linspace(0,100,100)
a = 1.1
b= 0.4
c = 0.1
d = 0.4
n0 = [10,10]
sol = odeint(F,n0,t,args = (a,b,c,d))

This returns a TypeError
<ipython-input-14-ea2a41feaef2> in F(t, n, a, b, c, d)
     1 def F(t,n,a,b,c,d):
----> 2     x, y = n
     3     deriv = [a*x-b*x*y,c*x*y-d*y]
     4     return deriv
     5

TypeError: cannot unpack non-iterable float object

Could anyone help me see what I'm missing? Specifically, why does the example code work if the second code is written with the same structure. Thanks!

A: I assume, that the arguments passed in this line are not in the right order:
sol = odeint(F,n0,t,args = (a,b,c,d))

Shouldn't it be:
sol = odeint(F,t,n0,args = (a,b,c,d))

Alternatively you can swap the argument order in the function definition to:
def F(n,t,a,b,c,d):


text:
Q: how to click on a button when specific image is asscoiated with it I am using selenium for testing my application.
In my application there are 5 buttons, each have a different image associated with it.
I want to click on button which have a specific image associated.
Currently i am using a while loop to get the node of image and then replacing this node into xpath of button to select it.
is there any way either with xpath or css to do this directly.
Providing more information-this is like submit button is there and then below this image is there. submit button and images are sibling element and need to click submit button when the next element is specific image

A: Could you include a snippet of your HTML? Below is an example of an image in a form and a few ways of locating it using Selenium, but these may not be relevant depending on your implementation:
<input id="submitForm" name="imgbtn" type="image" src="images/submit.png" />

*

*id=submitForm

*name=imgbtn

*//input[@src='images/submit.png']

*//input[contains(@src, 'submit.png')]

*css=input[src='images/submit.png']

UPDATE:
Given the HTML:

You can locate the 'submit' span parent of the 'marking2' div using the following XPaths:

*

*//div[@class='marking2']/..

*//div[@class='marking2']/parent::*

*//div[@class='marking2']/parent::span

UPDATE 2:
Based on the HTML now included in the question, you can locate the span with the class of submit related to the image many ways, a few examples follow:

*

*//div[//img[@alt='Marking2']/span[contains(@class, 'select')]

*//img[@alt='Marking2']/../../span

*//div[img[@alt='Marking2']]/preceding-sibling::span

I hope this gives you some ideas. I'd certainly recommend XPath over CSS for locating these elements as it's much better at these sorts of relationships.


text:
Q: How to open a tkinter window when a key is pressed I have this code:
from tkinter import *
import keyboard
#console
if keyboard.is_pressed('c'):
    console=Tk()
    console.geometry("500x425")
    console.title("Devoloper Console")
    console.resizable(True,True)
    console.configure(bg='gray95')

Basically, I'm trying to use the keyboard module to detect when I press C on my keyboard, and then open a Tkinter window when I press C.
The code above doesn't work (obviously) and I don't know why. However, I do know that the problem is that it isn't detecting the keypress and not a problem with the window.

A: You need a continuing loop to check when c is pressed.
from tkinter import *
import keyboard

x = True

while x:
    if keyboard.is_pressed('c'):
        x = False
        console=Tk()
        console.geometry("500x425")
        console.title("Devoloper Console")
        console.resizable(True,True)
        console.configure(bg='gray95')
        console.mainloop()

A: import tkinter as tk
import keyboard

while (not keyboard.is_pressed("c")):
       pass

root = tk.Tk()
root.bind("<c>", lambda e: tk.Toplevel())
root.mainloop()

Does this do what you wanted?

A: Module keyboard has a function called wait. It waits for a key to be pressed. You have to use that. Also use mainloop for the tkinter window to make it run corectly.
import tkinter as tk
import keyboard

keyboard.wait("c")   #< It'll wait for c to be pressed

console = tk.Tk()
console.geometry("500x425")
console.title("Devoloper Console")
console.resizable(True,True)
console.configure(bg='gray95')
...


text:
Q: Set timeout for alert in Ionic2 I've created an alert message which I want to close after a set defined time only. Below is my code:

showAlert() {
 let alert = this.alertCtrl.create({
 subTitle: 'The information you have provided is incomplete or invalid. Please check your entries and check again.'
 });
 alert.present();
}

showAlert() is the method that will be invoked after an event. Now, I want to set timeout for it but I couldn't get any solution for it.

A: If you want to use timeout to invoke alert,
you can use the global setTimeout() function like so:
showAlert() {
 let alert = this.alertCtrl.create({
 subTitle: 'The information you have provided is incomplete or invalid. Please check your entries and check again.'
 });
setTimeout(()=>alert.present(),3000);

}

In case you want to dismiss after timeout,
setTimeout(()=>alert.dismiss(),3000);

A: Instead of using alert , prefer using toast for such issues , you can display it for as much time you want.
for using toast , you may proceed like mentioned below:
import {Toast} from 'ionic-native';
     Toast.show("The information you have provided is incomplete or invalid. Please check your entries and check again.", '3000', 'center').subscribe(
            toast => {
              console.log(toast);
            }
          );

"3000" : is the time for which you want to display , timing is in milliseconds , hence , 3000 = 3 sec.
"center": is the position of the toast , it can either be top , center , or bottom.


text:
Q: Entity Framework 4.2 code first in a class library ignoring my connection string I'm building a class library for an application (exitgames photon) and it doesn't have a web.config or an app.config.
Therefore I am setting the connection string against the context like this:
db.Database.Connection.ConnectionString = "Data Source=machinename\\SqlExpress;Initial Catalog=AwesomeDB;Integrated Security=True";

The context (db) then ignores the connection string and uses the default one as if I didn't specify it (based on the namespace and context name etc).
Anyone know how to specify the connection string inline thus removing the requirement for an app.config?

A: If it's a class library, then it will use the connection string specified in web.config (web site) or app.config (application) which will use this library.

A: I wouldn't recommend hard coding the connection string. You can pass the connection string in the default constructor.
public class MyContext : DbContext
{
    public MyContext()
    : base("Data Source=machinename\\SqlExpress;Initial Catalog=AwesomeDB;Integrated Security=True")
    {
    }
}

A: You can pass the connection string as a parameter to the constructor of the context.


text:
Q: How to cut all tabulations and whitespaces Linux shell? I have a .sh file:
test -e "$APP_SERVER_HOME"

if [ $? != 0 ]; then

   echo "Application server home $APP_SERVER_HOME does not exist"

   exit 6

fi

How to cut all whitespaces and tabulations from APP_SERVER_HOME variable before test command?

A: APP_SERVER_HOME=`echo "$APP_SERVER_HOME" |sed 's/\s//g'`

Is this what you want?
Note: If it contained " C:\Program Files\Foo\bar.exe " it will now contain "C:\ProgramFiles\Foo\bar.exe" which is probably not what you want.
APP_SERVER_HOME=`echo "$APP_SERVER_HOME" |sed 's/^\s\+//' |sed 's/\s\+$//'`

This one will just trim the leading and trailing whitespace, not internal spaces.

A: You can also do this using shell parameter expansion approach (described here):
shopt -s extglob

${APP_SERVER_HOME##+([[:blank:]])}


text:
Q: DensityPlot on spherical surface? I just checked this example Construct a Globe Showing All Weather Stations. It looks good, but I would like to add a density plot of the stations on the spherical surface.
This can be done with the Texture command but it is just the last step, since we still need to firstly obtain the 2D density plot on a plane that can be used to correctly project on the spherical surface. As far as I know, this is not yet a built-in function of Mathematica 9. Can someone help? Thanks.


text:
Q: Error during building of YAML_CPP with CMake on WIndows I keep getting an error when I try to build yaml-cpp on Windows.
Using the CMake gui application I selected build- and sourcepath correctly, but as soon as I hit the "Configure" Button there is the following error thrown:
CMake Error: CMake was unable to find a build program corresponding to "**MinGW Makefiles**".  **CMAKE_MAKE_PROGRAM** is not set.  You probably need to select a different build tool.
CMake Error: CMake was unable to find a build program corresponding to "MinGW Makefiles".  CMAKE_MAKE_PROGRAM is not set.  You probably need to select a different build tool.
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_C_COMPILER_ENV_VAR
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_C_COMPILER
CMake Error: Could not find cmake module file:C:/Users/Robert/Programs/Lib/yaml-cpp/build/CMakeFiles/CMakeCCompiler.cmake
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_CXX_COMPILER_ENV_VAR
CMake Error: Error required internal CMake variable not set, cmake may be not be built correctly.
Missing variable is:
CMAKE_CXX_COMPILER
CMake Error: Could not find cmake module file:C:/Users/Robert/Programs/Lib/yaml-cpp/build/CMakeFiles/CMakeCXXCompiler.cmake
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
Configuring incomplete, errors occurred!

I know it has to do with the selected Generator, I selected CodeBlocks - MinGW Makefiles. However I have installed CodeBlocks correctly. So is there perhaps a way to set the CMAKE_MAKE_PROGRAM variable manually?