Q: Simple style swicher with less I want to create a simple style swicher using less.
I created a set of colored squares, and I would like by clicking on one of those, you can select a file. Css or even better, you can set the variable in the less file and generate a new style
The HTML-CSS code :
jsfiddle.net/AASH2/1/
Thanks in advance to those who will help me

A: You can change the href attribute of your link tag when click on the button
So using your example
$('li').on('click', function() {
    $('link').attr('href','new_file_path_here');
});

This is a basic example, you can give your link tag an id and target it that way
Also see How do I switch my CSS stylesheet using jQuery?


Q: right click event on URLs in richtext box I have a link in a richtextbox in C#. When I right on a url link, I want to show a menu. if it is not a url, then I do not want to show anything. Right now I am tapping into the mouse down event and selecting the line based on the mouse pointer position and if the selected line is a valid url, I show the menu. it works great, but when I have some text next to the url, still the line is detected as a valid url and the menu appears. Also I am unable to tap into the mouse changed event as well. Any ideas on how I could accomplish what I am trying to do?
Thanks,

A: Not sure if this is what you are looking for, but I believe that you'll find better than this
You may try this when the MouseDown is called
private void richTextBox1_MouseDown(object sender, MouseEventArgs e)
{
    // Continue if the Right mouse button was clicked
    if (e.Button == MouseButtons.Right)
    {
        // Check if the selected item starts with http://
        if (richTextBox1.SelectedText.IndexOf("http://") > -1)
        {
            // Avoid popping the menu if the value contains spaces
            if (richTextBox1.SelectedText.Contains(' '))
            {
               // Show the menu
               contextMenuStrip1.Show(Cursor.Position.X, Cursor.Position.Y);
            }
        }
    }
}

Or this when a Link is Clicked, but this won't apply for Mouse Right-Click
private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
{
     contextMenuStrip1.Show(Cursor.Position.X, Cursor.Position.Y);
}

Thanks,
I hope this helps :)


Q: Correct use of partial derivatives? (Example: polynomial regression) [update] It seems I had my question's original title misfocused a bit; concerning the use of partial derivatives I found some explanation/confirmation in wikipedia's partial derivative There it is stated -and explained with a 3-d-picture of a surface-, that indeed the three partial derivatives suffice to find the/a common extremum. In the occurrence of my problem I seem to have had a misleading intuition, based on the observation of non-independence of the x and x-square-data and felt thus cautious (too much, apparently).
Full exposition of my proceeding/reasoning and source of question is here
I adapted the subject of my question; if this seems inappropriate please feel free to roll it back. The original question follws below [end update]

I'm just trying to reinvent the wheel - I want to understand (and implement for an example) the computation of the polynomial regression.
For the simplest nonlinear approach let's use the estimated model

$$\hat y_k=a+b x_k + c x_k^2 \qquad \text{(for k=1 to  n)}$$
with the minimizing criterion
$$\sum (y_k - \hat y_k)^2 =\sum (y_k - (a+bx_k+cx_k^2))^2= \text{Min}$$
I have expressed all the occurrng and needed variances and covariances in a matrix, cofactored with $a,a^2,b,b^2,c \text{ and }c^2$ . To find the minimum I must use the derivatives; however I'm not much familiar with partial derivatives.
So my question is: do I get the global minimum if I solve my matrix-expression setting the partial derivatives resp to $a,b,c$ separately (and find the then possible common solution)? Or do I need to involve some "joint derivative" or "common derivative" where, for instance something like $\partial ab$, thus a and b, are simultanously used in one derivative?


Q: C# Regular Expressions for CSS Coloring I'm currently using the FastColoredTextBox to create a simple HTML/CSS editor. While FastColoredTextBox comes with some predefined formatting rules for HTML, etc. There is not one for CSS. It does support custom ones though.
This is where my problem is. I'm trying to write three Regular expressions to select the selector e.g. "div", the attribute e.g. "color" and the value e.g. "#fff" but I can't get them to work quite right.
Does anybody have any example of CSS regular expressions? Or does anybody know what they should be?
Thanks a lot


Q: How to create a standalone command line app with the Symfony2 ClassLoader and Console I am trying to write a command line app using the Symfony2 Console and ClassLoader Components.
This is a screenshot of my code hierarchy and the script being called

Here is the CLI script:
#!/usr/bin/env php
<?php
    require_once(dirname(__FILE__) . '/code/ClassLoader/UniversalClassLoader.php');
    use Symfony\Component\ClassLoader\UniversalClassLoader;
    use Symfony\Component\Console\Application;
    use Symfony\Component\Console\Input\ArgvInput;

    use BlueHeadStudios\Command\Deployer;

$loader = new UniversalClassLoader();
$loader->register();

$input = new ArgvInput();
$debug = $input->hasParameterOption(array('--debug', ''));

$console    = new Application();
$console->add(new Deployer());
$console->run();

I get this when running the script
dev@server:~/sites/pd/deployer$ php deployer.php
PHP Fatal error:  Class 'Symfony\Component\Console\Input\ArgvInput' not found in /home/dev/sites/pd/deployer/deployer.php on line 13

I know it must be a simple registerNamespace call or something similar, but I've tried multiple registrations but cannot get it to work.
Any help is greatly appreciated.

A: I would recommend you to use composer, which will generate autoload.php for you to include at the top of the file:
#!/usr/bin/env php
<?php

require_once './vendor/autoload.php';

use Symfony\Component\ClassLoader\UniversalClassLoader;

$loader = new UniversalClassLoader();
$loader->registerNamespace('BlueHeadStudios', __DIR__.'/src/');
$loader->register();

// write your code below

A: You should run the application with app/console check the example here


Q: CUDA Compute Capability 2.0. Global memory access pattern From CUDA Compute Capability 2.0 (Fermi) global memory access works through 768 KB L2 cache. It looks, developer don't care anymore about global memory banks. But global memory is still very slow, so the right access pattern is important. Now the point is to use/reuse L2 as much as possible. And my question is, how? I would be thankful for some detailed info, how L2 works and how should I organize and access global memory if I need, for example, 100-200 elements array per thread.

A: L2 cache helps in some ways, but it does not obviate the need for coalesced access of global memory.  In a nutshell, coalesced access means that for a given read (or write) instruction,  individual threads in a warp are reading (or writing) adjacent, contiguous locations in global memory, preferably that are aligned as a group on a 128-byte boundary.  This will result in the most effective utilization of the available memory bandwidth.
In practice this is often not difficult to accomplish.  For example:
int idx=threadIdx.x + (blockDim.x * blockIdx.x);
int mylocal = global_array[idx];

will give coalesced (read) access across all the threads in a warp, assuming global_array is allocated in an ordinary fashion using cudaMalloc in global memory.  This type of access makes 100% usage of the available memory bandwidth.
A key takeaway is that memory transactions ordinarily occur in 128-byte blocks, which happens to be the size of a cache line.  If you request even one of the bytes in a block, the entire block will be read (and stored in L2, normally).  If you later read other data from that block, it will normally be serviced from L2, unless it has been evicted by other memory activity.  This means that the following sequence:
int mylocal1 = global_array[0];
int mylocal2 = global_array[1];
int mylocal3 = global_array[31];

would all typically be serviced from a single 128-byte block.  The first read for mylocal1 will trigger the 128 byte read.  The second read for mylocal2 would normally be serviced from the cached value (in L2 or L1) not by triggering another read from memory.  However, if the algorithm can be suitably modified, it's better to read all your data contiguously from multiple threads, as in the first example.  This may be just a matter of clever organization of data, for example using Structures of Arrays rather than Arrays of structures.
In many respects, this is similar to CPU cache behavior.  The concept of a cache line is similar, along with the behavior of servicing requests from the cache.
Fermi L1 and L2 can support write-back and write-through.  L1 is available on a per-SM basis, and is configurably split with shared memory to be either 16KB L1 (and 48KB SM) or 48KB L1 (and 16KB SM).  L2 is unified across the device and is 768KB.
Some advice I would offer is to not assume that the L2 cache just fixes sloppy memory accesses.  The GPU caches are much smaller than equivalent caches on CPUs, so it's easier to get into trouble there.  A general piece of advice is simply to code as if the caches were not there.  Rather than CPU oriented strategies like cache-blocking, it's usually better to focus your coding effort on generating coalesced accesses and then possibly make use of shared memory in some specific cases.  Then for the inevitable cases where we can't make perfect memory accesses in all situations, we let the caches provide their benefit.
You can get more in-depth guidance by looking at some of the available NVIDIA webinars.  For example, the Global Memory Usage & Strategy webinar (and slides  ) or the CUDA Shared Memory  & Cache webinar would be instructive for this topic.  You may also want to read the Device Memory Access section of the CUDA C Programming Guide.


Q: Play YouTube videos from an array of video IDs : React import React, { Component } from 'react';
import YouTube from 'react-youtube';
let videoIdList=["XM-HJT8_esM","AOMpxsiUg2Q"];
var videoId = videoIdList[0];
let i=0;
class YoutubePlayer extends Component {
    render() {
        const opts = {
            height: '390',
            width: '640',
            playerVars: { // https://developers.google.com/youtube/player_parameters
                autoplay: 1
            }
        };

        return (
            <YouTube
                videoId={videoId}
                opts={opts}
                onReady={this._onReady}
                onEnd={this._onEnd}
            />
        );
    }

    _onReady(event) {
        // access to player in all event handlers via event.targe
        event.target.playVideo(videoIdList[i])
    }

    _onEnd(event) {
        videoId = videoIdList[i]
        event.target.playVideo(videoIdList[++i]);
        console.log(videoId);
    }
}
export default YoutubePlayer;

So I am trying to play youtube videos from a array of video ids. When a video ends I want to change the video to next video in the list. How can I do this?

A: You will have to maintain inner state with currently played video, and as soon as video is over, you will have to set next video in state which will re render the component again and start with next video. Below code should work.
import React from "react";
import ReactDOM from "react-dom";
import YouTube from '@u-wave/react-youtube';
import "./styles.css";
let videoIdList=["AOMpxsiUg2Q","XM-HJT8_esM","AOMpxsiUg2Q"];

class App extends React.Component {

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

componentDidMount() {
  this.setState({videoId: videoIdList[this.i]});
}

render() {
    const opts = {
        height: '390',
        width: '640',
        playerVars: { // https://developers.google.com/youtube/player_parameters
            autoplay: 1
        }
    };

    return (
        <YouTube
            video={this.state.videoId}
            opts={opts}
            onReady={this._onReady}
            onEnd={this._onEnd}
        />
    );
}

_onEnd = () => {
    this.setState({videoId: videoIdList[++this.i]});
 }

}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

You can check working code here -
https://codesandbox.io/s/7yk0vrzr36


Q: Invoking .Net COM assembly from Powerbuilder application (without registration) We have a Powerbuilder 10 application that is using .Net COM assemblies. We are trying to embed the manifest in the PB application (to invoke COM assemblies without registration). The merged manifest file has added sections for dependecies on the .Net COM assemblies. We have tries various tools to inject the new manifest with different results
- using GenMan32 to inject truncates the application from 6MB to 45KB.
- using ResourceTuner, the file size looks okay, but trying to launch application gives "Fatal Disk Error".
Any suggestions on invoked .Net ComEnabled assembly from PB without registration?

A: Have you tried it with an external manifest and ensured that works?  If an external manifest doesn't work, then the manifest information isn't correct.
Once you have a valid external manifest, you might try the Manifest Tool (MT.EXE) from the .Net SDK.  It works well with true EXE files.  As Terry noted though, the PB generated executable contains additional information that tools that manipulate the EXE need to respect or they will break it.
http://blogs.msdn.com/patricka/archive/2009/12/09/answers-to-several-application-manifest-mysteries-and-questions.aspx

A: This is more a redirection than an answer. One thing you need to be aware of is that PowerBuilder produces executables that do not follow standards for Windows executable files. Essentially they are a bootstrap routine to load the PowerBuilder virtual machine, plus a collection of class definitions (objects). The cases you've brought up are not the first I've heard of where utilities meant to modify executables don't work on PowerBuilder executables.
As for a positive contribution on what other directions to follow, I don't really know enough to give qualified advice. If it were me, I'd try to register the COM object if ConnectToNewObject() fails, but I've got no idea if that possible or if that route is a dead end.
Good luck,
Terry.


Q: Invalid use of group function in MySQL 4 (not in 5) Any idea why query
SELECT
  m.*
FROM
  products_description pd,
  products p
  left join manufacturers m on p.manufacturers_id = m.manufacturers_id,
  products_to_categories p2c
WHERE
  p.products_carrot = '0' and
  p.products_status = '1' and
  p.products_id = p2c.products_id and
  pd.products_id = p2c.products_id and
  pd.language_id = '4' and
  p2c.categories_id = '42'
GROUP BY manufacturers_id
ORDER BY COUNT(*)

might give following error:

#1111 - Invalid use of group function

at MySQL 4.0.24 and not on MySQL 5.0.51 ?

A: Self response. Mentioning column that I want to order by in SELECT clause and aliasing it did the trick:
SELECT
  m.*, COUNT(*) as cnt
FROM
  products_description pd,
  products p
  left outer join manufacturers m on p.manufacturers_id = m.manufacturers_id,
  products_to_categories p2c
WHERE
  p.products_carrot = '0' and
  p.products_status = '1' and
  p.products_id = p2c.products_id and
  pd.products_id = p2c.products_id and
  pd.language_id = '4' and
  p2c.categories_id = '42'
GROUP BY p.manufacturers_id
ORDER BY cnt


Q: A better way to say "allows one to" In german, we frequently use the phrases such as "...dies erlaubt einem dies/das zu tun ...". In English, I feel that "this allows one to do" sounds clumsy. Are there better, more common constructs to express this?
Examples:
"A lateral displacement error allows one to estimate the capability of path following."
"This tool allows one to calculate the performance of sample applications."

A: I think "enable" is much better in scientific contexts (which seems to be yours). "Allow" might be more associated with authority, which is the science context does not seem to be right. In effect, the "enabling" feature you are referring usually comes from design, data availability, or theoretical properties of the method under use, and not because of authority related issues.
"This tool enable us to calculate the performance of sample applications."

A:
The lateral displacement error provides an estimate of ....

(Your path following phrasing is problematic.)

This tool is used to calculate sample application performance.

(It's generally not a good idea to translate word for word.  Instead, focus on the idea you want to express, and then allow yourself to find a natural way for the idea to come out in the target language.)


Q: Using ref to find a nested element I'm using the gridjs-react library to create a table as follows:
<Grid
  columns={['Name', 'Email']}
  data={[
    ['John', 'john@example.com'],
    ['Mike', 'mike@gmail.com']
  ]}
  ref={tableRef}
  search={true}
  pagination={{
    enabled: true,
    limit: 1,
  }}
/>

However, I want to ultimately add an item to the dom to get this:

I thought about using ref but I couldn't get access to the following div since it is only rendered after the component Grid is mounted: (As far as I know)

A: You can access the grid reference in useEffect block when all it's content is rendered:
useEffect(()=> {
    const grid = ref.current.wrapper.current; //--> grid reference
    const header = grid.querySelector(".gridjs-head"); //--> grid header
    const itemContainer = document.createElement("div"); //--> new item container
    header.appendChild(itemContainer);
    ReactDOM.render(<Input />, itemContainer); //--> render new item inside header
  }, []);

You will need to use css to get the desired position inside the element.
Working example: https://stackblitz.com/edit/react-r5gsvw

A: Or just use a CSS solution for that component you want.
e.g.
<div style={{ position: 'relative'}}>
    <Grid
    ....
    />

    <MySearchComponent style={{ position: 'absolute', top: 0, right: 0 }} />
</div>


Q: $stmt->fetch() is not fetching the data I don't understand why my function is not getting the results and just getting null value. I'm using PhpStorm; all my connections are fine (Apache, MySQL, PhpMyAdmin) I've check them, also the other rest services are working.
This is my dbhandler.php file:
public function getRating($rating_id, $user_id) {
    $stmt = $this->conn->prepare("SELECT  ur.restaurant_id, ur.service_rating, ur.food_rating, ur.music_rating FROM user_ratings ur , user u WHERE u.user_id = ? AND u.user_id = ur.user_id  AND ur.rating_id = ?");
    $stmt->bind_param("ii", $rating_id, $user_id);

    if ($stmt->execute()) {

        $stmt->bind_result( $restaurant_id, $service_rating, $food_rating, $music_rating);
        // TODO
        //$rating_id = $stmt->get_result()->fetch_assoc();
        $stmt->fetch();
        $res = array();
        $res["user_id"] = $user_id;
        $res["rating_id"] = $rating_id;
        $res["restaurant_id"] = $restaurant_id;
        $res["service_rating"] = $service_rating;
        $res["food_rating"] = $food_rating;
        $res["music_rating"] = $music_rating;
        $stmt->close();

        return $res;
    } else {
        return NULL;
    }
}

and this is my index.php file
$app->get('/userRatings/:rating_id', 'authenticate', function($rating_id) {
        global $user_id;
        $response = array();
        $db = new DbHandler();

        // fetch rating
        $result = $db->getRating($rating_id, $user_id);

        if ($result != NULL) {
            $response["user_id"] = $result["user_id"];
            $response["rating_id"] = $result["rating_id"];
            $response["restaurant_id"] = $result["restaurant_id"];
            $response["service_rating"] = $result["service_rating"];
            $response["food_rating"] = $result["food_rating"];
            $response["music_rating"] = $result["music_rating"];
            echoRespnse(200, $response);
        } else {
            $response["error"] = true;
            $response["message"] = "The requested resource doesn't exists";
            echoRespnse(404, $response);
        }
    });

The response of the request is:
{"user_id":19,
"rating_id":"171",
"restaurant_id":null,
"service_rating":null,
"food_rating":null,
"music_rating":null}

A: There is a problem in param values. Change param values as follows.
$stmt = $this->conn->prepare("SELECT  ur.restaurant_id, ur.service_rating, ur.food_rating, ur.music_rating FROM user_ratings ur , user u WHERE u.user_id = ? AND u.user_id = ur.user_id  AND ur.rating_id = ?");

$stmt->bind_param("ii", $user_id,$rating_id);

According to your sql first param should be $user_id. Not the $rating_id.
According to your parameter settings there is no record to fetch.


Q: Swift: press button in external app via accessibility In my function, I run the following code, when a specific event shows up and Safari is in foreground:
if win.safariIsForeground() {
    let el = AXUIElementCreateApplication(win.getSafariPid())
    var ptr: CFArray?

    _ = AXUIElementCopyAttributeNames(el, &ptr)
}

The pointer returns an array that looks like this:

["AXFunctionRowTopLevelElements", "AXFrame", "AXChildren",
"AXFocusedUIElement", "AXFrontmost", "AXRole", "AXExtrasMenuBar",
"AXMainWindow", "AXFocusedWindow", "AXTitle",
"AXChildrenInNavigationOrder", "AXEnhancedUserInterface",
"AXRoleDescription", "AXHidden", "AXMenuBar", "AXWindows", "AXSize",
"AXPosition"]

I'd like to make Safari go one site back in the history. I think I will need AXUIElementCopyAttributeValue and AXUIElementPerformAction to do that but how do I find out the button's attribute and how do I call check AXUIElementCopyAttributeValue for that?

A: The easiest way to do that is by accessing the menu item. Using AXUIElementCopyAttributeValue works best with the provided constants:
// get menu bar
    var menuBarPtr: CFTypeRef?
    _ = AXUIElementCopyAttributeValue(safariElement, kAXMenuBarRole as CFString, &menuBarPtr)

    guard let menuBarElement = menuBarPtr as! AXUIElement? else {
        fatalError()
    }

Accessibility Inspector shows me, what items are child of the menu bar:

so lets get the children using kAXChildrenAttribute:
// get menu bar items
    var menuBarItemsPtr: CFTypeRef?
    _ = AXUIElementCopyAttributeValue(menuBarElement, kAXChildrenAttribute as CFString, &menuBarItemsPtr)

    guard let menuBarItemsElement = menuBarItemsPtr as AnyObject as! [AXUIElement]? else {
        fatalError()
    }

And so on all the way down to the menu item. Items also have an unique identifier that can look like _NS:1008. I'm not sure how to access them directly but by using AXUIElementPerformAction I can simply simulate pressing the menu item (action will be kAXPressAction).
I can use kAXRoleAttribute to identify the type of the item and where it occurs in the Accessibility hierarchy (see "Role:")

As I'm still a beginner at Swift, that was a quite challenging task as this is also not documented very well. Thanks a lot to Dexter who also helped me to understand this topic: kAXErrorAttributeUnsupported when querying Books.app

A: In your case you don't need necessarily need to use AXUI accessibility API. It's arguably simpler to send key strokes. You can go back in Safari history to previous page with CMD[. As an added bonus Safari does not need to be in foreground anymore.
let pid: pid_t = win.getSafariPid();
let leftBracket: UInt16 = 0x21
let src = CGEventSource(stateID: CGEventSourceStateID.hidSystemState)
let keyDownEvent = CGEvent(keyboardEventSource: src, virtualKey: leftBracket, keyDown: true)
keyDownEvent?.flags = CGEventFlags.maskCommand
let keyUpEvent = CGEvent(keyboardEventSource: src, virtualKey: leftBracket, keyDown: false)
keyDownEvent?.postToPid(pid)
keyUpEvent?.postToPid(pid)

Your app running on Mojave and newer MacOS versions will need the System Preferences -> Security & Privacy -> Accessibility permisions granted to be eligible for sending keystrokes to other apps.
The keyboard codes can be looked up:
here & here visually


Q: What determines if a particular DAC is "good" for audio? I want to generate low-end audio (sinewave, sampling rate 8kHz). How to determine if a particular DAC is okay for such application? Is it only the settling time (of course apart from resolution, interface, voltage etc.)?
For example the AD5601 has a maximum settling time of 10µs. At a rate of 8kHz a sample takes 125µs, so I would guess that this particular DAC could handle the sample rate. Is that correct?

A: The AD5601 allows data bits being sent at 30 MHz, each packet takes 16 bits.
\$\frac{30 MHz}{16}=1.875MHz\$.
That means that you can theoretically make waveforms up to the Nyquist frequency which is \$\frac{1.875 MHz}{2} = 937.5 kHz\$.
\$937.5 Khz > 8kHz\$
The slew rate is 5 V/µs, that means that if you got a signal bouncing between 0 and 5 volt, a sine wave of 1Hz of amplitude 2.5 V has a maximum dv/dt at sin(0) => dv/dt = 1*2.5V => 2.5V, so a 2Hz sine wave got a dv/dt of 5V at t = 0.
5V/µs => X/s = 5*10^6/s, so 2Hz*10^6 => the slew rate supports a whopping 2 Mhz sine wave.

So yes, you are correct. That DAC is good enough for making sine waves sampled at 8kHz. What you said, 125 µs and 10 µs, together with the data speed & slew rate => why I said you were correct.
But let's reverse the formula, say you want to output what you sampled.
\$8 kHz × 2 = 16 kHz\$
\$16 kHz × 16 = 256 kHz\$
This means that you need to send one bit every \$\frac{1}{256 kHz} = 3.9 µs\$.


Q: How to convert decimal to binary value of rows in multindex dataframe (python)? Could you let me know how to onvert decimal to binary value of rows in multindex dataframe?
below is dataframe I used
from pandas import Series, DataFrame

raw_data = {'Function': ['env', 'env', 'env', 'func1', 'func1', 'func1'],
            'Type': ['In', 'In', 'In', 'In','In', 'out'],
            'Name': ['Volt', 'Temp', 'BD#', 'Name1','Name2', 'Name3'],
            'Val1': ['Max', 'High', '1', '3', '5', '6'],
            'Val2': ['Typ', 'Mid', '2', '4', '7', '6'],
            'Val3': ['Min', 'Low', '3', '3', '6', '3'],
            'Val4': ['Max', 'High', '4', '3', '9', '4'],
            'Val5': ['Max', 'Low', '5', '3', '4', '5'] }
df = DataFrame(raw_data)
df= df.set_index(["Function", "Type","Name"])
print (df)

below is printed dataframe
                            Val1    Val2    Val3    Val4    Val5
 Function   Type    Name
 env        In      Volt    Max     Typ     Min     Max     Max
                    Temp    High    Mid     Low     High    Low
                    BD#     1       2       3       4       5
 func1      In      Name1   3       4       3       3       3
                    Name2   5       7       6       9       4
            out     Name3   6       6       3       4       5

I want to convert decimal to binary values of rows(func1 - In - Name1, Name2) in multi-index dataframe.
below is expected df I want.
                            Val1    Val2    Val3    Val4    Val5
 Function   Type    Name
 env        In      Volt    Max     Typ     Min     Max     Max
                    Temp    High    Mid     Low     High    Low
                    BD#     1       2       3       4       5
 func1      In      Name1   11      100     11      11      11
                    Name2   101     111     110     1001    100
            out     Name3   6       6       3       4       5

I have tried to get right results but I failed. TT
Plz let me know how to resolve it simply.

A: Use MultiIndex.get_level_values for create conditions, chain together and set new values by f-strings:
m1 = df.index.get_level_values(0) == 'func1'
m2 = df.index.get_level_values(1) == 'In'

df[m1 & m2] = df[m1 & m2].astype(int).applymap(lambda x: f'{x:b}')
print (df)
                     Val1 Val2 Val3  Val4 Val5
Function Type Name
env      In   Volt    Max  Typ  Min   Max  Max
              Temp   High  Mid  Low  High  Low
              BD#       1    2    3     4    5
func1    In   Name1    11  100   11    11   11
              Name2   101  111  110  1001  100
         out  Name3     6    6    3     4    5

A: By creating mask of the dataframe:
mask = ((df.index.get_level_values('Function') == 'func1')&
                (df.index.get_level_values('Type') == 'In')&
                (df.index.get_level_values('Name').isin(['Name1', 'Name2'])))

df[mask] = df[mask].astype(int).applymap(lambda x: format(x, 'b'))

print(df[mask])

                     Val1 Val2 Val3  Val4 Val5
Function Type Name
env      In   Volt    Max  Typ  Min   Max  Max
              Temp   High  Mid  Low  High  Low
              BD#       1    2    3     4    5
func1    In   Name1    11  100   11    11   11
              Name2   101  111  110  1001  100
         out  Name3     6    6    3     4    5


Q: Android. Как отключить resize для фона RelativeLayout? При появлении клавиатуры все содержимое layout уходит вверх, на размер равный размеру клавиатуры. То, что сверху не помещается, скрывается. У layout есть фоновая картинка, которая при появлении клавиатуры не сохраняет размеры уходя вверх, а сжимается.
Как это вылечить?
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
android:id="@+id/screen_2"
android:background="@drawable/screen_2"
android:visibility="visible"
android:onClick="hideKeyboard"
tools:showIn="@layout/activity_main" tools:context=".MainActivity">

<TextView
    style="@style/mainText"
    android:text="@string/screen_2_main_text"
    android:id="@+id/mainTextScreen2"
    android:layout_marginRight="67dp"
    android:layout_marginLeft="67dp"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="900dp" />

<EditText
    style="@style/review"
    android:id="@+id/review"
    android:onClick="pressingInput"
    android:hint="@string/hint_review" />

<TextView
    style="@style/SubmitSteepTwo"
    android:onClick="submitScreen_2"
    android:text="@string/submit_steep_two"
    android:id="@+id/submit_steep_two" />

<ImageView
    android:onClick="mediaRecord"
    android:src="@drawable/media"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/media"
    android:layout_alignTop="@+id/submit_steep_two"
    android:layout_toEndOf="@+id/submit_steep_two"
    android:layout_marginStart="30dp" />

в манифесте:
android:windowSoftInputMode="adjustResize"

Решение
в каталоге drawable создал xml файл с содержимым и указал его в качестве фона
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/screen_2" android:gravity="bottom" />

A: Почему бы в ресурсах не создать background_something.xml, внутри которого задать все параметры для вашего background?


Q: numberOfRowsInSection running in infinite loop  - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   int rows;     // Return the number of rows in the section.
    switch (section)
    {
         case 0:
           rows = 1;
           break;
         case 1:
            rows = 3;
            break;
         case 2:
            rows = 2;
            break;
         case 3:
             rows = 1;
            break;
         default:
            rows = 1;
            break;
    }
  return rows;
 }

this code is running in infinite loop. for the first it returns right no of rows. but after that starts running on infinite loop.
and one more thing, why section starts from the highest no and den come to 0 and den in ascending order??

A: There is no infinite loop in your code above. It's quite possible that it is being called from an infinite loop.
To find this, place a breakpoint in the method, continue a few times (to ensure you're in the loop rather than just the normal calls) and then look at the stack trace on the side. This should give you a pretty clear idea of where the looping is coming from. You are probably calling reloadData from within one of your datasource or delegate methods.


Q: Form_Shown and mouse click I have c# code which moves and clicks mouse, i must press button on form to start code, but i need that my code would start himself, not when button is pressed i tried to achieve this with formshown. It shows form but dont start the code. Its just a bit of code:
 private void Form1_Shown(object sender, EventArgs e)
    {
        Thread.Sleep(5000);
        RightClick(28, 132);
        Thread.Sleep(2000);
        LeftClick(35, 137);
    }

Any ideas how my form could start doing things after it is opened?
Every time i open my windowsform application i have to press start button and after that my mouse starts clicking coordinates. I want that mouse would start moving without me clicking button its like autostart or something i dont know how to explain.

A: Simply Call your code on Form Load Event
private void Form1_Load(object sender, System.EventArgs e)
    {
        Thread.Sleep(5000);
        RightClick(28, 132);
        Thread.Sleep(2000);
        LeftClick(35, 137);

    }

you can also call your code into constructor but it would be better if you call it inside form_load event
public yourform()
{
       Thread.Sleep(5000);
        RightClick(28, 132);
        Thread.Sleep(2000);
        LeftClick(35, 137);
}


Q: SensorManager.getRotationMatrix gravity parameter or accelerometer parameter values in android? In Android Documentation is specified the third parameter as
float[] gravity

then is specifies
[0 0 g] = R * gravity (g = magnitude of gravity)

Now, in most of the examples online I can see everyone sending accelerometer values to getRotationMatrix, but, Isn't suppose that I should send only gravity values?
For example, if the mobile phone has the gravity sensor,
Should I send it raw output to getRotationMatrix?
If it hasn't one, Should I send accelerometer values? Should I extract non gravity components first? (as accelerometer values are Acceleration minus G).
Will the use of gravity sensor values be more reliable than using accelerometer values in mobile phones that have that sensor?
Thanks in advance! Guillermo.

A: I think the reason you only see examples using the accelerometer values is because the gravity sensor was only launched in API 9 and also because most phones might not give this values separated from the accelerometer values, or dont have the sensor, etc, etc..
Another reason would be because in most of the cases the result tend to be the same, since what the accelerometer sensor outputs is the device linear acceleration plus gravity, but most of the time the phone will be standing still or even moving at a constant velocity, thus the device acceleration will be zero.
From the setRotationMatrix Android Docs:

The matrices returned by this function are meaningful only when the device is not free-falling and it is not close to the magnetic north. If the device is accelerating, or placed into a strong magnetic field, the returned matrices may be inaccurate.

Now, you're asking if the gravity data would me more reliable? Well, there is nothing like testing, but I suppose it wouldn't make much difference and it really depends on which application you want. Also, obtaining the simple gravity values is not trivial and it requires filtering, so you could end up with noisy results.


Q: Associate custom uri schemes with Java self contained application for windows I have a self contained JavaFX application. For an improved user experience, I would like the user to click on a button/link on the browser and start the application. Just like magnet URI for torrent, the link contains metadata that is required to start up the application.
Is there a way to generate the executable for JavaFX application to associate with custom URI just like magnet URIs associated with torrent applications.

A: Here is how to associate custom URIs with an application.
I already have a task that generates the native bundles.
First step is to enable verbose in your ant task so you can locate the build path.
As mentioned here, in 6.3.3 enable verbose and look for <AppName>.iss file in the build directory, which is usuablly AppData/Local/Temp/fxbundler*.
Make sure you have the directory that contains package directory in the classpath. Here is an example of how you can add that to the classpath:
<taskdef resource="com/sun/javafx/tools/ant/antlib.xml" uri="javafx:com.sun.javafx.tools.ant" classpath="${build.src.dir}:${JAVA_HOME}/lib/ant-javafx.jar"/>

In my example I have package/windows with Drop-In Resources in src directory.
If you have file association, you will see something like this:
[Registry]
Root: HKCR; Subkey: ".txt"; ValueType: string; ValueName: ""; ValueData: "AppNameFile"; Flags: uninsdeletevalue

Just after this line you can add lines to add custom URI's registry entries.
If you don't have file association then you will add entries after
ArchitecturesInstallIn64BitMode=ARCHITECTURE_BIT_MODE

You can find the template of how AppName.iss file is generated at this location:
C:\Program Files (x86)\Java\jdk1.8.0_60\lib\ant-javafx.jar\com\oracle\tools\packager\windows\template.iss
Here you will find how to write lines like the one above
Here you can find what registry keys and entries that needs to be added for custom URI association.


Q: Does MonetDB support parallel query execution when using merge tables? I have partitioned my data set into two separate sets of 5M rows. Each partition is loaded into a table on a machine of its own. I use a central monetdb instance where I register both tables as remote tables and add them to a merge table.
When I run a query on the merge table I would expect MonetDB to distribute the query, in parallel, to both partition tables. However, when looking at results created with tomograph I see that each remote table is queried sequentially.
I've compiled MonetDB myself using a recent source tarball. I've disabled geom and made sure embedded python was available. Other than that I've not changed any settings or configure flags. The two machine holding the partitions are 1 core VMs with 4GB memory. The central machine is my laptop, which has 4 cores and 16GB of memory. I have also run this experiment using a central node with the same configuration as the partitions.
I created the tables like this:
-- On each partition (X = {1, 2}):
CREATE TABLE responses_pX (
    r_id int primary key,
    r_date date,
    r_status tinyint,
    age tinyint,
    movie varchar(25),
    score tinyint
);

-- On central node:
CREATE MERGE TABLE responses (
    r_id int primary key,
    r_date date,
    r_status tinyint,
    age tinyint,
    movie varchar(25),
    score tinyint
);

-- For both partitions
CREATE REMOTE TABLE responses_pX (
    r_id int primary key,
    r_date date,
    r_status tinyint,
    age tinyint,
    movie varchar(25),
    score tinyint
) ON 'mapi:monetdb://partitionX:50000/partitionX';

ALTER TABLE responses ADD TABLE responses_pX;

I'm running the following queries on the central node:
SELECT COUNT(*) FROM responses;
SELECT COUNT(*), SUM(score) FROM responses;
SELECT r_date, age, SUM(score)/COUNT(score) as avg_score FROM responses GROUP BY r_date, age;

For all queries the parallelism reported by the tomograph tool is no higher than 2.11%.

A: yes, MonetDB uses parallel processing where possible. See the documentation
https://www.monetdb.org/Documentation/Cookbooks/SQLrecipes/DistributedQueryProcessing


Q: How is the ac load line for the following amplifier derived? So I am trying to derive the ac load line for the following class A power amplifier

First I considered the reflected load/equivalent resistance of the transformer, this becomes
$$R'_{L} = (\frac{n_{1}}{n_{2}})^2 R_{L}$$
This means the voltage drop across the equivalent resistance must be
$$i_{c}R'_{L}$$
So
$$V_{ce} = V_{cc} - i_{c}R'_{L}$$
However this is not the correct ac load line and I wanted to know what am I doing wrong?

A:
This means the voltage drop across the equivalent resistance must be
  \$i_{c}R′_{L}\$

No, you forgot that at DC, the transformer primary has a DC resistance of circa 0 ohms and this is in parallel with \$R'_L\$.
For AC signals of sufficient frequency that the primary inductance can be ignored (i.e. is much bigger in magnitude than \$R'_L\$), the AC signal at the collector is basically swinging symmetrically around \$+V_{CC}\$.
In other words a signal at the collector can swing from nearly 0 volts to +20 volts when \$+V_{CC}\$ is 10 volts: -

Picture taken from this slide show, page 16.

A: DC doesn't cause substantial voltage drop in the transformer, if it's properly designed. In idle state the voltage between the collector of the transistor and GND is =Vcc or more precisely Vcc - Ico x Rt where Ico is the idle state collector current and Rt is the resistance of the transformer primary.
The signal makes Ic swing around Ico. Voltage between the collector and GND swing around the idle value with amplitude Is x Rr where the Is is the signal current amplitude and Rr is your reflected load resistance. This is applicable if the signal is inside the usable frequency range of the transformer. It's essential to notice that the voltage at the collector can be momentarily more than the supply voltage Vcc.
The operation of the transistor needs that Vce is at least few hundred millivolts positive. Thus the signal voltage swing at the collector cannot be larger than the idle state voltage between the collector and emitter. Also Re causes some drop but if we can consider Ico x Re small the theoretical upper limit for the momentary voltage at the collector is 2Vcc.
Reliable operating point to prevent the thermal rush generally forces us to sacrifice at least few hundred millivolts as Ico x Re, so in practice we can approximate the maximum momentary voltage between the collector and GND to be 2Vcc-1V. The maximum momentary Vce is a little less, say 2Vcc-1,5V due the drop in Re, which is kept stable with a massive capacitor CE to prevent gain loss.
The whole circuit is very old fashioned. It's a class A single transistor output stage. It was widely used in walkie-talkies and cheap battery radios 50...65 years ago if the budget or the available space didn't allow a push-pull amp.
Circuit theorists would say we got the numerical relations by using the superposition principle. We calculated separately for DC and signal and added the resulted voltages and the resulted currents to get the total voltage and the total current.


Q: Getting error when I try to fetch rows using entity EF6 I use linq to entity 6 code first.
Here is two entities class:
    public class Site
    {
        public int Id { get; set; }
        public int UID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public int? ContractId { get; set; }
        public int? SiteTypeId { get; set; }

        public virtual ICollection<SiteRegion> Regions { get; set; }
    }

    public class SiteRegion
    {
        public int Id { get; set; }
        public int UID { get; set; }
        public int? SiteId { get; set; }
        public string Name { get; set; }
        public int? RegionTypeId { get; set; }

        [ForeignKey("SiteId")]
        public virtual Site Site { get; set; }

    }

As you can see above Regions field is constraint and I have one-to-many relation between to tables.
I have created this LINQ query to fetch desired rows from Sites table:
int?[] ContractId = [1,2];
int?[] siteTypeId = [1,2,3];

 var result = (from sites in context.Set<Site>()
               where contractsIDList.Contains(sites.ContractId) &&
               siteTypeId.Contains(sites.SiteTypeId) &&
               select sites).AsNoTracking<Site>();

And It works fine.
Now I have new requirement and I need to filter my query also by RegionTypeId column in SiteRegion table here is my new query:
int?[] ContractId = [1,2];
int?[] siteTypeId = [1,2,3];
int?[] regionTypeId = [1,2,3];

 var result = (from sites in context.Set<Site>()
               where contractsIDList.Contains(sites.ContractId) &&
               siteTypeId.Contains(sites.SiteTypeId) &&
    regionTypeId.Contains(sites.Regions.SelectMany(x=>x.RegionTypeId).ToArray())

               select sites).AsNoTracking<Site>();

But I get error:
Error   36  'int?[]' does not contain a definition for 'Contains' and the best extension method overload 'System.Linq.Queryable.Contains<TSource>(System.Linq.IQueryable<TSource>, TSource)' has some invalid arguments

On this row:
regionTypeId.Contains(sites.Regions.SelectMany(x=>x.RegionTypeId).ToArray())

How to fix my query above to get the desired rows?

A: You need to do it as shown below.
Note :
Wrong : regionTypeId.Contains(sites.Regions.SelectMany(x=>x.RegionTypeId).ToArray())
Correct : regionTypeId.Any(item => sites.Regions.Select(x => x.RegionTypeId).Contains(item))
Working sample :
 int?[] contractsIDList = { 1, 2};
 int?[] siteTypeId = { 1, 2, 3};
 int?[] regionTypeId = { 1, 2, 3};

var result = (from sites in db.Set<Site>()
              where contractsIDList.Contains(sites.ContractId) && siteTypeId.Contains(sites.SiteTypeId)
              && regionTypeId.Any(item => sites.Regions.Select(x => x.RegionTypeId).Contains(item))
              select sites).AsNoTracking<Site>();

Result :


Q: Spatializer not available on a pixel 6 with android 13 I just updated to Android 13 and one of the advertised features is the spatial audio, but when I access the spatializer class to check if it's available, I get a false. Also, in the settings there is nothing regarding the spatial audio. Is it already implemented or not?


Q: How can I open the A TAB at 768px? I apologize first, my English is not very good, but I will try to describe my problem.
I'm implementing an RWD effect, and this is it!
When the screen is below 768px, I want to wrap an A tag around the demo block to make the whole block clickable, but when the screen resolution is above 768px, I want to add an A tag to cover the demo block.
I have tried using display:none in the initial a tag;

.demo{
  background-color: #ccc;
  padding:20px;
}
a{
  text-decoration:none;
  color:#222;
}
.link{
  display: none;
}

@media(max-width:768px){
  .link{
    display: block;
  }
}

<object>我是標題</object>

            <object>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ab voluptatum v</object>

However, this will cause the whole picture to disappear at the beginning, which is not the effect I want. I would like to ask you how to write this better?

.demo{
  background-color: #ccc;
  padding:20px;
}
a{
  text-decoration:none;
  color:#222;
}
.link{
  display: none;
}

@media(max-width:768px){
  .link{
    display: block;
  }
}

<object>我是標題</object>

            <object>9999999999999999</object>

A: This is only a workaround
Do not use display: none;.
Instead write:
...

.link{
  display: block;
  cursor: default;
}

@media(max-width:768px){
  .link{
    cursor: pointer;
  }
}

This will make the mouse cursor appear normal in desktop and appear clickable on mobile.
In reality you can still click, but 99+% of visitors will not realize or attempt to check.
See: https://developer.mozilla.org/de/docs/Web/CSS/cursor


Q: Chrome prevents the site due to ads I'm facing a problem just with google chrome. My website home page works properly, but when trying to open a post on the site, it shows this message:
Security Wrror
The site is based on the latest WordPress version, and it works properly with all other browsers. I tried to remove ads (the only way to get the required fund). but nothing changed. It still doesn't open on Google Chrome.
I tried to update the sitemap, but nothing changed.
I hope you can help. Most of the visitors use Google Chrome as a default browser, and this is a major problem because we earn money due to ads viewed on the site.
here a link to my website


Q: Adding a string to a List inside of a List> Im trying to add a string object to a list inside of list> in a for & while loop, trying to use var i as the list object i wish to use.
here is the code of the class, any help on what im doing wrong would be very much appreciated :)
public class GenClass
{

    private static int _genCount;
    private static bool _filesLoadedToLists;
    private static List<string> _nounSetOne = new List<string>();
    private static List<string> _nounSetTwo = new List<string>();
    private static List<List<string>> _toLoad = new List<List<string>>();

    private string _emotionMidTrim = "";

    public const string FileOne = "NounSetOne.txt";
    public const string FileTwo = "NounSetTwo.txt";

    public GenClass()
    {
        while (_filesLoadedToLists == false)
        {
            TextToList(FileOne,FileTwo);
            _filesLoadedToLists = true;
        }

        _genCount++;
    }

the problem is withing this part of the class
    public void TextToList(string fileOne, string fileTwo)
    {
        List<string> filesToRead = new List<string>();

        filesToRead.Add(fileOne); // Add the text files to read to a list
        filesToRead.Add(fileTwo); // Add the text files to read to a list

        _toLoad.Add(_nounSetOne); // Add a list of words to this list
        _toLoad.Add(_nounSetTwo); // Add a list of words to this list

        for (int i = 0; i <= filesToRead.Count; i++)
        {
             using (var reader = new StreamReader(filesToRead[i]))
             {
                 string line;
                 while ((line = reader.ReadLine()) != null)
                 {
                     _toLoad[i.Add(line)]; // the error is here
                 }
             }
        }

A: You are correct, with the error, you need to understand that the

List<List<string>> will take a List<string> and NOT A String.

Try something like this;
List<string> listOfString = new List<string>;
for (int i = 0; i <= filesToRead.Count; i++)
{
      using (var reader = new StreamReader(filesToRead[i]))
      {
           string line;
           while ((line = reader.ReadLine()) != null)
           {
             listOfString.add(line);
           }
      }
}

Then,
_toLoad.add(listOfStrings);

A: Try using File.ReadAllLines().  Replace the for loop with:
foreach(var file in filesToRead) {
  _toLoad.Add(File.ReadAllLines(file).ToList());
}

A: You can cut this down considerably using LINQ:
List<string> filesToRead = new List<string> {"NounSetOne.txt", "NounSetTwo.txt"};
List<List<string>> _toLoad = new List<List<string>>();
_toLoad.AddRange(filesToRead.Select(f => File.ReadAllLines (f).ToList() ));

Note that there's no extraneous variables for the filename (why have FileOne/FileTwo if their only purpose is to get added to a list?) and that we're letting the AddRange take care of creating the List<string>s for us automatically.

A: for (int i = 0; i <= filesToRead.Count; i++)
    {
         using (var reader = new StreamReader(filesToRead[i]))
         {
             string line;
             while ((line = reader.ReadLine()) != null)
             {
                 _toLoad[i].Add(line);
             }
         }
    }


Q: Powershell Mysql Error This code is:
$cm = New-Object -TypeName MySql.Data.MySqlClient.MySqlCommand
$sql = "Select * FROM onaylanan Order by onaylanma_id ASC"
$cm.Connection = $Connection
$cm.CommandText = $sql
$dr = $cm.ExecuteReader()

while ($dr.Read())
{
$cm2 = New-Object -TypeName MySql.Data.MySqlClient.MySqlCommand
$sql2 = "Delete FROM onaylanan Where onaylanma_id=4"
$cm2.Connection = $Connection
$cm2.CommandText = $sql2
$dr2 = $cm2.ExecuteNonQuery()
  $dr2.Close();

}
$dr.Close();
$Connection.Close()

This Error is:

Exception calling "ExecuteNonQuery" with "0" argument(s): "There is already an open DataReader associated with this Connection which must be closed first."

A: As the error indicates, you can't execute two queries concurrently over the same connection.
Open a second connection (you could name it Connection2) and assign that to $cm2:
$cm2.Connection = $Connection2


Q: Remove PHP extension using .htaccess methods (Keeping Link Juice) I'm trying to remove the .php extension on my URLs to make it Search Engine Friendly using the .htaccess file Redirect 301, to keep the "rank juice" and I as much I've tried almost every example around - It just doesn't seem to work.
Here are some of the methods I've unsuccessfully tried already:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

This is the most common solution given but nothing happens and there is no changes.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /$1.php [L]

Nothing happens and there is no changes.
RewriteEngine On
# RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php
# RewriteRule (.*)\.php$ /$1 [L,R=301]
# RewriteRule (.*)/$ $1.php [L]

I get a Not Found : The requested URL /AMENPTHOME/hostnd/3/9/9/399fc7b78/www/htdocs/web/dive-sites.php was not found on this server.
Amen is my host and the file dive-sites.php in this specific real example is on the root.
My goal is to have: www.domain.com/dive-sites and not www.domain.com/dive-sites.php using a Redirect 301 because this url is already ranked for a while. Can someone please help ?
Thank you very much, all help appreciated.

A: If I didn't missed anything:
RewriteEngine On

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/(.+)\.php[^\s]* [NC]
RewriteRule ^ /%1 [R=301,NE,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [QSA,NC,L]

Requests to /dive-sites.php will issue a 301 redirect to /dive-sites, appending query-strings if any.
Requests to /dive-sites will get a 200 response with /dive-sites.php as Content-Location, appending query-strings if any.

A: try this:

RewriteEngine on
RewriteRule ^/(.+)(($|#)*(.*)) /$1.php$2

If removing only the .php this will work.

$1 = for the name of the page, e.g foo

$2 = take note of the hashtag or the get request
eg.

<domain>/example ----> <domain>/example.php
<domain>/example?get=this ----> <domain>/example.php?get=this
<domain>/example#hash ----> <domain>/example.php#hash

A: Try this code for .php extension removal:
RewriteEngine On

## hide .php extension
# To externally redirect /dir/file.php to /dir/file
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,L,NE]

# To internally forward /dir/file to /dir/file.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ /$1.php [L]


Q: Mustache (Nustache) arbitrarily rendering some of list inline I'm using the code:
{{#Object}}
{{{Name}}} - {{{Property}}}
{{/Object}}

to render a list, but halfway through the list, it'll start printing the list on the same line, which it will continue doing until the end of the list. We use this within emails, and our preview pane renders it within a <pre> tag, and it looks fine. When it's set as the body of an email, we get the line breaking problem. It'll render like the following:
Object1Name - Object1Property
Object2Name - Object2Property
Object3Name - Object3Property
Object4Name - Object4Property Object5Name - Object5Property Object6Name - Object6Property

There are also instances where it puts the entire list on the same line, and there are instances where it doesn't happen, most of the time it starts about halfway through the list and continues.
any help or ideas are welcome.


Q: knockout.js and property not being found in Jquery Template I am getting "caseStudy is not defined" with the below code.  I have to add the full prefix app.viewModel.caseStudy.showFlawDetails to not error.
 app.viewModel.caseStudy = {};
        app.viewModel.caseStudy.cases = ko.observableArray();
        app.viewModel.caseStudy.selectedCaseId = ko.observable(0);
        app.viewModel.caseStudy.selectedCase = ko.mapping.fromJS(caseModel);
app.viewModel.caseStudy.showFlawDetails = function (index) {
        console.log(index);
    };
ko.applyBindings(app.viewModel);

A: Inside of your flawTemplate the scope is caseStudy.selectedCase.Flaws, so when you put caseStudy.showFlawDetails, it is not found as a property of Flaws or globally.
So, you can either reference it with app.viewModel.caseStudy.showFlawDetails, if app has global scope (which it seems to since it works for you).
Otherwise, a good option is to pass the function in via templateOptions.  So, you would do:
data-bind='template: { name: "flawTemplate", data: caseStudy.selectedCase.Flaws, templateOptions: showFlawDetails: caseStudy.showFlawDetails } }'>

Then, you would access it using $item.showFlawDetails
The click (and event) bindings also expect that you pass it a reference to a function.  In your case you are passing it the result of executing the function.  Answered it further here: knockout.js calling click even when jquery template is rendered


Q: how to link through bootstrap tabs Hello the code which i am posting here is just a w3schools example. Its a bootstrap links tabs. All my problem is when i want for example just to link to the second tab i can't i want when i put a link like that http://127.0.0.1:61330/test2.html#menu2
i want it to work to go to menu2 section or div what ever but it doesn't work
i want at the link up tp be like  /test2.html#menu2 /test2.html#menu3 like that but it doesn't happen
i found also this here on stackoverflow but it just show the link up in the browser but when i change the link like http://127.0.0.1:61330/test2.html#menu3 for example it don't work
// Javascript to enable link to tab
var url = document.location.toString();
if (url.match('#')) {
    $('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
}

// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash;
})

main
<!DOCTYPE html>

  <title>Bootstrap Case</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

Dynamic Tabs

Home

Menu 1

Menu 2

Menu 3

HOME

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Menu 1

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Menu 2

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.

Menu 3

Eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.

A: $(document).ready(function(){
    if (location.hash) {
        $('a[href=' + location.hash + ']').tab('show');
    }
});

this is the solution i found it here
here


Q: Multiple ground planes, single point ground, and a level shifter I'm using a level shifter to go from 3.3V to 5V (digital/analog). According to the datasheet, if I put 1 ground on the left side of the IC and the other on the right, it would tie the grounds together inside the IC.
This would be bad since I'm trying to use a single point star ground with separate ground planes and it seems like this ruins it. If I want to keep using the same part, whats the best approach? I'm thinking tie both sides of the level shifter to the input ground and have the output current take a long path through the single point ground? or vice versa?
http://www.ti.com/lit/ds/symlink/sn74lvc8t245.pdf

A: I'm thinking tie both sides of the level shifter to the input ground and have the output current take a long path through the single point ground?
I would do the opposite, so keep the loop at the output short because that's where the current flows.
The inputs are high impedance so almost no current flows. For noise reasons the argument could be made that the inputs should have the better ground connection but since we're dealing with digital input signals, I would not be too concerned about noise at the inputs.
I think in the end there isn't that much difference between ground at input side or ground at output side. This isn't RF, not very sensitive (using low voltages) and also not high current.
If you still have doubts you could consider to connect the levelshifter's grounds to a local ground plane and then connect that plane via a link / zero ohm resistor / blob of solder to the output side or the input side.


Q: Insert data to table row using Angular I am new to angular, and currently working on my personal project.
I have a question about how to insert new data to table row.
Can anyone give me snippet/example how to do this?
Here is the form and the table headers:

ADD

Add

              <button type="button" class="close pull-right" aria-label="Close" (click)="smModal.hide()">
                ×
              </button>

              <form>
                ID
                <input type="text" class="form-control" placeholder="id">

                name
                <input type="text" class="form-control" placeholder="name">

                year
                <input type="text" class="form-control" placeholder="year">

                major
                <input type="text" class="form-control" placeholder="major">

                address
                <input type="text" class="form-control" placeholder="address">

                Email
                <input type="text" class="form-control" placeholder="email">

                phone
                <input type="text" class="form-control" placeholder="phone">

                <button type="submit" class="btn btn-primary">Simpan</button>
                <button class="btn btn-danger">Batal</button>
              </form>

      id
      name
      year
      major
      address
      email
      phone

Here is the typescript file:
//app.component.ts

import { Component } from '@angular/core';
import { TemplateRef } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/modal-options.class';
import { NgIf } from '@angular/common';

 @Component({
  selector: 'app-root',
  styleUrls:['app.component.css'],
  templateUrl:'app.component.html',
  //template:`<h1 align="center">template</h1>`
})

export class AppComponent
{
  title = 'title';

}

What I need to do is simply insert the user input from that from into a table row.
Please let me know if more snippets are needed.

A: You can declare custom object array in your app.component.ts file like this
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-root',
  template: `

      id
      name
      year

      {{row.id}}
      {{row.name}}
      {{row.year}}

  <input type="text" [(ngModel)]="id" placeholder="id" />
  <input type="text" [(ngModel)]="name" placeholder="name" />
  <input type="text" [(ngModel)]="year" placeholder="year" />

  <button (click)="buttonClicked()">Click to Insert New Row</button>
  `,
  styles: []
})
export class AppComponent {
  title = 'app';

  public id: number;
  public name: string;
  public year: number;
  public rows: Array<{id: number, name: string, year: number}> = [];

  buttonClicked() {
    this.rows.push( {id: this.id, name: this.name, year: this.year } );

    //if you want to clear input
    this.id = null;
    this.name = null;
    this.year = null;
  }
}

A: // html data//

        Type
        Name
        Batters
        Toppings

          {{data.type}}

              {{data.name}}

                    {{item.type}}

                       {{y.type}}

//component.ts file//

export class AppComponent {
public newtext:any;
public rows:any=[];
public url:any=["../assets/images/image.jpeg","../assets/images/danger.jpeg","../assets/images/crab.jpeg",
"../assets/images/aws.png","../assets/images/error404.jpg","../assets/images/night.jpg"];
public displayimage:any=["../assets/images/image.jpeg"];
public setimage:boolean=true;
public i:any=1;

Newjson=[
    {
      "id": "0001",
      "type": "donut",
      "name": "Cake",
      "ppu": 0.55,
      "batters":
        {
          "batter":
            [
              { "id": "1001", "type": "Regular"},
              { "id": "1002", "type": "Chocolate"},
              { "id": "1003", "type": "Blueberry"},
              { "id": "1004", "type": "Devil's Food"}
            ]
        },
      "topping":
        [
          { "id": "5001", "type": "None" },
          { "id": "5002", "type": "Glazed" },
          { "id": "5005", "type": "Sugar" },
          { "id": "5007", "type": "Powdered Sugar" },
          { "id": "5006", "type": "Chocolate with Sprinkles" },
          { "id": "5003", "type": "Chocolate"},
          { "id": "5004", "type": "Maple" }
        ]
    },
    {
      "id": "0002",
      "type": "donut",
      "name": "Raised",
      "ppu": 0.55,
      "batters":
        {
          "batter":
            [
              { "id": "1001", "type": "Regular"}
            ]
        },
      "topping":
        [
          { "id": "5001", "type": "None" },
          { "id": "5002", "type": "Glazed" },
          { "id": "5005", "type": "Sugar" },
          { "id": "5003", "type": "Chocolate"},
          { "id": "5004", "type": "Maple" }
        ]
    },
    {
      "id": "0003",
      "type": "donut",
      "name": "Old Fashioned",
      "ppu": 0.55,
      "batters":
        {
          "batter":
            [
              { "id": "1001", "type": "Regular"},
              { "id": "1002", "type": "Chocolate"}
            ]
        },
      "topping":
        [
          { "id": "5001", "type": "None" },
          { "id": "5002", "type": "Glazed" },
          { "id": "5003", "type": "Chocolate"},
          { "id": "5004", "type": "Maple" }
        ]
    }
  ]
}


Q: Do all sites have Winterbash? The Winter Bash FAQ mentions:

I'm on Stack Overflow (or on one of a few other sites). Where are my hats?
Users on these sites have to choose to opt-in individually. Just click the "Winter Bash" popup at the top and click "I love hats!", and you'll be able to earn hats and see other hat-loving users sporting dashing works of millinery.

I don't see a pop-up (snowflake) on TeX.SE, nor is it listed in the Winter Bash Leaderboard. Are all sites able to participate in Winter Bash 2014? What about per-site metas (as it's currently not available on Meta.SO)?

Related (not duplicate): Where is my snowflake on Stack Overflow?; I tried in both Google Chrome and Mozilla Firefox with no luck, nor am I running any of mentioned extensions/plug-ins.

A: To the second, easy answer: hats are not enabled on per-site metas.
Additionally, sites have the option of opting out of Winterbash for 2014. Given that TeX neither appears on the leaderboards nor has the Winterbash plugin, I'd assume that for one reason or another they decided to opt out.

A: This year the breakdown is as follows:

*

*Stack Overflow by default has no hats, but users can opt in to wear and see them (either by clicking "I love hats" in the snowflake dropdown, or simply by putting on a hat somewhere).

*TeX, Math Overflow, and Japanese Stack Overflow have no hats at all, with no way of opting in.

*The experimental edX sites have no hats either, period.

*All other Q&A sites (except for discuss.area51) have hats, and they're enabled by default.

A: Child metas now have hats (if parent site has hats)!
From balpha's answer:

You wear the same hat on the child meta that you wear on the parent site, and the hat count on a meta user profile takes you to your hat rack on the parent site, similar to how it works for profile editing.


Q: Program on GD32f103 microcontroller runs only with debugger attached, won't run after reset I'm using a J-Link EDU Mini debugger/programmer, to upload a simple test program to a GD32f103 microcontroller (the ST32f103 clone/copy). The program is a mere test program, meant to turn an LED on. It's written in SMT32CubeIDE, and here, it is based on the ST32f103.
After uploading the compiled .elf file to the GD32f103 using the J-Kink, the LED turns on just fine. However, once I detach the J-Link and reset the processor, the program appears not to boot, because the LED won't turn on.
What can the source of this problem be?


Q: How to combine multiple querysets in django Suppose there is an event model and for each event there is one client and one consultant. Also, one consultant can have multiple events. Each event has number of different documents. I am trying to display list of events when a consultant logs in and in that list od events it should display their respective documents.
Models.py:
class Client_Profile(models.Model):
    user_id = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)  # Field name made lowercase.
    first_name = models.CharField(db_column='First_name', max_length=50)  # Field name made lowercase.
    last_name = models.CharField(db_column='Last_name', max_length=50)  # Field name made lowercase.
    phone_number = models.PositiveIntegerField(db_column='Phone_number', max_length=10)  # Field name made lowercase.
    # role_id = models.ForeignKey(Role, on_delete=models.CASCADE)

    def __str__(self):
        return self.first_name

class Consultant_Profile(models.Model):
    user_id = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)  # Field name made lowercase.
    first_name = models.CharField(db_column='First_name', max_length=50)  # Field name made lowercase.
    last_name = models.CharField(db_column='Last_name', max_length=50)  # Field name made lowercase.
    phone_number = models.PositiveIntegerField(db_column='Phone_number', max_length=10)  # Field name made lowercase.
    # role_id = models.ForeignKey(Role, on_delete=models.CASCADE)

    def __str__(self):
        return self.first_name

class Event(models.Model):
    event_id = models.AutoField(db_column='event_id', primary_key=True)
    client_id = models.ForeignKey(Client_Profile, db_column='Client_ID', on_delete=models.CASCADE)  # Field name made lowercase.
    consultant_id = models.ForeignKey(Consultant_Profile, db_column='Consultant_ID', on_delete=models.CASCADE)  # Field name made lowercase.

    def __str__(self):
        return str(self.event_id)

class Document(models.Model):
    document_id = models.AutoField(db_column='document_id', primary_key=True)
    document_name = models.CharField(db_column='document_name', max_length=50, null=True, blank=True)  # Field name made lowercase.
    path = models.FileField(null=True, upload_to='files/')
    date_uploaded = models.DateTimeField(default=timezone.now, null=True, blank=True)
    event_id = models.ForeignKey(Event, db_column='Client_ID', on_delete=models.CASCADE)  # Field name made lowercase.

    def __str__(self):
        return self.document_name + ": " + str(self.path)  # this specifies how should instance of this class should be printed.

views.py
@login_required
def consultant_home(request):
    consultant_pr = Consultant_Profile.objects.get(user_id=request.user)
    event_id = Event.objects.filter(consultant_id=consultant_pr.pk)
    for id in event_id:
        doc = Document.objects.filter(event_id=id)
    context = {'id': event_id, 'doc': doc, 'consultant_pr': consultant_pr}
    return render(request, 'Consultant/consultant_documents.html', context)

document.html
                    {% for eve in id %}

Event id: {{ eve.event_id }}

                        {% for dox in doc %}

document name: {{ dox.document_name }}

path: {{ dox.path}}

                        {% endfor%}
                    {% endfor %}

A: You can simply loop over the related Document objects from the Event object itself by using document_set (the default related_name for Document i.e. the model name in lowercase with _set appended). Also you can optimise the number of queries made by using prefetch_related [Django docs]:
In your view:
@login_required
def consultant_home(request):
    consultant_pr = Consultant_Profile.objects.get(user_id=request.user)
    events = Event.objects.filter(consultant_id=consultant_pr.pk).prefetch_related('document_set')
    context = {'events': event, 'consultant_pr': consultant_pr}
    return render(request, 'Consultant/consultant_documents.html', context)

In your template:
{% for event in events %}

Event id: {{ event.event_id }}

    {% for document in event.document_set.all %}

document name: {{ document.document_name }}

path: {{ document.path }}

    {% endfor%}
{% endfor %}


Q: Difference between two tables I am trying to pull the differences between two tables, each in a different database.  I thought I could just do a full outer join but I am getting back too many results.
The T-SQL below returns 167 results
SELECT N'{'+ADobjectGUID+N'}' [GUID], first_name [First], last_name [Last], description [Full] FROM [db1].[dbo].[tb1] where delete_date is null
except
SELECT ObjectGUID [GUID], GivenName [First], sn [Last], displayName [Full] FROM [db2].[dbo].[tb1]

When I reverse it to be the below, it returns 214 results
SELECT ObjectGUID [GUID], GivenName [First], sn [Last], displayName [Full] FROM [db2].[dbo].[tb1]
except
SELECT N'{'+ADobjectGUID+N'}' [GUID], first_name [First], last_name [Last], description [Full] FROM [db1].[dbo].[tb1] where delete_date is null

However, I need more than just those columns from the databases, so I can't use the except statement.
select N'{'+ADobjectGUID+N'}' [GUID], first_name [First], last_name [Last], db1.dbo.tb1.description [Full], domain_user_id, sAMAccountName, employeeID
from db1.dbo.tb1
full outer join [db2].[dbo].[tb1]
on ObjectGUID = N'{'+ADobjectGUID+N'}'
    and first_name = GivenName
    and last_name = sn
    and tb1.description = displayName
where db1.dbo.tb1.delete_date is null

That query results in 1784 results.  Based on the above, I should be getting 371 results.  What am I missing.  I am still new to SQL and am sure it is something small.

A: FULL joins can be tricky. Try this version:
select
    -- columns from db1
    a_GUID = a.ObjectGUID,
    a_First = a.first_name,
    a_Last = a.last_name,
    a_Full = a.description,
    a.domain_user_id,
    a.sAMAccountName,
    a.employeeID,

    -- columns from db2
    b_GUID = N'{' + b.ADobjectGUID + N'}',
    b_First = b.GivenName,
    b_Last = b.sn,
    b_Full = b.displayName,
from
    ( select *
      from db1.dbo.tb1 as a
      where a.delete_date is null
    ) as a
  full outer join
    db2.dbo.tb1 as b
  on
      a.ObjectGUID = N'{' + b.ADobjectGUID + N'}'
  and a.first_name = b.GivenName
  and a.last_name = b.sn
  and a.description = b.displayName
where
      a.ObjectGUID is null
   or b.ADobjectGUID is null
  ;

A:
That query results in 1784 results. Based on the above, I should be
  getting 371 results

No, this is a wrong conclusion, you misunderstand full outer join. It does not produce the "difference" between two tables.
When you do t1 full join t2 you'll get all the rows that are matched by your ON condition plus all the rows that are not matched from the left table + all the rows that are not matched from the right table.
So the result cardinality will be greater or equal (in case of complete match) to each table cardinality.
Maybe you forgot to filter your query?
Here is a simple example of what you did:
declare @t1 table (col1 int, col2 int);
insert into @t1 values
(1, 1), (2,2), (3,3);

declare @t2 table (col1 int, col2 int);
insert into @t2 values
(1, 1), (2,2), (4,4), (5,5);

select * from @t1
except
select * from @t2;

select * from @t2
except
select * from @t1;

select *
from @t1 t1 full join @t2 t2
        on t1.col1 = t2.col1 and t1.col2 = t2.col2

Here in red you see the matched rows.
To filter them out you should consider only rows with NULL join columns on the "other" side like this:
select *
from @t1 t1 full join @t2 t2
        on t1.col1 = t2.col1 and t1.col2 = t2.col2
where (t1.col1 is null and t1.col2 is null) or
      (t2.col1 is null and t2.col2 is null);


Q: Randomly SSLException Unsupported record version Unknown-0.0 Sometimes the code below fails and sometimes it work. I'm using Java8. Is it a server side problem?
Exception in thread "main" javax.net.ssl.SSLException: Unsupported record version Unknown-0.0.
EDIT:
I downgrade to JDK7 from JDK8 and it works. The only solution i found that works.
public static void main(String[] args) throws Exception {
    URL u = new URL("https://c********.web.cddbp.net/webapi/xml/1.0/");
    HttpURLConnection connection = (HttpURLConnection) u.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "text/plain");
    connection.setRequestProperty("charset", "utf-8");
    connection.setRequestProperty("Content-Length", "" + 140);
    connection.setUseCaches(false);
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
}

A: I got the same error message in a new java installation when trying to use an SSL connection that enforces 256-bit encryption. To fix the problem I found I needed to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files (e.g. http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html)

A: I had this line
    SSLContext sc = SSLContext.getInstance("SSL");

Had to change it to
    SSLContext sc = SSLContext.getInstance("TLSv1");

And now it works on both, java 7 and java 8
Note: (In java 7 SSL and TLS both worked with the same url, in java 8 just tried TLSv1 but I guess SSLv1 also works)

A: Download the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files according to your JDK/JRE version and put it in lib/security folder
By default,Java Cryptographic Extension is limited in accessing function and algorithm usage.We need to make it unlimited.

A: According to the stack trace, the RecordVersion Unknow-0.0 is produced from here
=> referenced from here => which is invoked in InputRecord.readV3Record
most of the time, these two values should not be 0, the reason for this happening is probably the wrong response from server while handshaking.
(This is not an answer though, just some information for easier figuring out the problem and solution)

A: This error is fixed in latest jre's, just upgrade the version of jre. This issue is caused by SNI


Q: File Upload not working in IE and Firefox I have the following code to upload a file to the server. For some weird reason, it does not work in IE and Mozilla Firefox but works perfect in Chrome. What is the problem?
PHP:
// Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762)
    $POST_MAX_SIZE = ini_get('post_max_size');
    $unit = strtoupper(substr($POST_MAX_SIZE, -1));
    $multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));

    if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE)
        HandleError('File exceeded maximum allowed size. Your file size MUST NOT be more than 100kb.');

// Settings
    $save_path = 'uploads/'; //getcwd() . '/uploads/';The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
    $upload_name = 'userfile';                          // change this accordingly
    $max_file_size_in_bytes = 102400;               // 100k in bytes
    $whitelist = array('jpg', 'png', 'gif', 'jpeg');    // Allowed file extensions
    $blacklist = array('php', 'php3', 'php4', 'phtml','exe','txt','scr','cgi','pl','shtml'); // Restrict file extensions
    $valid_chars_regex = 'A-Za-z0-9_-\s ';// Characters allowed in the file name (in a Regular Expression format)

// Other variables
    $MAX_FILENAME_LENGTH = 260;
    $file_name = $_FILES[$upload_name]['name'];
    //echo "testing-".$file_name."
";
    //$file_name = strtolower($file_name);
    ////////$file_extension = end(explode('.', $file_name));

    $parts = explode('.', $file_name);
    $file_extension = end($parts);

    $uploadErrors = array(
        0=>'There is no error, the file uploaded with success',
        1=>'The uploaded file exceeds the upload max filesize allowed.',
        2=>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
        3=>'The uploaded file was only partially uploaded',
        4=>'No file was uploaded',
        6=>'Missing a temporary folder'
    );

// Validate the upload
    if (!isset($_FILES[$upload_name]))

        **HandleError('No upload found for ' . $upload_name);**//THROWS UP ERROR HERE in IE and Firefox

    else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0)
        HandleError($uploadErrors[$_FILES[$upload_name]['error']]);
    else if (!isset($_FILES[$upload_name]['tmp_name']) || !@is_uploaded_file($_FILES[$upload_name]['tmp_name']))
        HandleError('Upload failed.');
    else if (!isset($_FILES[$upload_name]['name']))
        HandleError('File has no name.');

HTML:
<form name="upload" action="/upload" method="POST" ENCTYPE="multipart/formdata">

'.MSG142.': <input class="font_upload_picture" type="file" name="userfile">
<input type=hidden name=MAX_FILE_SIZE value=102400 />

                                <input type="image" name="upload" value="upload" src="/img/layout/btnupload.gif" border="0" />

 '.MSG143.'

        </form>

A: The enctype of the form should be multipart/form-data

A: You have errors in your html. You're missing closing tags for a tr and td tag. Also, close off your file upload input tag />.

A: Some of your logic is off:
if (!isset($_FILES[$upload_name]))

will always pass. For every <input type="file"> in your form, there'll be a matching $_FILES entry, whether a file was actually uploaded or not. If no file was uploaded to being with, then you'll get error code 4.
else if (isset($_FILES[$upload_name]['error']) && $_FILES[$upload_name]['error'] != 0)

You don't have to check if the error parameter is set. as long as $upload_name has a valid file field name in it, the error section will be there. You can check for $_FILES[$upload_name], though. in case your variable's set wrong.
You've commented it out, but you're checking for valid upload types by checking the user-provided filename. Remember that the ['type'] and ['name'] parameters in $_FILES are user-supplied and can be subverted. Nothing says a malicious user can't rename bad_virus.exe to cute_puppies.jpg and get through your 'validation' check. Always determine MIME type on the server, by using something like Fileinfo. That inspects the file's actual contents, not just the filename.
So, your upload validation should look something like:
if (isset($_FILES[$upload_name]) && ($_FILES[$upload_name]['error'] === UPLOAD_ERR_OK)) {
    $fi = finfo_open(FILE_INFO_MIME_TYPE);
    $mime = finfo_file($fi, $_FILES[$upload_name]['tmp_name']);
    if (!in_array($valid_mime_type, $mime)) {
       HandleError("Invalid file type $mime");
    }
    etc...
} else {
    HandleError($uploadErrors[$_FILES[$upload_name]['error']]);
}


Q: kill all process spawned by parent process with ssh -x -n on other node A software named G09 works in parallel using Linda. It spawns its parallel childs on other node as
/usr/bin/ssh -x compute-0-127.local -n /usr/local/g09l/g09/linda-exe/l1002.exel ...other_opts...
However, when the master node kills this process, the corresponding child process on other node, namely compute-0-127 does not die but keeps running in background. Right now, I manually go to each node which has these orphaned Linda processes and kill them with kill. Is there any way to kill such child processes?
Look at pastebin 1 for PSTREE before killing the process and at pastebin 2 for PSTREE after parent is killed
pastebin1 - http://pastebin.com/yNXFR28V
pastebin2 - http:// pastebin.com/ApwXrueh
-not enough reputation points for hyperlinking second pastebin, sorry !(

A: The best option is to try to solve the problem itself and check why the child procceses are not terminated when their parent die.
You can use this command to execute a command remotely on another machine:
ssh user@remote_machine command

Of course, you need to replace the values: user, remote_machine, and command with the appropriate values.
For example, you can do:
ssh root@remote_machine "killall compute-0-127"


Q: JavaFX 2 Window Icon not working I'm trying to add an Icon to my JavaFX 2 application, but the ways I have found don't seem to work.
Image icon = new Image(getClass().getResourceAsStream("/images/icon.png"));
stage.getIcons().add(icon);

The icon is 32x32 in size.
When I try
Image icon = new Image("http://goo.gl/kYEQl");

It does work, in Netbeans and in the runnable jar.
I hope this can be fixed.

A: The problem was in the icon itself. It did load it like it should, but for some reason it didn't display like it should.
I remade the icon I was trying to use to different sizes (16x16 up to 512x512) and added them all to the icon list.
stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_16.png")));
stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_32.png")));
stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_64.png")));
stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_128.png")));
stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_256.png")));
stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/logo_512.png")));

Now it uses the icon like it should.


Q: Unset one Array on the basis of another array value in php? How can I remove one array index on the basis of another array value.
For example-
Array1
(
[0] => @@code
[1] => @@label
[2] => @@name
[3] => @@age
)

Array2
(
[0] => 123jj
[1] => test
[2] => john
[3] => 45
)

Array3
(
[0] => 2 #2 is index to be unset in array1 and array2
[1] => 3 #3 is index to be unset in array1 and array2
)

I have  3 arrays , I want to unset array1 and array2 index on the basis of value of array3 using php.How can I use unset() Method for this?
unset($array1,$array3) #this is wrong, but some thing like that
unset($array2,$array3)

With Out for loop.
I should get
Array1
(
[0] => @@code
[1] => @@label
)

Array2
(
[0] => 123jj
[1] => test
)

A: You asked similar question and removed it after getting the answer :
unset array indexs from value of another array?
$firstArray = array( 0 => '@@code' ,1 => '@@label' ,2 => '@@name' ,3 => '@@age' );

$keysArray = array( 0 ,1 );

$resultArray = array_diff_key( $firstArray ,array_flip( $keysArray ) );

var_dump( $resultArray );

A: Maybe you need this?
foreach($array3 as $tmp){
  unset($array1[$tmp]);
  unset($array2[$tmp]);
}


Q: executing two queries in firebase and finding the difference of the two
My Firebase has two children

*

*expenditure

*sales

I want to find the difference between sales and expenditure.
Currently i am able to find the total of both children.
However i am stuck trying to find the difference between the two.
Below is the code I have executed to compute the sum.
    dref = FirebaseDatabase.getInstance().getReference();

    DatabaseReference dref = FirebaseDatabase.getInstance().getReference();
    dref= dref.child("LukenyaExpenditure");

    dref.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot snapshot) {
            int totalAmount = 0;
            for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                DogExpenditure dogExpenditure = postSnapshot.getValue(DogExpenditure.class);
                totalAmount += dogExpenditure.getAmount();
            }

            textView4.setText("Your total expenses for Lukenya Unit is:" +Integer.toString(totalAmount));
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }

        public void onCancelled(FirebaseError firebaseError) {
            System.out.println("The read failed: " + firebaseError.getMessage());
        }
    });

Any help will be appreciated


Q: How to add trace to plotly scatter plot  p <- plot_ly(data = bData,  x = ~`Maturity Date`, y =  ~YVal,  type = 'scatter', mode='markers',
               symbol = ~Sym,  symbols = c('circle-open','x-open','diamond-open','square-open') ,
               text = ~paste(bData$Security,bData$Crncy, bData$YTM, bData$DM,sep = "
") ,hoverinfo = 'text'
         )

Above code produces this plot.

Now to this chart I want to add a trace with scatter plot with color depending on Currency column.
I tried this but it produces combination of two field as the legend.
Basically I want to classify the plot based on currency type but also add overlay or trace based on column SYM as the symbol.
  p <- plot_ly(data = bData,  x = ~`Maturity Date`, y =  ~YVal,  type = 'scatter', mode='markers',
               symbol = ~Sym,  symbols = c('circle-open','x-open','diamond-open','square-open') ,
               text = ~paste(bData$Security,bData$Crncy, bData$YTM, bData$DM,sep = "
") ,hoverinfo = 'text'
         ) %>%
    add_trace(x = ~`Maturity Date`, y =  ~YVal , color=~Crncy)

data:
bData <- structure(list(Crncy = structure(c(9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 3L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 5L, 9L, 9L, 9L, 9L, 9L, 9L,
5L, 9L, 9L, 9L, 9L, 6L, 5L, 9L, 9L, 3L, 9L, 5L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 5L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 7L, 6L, 7L, 6L, 9L,
7L, 7L, 3L, 2L, 7L, 9L, 9L, 9L, 9L, 8L, 9L, 9L, 9L, 10L, 9L,
9L, 4L, 4L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 4L, 9L, 9L,
9L, 5L, 9L, 9L, 9L, 9L, 5L, 9L, 5L, 9L, 2L, 9L, 5L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 2L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 1L, 5L, 1L, 9L, 9L, 9L,
9L, 9L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 6L, 9L, 9L,
9L, 9L, 1L, 1L, 9L, 9L, 9L, 9L, 9L, 1L, 9L, 9L), .Label = c("AUD",
"CAD", "CHF", "COP", "EUR", "GBP", "JPY", "PEN", "USD", "ZAR"
), class = "factor"), `Maturity Date` = structure(c(20772, 19689,
18969, 18969, 20815, 20119, 20865, 20864, 20134, 20873, 20873,
20887, 20011, 20897, 20162, 19797, 20908, 20908, 20923, 19841,
19107, 19107, 20941, 20935, 20936, 20936, 20953, 20049, 19138,
19860, 21005, 21027, 19562, 19562, 21014, 19222, 21047, 19950,
19264, 19285, 19292, 19292, 19323, 19382, 19381, 20000, 19404,
20176, 19437, 19875, 19875, 19508, 20635, 19555, 19555, 20658,
19038, 19628, 18946, 19745, 19746, 19021, 19042, 19042, 20545,
20623, 19047, 19412, 19415, 20178, 20178, 19611, 19807, 20168,
20551, 20640, 20957, 20223, 19858, 19692, 19158, 20258, 19720,
20269, 20999, 20999, 20290, 20278, 20300, 20300, 21029, 19753,
20318, 20328, 20423, 20120, 20223, 20240, 19335, 20594, 19510,
19905, 20073, 20347, 20392, 18897, 20962, 20994, 21009, 21043,
19287, 19505, 18899, 19006, 19081, 19323, 19373, 19203, 19417,
19415, 19430, 19469, 19492, 19527, 19599, 20344, 19638, 19655,
19675, 19688, 20068, 19711, 19780, 19803, 19838, 19865, 19892,
19890, 19940, 19962, 20706, 20011, 18927, 20041, 18949, 20777,
20116, 20145, 19041, 20156, 20177, 20174, 20173, 20205, 20208,
20235, 20248, 20249, 19523, 20521, 20588, 20574, 20465, 20482,
19400, 20588, 21021, 20649, 20389, 20409, 19950, 19600, 19601,
20346, 19658, 20747, 19657, 19656, 19657, 20307, 20347, 19259,
20087, 20810, 20077, 19349, 20118, 20483, 20112, 20109, 19392,
19594, 20144, 21056, 19407, 20749, 20573, 19296, 19300, 19300,
19310, 20041, 19346, 20907, 19976, 20744, 20202, 19132, 19132,
19132), class = "Date"), Sym = structure(c(4L, 3L, 4L, 1L, 2L,
3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 3L, 4L, 3L, 4L, 1L, 4L, 3L, 2L, 1L, 4L, 1L, 2L, 1L, 2L,
1L, 2L, 3L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 3L, 4L, 3L, 2L,
1L, 4L, 1L, 4L, 1L, 2L, 1L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 1L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 3L, 4L, 3L, 2L, 1L, 2L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L, 3L, 4L,
3L, 4L, 3L, 4L, 3L, 2L, 1L, 2L, 3L, 4L, 3L, 4L, 3L, 2L, 3L, 4L,
3L, 4L, 1L, 2L, 1L, 2L, 1L, 2L, 3L, 4L, 4L, 4L, 4L), .Label = c("Axe",
"Axe, Owned", "None", "Owned"), class = "factor"), YVal = c(20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68,
69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100,
101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113,
114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126,
127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139,
140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152,
153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165,
166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178,
179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204,
205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217,
218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229)), class = "data.frame", row.names = c(NA,
-210L))

A: Maybe is this what you are looking for? (I have used split from plotly):
library(plotly)
#Code
plot_ly(data = bData,  x = ~`Maturity Date`, y =  ~YVal,  type = 'scatter', mode='markers',
        symbol = ~Sym,  symbols = c('circle-open','x-open','diamond-open','square-open') ,
        split = ~Crncy,
        text = ~paste(bData$Security,bData$Crncy, bData$YTM, bData$DM,sep = "
") ,
        hoverinfo = 'text')

Output:

Update: Here somo other options for OP:
#Option 1
plot_ly(data = bData,  x = ~`Maturity Date`, y =  ~YVal,  type = 'scatter', mode='markers',
        symbol = ~Sym,  symbols = c('circle-open','x-open','diamond-open','square-open') ,
        text = ~paste(bData$Security,bData$Crncy, bData$YTM, bData$DM,sep = "
") ,
        hoverinfo = 'text',legendgroup = 'group1'
) %>%
  add_trace(x = ~`Maturity Date`, y =  ~YVal , symbol=~Crncy,legendgroup = 'group2')

Output:

Option 2:
#Option 2
plot_ly(bData, x = ~`Maturity Date`, y =  ~YVal,  type = 'scatter', mode='markers',
               legendgroup = 'group1',color = ~Sym) %>%
  add_trace(y = ~YVal, legendgroup = 'group2',type = 'scatter', mode='markers',
            color=~Crncy)

Output:


Q: define parameter in update query in python psycopg2 This my python code which is used to perform update operation from reading the csv file. I tried with this also. It doesn't work out.
for i  in cin:
    try:
        conn=psycopg2.connect("dbname=pharmaflare user=postgres")
        cursor=conn.cursor()
        cursor.execute("UPDATE pharmaflare_drug_interaction SET se_interaction ='%s' WHERE primary_drug ='%s' AND secondary_drug ='%s' AND side_effect ='%s'"%(i[3],i[0],i[1],i[2]))
        conn.commit()
        cursor.close()
        conn.close()
        #print "done",i[0],i[1],i[2],i[3]
    except Exception as e:
        cerr.writerow(i)
        ferr.flush()
        traceback.print_exc(file=sys.stdout)
        continue

Here I am facing the exception like syntax error due to the QUOTE's problem:
Wherever the single quotes presents this exception arises.
  Traceback (most recent call last):
  File "<ipython console>", line 5, in <module>
  ProgrammingError: syntax error at or near "S"
  LINE 1: ...secondary_drug ='NEUER' AND side_effect ='MENIERE'S DISEASE'

Is there any alternative way available to define query statement without troubling the Quotes problem?

A: There are a couple ways to solve it. The easy/hack way to do it is to employ the re.escape() function. That function can be thought of as an equivalent to PHP's addslashes() function, though it pains me to make that comparison.
Having said that, my reading indicates psycopg2 takes advantage of PEP 249. If that's true, then you should be able to pass in parameterized queries and have it escape them for you.