text:
Q: Is there a way to change where the error message is rendered using the standards properties of Ant Design Forms? I'd like to reposition my error messages so they render to the right of the input as to not displace my layout. Is that possible using Antd forms (I'm using and 3.X)? The standard way they render is below the input.
https://3x.ant.design/components/form/#components-form-demo-validate-static

A: Can use the rules properties which has message property. For example,
    <Form.Item
      name="workDescription"
      label="Description:"
      rules={[
        {
          required: true,
          message: "Please Enter Order Description",
          whitespace: true,
        },
      ]}
    >
      <TextArea rows={3} placeholder="Order Description" />
    </Form.Item>


text:
Q: Datagrid Easyui Not Work Help.
Datagrid EasyUI Not Work
Error :
jquery.easyui.min.js:11286 Uncaught TypeError: Cannot read property 'length' of undefined
    at Object.renderTable (jquery.easyui.min.js:11286)
    at Object.render (jquery.easyui.min.js:11263)
    at _6e1 (jquery.easyui.min.js:10149)
    at HTMLTableElement.<anonymous> (jquery.easyui.min.js:11055)
    at Function.each (jquery.min.js:2)
    at m.fn.init.each (jquery.min.js:2)
    at Object.loadData (jquery.easyui.min.js:11054)
    at m.fn.init.$.fn.datagrid (jquery.easyui.min.js:10816)
    at jquery.easyui.min.js:10770
    at Object.success (jquery.easyui.min.js:11526)

Code in : https://pastebin.com/Y2L8UyeV
Controller Pencatatan.php
class Pencatatan extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
        $this->load->model('M_Pencatatan');
    }
    function index(){
        $data['title'] = 'Pencatatan Transaksi';
        $data['content'] = 'V_Pencatatan';

        $this->load->view('Template/full',$data);
    }

    function data()
    {
        $data['datatables'] = $this->M_Pencatatan->show_keuangan_all();
        echo json_encode($data);
    }
}

Model M_Pencatatan.php
function show_keuangan_all(){
    $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
    $rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
    $sort = isset($_POST['sort']) ? strval($_POST['sort']) : 'id_keuangan';
    $order = isset($_POST['order']) ? strval($_POST['order']) : 'asc';
    $offset = ($page-1) * $rows;

    $result = array();
    $result['total'] = $this->db->get('keuangan')->num_rows();
    $row = array();

    $this->db->limit($rows,$offset);
    $this->db->order_by($sort,$order);
    $criteria = $this->db->get('keuangan');

    foreach($criteria->result_array() as $data)
    {
        $row[] = array(
                'id'=>$data['id_user'],
                'keterangan'=>$data['keterangan'],
                'value'=>$data['value'],
                'tanggal'=>$data['tanggal_transaksi']
            );
        }

        $result=array_merge($result,array('rows'=>$row));
        return $result;
    }

}

Full View

    <meta charset="UTF-8">
    <title>Pencatatan</title>
    <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>asset/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>asset/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>asset/demo/demo.css">

                Pencatatan Keuangan

                Selamat Datang,
                <?php echo date('d F Y'); ?>     :
                    :

                    Transaction

                            <a style="color:black;text-decoration:none;" href="<?php base_url();?>Pencatatan" data-options="plain:true" onclick="addPencatatan()">Pencatatan

east region

© Tuyullie

            <?php if(isset($content)) {$this->load->view($content);} ?>

V_Pencatatan.php View

redpajama_set_name: RedPajamaStackExchange


text:
Q: omdbapi.com REST api JSON into Angular 5 Hey guys I am trying to get the data from a moviedatabase api to show up in my Angular 5 app. I managed to get it to post in the console with JSONstringify, but as soon as i try to ngFor loop through the data it either gives me nothing at all or [object, Object].
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { Observable } from 'rxjs/Observable';
import { IMovie } from './movie';

@Injectable()
export class MoviesService {

private _url: string = "http://www.omdbapi.com/?i=tt3896198&apikey=*took-that-out*";
constructor(private http: HttpClient) {}

getMovies(): Observable<IMovie[]> {
  return this.http.get<IMovie[]>(this._url);
}

component
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MoviesService } from './../movies.service';

@Component({
  selector: 'app-featured',
  templateUrl: './featured.component.html',
  styleUrls: ['./featured.component.css']
})

export class FeaturedComponent implements OnInit{

  public movies = [];

  constructor(private _moviesService: MoviesService){
  }

  ngOnInit() {
    this._moviesService.getMovies()
      .subscribe(data => this.movies = data);
  }

 }

the interface
export interface IMovie{
title: string;
year: string;
rated: string;
released: string;
runtime: string;
genre: string;
director: string;
writer: string;
actors: string;
plot: string;
language: string;
country: string;
awards: string;
poster: string;
//ratings: Ratings;
metascore: string;
imdbrating: string;
imdbVotes: string;
imdbid: string;
type: string;
dvd: string;
boxOffice: string;
production: string;
website: string;
response: string;
}

and the html

list of movies

{{movie.title}}

Edit: added the JSON from the api below
{
  "Title": "Guardians of the Galaxy Vol. 2",
  "Year": "2017",
  "Rated": "PG-13",
  "Released": "05 May 2017",
  "Runtime": "136 min",
  "Genre": "Action, Adventure, Sci-Fi",
  "Director": "James Gunn",
  "Writer": "James Gunn, Dan Abnett (based on the Marvel comics by), Andy     Lanning (based on the Marvel comics by), Steve Englehart (Star-lord created by), Steve Gan (Star-lord created by), Jim Starlin (Gamora and Drax created by), Stan Lee (Groot created by), Larry Lieber (Groot created by), Jack Kirby (Groot created by), Bill Mantlo (Rocket Raccoon created by), Keith Giffen (Rocket Raccoon created by), Steve Gerber (Howard the Duck created by), Val Mayerik (Howard the Duck created by)",
  "Actors": "Chris Pratt, Zoe Saldana, Dave Bautista, Vin Diesel",
  "Plot": "The Guardians must fight to keep their newfound family together as they unravel the mystery of Peter Quill's true parentage.",
  "Language": "English",
  "Country": "USA, New Zealand, Canada",
  "Awards": "Nominated for 1 Oscar. Another 7 wins & 26 nominations.",
  "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTg2MzI1MTg3OF5BMl5BanBnXkFtZTgwNTU3NDA2MTI@._V1_SX300.jpg",
  "Ratings": [
    {
      "Source": "Internet Movie Database",
      "Value": "7.7/10"
    },
    {
      "Source": "Rotten Tomatoes",
      "Value": "83%"
    },
    {
      "Source": "Metacritic",
      "Value": "67/100"
    }
  ],
  "Metascore": "67",
  "imdbRating": "7.7",
  "imdbVotes": "336,851",
  "imdbID": "tt3896198",
  "Type": "movie",
  "DVD": "22 Aug 2017",
  "BoxOffice": "$389,804,217",
  "Production": "Walt Disney Pictures",
  "Website": "https://marvel.com/guardians",
  "Response": "True"
}

A: The reason you are getting [Object Object] is because OMDb API returns an Object with three properties:  { Response, Search, totalResults }.
In order to skip that error you only have to access the Search property containing your movies[] and loop trough it using *ngFor.
Code example:

{{ movie.Title }}

Please remember to check your {{ data binding }} and make sure your property matches the response obj property -- they are capitalized.


text:
Q: Biblatex: two bibliographies with increasing numbers I'm currently using biblatex to make two bibliographies, using \printbibliography and the keyword argument. I just label which citation I want in which bibliography using keywords in the .bib file. When I do this, the references are sorted and numbered as a whole and then divided between the two bibliographies. This causes numbers to appear in a slightly strange order. Is there a simple way to make the ordering be monotone? Or should I just switch to a non-numeric citation style?
I think a MWE is
@article{A,
author={A B},
title={Test 1},
keywords={primary}
}
@article{B,
author={C D},
title={Test 2},
keywords={secondary}
}
@article{C,
author={E F},
title={Test 3},
keywords={primary}
}

in a bib file called bibtest.bib, and then
\documentclass{article}
\usepackage[backend=biber]{biblatex}
\addbibresource{bibtest.bib}

\begin{document}

This document is a test \cite{A},\cite{B},\cite{C}.

\printbibliography[title={Primary},keyword={primary}]

\printbibliography[title={Secondary},keyword={secondary}]

\end{document}

If sorted by author then the numbers will appear as 1 3 in the primary and 2 in the secondary, whereas I would prefer them to appear as 1 2 in the primary and 3 in the secondary.

A: You need the load-time/global option
defernumbers=true

i.e. \usepackage[backend=biber,defernumbers=true]{biblatex}.
With that setting labels are assigned for each of the subbibliographies chronologically.
The default defernumbers=false assigns labels based on a global list of references even if that global list is never printed.


text: Q: Calling URL and Retry logic in Android application I have a Java Spring web application running & can be pulled up through an URL.  The web application runs in a loop to display different contents.  Also I wrote an android app that launches the URL using WebView after Android boot complete so far so good.  But I am looking for some ideas on retry logic or restart android app to open the URL if the URL is down in the middle?. The intention is to avoid user intervention, Can somebody shed some light on it?.  Thanks.


text:
Q: Adding Key to BuildConfig and calling it inside @header kotlin So I don't want to share the api key by accident, but unlike Java I don't know how to call the API_KEY in my buildconfig file inside the Header.
Sample Code:
interface Api {
// This is how it looks but it exposes my API
    @Headers(
        "x-rapidapi-key: hwyehajkse.qjkdagf,kjbgekuh,jc", //currentfakeAPI
        "Content-type:application/json"
    )

I have managed to add the API in BuildConfig files but how can I call it on the header the below method is what I tried but it wont work.
    @Headers(
            "x-rapidapi-key:",API_KEY,
           "Content-type:application/json"
   )

Help highly appreciated.

A: You can use this cool feature in Kotlin.
@Headers(
   "x-rapidapi-key:$API_KEY",
   "Content-type:application/json"
)

prefix

$

to the variable you want to use along with the string

${method.variable}

to access a variable from a method.
Eg:
@Headers(
       "x-rapidapi-key:${BuildConfig.API_KEY}",
       "Content-type:application/json"
    )


text:
Q: android.os.StrictMode$StrictModeDiskReadViolation: on com.android.server.policy.sec.TspStateManager.updateTspState When I turn on StrictMode at my Application onCreate(), everything was good, and the issue found fixed.
However, I realize there's a bug of StrictMode as per this issue. So I made the workaround (using Handler), and indeed more issue surfaced. I could identify them to either suppress or fix them.
But the below error is something that I have no clue, as the stack trace doesn't seems related to any piece of code that I could related to.
D/StrictMode: StrictMode policy violation; ~duration=38 ms: android.os.StrictMode$StrictModeDiskReadViolation: policy=4522015 violation=2
     at android.os.StrictMode$AndroidBlockGuardPolicy.onReadFromDisk(StrictMode.java:1263)
     at libcore.io.BlockGuardOs.access(BlockGuardOs.java:67)
     at java.io.File.doAccess(File.java:281)
     at java.io.File.exists(File.java:362)
     at com.android.server.policy.sec.TspStateManager.updateTspState(TspStateManager.java:139)
     at com.android.server.policy.sec.TspStateManager.updateWindowPolicy(TspStateManager.java:103)
     at com.android.server.policy.PhoneWindowManager.focusChangedLw(PhoneWindowManager.java:8640)
     at com.android.server.wm.WindowManagerService.updateFocusedWindowLocked(WindowManagerService.java:18320)
     at com.android.server.wm.WindowManagerService.relayoutWindow(WindowManagerService.java:5768)
     at com.android.server.wm.Session.relayout(Session.java:208)
     at android.view.IWindowSession$Stub.onTransact(IWindowSession.java:288)
     at com.android.server.wm.Session.onTransact(Session.java:139)
     at android.os.Binder.execTransact(Binder.java:453)
 # via Binder call with stack:
 android.os.StrictMode$LogStackTrace
     at android.os.StrictMode.readAndHandleBinderCallViolations(StrictMode.java:1911)
     at android.os.Parcel.readExceptionCode(Parcel.java:1601)
     at android.os.Parcel.readException(Parcel.java:1570)
     at android.view.IWindowSession$Stub$Proxy.relayout(IWindowSession.java:956)
     at android.view.ViewRootImpl.relayoutWindow(ViewRootImpl.java:6690)
     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1994)
     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1437)
     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7403)
     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:920)
     at android.view.Choreographer.doCallbacks(Choreographer.java:695)
     at android.view.Choreographer.doFrame(Choreographer.java:631)
     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:906)
     at android.os.Handler.handleCallback(Handler.java:739)
     at android.os.Handler.dispatchMessage(Handler.java:95)
     at android.os.Looper.loop(Looper.java:158)
     at android.app.ActivityThread.main(ActivityThread.java:7224)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

This error happens on the Samsung S7 phone but not Nexus 6P. I want to suppress this error, but I first need to know which part of code that trigger this, so I could either spawn a different thread on that code or turn off the detectDiskReads on that part.
Any help of hint of how to check this on? Where to begin with?


text:
Q: Use GTK3 progress bars in Ruby This is my code:
require "gtk3"
builder_file = "#{File.expand_path(File.dirname(__FILE__))}/example.ui"
builder = Gtk::Builder.new(:file => builder_file)
window = builder.get_object("window")
window.signal_connect("destroy") { Gtk.main_quit }
progressbar=builder.get_object("progressbar1")
progressbar.set_fraction(0.5)
button = builder.get_object("button1")
button.signal_connect("clicked") {
  for i in(0..4)
    sleep(1)
    puts "query " + (i+1).to_s + " done"
    a=(i+1)/5.to_f
    puts a
    progressbar.set_fraction(a)
  end
  }
Gtk.main

sleep is just a placeholder for a web query that takes about 1 second. When I execute this code on my machine, the console output is fine, but the progress bar stays empty until it jumps to full after five seconds, which is not what I want. How can I make use of the progress bar?

A: The integration of the event loop of the GUI tool (Gtk, Tk, etc) and Ruby  annoys beginners including me. I know two ways.
1.add thread
require 'gtk3'

win = Gtk::Window.new('Sample')
win.signal_connect('destroy') { Gtk.main_quit }

box = Gtk::Box.new(:vertical)

pb = Gtk::ProgressBar.new
pb.set_fraction(0.5)

b = Gtk::Button.new(label: 'Button')
b.signal_connect('clicked') do
  Thread.new do
    5.times do |i|
      sleep 1
      pb.fraction = (i + 1) / 5.0
    end
  end
end

win.add box
box.pack_start pb
box.pack_start b

win.show_all

Gtk.main

2.use GLib::Timeout
b.signal_connect('clicked') do
    i = 0.0
    GLib::Timeout.add(1000) do |a|
           i += 0.2
           pb.fraction = i
           i < 1.0 # return false and stop when i >= 1.0
    end
end


text:
Q: Displaying vectors with origin and direction in Google Earth Would like to display direction vectors at defined locations in Google Earth. In a 3D tool direction vectors differ from a position vector (i.e. 2 geographical points connected via a line) that the displayed size is independant of the zoom level, just dependant on the aspect angle (projection).
Side mote: Finally I would like to display 3 direction vectors which span a orthoganal coordinate frame. So each "vector" would point in 3D Space.
Any solution existing? Or any idea of workaround for it?
I am familiar with KML and already reached my first goal to display a ground track and to highlight areas of interests using polygons. However I have found no solution for my request.

A: You can create points with icon images that look like an arrow, and rotate them with the appropriate tags, like in the KML below. Try copy/pasting that into Earth Pro.
Note that in this example I used an easily available icon where the arrow points down, but you might want to use your own where the arrow points up, so that the icon heading matches the compass angle. Also, you can play with the icon hotspot tag, to define what part of the icon image is anchored at your point's lat/lon. In this case I used the center of the image, but you could use the origin or tip of the arrow if you wanted.
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
    <name>arrow icons with headings</name>

    <Placemark>
        <name>heading: 0</name>
        <Style>
            <IconStyle>
                <scale>3</scale>
                <heading>0</heading>
                <Icon>
                    <href>http://maps.google.com/mapfiles/kml/shapes/arrow.png</href>
                </Icon>
                <hotSpot x="0.5" y="0.5" xunits="fraction" yunits="fraction"/>
            </IconStyle>
        </Style>
        <Point>
            <coordinates>-90,38</coordinates>
        </Point>
    </Placemark>

    <Placemark>
        <name>heading: 75</name>
        <Style>
            <IconStyle>
                <scale>3</scale>
                <heading>75</heading>
                <Icon>
                    <href>http://maps.google.com/mapfiles/kml/shapes/arrow.png</href>
                </Icon>
                <hotSpot x="0.5" y="0.5" xunits="fraction" yunits="fraction"/>
            </IconStyle>
        </Style>
        <Point>
            <coordinates>-85,38</coordinates>
        </Point>
    </Placemark>

    <Placemark>
        <name>heading: 150</name>
        <Style>
            <IconStyle>
                <scale>3</scale>
                <heading>150</heading>
                <Icon>
                    <href>http://maps.google.com/mapfiles/kml/shapes/arrow.png</href>
                </Icon>
                <hotSpot x="0.5" y="0.5" xunits="fraction" yunits="fraction"/>
            </IconStyle>
        </Style>
        <Point>
            <coordinates>-80,38</coordinates>
        </Point>
    </Placemark>

</Document>
</kml>


text:
Q: Reusing ObjectOutputStreams in Java I am reusing ObjectOutputStream to send updates between the two clients, this is the server code,
 public void run() {

    try {
        toPlayer1.writeBoolean(true);
        toPlayer1.flush();

        while (true) {

            try {
                found = (boolean[][]) fromPlayer1.readObject();
                player1Int = fromPlayer1.readInt();

            } catch (Exception ex) {
                // Handle  exception here...
            }

            if (isWon(player1Int)) {
                toPlayer1.writeInt(P1_WON);
                toPlayer1.flush();
                toPlayer2.writeInt(P1_WON);
                toPlayer2.flush();

                sendMove(toPlayer2, found, player1Int);
                break;
            } else {
                toPlayer2.writeInt(CONTINUE);
                toPlayer2.flush();

                sendMove(toPlayer2, found, player1Int);
            }

            try {
                found = (boolean[][]) fromPlayer2.readObject();
                player2Int = fromPlayer2.readInt();

            } catch (Exception ex) {
                // Handle  exception here...
            }

            if (isWon(player2Int)) {
                toPlayer1.writeInt(P2_WIN);
                toPlayer1.flush();
                toPlayer2.writeInt(P2_WIN);
                toPlayer2.flush();
                sendMove(toPlayer1, found, player2Int);
                break;
            } else {
                toPlayer1.writeInt(CONTINUE);
                toPlayer1.flush();

                sendMove(toPlayer1, found, player2Int);
            }
        }
    } catch (IOException ex) {
        System.err.println(ex);
    }
}

private void sendMove(ObjectOutputStream out, boolean[][] found, int score) throws IOException {

    try {
        out.reset();
        out.writeObject(found);
        out.writeInt(score);
        out.flush();
    } catch (Exception ex) {
       // Handle  exception here...
    }
    out.writeInt(score);
}

the problem seems to be that some messages are not being delivered correctly, any suggestions? Am I using the flush() correctly? I have added reset(); it is still not working
update, these are the streams:
                public void run() {
    try {
             toPlayer1 = new ObjectOutputStream(player1.getOutputStream());
             fromPlayer1 = new ObjectInputStream(player1.getInputStream());
             toPlayer2 = new ObjectOutputStream(player2.getOutputStream());
             fromPlayer2 = new ObjectInputStream(player2.getInputStream());

regards, c

A: If you want an object or objects to be sent again, you need to call reset() on the ObjectOutputStream object.
The problem that reset() solves is that when you send an object in a object stream, the protocol attempts to preserve object identity.  The first time you send it, the stream sends the object state.  Subsequent times, it just sends a marker that says (in effect) "use this object that I sent you previously".
The reset() method says (in effect) to the ObjectOutputStream ... "forget about all objects that I sent previously".
So if you want to send the same object twice, you need to do something like this:
  out.writeObject(found);
  // change the state of 'found'
  out.reset();
  out.writeObject(found);

Note that this doesn't affect primitive values sent using their corresponding write methods.  Primitive values don't have "identity" and are sent literally each time.

I should also point out that the following is very bad practice.
        } catch (Exception ex) {
        }

You are silently ignoring all exceptions.  This is lazy and dangerous, and you are likely to come to regret it.  (Don't do it even in sample code in SO Questions ... 'cos someone might copy your bad code or some Java beginner might emulate your bad habits.)


text:
Q: How to download file(*.txt or *.pdf) which received from GET api response through Curl command? I want to download files(*.txt and *.pdf) from Ariba site through GET api request and want to automate the whole download process.
Initially I have used Postman for testing purpose which gives me result in the form of file content.
For eg. test.txt file is present on remote site, after GET request from Postman, the result I am getting, it is in form of content of file, so if 'abc' is written in file, I am getting 'abc' as response from test.txt file.
Now if I click on Send and Download button in Postman it gives me option to download file 'test.txt'
I have to automate this process to send GET response and get required file download at specific location. I am trying to use Curl script for this.
I have written corresponding Curl script and tried to execute it.
It gives me response in the form of file content.
curl -X GET \
  'https://openapi.ariba.com/api/approval/v1/prod/invoices/INVASINV6-902/attachments/bnMyMDE5LzA0LzAzLzE1MjkyNDE4MQ==?realm=ProjectName&Content-Disposition=attachement' \
  -H 'Accept: */*' \
  -H 'Authorization: Bearer 7648d29a-db04-4046-b49c-5daed43a145c' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Host: openapi.ariba.com' \
  -H 'accept-encoding: gzip, deflate' \
  -H 'apiKey: xxxxxxxxxxxxxxxxxx' \
  -H 'cache-control: no-cache'

I want to write a curl script which will download file at specific location.
For eg. Above curl command give content(abc) from file Test.txt and not file Test.txt as output
Really appreciate your helpCurl Get Response
Postman Get Response

A: Finally I got answer to the question, I just need to remove -X GET from my curl script and at the end add -o to download file name.
Below is the final code:
curl  'https://openapi.ariba.com/api/approval/v1/prod/invoices/INVASINV6-902/attachments/bnMyMDE5LxxxxLzE1MjkyNDE4MQ==?realm=ProjectName' \
  -H 'Accept: */*' \
  -H 'Authorization: Bearer 77876887-xxxxx-42fb-b865-9cf8ff5c2b25' \
  -H 'Cache-Control: no-cache' \
  -H 'Connection: keep-alive' \
  -H 'Host: openapi.ariba.com' \
  -H 'accept-encoding: gzip, deflate' \
  -H 'apiKey: XXXXXXXXXXXXXXXX' \
  -H 'cache-control: no-cache' \
  -H 'Content-Type: application/octet-stream' \
  -H "Content-Transfer-Encoding: Binary" \
  -o "Test.txt"

Above code give me file downloaded at specific location.
Thanks BlackPearl.


text:
Q: Selenium driver - find elements containing data attribute (HTML5) So, imagine a page that has the following HTML:
<button data-my-custom='{"fileName":"SomethingRandom.zip"}'>
                 Download build 1023
</button>

There will be several of these on the page, each will have a different filename value for the data-my-custom HTML 5 attribute.
How can I get the elements that contain the HTML5 attribute "data-my-custom" in Selenium?
I cannot figure out if I should use XPATH and if so, what the expression would be?
Thank you.

A: For CSS-path, the selector will be: button[data-my-custom], or button[data-my-custom=<{yourFileNameObject}>] if you want to find a specific one.
Full credit to iamdanchiv.


text:
Q: Slow plotting of trigonometric functions I have two sets of solutions for a and b. I'm plotting solution only if it is positive for both a and b.
 a = 2; b = 3;
 solutionsA[x_, a_, b_] = {a Sin[b*x], a Sin[b*x + Pi/2], a Sin[b*x + Pi]};
 solutionsB[x_, a_, b_] = {a Tan[b*x], a Tan[b*x + Pi/2], a Tan[b*x + Pi]};
 Plot[Select[
    Transpose[
      {solutionsA[x, a, b], solutionsB[x, a, b]}
    ]
   , (#[[1]] > 0 && #[[2]] > 0 ) &]
 , {x, 0, 10}, Exclusions -> {Cos[b*x] == 0, Sin[b*x] == 0}]

My output is very slow. Why?

A: A solution which outperforms the currently given answers is the following: You build up the complete expression of your function using Which, so that you have in the end
tuned[x_]:=Which[
  Positive[Sin[3 x]]&&Positive[Tan[3 x]],{2 Sin[3 x],2 Tan[3 x]},
  Positive[Cos[3 x]]&&Positive[-Cot[3 x]],{2 Cos[3 x],-2 Cot[3 x]},
  Positive[-Sin[3 x]]&&Positive[Tan[3 x]],{-2 Sin[3 x],2 Tan[3 x]},
  True,None]

This approach works even if you don't know specific values for a and b. To get the definition of tuned automatically from you two solutionsA and solutionsB the following injection code can be used:
With[{arg = Transpose[{solutionsA[x, a, b], solutionsB[x, a, b]}]},
 (tuned[x_] := #) & [
   Which @@ Sequence @@@ Append[{And @@ (Positive[#]), #} & /@ arg, {True, None}]]
 ]

On my machine, creating the graphics 10x gives the following timings for the different answers (I'm on my desktop pc now, so timings are in general faster):

*

*my approach 0.46 seconds. If I tweak it with Compile (see below) we can improve it to 0.21 seconds.

*the original approach of the OP takes 7.71 seconds.

*Leonid's compiled version 0.59 seconds and when you compile it to "C" then 0.55 seconds

*chyaongs needs 0.61 seconds

For testing, I iterated your original Plot command and measured the AbsoluteTiming. Let me point out that all current answers use the same approach and the tweaking to improve from 0.6 to 0.2 seconds isn't really worth it.
Let me give the code of my compiled version for comparison
With[{arg = Transpose[{solutionsA[x, a, b], solutionsB[x, a, b]}]},
 tunedC = Compile[{{x, _Real}}, #] &[
   Which @@
    Sequence @@@
     Append[{And @@ (Positive[#]), #} & /@ arg, {True, {0., 0.}}]]]

A: a = 2; b = 3;
solutions[f_, a_: a, b_: b] = a {f[b*x], f[b*x + Pi/2], f[b*x + Pi]};
expr = If[#1 > 0 && #2 > 0, {##}] & @@@ Transpose[solutions /@ {Sin, Tan}]
Plot[expr, {x, 0, 10}, Exclusions -> {Cos[b*x] == 0, Sin[b*x] == 0}]

A: A nice compact one, using the two argument form of UnitStep and summing the solutions:
sol = Total @ MapThread[UnitStep[##] {##} &, {solutionsA[x, a, b], solutionsB[x, a, b]}]

Block[{a = 2, b = 3}, Plot[sol, {x, 0, 10}, Exclusions -> {Cos[b*x] == 0, Sin[b*x] == 0}]]

A: You can get it about 5-6 times faster if you define a separate function (to do Transpose just once):
ClearAll[f];
f[x_?NumericQ] =
   # * UnitStep[First @ #] * UnitStep[Last @ #] & /@
       Transpose[{solutionsA[x, a, b], solutionsB[x, a, b]}],

and the presence of UnitStep makes Select unnecessary, with visually the same output. You can then plot it as e.g.
Plot[f[x], {x, 0, 10}, Exclusions -> {Cos[b*x] == 0, Sin[b*x] == 0}, PlotRange -> {Automatic, {0, 7}}]

A cleaner way to do this is to have a function generator that would embed your parameters, so that you don't have a dependence on global variables a and b:
makeF[a_, b_] :=
   Function[
      x,
      # * UnitStep[First @ #] * UnitStep[Last @ #] & /@
         Transpose[{solutionsA[x, a, b], solutionsB[x, a, b]}]
   ]

and then
ClearAll[f];
f = makeF[a,b]

and then use f as before.
To get some further speed-up, you can compile this. Here is the corresponding function generator:
ClearAll[makeFC];
makeFC[a_, b_, opts___?OptionQ] :=
    Block[{x},Compile[x, Evaluate[makeF[a, b][x], opts]]]

Now you can do
fc = makeFC[a, b];

and then plot fc. I can't test now, but presumably by passing CompilationTarget -> "C" to makeFC, you can get the plotting faster still.


text:
Q: Is it more pythonic to separate Exception catches or do them within one try-block? Python I hope this is not too opinion based, but I've understood that the Python community has some strong guidelines for how to use exception handling, though I couldn't find any commentary fitting to my situation.
I'm in the process of writing the main API function of a web-based script. The incoming data is first preprocessed/sanitized, then pushed through the complicated processing, and the result is finally postprocessed/formatted before being sent back to the requester. Each of the three parts can fail due to various reasons, so I need to wrap them into try-except blocks.
My question is: Is it more pythonic to wrap the whole process in one try-except -block an capture various types of exceptions, or to create individual blocks? I.e., of the following two styles, should I prefer one of them?
Version 1
def main(input_data):

    try:
        parsed_data = parse_incoming_data(input_data)
    except LookupError as e:
        return func.HttpResponse(f"Misformatted data, key not found: {e}", status_code=400)

    try:
        processed_data = big_process(parsed_data)
    except CustomProcessingException as e:
        return func.HttpResponse(f"Main service failed due to {e}.", status_code=500)

    try:
        output = postprocess_result(processed_data)
    except CustomPostprocessingException as e:
        return func.HttpResponse(f"Postprocessing error {e}.", status_code=555)

    return func.HttpResponse(output, status_code=200)

Version 2
def main(input_data):

    try:
        parsed_data = parse_incoming_data(input_data)
        processed_data = big_process(parsed_data)
        output = postprocess_result(processed_data)
    except LookupError as e:
        return func.HttpResponse(f"Misformatted data, key not found: {e}", status_code=400)
    except CustomProcessingException as e:
        return func.HttpResponse(f"Main service failed due to {e}.", status_code=500)
    except CustomPostprocessingException as e:
        return func.HttpResponse(f"Postprocessing error {e}.", status_code=555)

    return func.HttpResponse(output, status_code=200)

A: This depends on the specifics of the code and the errors being thrown.
With the first way, say processed_data = big_process(parsed_data) fails.  output = postprocess_result(processed_data) will still run since they're separate checks. Also, all three failures have the potential to be handled in three different ways.
With the second way, say the first line fails. The third line will not run since execution is transferred to the except block. Also, all three failures will be handled the same way (unless you manually use flags or some other mechanism to differentiate).
So the answer is, neither is really more Pythonic. The pieces of code are not equivalent, so you should use whichever is more appropriate for your particular case.


text:
Q: VirtualBox bridged network not working as expected I am having hard time getting a bridged network to work with VirtualBox. The idea is to have the host as well as one or more guests on same LAN.
Using NAT (default) I do get access to the Internet and any node on the LAN when working from one of the VM guests. However, no LAN node including the host can access (or ping) guests in the VM.
I need to be able to use any guest as if it was a physical computer on the network (need to be accessed by any machine on LAN). According to my understanding of the VirtualBox documentation, this should be Bridged mode.
I think I set it correctly, well, actually there is not much to it:

*

*Select Bridged mode in VM network setup

*Select physical NIC of the host to connect the bridge to

*Start VM

When I do this, each VM does get new IP address that corresponds to LAN settings:
192.168.1.100
192.168.1.102
192.168.1.103

where host is 192.168.1.80 / 255.255.255.0 (IP addresses above 100 are served by DHCP server).
This seem to be correct based on what I know about Ethernet. From the VM I can ping other nodes like 192.168.1.50 and I still get Ethernet access.
However I STILL cannot ping any of the other VMs (those that are running, of course). I cannot ping them from other VMs, from the host or from other nodes on the LAN. Aside from fact that IP addresses handed to guests are now local, this still acts the same as the NAT setup.
What is going on? What am I missing?

A: If the VMs you cannot ping are not using bridged networking, then you can't ping them because they are behind virtual NAT routers.
If they are using bridged networking, then their operating systems may have firewalls turned on.


text:
Q: QML ListView in qml is not updated when model changed I am trying to update a model in a QML ListView from a cpp file..
Here is my implemenation. I copied evrything to this therfore it will be a little bit bigger from code size.
this is my model implementation albummodel.h
#include <QAbstractListModel>
#include <QStringList>
#include <QQmlListProperty>

class Album
{
public:
    Album(const QString &type, const QString &size);

    QString type() const;
    QString size() const;

private:
    QString m_type;
    QString m_size;

};

class AlbumModel : public QAbstractListModel
{
    Q_OBJECT
    Q_PROPERTY(QQmlListProperty<QObject> myModel NOTIFY listChanged)

public:

    enum AlbumRoles {
        TypeRole = Qt::UserRole + 1,
        SizeRole
    };

    AlbumModel(QObject *parent = 0);

    //QQmlListProperty<QObject> getList();

    void addAlbum(const Album &album);

    int rowCount(const QModelIndex & parent = QModelIndex()) const;

    QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;

protected:
    QHash<int, QByteArray> roleNames() const;
private:
    QList<Album> m_albums;
signals:
    void listChanged();
#include <QAbstractListModel>
#include <QStringList>
#include <QQmlListProperty>

class Album
{
public:
    Album(const QString &type, const QString &size);

    QString type() const;
    QString size() const;

private:
    QString m_type;
    QString m_size;

};

class AlbumModel : public QAbstractListModel
{
    Q_OBJECT
    Q_PROPERTY(QQmlListProperty<QObject> myModel NOTIFY listChanged)

public:

    enum AlbumRoles {
        TypeRole = Qt::UserRole + 1,
        SizeRole
    };

    AlbumModel(QObject *parent = 0);

    //QQmlListProperty<QObject> getList();

    void addAlbum(const Album &album);

    int rowCount(const QModelIndex & parent = QModelIndex()) const;

    QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;

protected:
    QHash<int, QByteArray> roleNames() const;
private:
    QList<Album> m_albums;
signals:
    void listChanged();
};

This is my albummodel.cpp
#include "albummodel_mediaplayer.h"

Album::Album(const QString &type, const QString &size)
    : m_type(type), m_size(size)
{
}

QString Album::type() const
{
    return m_type;
}

QString Album::size() const
{
    return m_size;
}

AlbumModel::AlbumModel(QObject *parent)
    : QAbstractListModel(parent)
{
}

void AlbumModel::addAlbum(const Album &album)
{
    beginInsertRows(QModelIndex(), rowCount(), rowCount());
    m_albums << album;
    endInsertRows();

    emit listChanged();
}

int AlbumModel::rowCount(const QModelIndex & parent) const {
    Q_UNUSED(parent);
    return m_albums.count();
}

QVariant AlbumModel::data(const QModelIndex & index, int role) const {
    if (index.row() < 0 || index.row() >= m_albums.count())
        return QVariant();

    const Album &Album = m_albums[index.row()];
    if (role == TypeRole)
        return Album.type();
    else if (role == SizeRole)
        return Album.size();
    return QVariant();
}

QHash<int, QByteArray> AlbumModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[TypeRole] = "type";
    roles[SizeRole] = "size";
    return roles;
}

/*QQmlListProperty<QObject> AlbumModel::getList(){
    return QQmlListProperty<QObject>(this, *list);
}*/

and my qml file
import AlbumModel 1.0
ListView {
model: AlbumModel.myModel
delegate: playListThumbnail
Component {
id: playListThumbnail
            Item {
 Text {
                    id: albumTitleText
                    text:  type//item_title
}}
....
}

I added the main Programm Code. Hope this is enough for a mvp
Main.cpp
 void main() {
       qmlRegisterType<AlbumModel>("AlbumModel",1,0,"AlbumModel");
       Album g("test", "test");
        AlbumModel h();
        h.addAlbum(g);
   }

But the model isn't updated. Which signal did i miss?


text:
Q: How to get display name for NSLocale in Cocoa? I have the following problem:
I have a NSLocale object and want to access a resource in a .lproj directory for this locale.
For this to work I need to full name of the locale, for example "German". I can't find a way to get this string from a NSLocale object.
How do I accomplish this?

A: Nevermind:
NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:language] autorelease];
[locale displayNameForKey:NSLocaleIdentifier value:language]);


text:
Q: Django local version using remote static files despite local settings I have managed to successfully deploy my Django app to AWS Elastic Beanstalk (using eb). I have followed the steps laid out here http://www.youtube.com/watch?v=YJoOnKiSYws and here http://grigory.ca/2012/09/getting-started-with-django-on-aws-elastic-beanstalk/ and am using the django-storages (boto) framework to assist with staticfile management to S3.
I have the following settings in my SETTINGS.PY:
STATIC_ROOT = os.path.join(
    os.path.dirname(
        os.path.dirname(
            os.path.abspath(__file__))), 'static')

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_ACCESS_KEY_ID = 'access-key'
AWS_SECRET_ACCESS_KEY = 'secret-key'
AWS_STORAGE_BUCKET_NAME = 'bucket-name'
STATIC_URL = '/static/'
STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
.
.
.
try:
 from local_settings import *
except ImportError, e:
 pass

and my LOCAL_SETTINGS.PY has the following:
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
  ('js', '/blah/blah/static/js'),
  ('css', '/blah/blah/static/css'),
  ('images', '/blah/blah/static/images'),
)

In my templates I use:
{% load staticfiles %}
<link href="{% static "css/styles.css" %}" rel="stylesheet">

The issue is that when I run the app locally it references my static files in S3 and not in my local directories. What settings do I need to change so that when I run the app locally it uses local static files and that when it runs on AWS it uses S3 files?

A: The issue is that you have to reset the default storage backends in your local_settings.py file; the settings.py file is processed first, and when you get to local_settings.py, Django is still using the defaults.
An alternative strategy (and perhaps a preferable one) is to test the environment in settings.py to determine if you are local or remote (i.e. development or production) and then decide which settings to use.
edit: So, as an example, the AWS Django guides tell you to do something like this:
if 'RDS_DB_NAME' in os.environ:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': os.environ['RDS_DB_NAME'],
            'USER': os.environ['RDS_USERNAME'],
            'PASSWORD': os.environ['RDS_PASSWORD'],
            'HOST': os.environ['RDS_HOSTNAME'],
            'PORT': os.environ['RDS_PORT'],
        }
    }

And then, in local_settings.py, you define DATABASES for your local configuration. What I have done in the past is something like this:
if 'RDS_DB_NAME' in os.environ:
    LOCAL_ENVIRONMENT = False
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': os.environ['RDS_DB_NAME'],
            'USER': os.environ['RDS_USERNAME'],
            'PASSWORD': os.environ['RDS_PASSWORD'],
            'HOST': os.environ['RDS_HOSTNAME'],
            'PORT': os.environ['RDS_PORT'],
        }
    }

And then use LOCAL_ENVIRONMENT (or whatever you want to name it) to drive the rest of the configuration.

A: can you post your urls.py
btw you have to have debug=True to serve static locally
This might help you to configure your settings and local_settings


text:
Q: mysql transaction in stored procedure (locking/rollback) does a transaction in a stored procedure do any locking to prevent others from updating tables?
also do i need to explicitly put in rollback logic or will the transaction automatically roll back if an error occurs because it never reaches the commit command.

A:
Does a transaction in a stored procedure do any locking to prevent others from updating tables?

When you perform some DML on an InnoDB table, the rows affected get locked until the end of transaction (doesn't matter is it inside a stored procedure or not).
You can modify the locked rows inside the same transaction that locked it.
To explicitly lock some rows, issue:
SELECT  *
FROM    table
WHERE   condition
FOR UPDATE

Except for commiting or rolling back the transaction, there is no other way to unlock the rows

Do i need to explicitly put in rollback logic or will the transaction automatically roll back if an error occurs because it never reaches the commit command.

You'll need to perform a rollback explicitly.


text:
Q: Binding a WPF DataGrid inside a UserControl I would like to create a UserControl containing a DataGrid and then define the columns directly inside my UserControl:
<my:ControlContainingDataGrid ItemsSource="{Binding}">
  <my:ControlContainingDataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Path=Property1}" Header="Property 1"/>

In the UserControl I expose the columns of the DataGrid :
static ControlContainingDataGrid()
{
  ColumnsProperty = DependencyProperty.Register(
    "Columns",
    typeof(ObservableCollection<DataGridColumn>),
    typeof(ControlContainingDataGrid),
    new UIPropertyMetadata(new ObservableCollection<DataGridColumn>())
  );
}

[Description("Columns"), Category("Columns")]
public ObservableCollection<DataGridColumn> Columns
{
  get { return _datagGrid.Columns; }
}

public static readonly DependencyProperty ColumnsProperty;

=> it doesn't work : the column binded to Property1 is not created.
I try to create the column programatically :
    _datagGrid.Columns.Add(new DataGridTextColumn {
      Header = "Property 1",
      Binding = new Binding {
        Path = new PropertyPath("Property1"),
        Mode = BindingMode.TwoWay,
      },
    });

_datagGrid.ItemsSource = testList;

=> it doesn't work : the header is displayed but each row of my DataGrid is empty (bad binding ?).

1- What is the simpliest way to bind the columns of a DataGrid via the UserControl in the XAML part ?
2- What is the simpliest way to bind the columns of a DataGrid via the UserControl programatically ?

A: I do this programmatically. Pretty much the same code as you have. Works fine. I have never tried to bind the Columns collection itself though I don't see why that should not work.
Your message is a little ambiguous. If you mean to say that your column does not show up, maybe you need to add the columns prior to creating the table. If the rows show up with empty value in the column, then your binding 'Property1' is wrong.
I don't work in XAML so don't know nothing about that.


text:
Q: How can I check if input.value is the same as a random number I want to make a little game where the browser selects a random number between 1 and 10 and the user has to guess which number it is. So I made an input, button and the random function, but every time, also when the inputNumber and the randomNumber are the same, it doesn't output the code I want!
<input type="numebr" id="userInput" />
<button id="button">Sure?</button>

let button = document.getElementById('button');
let input = document.getElementById('userInput').value;
let awnser = document.getElementById('awnser');

  button.onclick = function randomFunc() {
    var randomnr = Math.floor(Math.random() * 10 +1);

    if (input == randomnr) {
        awnser.innerHTML = randomnr + '
 You got it!';
    } else {
        awnser.innerHTML = randomnr + '
 Nevermind... idiot :P';
    }
  }

I tried to solve it's with parseInt
let input = parseInt(document.getElementById('userInput').value);
but it doesn't work. I think its a problem with the input value so that this is not a number rather a string...
Some tips for me?

A: It's because of what you do with this line:
let input = document.getElementById('userInput').value;

This gets the value when the page loads. when you click on a button, its value is the same as it was when the page got loaded. just move this line into button.onclick function and you should be fine.

A: Put
let input = document.getElementById('userInput').value;

inside the onclick function


text:
Q: Regex Pattern not alow zero I have this Pattern it's worked successful:
@"^-?(0\.\d*[0-9]|[0-9]\d*(\.\d+)?)$

but I want this pattern not allow zero like this inputs:
not allowed inputs:
0.0     //not allowed
00.00   //not allowed

allowed inputs:

0.07    // allowed
0.70    // allowed
and any number decimal

A: I would use a negative lookahead assertion to make the regex fail if it is only "0".
@"^-?(?!0*(\.0*)?$)(0\.\d*[0-9]|[0-9]\d*(\.\d+)?)$

See it here on Regexr
This expression (?!0*(\.0*)?$) makes the whole regex fail, if the number consists only of zeros.

A: Regular expressions are for matching patterns, not checking numeric values. Find a likely string with the regex, then check its numeric value in whatever your host language is (PHP, whatever).


text:
Q: Creating chat login system with javascript/ php? $(function() {
    $('.newMessage').hide();
    $('#messageBoxSignIn').click(function() {
        $('#username').focus();
    });
}) ;

$(function() {
    $('.error').hide();
    $('#signIn').click(function() {
        var username = $('#username').val();

        if (username == "" || username == "Enter Username") {
            $('.error').show();
            return false;
        }

        $('#messageBoxSignInForm').hide();
        $('.newMessage').show();

        var dataString = 'username=' + username;

        $.ajax({
            type: "POST",
            url: "singinout.php",
            data: dataString,
            success: function () {
                $('.user').html('Welcome ' + username + '! SIGN OUT');
            }

            });

    });
})

My code for the javascript, I want to make it so when the user types in a username in the messageboxsignin, a "welcome (username)!" text would appear as well as the sign in button would be changed to sign out. But it doesn't work, the text doesn't appear and the button still appears as sign in.
HTML code:

<link rel="stylesheet" type="text/css" href="chatcss.css">

<title>4thebored</title>

        <form name="signIn" action="" onsubmit="return false">
            Invalid Username
            <input type="text" size="13px" name="username" id="username" value="Enter Username" onclick='document.signIn.username.value = ""' />
            <input type="submit" id="signIn" value="SIGN IN" />
            </form>

admin: *******

    <form name="messageBoxSignInForm" id="messageBoxSignInForm" onsubmit="return false">
    <input type="submit" id="messageBoxSignIn" value="Sign in to enter chat" />
    </form>

    <form name="newMessage" class="newMessage" action="" onsubmit="return false">

    <textarea name="newMessageContent" id="newMessageContent">Enter your message here</textarea>

    <input type="submit" id="newMessageSend" value="SEND" />

    </form>


text:
Q: Trying to build a network from the data I collected but facing issues Trying to access the edge using the source user_id and the target user_id
# so we can access the edge using the source user_id and the target user_id
G.edges([nodelist[0]][list(e.keys())[0]])

Error:
AttributeError                            Traceback (most recent call last)
<ipython-input-48-12593dd17b79> in <module>
      1 # so we can access the edge using the source user_id and the target user_id
----> 2 G.edges([nodelist[0]][list(e.keys())[0]])

AttributeError: 'OutEdgeDataView' object has no attribute 'keys'

Another error I am facing...
Trying to list all nodes
# listing all nodes
nodelist = G.nodes()
nodelist[:3]

Error:
TypeError                                 Traceback (most recent call last)
<ipython-input-56-0135a95aa2ab> in <module>
      1 # listing all nodes
      2 nodelist = G.nodes()
----> 3 nodelist[:3]

~\anaconda3\lib\site-packages\networkx\classes\reportviews.py in __getitem__(self, n)
    176
    177     def __getitem__(self, n):
--> 178         return self._nodes[n]
    179
    180     # Set methods

TypeError: unhashable type: 'slice'

A: I believe your errors are related. I'm not sure because you don't define the variable e in the code above, but based on the type in the error it looks like you defined it as e = G.edges() which returns an OutEdgeDataView object rather than a dict as you desire. You can get a list of the graph edges using e = list(G.edges()) which gives you a list of tuples where the first item of the tuple is the source node and the second item is the target node. Then to get the edge attributes for the edge corresponding to nodelist[0] you can say G.edge[nodelist[0],the_tail_node].
For your second error, G.nodes() is not a list and doesn't support slicing. When you define nodelist above you can do nodelist = list(G.nodes()) and then you can slice as desired.


text:
Q: PHP String Parsing Strip *First* enter/return space from form textarea How do you strip the first (before any visible text) enter/return space from text taken from a variable (submitted from a textarea)?

A: Like this:
$str = str_replace("\n\r", '', $content);

Note: If you want to convert newliness to <br />, use nl2br instead.
Note also that "\n\r" is for Windows systems, it is \n on unix/linux.
Update:
Try this regex:
$str = preg_replace(/[\n\r{2,}]+/, "\n", $content);

A: $userinput = trim($userinput)

trim() works for followings, though you can strip some of those giving a char list
    * " " (ASCII 32 (0x20)), an ordinary space.
    * "\t" (ASCII 9 (0x09)), a tab.
    * "\n" (ASCII 10 (0x0A)), a new line (line feed).
    * "\r" (ASCII 13 (0x0D)), a carriage return.
    * "\0" (ASCII 0 (0x00)), the NUL-byte.
    * "\x0B" (ASCII 11 (0x0B)), a vertical tab.

A: ltrim removes only whitespaces before the text. you can put an array of additional chars you dont need into the second argument.
$userinput = ltrim($userinput, $charsYouDontNeed);

the fact that it doesn't work might mean that the chars you are trying to delete are not really new line chars

A: Try:
$str = preg_replace('/[\n\r{2,}]+/', "\n", $content);


text:
Q: View Soap Requests from imported connected service I'm trying to implement a consumer for a 3rd party SOAP service.  I've imported the asmx in as a connected service and able to initialise the client and make requests etc all fine to a point.
Where my trouble begins is a couple of the requests I'm making from all appearances are working correctly and returning me success results but when viewing the results at the other, the data I'm posting is just not there.  I've been speaking to the providers of this SOAP service, and they've asked I send them the requests I'm making.  However, since I'm using the generated SOApClient, I'm not sure exactly how to get the actual request.
Is there away to view the actual SOAP messages?  Did have a look at Fiddler, but couldn't see anything bar the network traffic.
My project is C# .Net 4.8 and working in Visual Studio 2022

A: There should be options in App.config or Web.config to enable logging of the messages.
For example: https://learn.microsoft.com/en-us/dotnet/framework/wcf/diagnostics/tracing/configuring-tracing


text:
Q: How can I send xml variable by select's option value? var services = $(result).find("root>content>root");
services.each(function () {
  var r = $(this);
  var name = r.find('service').attr("name");
  $('#service_select').append('<option value="'+ r +'">' + name + '</option>');
}

var r contains:
    <root>
      <service name="" status="" .. ></service>
    </root>

when select changes, I wanted to get that xml
$(document).on('change', '#service_select', function ()  {
    var selected = $('#service_select').val();
    var name = selected.find('service').attr("name");

    console.dirxml(selected);
});

I can't get values from variable selected. In console I get [object Object]. How to get xml format instead?

A: You can parse the XML using jQuery parseXML utility.
var xmlDoc = $.parseXML( r ),
  $xml = $( xmlDoc ),
  name = $xml.find( "service" ).attr("name");


text:
Q: Is "tactical awareness" an alias of "interceptions"? I only find "interceptions" attribute on my FIFA 14 (Just like this), but I notice many guys mentioned something called "tactical awareness" attribute (example).
I think it's an alias of "interceptions" in fact, but I'm not sure. So, is it an alias?

A: So here is the answer to the best of my knowledge, They are definately different things as in reality, Like user85756 mentioned in the comments of the OP Tactical awareness is the ability to play the teams tactics better whether it be on the counter attack or the offside trap, It is akin to the all important positioning stat for strikers but more important for defenders.
Interceptions on the other hand is the defenders ability to actually intercept the ball if he is in the correct position.
The best defender will have a combination of both of these so that the player is in the right position and can execute.
You will find on most forums that the TA stat is largely debateble whether it actually effects ingame play but i have found that defenders with a much higher stat play the offside trap much better than the ones with a low one.
Source for Tactical awareness

A: I don't think they are. According to what I researched: Tactical Recognition: For the people which have established your teams' route to shorter passing and you have got an individual prosperous in Tactical Awareness, he'll be nearer towards the ball much more normally when compared to the usual participant with lower Tactical Consciousness.
So in this case, I would say they are the opposite: Tactical Awareness is the ability to have your own players well positioned for a pass... Interception meaning you read the opponent to know where the pass is going and take possession.
Hope this answers the question :)


text:
Q: Best practice for threaded getter method I also faced with the NetworkOnMainThreadException in my application but I don't see how to resolve it.
I have a class with a getter method. Like:
public ArrayList<News> get(int i){
   // get the list of news from a HTML on the net. The news are split up into web pages   on the site
   // and i is the page number
   return NewsParser(i);
}

Since Android throws the exception I come up with an idea of a downloader class which downloads the HTML content in a separate thread
pubic ArrayList<News> get(int i){
   Downloader dl = new Downloader(i);
   String HTMLcontent = dl.getContent(); <-- AsyncTask starts in getContent()
   return NewsParser(HTMLcontent); <-- What happens here in the main thread???
}

Any ideas/best practices for this problem?

A: Just looking at your code and your question, it seems like you don't have a very solid understanding of how AsyncTask (or threads in general) works.
I would recommend reading this article.
Basically, your AsyncTask should query the web URL and download the data.  Once the data is complete, your AsyncTask should send the HTMLContent to a handler object.  The handler will be running on your main thread, so you can display the information to the user at that point.
You shouldn't be calling
dl.getContent();

to retrieve the content.  AsyncTask runs on a separate thread, so you can't just call methods like this from your main thread.  You need to create the Downloader object (like you did) and then call
dl.execute();

to start the AsyncTask.

A: run the get method inside a thread,
    new Thread(new Runnable() {

        @Override
        public void run() {
            // call get method here

        }

    }).start();

A: Since Honeycomb (Android 3.0) you can't use Networking Operations in the MainThread to avoid freezes on the Phone. This is important in order to make your app responsive.
More info:
NetworkOnMainThreadException
Responsiveness


text: Q: Connecting webapp to user's BigQuery project I have made a webapp using streamlit framework that can connect to BigQuery project of a user to fetch the required table and perform certain operations on it and result the output. Rightnow, we are getting the link to the authentication code on the command line. Since we are now planing to deploy the app on the google app engine, is there any way to authenticate a user some other way (other than getting authentication link on CLI since it wouldn't be possible after deployment on app engine).


text:
Q: SQL: How to select elements in a rectangle range from a large continuous matrix? **UPDATED** I'm having a hard time working out the following problem efficiently.
I have a 15000x15000 xy matrix. I'm storing element locations in this matrix by defining a x,y coordinate for the element. I want to display a part of the matrix in a so called viewport. The viewport dimensions are e.g. 1600x1000
Consider the following db structure:

Element (element_id, image, width, height)
Globe_Element (ge_id, x, y, element_id)

With the only input being a x,y coordinate somehwere in the grid (500x500) how can I select all the Globe_Element rows which are visible in the viewport (6x4)?
Viewport example http://img33.imageshack.us/img33/6089/viewportexample.jpg
The above image demonstrates the issues. The small orange squares are elements which should be included, small red squares shouldn't (looking at the nearest viewport). The big colored blocks (blue, yellow, green and red (yes again, sorry for confusion) are viewports. One color is one viewport. Gray circles define the input coordinates.

A: Assuming your coordinate parameter is the upper left corner of the viewport, something like this is generally how to select the corresponding rows:

select * from globe_element g, element e
where
e.element_id = g.element_id and
((x < width and x between @x_param and (@x_param + 6))
or (x >-1 and x between (@x_param - width) and (@x_param - width + 6)))
and
((y_loc < height and y_loc between @y_param and (@y_param + 4)) or (y_loc >-1 and y_loc between (@y_param - height) and (@y_param - height + 4)))

This is just generic sql, not mysql specific (the parameters, at least).
Generally: Select where x is between the x_param and x_param+ view_port_width, and y is between y_param and y+param + view_port_height. If the calculated coordinate is greater than the view_port_width/height, subtract 500 to get the corresponding wrapped location.
This does not order the coordinates in any way.
Also, your "Spherical" environment doesn't really appear to be spherical at all.... how are you mapping a grid to a sphere? Just like degrees lat/long on the earth where the area of each square unit shrinks as you get to the poles? If that's the case, then this will work. If not, then what I've posted is rubbish. However, if that's the case then solving this in SQL is also.... wrong.

A: For doing this efficiently in SQL I would recommend you to choose a DBMS with spatial support (often going under the name GIS support) or with support for two- or multi-dimensional indexes (I don't know any such).
I think only then will you be able to make your queries use indexes to perform efficiently.
Postgres has spatial support (under the name PostGIS), as does MS SQL 2008 and Oracle. I only used MS SQL 2008 for spatial, here is a nice overview of how its spatial index subdivides the surface.
Without multi-dimensional indexes you'll have your objects on disk ordered along one coordinate axis, consequently you will only be able to narrow down the table scan for objects only along one coordinate axis.

If you want to stay with MySQL (reply to OP comment below):
I think it is better to create the query with concrete values - whether you do that in PHP or in a stored procedure on the SQL side, is a different question. But it is simple and easy enough to do in PHP so I would recommend that.
You can make decisions like whether the viewport is in a non-wraparound position (blue in your diagram above) and then its enough to emit a single query with a simple WHERE xmin>=viewport_xmin AND xmax<=viewport_xmax AND ymin>=viewport_ymin AND ymax<=viewport_ymax clause. Or see that the viewport wraps, and then experiment whether it is faster to execute 2/4 separate simple queries for each of the 2/4 unwrapping parts of the portal, or put all the 2/4 simple queries with ORs between them in one big query. You will have to see which one will be faster, experiment with indexes, look at query plans, etc.


text:
Q: looking for reducing time of a big sql request in oracle I have two tables:
D with field d1 and field d2
and T with field s
the two fields are of type Varchar2(255)
select d2
FROM
D ,
(select s from T where (s = 'val_1') OR (s='val_2') OR .. OR (s='val_n')  ) S
WHERE d1 LIKE CONCAT(CONCAT('%,',S.s),'%')

My problem is that the number n is huge (superior than 2500)
then the time to resolve the request is about five minutes
is there a solution to reduce this time

A: Let's start with D.  This WHERE clause ...
WHERE d1 LIKE CONCAT(CONCAT('%,',S.s),'%')

... is deadly.  It means the query needs to probe every single value of D1.  No regular index will help find a value with a wildcard at each end.
Now let's consider T.  This WHERE clause ...
 (s = 'val_1') OR (s='val_2') OR .. OR (s='val_n')

... apparently has more than 2500 elements in it.  Pure poison to tune.
Despite the assertion (in a comment) that "there aren't indexes on tables" the posted creation table statements have primary keys, so there are indexes available.
But as T appears to have just the one column, an index on column T.S doesn't make any difference: a Full Fast Index Scan will be as quick (or as slow) as a Full Table Scan.  Given that S is a varchar2(255) that will be pretty slow, as there won't be many values to the block.
For the reasons already stated, the index on D.D1 is irrelevant, so again we're left with a Full Table Scan as the only access path.
So what's the best execution plan we could hope for?   Something like:

*

*Full Table Scan of T

*Filter of the 2500+ values of S

*Full Table Scan of D

*A hash join of T.S and D.D1

...except that those wildcards will mean a Nested Loop operation instead of a Hash Join.
Finally let's consider this statement:

"the time to resolve the request is about five minutes"

The single post important thing in tuning is have a reasonable expectation of elapsed time.  Five minutes might represent a horribly slow response or a fantastically fast response under the circumstances.  Who can tell?  We certainly cant.  Only the OP can, because only they have the access to the data and hence the ability to answer these questions:

*

*What is the average length of  columns D1 and D2?

*How many rows are there in table D?

*What would be a reasonable to read them all?

*What is the average length of  columns S?

*How many rows are there in table T?

*What would be a reasonable to read them all?

*How many rows in T where S matches '%val_1%' through '%val_n%' ?

*How many rows i  D where D1 matches  '%val_1%' through '%val_n%'?

*What would be a reasonable time to match them all?

*What would be a reasonable time to display all the relevant values of D2?

A: There are indexes as each primary key creates an index. However, using LIKE with a "%" at the beginning of the match string renders the indexes useless.
But in general, having >2500 OR clauses hints at a more fundamental problem. This huge number of OR clauses must have been generated, because no human would ever enter or code such a  query. It seems to me, that part of the query migrated to the code generating the query.
So you should take a step back and ask yourself the question, what rows you really want, what condition the rows need to satisfy. Should the val_1 .. val_n come from outside the database consider putting them into the database first.


text:
Q: Sails 1.0 Models without primary key I try to use new version 1.0 and refactoring my project. I have one problem and i don't now how i can solve her. Some tables on my BD don't have primary keys and when i migrate to sails 1.0, i have this error

In model friends: The primary key is set to id, but no such
  attribute was found on the model. You must define an id attribute in
  api/Friends.js or in config/models.js. See
  http://sailsjs.com/upgrading#?changes-to-model-configuration for
  info

Can i use my model without primary keys?

A: i have the same problem i used to change the primarykey this:
in file config/model.js
attributes: {
      id: {
         type: 'number',
         autoIncrement: true,
      },
    }

    and in the model api/any_model.js i used:

    tableName : 'table',
    attributes: {
      id: {
       type: 'number',
       columnName : 'column_you_like_to_be_a_primaryKEY',
       required : true
      },
    }


text:
Q: Positional operator and field limitation In a find query projection, fields I specify after the positional operator are ignored and the whole document is always returned.
'myArray.$.myField' : 1 behave exactly like 'myArray.$' : 1
the positional operator selects the right document. But this document is quite big.  I would like to project only 1 field from it.
Exemple:
db.getCollection('match').find({"participantsData.id" : 0001}, { 'participantsData.$.id': 1,  })

here the response I have
{
    "_id" : "myid",
    "matchCreation" : 1463916465614,
    "participantsData" : [
        {
            "id" : 0001,
            "plenty" : "of",
            "other" : "fields",
            "and" : "subdocuments..."
        }
     ]
}

This is what I want
{
   "_id" : "myid",
    "matchCreation" : 1463916465614,
    "participantsData" : [
        {
            "id" : 0001
        }

    ]
}

Is it possible with mongo?

A: Yes it can be done in mongo
Please try the below query
db.getCollection('match').find(
    {"participantsData.id" : 0001},
    {"participantsData.id": 1, "matchCreation": 1 })

This will give you the below result
{
        "_id" : "myid",
        "matchCreation" : 1463916465614,
        "participantsData" : [
                {
                        "id" : 1
                }
        ]
}


text:
Q: Beginner at Python, math functions for a simple calculator program I'm making a basic calculator for a programming course and I've read over the PDF's but I can't figure out how to make a function and then use it to print the results of the addition of two numbers. Can someone help me out?
def addition(intFirstOperand, intSecondOperand):
    addition = intFirstOperand + intSecondOperand

print ('What mathematical operation would you like to perform? Enter a number:')
print ('1 - addition')
print ('2 - subtraction')
print ('3 - multiplication')
print ('4 - division')

intOperation = input()
intOperation = int(intOperation)

addition = '1'
subtraction = '2'
multiplication = '3'
division = '4'

if intOperation == 1 :
    print ('Please enter the first operand for addition:')
    intFirstOperand = input()
    print ('Please enter the second operand for addition:')
    intSecondOperand = input()
    print addition(intFirstOperand, intSecondOperand)

if intOperation == 2 :
    print ('Please enter the first operand for subtractiom:')
    intFirstOperand = input()
    print ('Please enter the second operand for subtraction:')
    intSecondOperand = input()

if intOperation == 3 :
    print ('Please enter the first operand for multiplication:')
    intFirstOperand = input()
    print ('Please enter the second operand for multiplication:')
    intSecondOperand = input()

if intOperation == 4 :
    print ('Please enter the first operand for division:')
    intFirstOperand = input()
    print ('Please enter the second operand for division:')
    intSecondOperand = input()

A: I would recommend choosing a different variable name within your function as it can be confusing to have a function and variable with the same name. You can choose to print from within the function, or you can return a value, and then print the returned value outside of the function.
def addition(first,second):
    result = int(first) + int(second)
    #print result
    return result

print(addition(5,3)) #prints 8 in python 3.x

Alternatively, you can skip assigning a value to 'result' and just return first+second instead.

A: def addition(intFirstOperand, intSecondOperand):
    addition = intFirstOperand + intSecondOperand
    return addition

You want to return the value that you calculated. Then your print statements should work.


text:
Q: how can I reload a View iOS swift, MFMailComposeViewController I'm trying to implement a Email functionality inside my app, I wrote this class following a tutorial:
import UIKit
import MessageUI

class EmailController: UIViewController, MFMailComposeViewControllerDelegate {

@IBOutlet weak var subject: UITextField?
@IBOutlet weak var body: UITextView?
var alert: UIAlertView = UIAlertView()
var subjectText:String?
var bodyText:String?
var toSomeone:AnyObject!
var mailController:MFMailComposeViewController = MFMailComposeViewController()

override func viewDidLoad() {
    super.viewDidLoad()
    //AlertView
    alert.title = "Error"
    alert.message = "Faltan datos"
    alert.addButtonWithTitle("Ok")
    //Recipients
    toSomeone = "xxxxxx@gmail.com"
    //asignar delegado al controlador de email
    mailController.mailComposeDelegate = self

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

@IBAction func sendEmail(sender: UIBarButtonItem) {

    //bool var becouse optionals can't be used like bools
    var condicion1:Bool? = subject?.text.isEmpty
    var condicion2:Bool? = body?.text.isEmpty

    //unwraped the variables
    if (!condicion1! && !condicion2!) {

        subjectText = self.subject!.text
        bodyText = self.body!.text

        //Completar objeto mailController

        mailController.setSubject(subjectText)
        mailController.setMessageBody(bodyText, isHTML: false)

        var recipients = [toSomeone]

        mailController.setToRecipients(recipients)

        self.presentViewController(mailController, animated: true, completion: nil)

    }else {

        self.alert.show()

    }

}

func  mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {

    switch result.value {

    case MFMailComposeResultCancelled.value:
        //se cancelo envio
        alert.title = "Envio cancelado"
        alert.message = "Se cancelo el envio"
        alert.addButtonWithTitle("Ok")
        alert.show()

    case MFMailComposeResultSaved.value:
        //se guardo draft
        alert.title = "Correo guardado"
        alert.message = "Se guardo el correo en la app de Mail"
        alert.addButtonWithTitle("Ok")
        alert.show()

    case MFMailComposeResultFailed.value:
        //fallo el envio
        alert.title = "Error"
        alert.message = "El correo no pudo ser enviado"
        alert.addButtonWithTitle("Ok")
        alert.show()

    case MFMailComposeResultSent.value:
        //el mail se pudo enviar y esta en la pila de envio
        alert.title = "Correo enviado"
        alert.message = "El correo se envio exitosamente"
        alert.addButtonWithTitle("Ok")
        alert.show()

    default:
        break

    }

                                                    //bloque de codigo a ejecutar al finalizar de mostrar la vista
    mailController.dismissViewControllerAnimated(true, nil)

     }

   }

I can send the email just fine but when I dismiss the mail view I see my initial view (thats ok) the problem is that if I try to invoke the email view again(I mean try to send another email) the program don't respond and I can't dismiss it anymore, I think that I need to reload the initial view???
Thanks for your help!

A: You can present a new MFMailComposeViewController each time you send an email, like this
mailController = MFMailComposeViewController()

Declare it like this.
var mailController:MFMailComposeViewController?


text:
Q: If data caching used like a session would it have better performance I am working on a maintenance of one asp.net application where I found pervious developers have implemented data caching as like a session, means they stored data in a cache for per session like this
Public Function GetDataCache(ByVal dataCacheKey As String) As Object
    dataCacheKey = dataCacheKey & Convert.ToString(LoginSessionDO.UserID)
    Return Cache(dataCacheKey)
End Function

In this application there are many screens where user can add multiple rows (data) in a grid temporary which actually store in cache for that particular current user only and finally press save button to save data in database.
My question is if caching is used like a session! will it give any performance improvement?
actually I can change it in my dev. environment to check performance but we cannot create load like prod in our environment and also without any surety I cannot change and deploy code in production.
Please suggest me

*

*Is caching is good  the way its implemented?.

*It's using like a session would it have better performance than session?

A: The cache will need to be cleared out, otherwise all items will remain until the app domain recycles. Session has a much shorter expiry and can be explicitly abandoned on log out, for example.
This might be a scaling issue if your site grows. However, the shorter expiry time of the session might cause you issues with saving if it is no longer there when expected. A staging table in the db might be a better approach.

An edit from several years after the initial answer.
In reality, it would be much preferable to store the added rows on the client side and then submit them all in one go.  Either of the server side options above run into issues if the app domain recycles in the middle of a session and both will cause you scaling issues on the server with enough users/data.


text:
Q: Can I create an angular component that doesn't render given a certain condition? I have created a debugging component which is very simple and looks like this.
debug.component.html
<ng-container *ngIf="debugging">
    <ng-content></ng-content>
</ng-container>

export class DebugComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    this.debugging =  environment.debugging;
  }

  debugging: boolean;

}

I use it like this
 <app-debug>{{data | json}}</app-debug>

I have an environment variable that I can turn on and off if I want to see the debugging data or not.
export const environment = {
...
  debugging: false,
...
}

However, I notice that when I render my page, even when I have debugging = false, in my rendered HTML, I still see lines like this
<app-debug _ngcontent-ydq-c8="" _nghost-ydq-c16=""><!--bindings={
  "ng-reflect-ng-if": "false"
}--></app-debug>

It's invisible but if possible, I don't really want my debugging code being deployed to prod.
Is it possible to create a component that doesn't render given a certain condition?

A: You could remove the debug component host "by hand" with standard DOM methods. Here is one way to do it with ElementRef and removeChild:
@Component({
  selector: "app-debug",
  template: `<ng-content></ng-content>`
})
export class DebugComponent implements OnInit {
  debugging: boolean;

  constructor(private elementRef: ElementRef) { }

  ngOnInit() {
    this.debugging =  environment.debugging;
    if (!this.debugging) {
      let element = this.elementRef.nativeElement as HTMLElement;
      element.parentElement.removeChild(element);
    }
  }
}

See this stackblitz for a demo.

A: how about a structural directive instead of a component...
@Directive({
  selector: "[appDebug]"
})
export class DebugDirective {
   constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {
     if (environment.debugging) {
       this.viewContainer.createEmbeddedView(this.templateRef);
     }
   }
}

which you should be able to just toss where ever it's needed...
<ng-container *appDebug>{{data | json}}</ng-container>

this is higher performance than a component in production as it will just never render and you will not need to remove it from the DOM. It will also work the same on any element, not just an ng-container
blitz demo: https://stackblitz.com/edit/angular-ivy-rzzgsy?file=src%2Fapp%2Fapp.component.ts
the only artifact from this method will be some html comment like:
<!--container-->

A: The child component isn't wrapped in the condition. To completely disable the rendering of a component, the condition should be applied to the it's selector.
<ng-container *ngIf="debugging">
  <app-debug>{{data | json}}</app-debug>
</ng-container>

or
<app-debug *ngIf="debugging">{{data | json}}</app-debug>


text:
Q: Resizing fonts for different screen width using @media – not working in Safari I have a logo that is plain text, and have set up 3 media query to respond to different screen-sizes. In firefox the media queries work correctly, but in safari the last @media (max-width: 680px), has no effect on the font size.
@media (max-width: 1000px) {
  header {
    padding: 0;
  }

.logo {
   z-index: 0;
   position: relative;
   padding: 0 20px;
   margin: 20px auto;
   height:40px;
   margin-top:40px;
}

.logo p {
   text-align: center;
   text-indent: -110px;
}

.logo p a {
   font-size:140px;
   font-family: "MaiolaBasic-BoldItalic", Georgia, serif;
   color: #000000;
}

@media (max-width: 680px) {
  header {
    padding: 0;
  }

.logo {
   z-index: 0;
   position: static;
   padding: 0 20px;
   margin: 20px auto;
   height:0px;
   margin-top:40px;
}

.logo p {
   text-align: left;
   text-indent: 0px;
}

.logo p a {
   font-size:80px;
   font-family: "MaiolaBasic-BoldItalic", Georgia, serif;
   color: #000000;
}

Thanks!

A: I think you just forgot to close some brackets!  I always do this with media queries because they color code strangely in my code editor.
Add a closing squiggly bracket before the 2nd @media and also at the end of your code.
Here's it done for you
    @media (max-width: 1000px) {
  header {
    padding: 0;
  }

.logo {
   z-index: 0;
   position: relative;
   padding: 0 20px;
   margin: 20px auto;
   height:40px;
   margin-top:40px;
}

.logo p {
   text-align: center;
   text-indent: -110px;
}

.logo p a {
   font-size:140px;
   font-family: "MaiolaBasic-BoldItalic", Georgia, serif;
   color: #000000;
}}  /*Added bracket*/

@media (max-width: 680px) {
  header {
    padding: 0;
  }

.logo {
   z-index: 0;
   position: static;
   padding: 0 20px;
   margin: 20px auto;
   height:0px;
   margin-top:40px;
}

.logo p {
   text-align: left;
   text-indent: 0px;
}

.logo p a {
   font-size:80px;
   font-family: "MaiolaBasic-BoldItalic", Georgia, serif;
   color: #000000;
}} /*Added Bracket*/


text:
Q: C# MongoDB BsonDocument not getting serialized to custom class using BsonSerializer I am having an issue with serializing BsonDocuments using BsonSerializer.
I am using var bsonDoc = collection.Find(...) to pull a single document from a MongoDB database.
I then try to serialize it using
var strongTypedDocument = BsonSerializer.Deserialize<MainSDocument>(bsonDoc);
Here is the BsonDocument
   {
      "MainSPayload" :
        {
           "GDeets" : { "Id" : 0, "GSerial" : "XX123XX123" }
        }
   }

Here are the C# classes
[JsonObject(MemberSerialization.OptIn)]
[BsonIgnoreExtraElements]
public class MainSDocument
{
    [JsonProperty(Required = Required.Always)]
    public MainState MainSPayload
    {
        get; set;
    }
}

[JsonObject(MemberSerialization.OptIn)]
public class MainState
{
    [JsonProperty(Required = Required.Always)]
    public GDetails GDeets
    {
        get; set;
    }
}

public class GDetails
{
    public int Id
    {
        get; set;
    }

    public string GSerial
    {
        get; set;
    }
}

The error I am getting is: FormatException: An error occurred while deserializing the GDetails property of class MainState : Element 'Id' does not match any field or property of class GDetails .'
Why is this happening? Why doesn't the element Id match the int element Id in the GDetails class?

A: Serialization for Id field has a special workflow that effectively converts this value into how the server side represents it: _id. To workaround it you can use:
        BsonClassMap.RegisterClassMap<GDetails>(c =>
        {
            c.AutoMap();
            c.UnmapField(u => u.Id); // remove default _id workflow
            c.MapField(u => u.Id); // add a simple Id field
        });

or simpler:
        BsonClassMap.RegisterClassMap<GDetails>(c =>
        {
            c.AutoMap();
            c.SetIdMember(null);
        });

UPDATE:
There is a bit more flexible way. You can configure a new convention and set for what types you will need using it:
        var customPack = new ConventionPack();
        customPack.Add(new NoIdMemberConvention());
        ConventionRegistry.Register("NoIdConvention", customPack, t => t == typeof(GDetails));

also instead the above, you can just add BsonNoId attribute to your class:
    [BsonNoId]
    public class GDetails
    {
        public int Id
        {
            get; set;
        }

        public string GSerial
        {
            get; set;
        }
    }


text:
Q: How can I differentiate between $ (jQuery) and $scope from AngularJS? In jQuery, we do DOM Manipulation like,
$(this).hide();

whereas in AngularJS , we have the scope of the controller using which we can do a lot.
$(scope).somevar=somevalue;

Can we compare these two different Javascript Objects?

A: $(scope) is not proper angular syntax AFAIK. The dollar sign $ in JS is not a special character. it can be part of a variable like a lot of other symbols.
There is no conflict natively between jQuery's $ and angular's $scope, $resource, $q etc. They're different variables, just like j, jscope, jresource, jq would be different variables.
As for comparing these values, you're in a severe case of apples to oranges. jQuery-wrapped DOM elements may be comparable to arbitrary values in your scope but you'd have to determine some meaningful way to perform that comparison.


text:
Q: Don't have the correct permission for /var/www/html I'm able to write changes in the home directory, but when it comes to the /var/www/html folder, it's not allowing me to make any changes or create new files or folders. I can view the folders and files as well.
I have tried to add my username to the group that it belongs to, but I get the message that I don't even have the correct permissions to change that inside the terminal. Please suggest what I should do to correct this. Thanks.
This is inside Whonix if that helps.

A: Let me show my current setting, that may help you to to give correct permission and group owner to files and directory.
This my current chown and chmod for /var/www/
$ ls -l /var/www/
drwxr-xr-x. 2 root root 4096 Jan  4 16:25 cgi-bin
drwxr-xr-x. 8 root root 4096 Mar  4 08:54 html

And for inside /html/
$ ls -l /var/www/html/
drwxr-xr-x.  3 rob rob 4096 Nov  4 11:41 adminer
drwxr-xr-x.  8 rob rob 4096 Oct  5  2015 DVWA-1.9
drwxr-xr-x. 11 rob rob 4096 Dec 10 14:24 eDokumen

I alway use this recursive command. PHP files are run under the user of the website instead of the Apache user and globally reset all files (user,group,file and directory):
$ sudo chown -R user:group *
$ sudo find . -type f -exec chmod 644 {} \;
$ sudo find . -type d -exec chmod 755 {} \;

* Note : Replace the user and group label with you own setting


text:
Q: Getting calculated fields with sequelize models I'm trying to add calculated fields to my model, that I want to reuse without rewriting custom queries all the time.
I've tried two different ways of adding calculated fields as Sequelize.literal's that allow me to get the desired result from 2 out of three use cases.
The model is a classic ordering system.

*

*There are articles, articles has a stock count

*There are orders

*orders have order rows

*order rows have an fk to an article, and an ordered amount.

I want a field on the article model that is similar to:
article.stockQuantity - SUM(orderrows.orderedQuantity) where order.state <> 'fullfilled'
So when I look at an article I can see how many of those articles are available in stock.
With the sequelize.literal solution I can get close. The result is calculated using a subquery, which is fine for me. An example of a virtual field that does the trick is below.
const article = sequelize.define('article', {
    ...
  stockQuantity: {
type: Sequelize.DECIMAL
  },
availableQuantity: {
    type: Sequelize.VIRTUAL(Sequelize.DECIMAL,
      [Sequelize.literal(`(COALESCE((select article."stockQuantity" - sum("orderRows"."orderedQuantity") from "orderRows" left join orders on orders.id = "orderRows"."orderId" where "orderRows"."articleId" = article.id and orders."state" <> 'fullfilled'), 0)) as "availableQuantity"`), "availableQuantity"]),

    },
...
});

This works for listing articles with findAll and for geting the full article.
However when I try to get an order, in which I have an article listing, the subqueries break.
Because they cannot follow the renaming for the nested children in the subquery.
The resulting sql describes the problem clearly
--- clipped from the select part of the generated query
    "orderRows->article"."name" AS "orderRows.article.name",
    (
        COALESCE(
            (
                select
                    article."stockQuantity" - sum("orderRows"."orderedQuantity")
                from
                    "orderRows"
                    left join orders on orders.id = "orderRows"."orderId"
                where
                    "orderRows"."articleId" = article.id
                    and orders."state" <> 'fullfilled'
            ),
            0
        )
    ) as "availableQuantity",

---

Of course this gives me an error, as the article table is no longer called article when included from a order.findAll:
{
  "name": "SequelizeDatabaseError",
  "message": "missing FROM-clause entry for table \"article\"",
}

Without having to do excess round-trips to get the calculated fields as a separate query.
Is there a way for me to get get the desired values in the sequelize model system so I have the models as contained business units?


text:
Q: How to debug python source code using GDB in Cygwin for Windows 10 (x64) I usually code in python and I need a debugger. I chose GDB as it also helps in debugging my c++ applications. i have read the python documentation on GDB debugger but it isn't clear to me still. i had cygwin installed and with it i have also installed GDB on windows 10 (x64) . Do i still need to install somethong more?
And after installing it what should be my next steps to run the debugger with breakpoints and all other regular features (without creating an extra file, as I read in some answers)


text:
Q: Undeclared identifier in function parameter I'm getting an undeclared identifier error when compiling my little game that I'm working on for education purposes and I can't for the world understand why and where it is coming from. Any help is greatly appreciated.
Why does the following line from my "laser header" file generate undeclared identifier error C2065?
bool hit(std::vector<Alien*> aliens);

Here is the full header file:
#ifndef LASER_HPP_
#define LASER_HPP_

#include "Ship.h"
#include "Alien.h"
#include "Vector.h"

class Laser : public Sprite {
    private :
        bool armed;
        int reloadTime, width, height, radius;

        std::vector<Vector> bullets;

        bool circleCollision(int x, int y, Ship* ship);
        void reload();
    public:
        enum Type {
            RED,
            BLUE
        };

        Laser(Type type);

        bool hit(std::vector<Alien*> aliens);
        bool hit(Ship* ship);
        void shoot(int x, int y, int dy);
        void update();
        void draw();
};

#endif LASER_HPP_

And also the header file for Alien:
#ifndef ALIEN_HPP_
#define ALIEN_HPP_

#include "Laser.h"
#include "Ship.h"

class Alien : public Ship {
    private:
        int nextX, laserSpeed, shotDelay;
        bool attacking;
        time_t lastShot;

        bool targetReached();
        bool timeToShoot();
        bool enteringStage();

        void shoot();
        void move();
        void init();
    public:
        Alien();
        Alien(const char* filename);
        Laser* laser;

        void setNextTarget();
        void update();
        void attack();
        void die();
};

#endif ALIEN_HPP_

I'm using VisualStudio 2012 :S
Error:
 error C2065: 'Alien' : undeclared identifier

A: It's a classic example of circular inclusion dependency. The Laser.hpp file needs the Alien.hpp file which needs the Laser.hpp file and so on.
In this case, Laser.hpp doesn't really need the Alien.hpp file at all, it just need to know that there is a class named Alien. So to solve the problem you remove the inclusion of Alien.hpp in Laser.hpp, and add a declaration of the Alien class:
class Alien;

A: This is because of recursive header file including. Consider, laser.h includes alien.h which, once again, includes laser.h. This thing, the compiler could not do, even w/ header guards at place. What you need here is a forward declaration, instead of #include "Alien.h" add a declaration class Alien;, which is sufficient in your case because you use only a pointer to Alien class.


text:
Q: Make Dockerfile VOLUME behave like docker-compose volumes I am trying to setup a Dockerfile to mount my host directory to my specified docker container directory (so code changes will be reflected immediately). When I run docker run -p 3000:3000 -d -v ~/Projects/test:/app test the files are mounted and everything works fine. However, once I close the container, the file changes don't stay within the container like the changes would if I were running volumes from a docker-compose file.
Here is my Dockerfile:
FROM node:onbuild
EXPOSE 3000
RUN mkdir /app
VOLUME ./:/app/
WORKDIR /app/
RUN npm install -g nodemon
CMD nodemon server.js

Here is a working docker-compose.yml:
test:
  build: ./
  volumes:
    - ./:/app/
  working_dir: /app/
  command: npm start
  ports:
    - "3000:3000"

A: The VOLUME command in Dockerfile has a slightly different meaning:

*

*you cannot define mounted volumes within a Dockerfile

*it's only used for specifying inter-container volumes

So in your Dockerfile, VOLUME ./:/app/ must be changed to VOLUME /app/. Your docker-compose definition will tell docker to mount local dir . to /app in the container.

The -v option and the volumes tag in docker-compose work the same way. The host directory is mounted to a container directory. Any file which was present in the image in the container directory will be replaced by the files from the host directory.


text:
Q: Why is it bad to develop on a testserver? At our current project we have 1. a production server, 2. a test server and 3. several developers using xampp under Windows. Prod- and Testserver are run by UNIX.
One of the other developers is repeatedly complaining about us using xampp under windows. He's saying that we should create a v-server on the test-environment for developing purposes (maybe one v-server for each developer, I don't quite know). To me, this feels just awfully wrong. But I can't really explain why, except obvious reasons like you have to connect to the remote dev-server, etc.

A: Here's how I do it.  There are 4 stages.
1) Local server.  Here, you can work on your own changes, feature branches, etc.  Do your work, make sure it works on your machine, and then request it get pulled into the development branch.
2) Dev Server.  This is a carbon copy of whatever's in the development branch, and is meant as a means to see how your code is a) working in an actual environment and b) playing with other people's code.
3) "Test Server", which is where QA should be done.  The settings on this server should be as close to those on Production as possible. and allow for all the bug fixes, features, and improvements you've been working on to be looked over and either resolved or reported back on.
4) Production.  By the time the code makes it here, it should be stable and ready to go.  This should be the "final product" for the client (even if you're still fixing bugs / doing maintenance)

A: You're less likely to get a surprise when you move between environments (dev to test to live) if the environments are all configured as similarly as possible.
Running PHP under Windows via XAMPP will lead to subtle differences in behaviour compared to running it on a Unix/Linux based server. Having to deal with these adds unnecessary overhead to your development, and increases the risk of bugs not being spotted soon enough.
Running virtual servers in your office allows you to continue using Windows desktops, but run your code on an accurate simulation of your production servers even as you're writing it. It can also simplify the sysadmin's job because they don't have to manage lots of separate PCs when you need to upgrade PHP, set up backups, etc.
As for the inconvenience, this isn't that big a deal if you use "samba" - the files on the development server are accessible as a Windows fileshare, so you carry on editing them just like you would if they were on your own machine. Pretty much the only time you need to connect to the server directly (over SSH) is when you change the Apache configuration and need to restart/reload the daemon for the changes to take effect.

A: One benefit of managing a dedicated development environment is that you can implement an automated build process that redeploys the dev server on a regular schedule. This increases the likelihood of discovering incompatible changes earlier in the development cycle.


text:
Q: access dlopen flags I'm inside a shared object (code) loaded with dlopen. I want to know the flags given to the loading call. I do not have access to the loader (code) - e.g. it may be a script interpreter - but I have to create subsequent dlopen calls with the same flags.
How can I do this?

A: You could use the following library in place of a debugger:
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>

typedef void *(*orig_dlopen_type)(const char *file, int mode);

void *dlopen(const char *file, int mode)
{
    fprintf(stderr, "dlopen called (mode: %d) on %s\n", mode, file);
    orig_dlopen_type orig_dlopen;
    orig_dlopen = (orig_dlopen_type)dlsym(RTLD_NEXT, "dlopen");
    return orig_dlopen(file, mode);
}

Compile with gcc -shared -fPIC dlopen_trace.c -o dlopen_trace.so -ldl
Then execute your program as normal with LD_PRELOAD=dlopen_trace.so.  You should get a debug line printed every time dlopen is called.
If you want you can also modify the flags en-route...

A: I think this is NOT possible without the aid of debuggers.
From the latest glibc code , here is the source code of dlopen
void *
dlopen (const char *file, int mode)
{
  return __dlopen (file, mode, RETURN_ADDRESS (0));
}

And __dlopen is in turn defined as
void *
__dlopen (const char *file, int mode DL_CALLER_DECL)
{
# ifdef SHARED
  if (__builtin_expect (_dlfcn_hook != NULL, 0))
    return _dlfcn_hook->dlopen (file, mode, DL_CALLER);
# endif

  struct dlopen_args args;
  args.file = file;
  args.mode = mode;
  args.caller = DL_CALLER;

# ifdef SHARED
  return _dlerror_run (dlopen_doit, &args) ? NULL : args.new;
# else
  if (_dlerror_run (dlopen_doit, &args))
    return NULL;

  __libc_register_dl_open_hook ((struct link_map *) args.new);
  __libc_register_dlfcn_hook ((struct link_map *) args.new);

  return args.new;
# endif
}

The flags you are looking for, RTLD_LAZY, RTLD_NOW, RTLD_GLOBAL and RTLD_LOCAL are ORed and stored in mode variable. As you can see there is no route through which it is passed back or anything like that.
EDIT: It seems there indeed is a way of achieving what you want as shown by the other answer. If you can un-accept my answer, I can delete it so as to help future visitors