text:
Q: javascript to render form rails 4.0 I am trying to use JavaScript to render a form. I want to click a link that will add a New Link form below. The New Link form is contained in my links/new.html.erb file.
Below is my "Show" page where I have a link to render a "New Link" form.

Links

  <%= render @opportunity.links %>

<%= link_to "Add URL", new_opportunity_link_path(@opportunity, :format => :js), :remote =>     true, :id => 'new_link_link' %>

Below is my views/links/new.js.erb file
    $("<%= escape_javascript render(file: 'links/new.html.erb') %>").insertAfter('#links');
    $('#new_link').hide().slideDown();
    $('#new_link_link').hide();

For some reason, when I click the link I made, a new form does not appear. This code is copied and modified from Beginning Rails 4 by Gamble, Carneiro, and Al Barazi.


text:
Q: pandas to_csv alters data by adding \n line break or Storing numpy arrays in dataframe cell I am generating a pandas dataframe with some data (some are numpy arrays) and saving the data with the pandas.to_csv function.
However, when reading the csv file to a dataframe again with pandas.read_csv I notice that pandas added line breaks within the numpy array like so (see last output)
import pandas as pd
import numpy as np

# In[34]:
# create the dataframe
d = {'col1': [1, 2], 'col2': [3, 4]}
df=pd.DataFrame(data=d)
df.head()

Out:

   col1  col2
0   1   3
1   2   4

# In[35]:
# append array data to dataframe
data = np.array([])
data = np.zeros(512)
df = df.append({'col1' : data },  ignore_index=True)
df.head()

# In[37]:
# write to csv
df.to_csv('records.csv')

#read csv
df= pd.read_csv('records.csv')
df.head()

# In[40]:
array = df['col1'].values
print(array)

Out[]:
 ['1' '2'
 '[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0.]']
Any ideas of how to fix this or why is this happening?
ps. thanks for the comments I included an example that replicates the issue and re-phrased the question since it seems that as commented what I want to do is to store a numpy array in a data frame cell.

A: This is how we resolved the issue.
array_list = np.array([])
for i in array:
    data_tmp = np.fromstring(i[1:-1],dtype=np.float,sep=' ')
    array_list = np.concatenate([array_list, data_tmp])
array_list = array_list.reshape((1,-1))

print(array_list)

[OUT]
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
  0. 0. 0. 0. 0. 0. 0. 0.]]

A: You can now use numpy.printoptions with NumPy >= 1.15 [link]
Code:
import numpy as np
import pandas as pd

df = pd.DataFrame([{'name': 'test', 'value': np.random.rand(10)}])

df.to_csv('to_csv_wo_printoption.csv')

with np.printoptions(linewidth=10000):
    df.to_csv('to_csv_w_printoption.csv')

Result without the print option
,name,value
0,test,"[0.73211706 0.3526481  0.8835388  0.97391453 0.48252462 0.82451648
 0.19150101 0.32714367 0.13065582 0.93367579]"

Result with the print option
,name,value
0,test,[0.73211706 0.3526481  0.8835388  0.97391453 0.48252462 0.82451648 0.19150101 0.32714367 0.13065582 0.93367579]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linking on Solaris with Developer Studio 12.5 I am experiencing some problems linking on Solaris 11.3 using Developer Studio 12.5.
The code appears to compile fine, but fails at the link stage:
CC  -o bin/libBlah.so -mt -G -z defs -fast -s -KPIC -xarch=generic \
-M mapfiles/solaris.map -library=stlport4 -staticlib=stlport4  \
<my .o files> <some boost .a libs> <openssl .a libs> \
-lCrun -lsocket -lnsl -lposix4 -lc -lm -lw -ldl

Undefined                       first referenced
symbol                             in file
void __Crun::ex_end_init()        obj/Blah.o
void __Crun::ex_start_init()      obj/Blah.o
ld: fatal: symbol referencing errors
gmake: *** [bin/libBlah.so] Error 2

If I remove the '-z defs' from the command line (link options), it will link fine.  Running 'ldd libBlah.so' does not show any missing references.
A colleague used 'nm' to locate the symbols, which were only found in the static libCrun libs (not the shared libs):
# nm /opt/developerstudio12.5/lib/compilers/libCrun.so | grep ex_end_init
# nm /opt/developerstudio12.5/lib/compilers/libCrun.a | grep ex_end_init
00000340 T __1cG__CrunLex_end_init6F_v_

The manual advises using '-zdefs' to point out missing symbols, which we had done previously (makefile already had that flag), so, I am at a loss to explain what I am seeing.
Question is simply: What should I make of this and what should I do about it?


text:
Q: Syntax error: Non-UTF-8 code starting with '\xe1" Technically:

I just want to use "Dash" by "plotly", "getting started" example (https://plot.ly/dash/getting-started), but I cannot. Any assumptions?
I cannot define the error more then it is in title.
(I do not want to feed you with inaccurate assumptions. Thank you for possible answer :) )

A: Your text editor has not saved the file as UTF-8, so Python can't read the file.
You have 3 options:

*

*Change the first line to use the correct codec. It probably is Windows Codepage 1252, given that you are using Windows and the é character is encoded as 0xE1 in that codec:
# -*- coding: cp1252 -*-

*Use a text editor that lets you specify the encoding to be used when saving, like Notepad++ or Sublime Text or Visual Studio, and make sure the file is actually saved as UTF-8.

*Use only ASCII codepoints in the file; the u'Montréal' value can also be specified using an \xhh or \uhhhh escape sequence for the é character:
u'Montr\u00e9al'

A: Error was actually because of the name of my computer.
It was named "Timemachine×2", however "×" (not "x") was not an unicode character.
So I simply renamed my computer to Timemachine2 and it started to work fine.
Error was not related to the code itself.


text:
Q: TimeType ARRIVAL not working in Android SDK I want my users to be able to switch between departure and arrival time. But when I send a routeplan request with TimeType.ARRIVAL in the routeOptions.setTime it gives me an INVALID_PARAMETERS error. But the exact same request with TimeType.DEPARTURE works fine.
Below is my code. Did I do something wrong or is TimeType.ARRIVAL deprecated or just not working?
   RoutePlan routePlan = new RoutePlan();

    RouteOptions routeOptions = new RouteOptions();
    routeOptions.setTransportMode(RouteOptions.TransportMode.PUBLIC_TRANSPORT);
    routeOptions.setRouteType(RouteOptions.Type.FASTEST);
    routeOptions.setRouteCount(3);
    routeOptions.setLocale(Locale.getDefault());
    if (toggleSwitch.getCheckedTogglePosition() == 0) {
        routeOptions.setTime(selected_time, RouteOptions.TimeType.DEPARTURE);
    }
    else {
        routeOptions.setTime(selected_time, RouteOptions.TimeType.ARRIVAL);
    }
    routePlan.setRouteOptions(routeOptions);

    // Select Waypoints for your routes
    routePlan.addWaypoint(new RouteWaypoint(start_address_coordinate));
    routePlan.addWaypoint(new RouteWaypoint(end_address_coordinate));
    router.calculateRoute(routePlan, new RouterListener());

A: As per the HERE documentation:

ARRIVAL time type option is supported only for UMRouteOptions. Using this value in RouteOptions.setTime(Date, TimeType), with unsupported RouteOptions, will result in RoutingError.INVALID_PARAMETERS when requesting a route.

So, the error you are getting is an expected behaviour. Please correct your code as per the HERE documentation.


text:
Q: Add image as attachment link in Post topic I have to add image as attachment in post in wordpress. Currently image is set as a part of Post content but i have to display a attachment link in post so users can download that image via attachment link.
Thank you,

A: If you will always have only ONE image - it will be better to set it as "featured image" and then :
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'your-image-size' )

then
echo $image[0] ;is your link

full code :
<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' ); ?>
<a href='<?php echo $image[0]; ?>'> my image link </a>

if you do not want to use featured image - the next function will get you always the FIRST image in a post
// Get URL of first image in a post

function postimage( $echo = true ) {
    $image = get_children( array(
        'post_parent' => get_the_ID(),
        'post_type' => 'attachment',
        'numberposts' => 1,
        'order' => 'asc',
        'orderby' => 'ID',
        'post_mime_type' => 'image',
    ) );
    $image_url = ( $image ) ? wp_get_attachment_url( current($image)->ID ) : "No Image";
    if( $echo )
        echo $image_url;
    else
        return $image_url;
}

if you have more than one image the thing gets a little more complicated - and you will have to search for all attachments and loop through the array . (change 'numberposts' => -1,  to get all)


text:
Q: Pass Dynamic Values from one function to another function in class Hi all i have a function in a class which will print all the variable pass for this function
Class Code :
<?php
 class MyPrintClass {
   public function printVaraible() {
     var_dump(func_get_args())
   }
 }

 $printVar = new MyPrintClass;
?>

if i use like below its correctly working and printing all the values pass.
$print->printVaraible('value1','Value2',20);

The output i got for above cmd
array (size=1)
  0 => string 'value1' (length=6)
  1 => string 'value2' (length=6)
  2 => string 'value3' (length=6)

if i use like blow its showing as a single array.. i want the value seperated.. how its possible ?
function getVal(){
  global $printVar;
  $print->printVaraible(func_get_args());
}

I need to pass the value like below
getVal('value1','Value2',20);

and i need the output as
array (size=1)
  0 => string 'value1' (length=6)
  1 => string 'value2' (length=6)
  2 => string 'value3' (length=6)

Currently i get NULL as the output
Updated Question Based On the Answer Given By deceze
** I Also had a small change in my code**
Class Code :
<?php
  class MyPrintClass {
    public function printVaraible($tag,$value) {
      echo $tag.' == '.$value;
      var_dump(func_get_args());
    }
  }

  $printVar = new MyPrintClass;
?>

Converted Class To Function By
<?php
function getVal($tag,$value) {
 global $printVar;
 call_user_func_array([$printVar, 'printVariable'], $tag,$value,func_get_args());
}

?>
If i try to use it as below i get error
<?php getVal('first','second','third,'fourth'); ?>

Warning: call_user_func_array() expects exactly 2 parameters, 4 given

A: call_user_func_array([$print, 'printVariable'], func_get_args());

This calls the function with separate parameters from an array. I'd question the usefulness of this though, since you'll just end up with an array from func_get_args anyway. Why not pass arrays around in the first place?

A: Your getting null in the return because you never return anything, from the functions above.
if you want to call a class method I suggest you look into Refection or you can also do
$a = 'printVaraible';

$class->$a(1,3); //

besides using call_user_func_array, I would also suggest looking into closures (php > 5.3 ), which will let you write them this way.
$a = function foo(){ echo 'foo'};
$a();

Last thing I would generally avoid using global, as it obscures in your code where the values come from.  It is always better to inject values into the function scope and not mix that with the global, imaging hunting that global down in a large project, I just avoid them at all cost and forget they exist.


text:
Q: Solve for constants: Derivatives using first principles
*

*Question
Find the values of the constants $a$ and $b$ such that $$\lim_{x \to 0}\frac{\sqrt[3]{ax + b}-2}{x} = \frac{5}{12}$$

*

*My approach

*

*Using the definition of the derivative, $$f'(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}$$

*I view limit as a derivative of a function $f$ at some value, let's call that value $c$, as follows :$$f'(c) = \lim_{x\to 0}\frac{f(c + x) - f(c)}{x} = \frac{\sqrt[3]{ax + b} - 2}{x} = \frac{5}{12}$$

*Now I deduce the following: $$f(c + x)  = \sqrt[3]{ax + b}$$ and $$f(c) = 2$$

*Use limits as follows: $$\lim_{x\to 0} f(c + x) = f(c) = 2$$ that is, $$\lim_{x\to 0} f(c + x) = \lim_{x\to 0} \sqrt[3]{ax + b} = \sqrt[3]{b} = 2$$ now solve for $b$, $$\sqrt[3]{b} = 2 \Leftrightarrow b = 8$$

*Since I know that $$f(c + x) = \sqrt[3]{ax + 8}$$, I can solve for $a$, which is $$a = \frac{[f(c+x)]^3 - 8}{x} = \frac{[f(c+x)]^3 - [f(c)]^3}{x}$$

*Let $g(x) = [f(x)]^3$, such that $$g'(x) = 3\cdot [f(x)]^2 \cdot f'(x)$$
so $$g'(c) = 3\cdot [f(c)]^2 \cdot f'(c) = 3 \cdot 4 \cdot \frac{5}{12} = 5$$

*Rephrase $g'(c)$ using first principles such that $$g'(c) = \lim_{x \to 0}\frac{g(c + x)- g(c)}{x}= \lim_{x \to 0}\frac{[f(c + x)]^3 - [f(c)]^3}{x} = \lim_{x \to 0} a = 5$$

*Since $a$ is a constant, $\lim_{x \to 0} a = a$, that is, $$a = 5$$

*My solution: $b = 8, a = 5$.

Please have a look at my approach and give me any hints/suggestions regarding the solution and/or steps taken.

A: It is fine. However, there is a short proof if you know this

$(1+x)^\frac1n=1+\frac1nx+o(x)$, where $\lim_{x\to 0}\frac{o(x)}{x}=0.$

So $$\lim_{x \to 0}\frac{\sqrt[3]{ax + b}-2}{x} = \lim_{x \to 0}\frac{b^\frac13 \sqrt[3]{\frac a bx + 1}-2}{x}=\lim_{x \to 0}\frac{(b^\frac13-2)+  \frac13 b^\frac13 \frac abx+b^\frac13o(x)}{x}=\frac{5}{12}.$$
So, $b^\frac13-2=0$ and $\frac13 b^\frac13 \frac ab=\frac{5}{12}$.

A: Your approach looks fine, and it is explained well.  Here is a variant of your solution, that uses similar ideas:
1) $\displaystyle\lim_{x\to0}(\sqrt[3]{ax+b}-2)=\lim_{x\to0}\bigg(\frac{\sqrt[3]{ax+b}-2}{x}\cdot x\bigg)=\frac{5}{12}\cdot 0=0,\;\;\;$ so $\sqrt[3]{b}=2$ and $b=8$.
2) Let $g(x)=\sqrt[3]{ax+8}.\;\;\;$  Then $\displaystyle g^{\prime}(0)=\lim_{x\to0}\frac{g(x)-g(0)}{x-0}=\frac{\sqrt[3]{ax+8}-2}{x}=\frac{5}{12}$,
so $g^{\prime}(x)=\frac{1}{3}(ax+8)^{-2/3}\cdot a\implies\frac{1}{3}\cdot\frac{1}{4}a=\frac{5}{12}\implies a=5$.

A: Using
$$ a^3-b^3=(a-b)(a^2+ab+b^2, $$
one has
\begin{eqnarray}
\lim_{x \to 0}\frac{\sqrt[3]{ax + b}-2}{x} = \lim_{x \to 0}\frac{ax+b-8}{x[(\sqrt[3]{ax + b})^2+2\sqrt[3]{ax + b}+4]}.
\end{eqnarray}
Thus if the limit exists, one must have $b=8$, under which it is easy to get
\begin{eqnarray}
\lim_{x \to 0}\frac{\sqrt[3]{ax + b}-2}{x} &=& \lim_{x \to 0}\frac{ax+b-8}{x[(\sqrt[3]{ax + b})^2+2\sqrt[3]{ax + b}+4]}\\
&=&\frac{a}{[(\sqrt[3]{8})^2+2\sqrt[3]{8}+4]}=\frac{a}{12}.
\end{eqnarray}
Thus $a=5$.


text:
Q: Under what circumstances do ZeroMQ sockets drop or fail to deliver messages? Is there some sort of a specification or other explanation that describes the normal cases where you can expect a message sent on a ZeroMQ socket to not be received by ( all ) the listening processes, for each communication type?
For example I have an experimental program which basically assumes that all subscribers to a PUB socket receive all messages sent on that socket ( after an initialization handshake ).  I would like to understand the cases where that assumption may be false.  Thanks, and sorry if this has already been asked.

A: The chart in this image is a good guide to when zmq sockets drop messages: https://raw.github.com/imatix/zguide/master/images/fig25.png
For more information, you might want to read http://zguide.zeromq.org/py:all#Missing-Message-Problem-Solver


text:
Q: Multi-dimensional points in PostGIS I have experience in PostgreSQL but I am fresh new in PostGIS and I can see how quickly would I like it. I have extensively worked on time series and now I am discovering the spatial side of my data. I have installed PostGIS on my server and then I am wondering how to anwser tons of questions. Thus I am in the prospective part of my work and I have everything to learn.
Anyway, I would like to have some clues from GIS expert in order to take the good start. Basically, I am monitoring concentrations at constant places, but we also have some campaigns where we monitor concentrations when we are in motion. That is, we have, at least, a five dimension problem, spatial and time is tracked down by GPS and another dimensions are assessed by dedicated monitors.
I know that PostGIS have a multipoint object, but all example that I have seen on the web are limited to 4D. Is it possible to use this structure to store multiple concentrations in addition of space and time. If so, is there a simple way to get rid of extra dimensions such as concentrations and time, when we are just working on space? If I want to post process my data with QGIS, will I be able to use such structure?

A:
I know that PostGIS have a multipoint object, but all example that I have seen on the web are limited to 4D. Is it possible to use this structure to store multiple concentrations in addition of space and time. If so, is there a simple way to get rid of extra dimensions such as concentrations and time, when we are just working on space? If I want to post process my data with QGIS, will I be able to use such structure?

PostGIS supports up to four dimensions (x,y,z,m). That is all. I suggest never using m. Instead, store these attributes on the table instead.
However, if you want to do this with PostgreSQL and not PostGIS this answer may be of use.. Or at the least entertaining.

A: In GIS, there is a concept for POINT, LINE and POLYGON (in a vector sense). There's no concept of LINE MADE OF POINTS, or SEQUENTIAL MULTI-POINT.
A multi-point dataset is simply many points grouped together with one set of attribute for the group.
For what you want to do, I think you just want to have something like:
id, station_id, datetime, geometry, observation_1, observation_2

If you want to display them together, you can style them by station_id, perhaps. You can also create a view that joins them into lines, to view a track, if that makes sense.
There is also a plugin for QGIS that does time-series visualisation (it does a real-time select based on a datetime range as you move a slider).


text:
Q: ECS Fargate Public IP connection refused I have a docker container that is being hosted on ECS via Fargate. The Docker container itself is in ECR. In ECS, I have a task definition that uses the image in ECR and also has a port mapping on port 80 (the port the docker image is running on). I also have a Service defined in the ECS Fargate cluster used to use the Task Definition of this image. When creating the service a new security group is created that allows all traffic from port 80(HTTP). So essentially any kind of HTTP traffic should be able to access this image using the public IP generated via the Service. For some reason, when accessing the public IP whether incognito or not, I am getting "This site can't be reached. ERR_CONNECTION_REFUSED
I have verified countless times the security group is open to allow any HTTP traffic and have also ensured the public subnet has an Internet Gateway to allow the internet. Any advice would be appreciated. Below is the Dockerfile I am using to create this image.
Dockerfile
FROM nginx:mainline-alpine
RUN rm /etc/nginx/conf.d/*
ADD hello.conf /etc/nginx/conf.d/
ADD index.html /usr/share/nginx/html/
CMD tail -f /dev/null

Update
I've tried to run this image locally on my machine and am getting the same error.

A: You've forgot to EXPOSE the port in the Dockerfile.
FROM nginx:mainline-alpine
RUN rm /etc/nginx/conf.d/*
ADD hello.conf /etc/nginx/conf.d/
ADD index.html /usr/share/nginx/html/
EXPOSE 80
CMD tail -f /dev/null

https://docs.docker.com/engine/reference/builder/#expose


text:
Q: Dynamic "Scoping" of C# Checked Expression Is it possible (in C#) to cause a checked(...) expression to have dynamic "scope" for the overflow checking? In other words, in the following example:
int add(int a, int b)
{
    return a + b;
}
void test()
{
    int max = int.MaxValue;
    int with_call = checked(add(max, 1)); // does NOT cause OverflowException
    int without_call = checked(max + 1);  // DOES cause OverflowException
}

because in the expression checked(add(max, 1)), a function call causes the overflow, no OverflowException is thrown, even though there is an overflow during the dynamic extent of the checked(...) expression.
Is there any way to cause both ways to evaluate int.MaxValue + 1 to throw an OverflowException?
EDIT: Well, either tell me if there is a way, or give me a better way to do this (please).
The reason I think I need this is because I have code like:
void do_op(int a, int b, Action<int, int> forSmallInts, Action<long, long> forBigInts)
{
    try
    {
        checked(forSmallInts(a, b));
    }
    catch (OverflowException)
    {
        forBigInts((long)a, (long)b);
    }
}
...
do_op(n1, n2,
    (int a, int b) => Console.WriteLine("int: " + (a + b)),
    (long a, long b) => Console.WriteLine("long: " + (a + b)));

I want this to print int: ... if a + b is in the int range, and long: ... if the small-integer addition overflows. Is there a way to do this that is better than simply changing every single Action (of which I have many)?

A: To be short, no it is not possible for checked blocks or expressions to have dynamic scope.
If you want to apply this in the entirety of your code base you should look to adding it to your compiler options.
Checked expressions or checked blocks should be used where the operation is actually happening.
    int add(int a, int b)
    {
        int returnValue = 0;

        try
        {
            returnValue = checked(a + b);
        }
        catch(System.OverflowException ex)
        {
            //TODO: Do something with exception or rethrow
        }

        return returnValue;
    }

    void test()
    {
        int max = int.MaxValue;
        int with_call = add(max, 1);
    }

A: You shouldn't catch exceptions as part of the natural flow of your program. Instead, you should anticipate the problem. There are quite a few ways you can do this, but assuming you just care about int and long and when the addition overflows:
EDIT: Using the types you mention below in your comment instead of int and long:
void Add(RFSmallInt a, RFSmallInt b)
{
    RFBigInt result = new RFBigInt(a) + new RFBigInt(b);
    Console.WriteLine(
        (result > RFSmallInt.MaxValue ? "RFBigInt: " : "RFSmallInt: ") + result);
}

This makes an assumption that you have a constructor for RFBigInt that promotes a RFSmallInt. This should be trivial as BigInteger has that same for long. There is also an explicit cast from BigInteger to long that you can use to "demote" the value if it is does not overflow.

A: An exception should be an exception, not the usual program flow. But lets not care about that for now :)
The direct answer to you question I believe is no, but you can always work yourself around the problem. I'm posting a small part of some of the ninja stuff I made when implementing unbounded integers (in effect a linked list of integers) which could help you.
This is a very simplistic approach for doing checked addition manually if performance is not an issue. Is quite nice if you can overload the operators of the types, ie you control the types.
public static int SafeAdd(int left, int right)
{
if (left == 0 || right == 0 || left < 0 && right > 0 || right < 0 && left > 0)
    // One is 0 or they are both on different sides of 0
    return left + right;
else if (right > 0 && left > 0 && int.MaxValue - right > left)
    // More than 0 and ok
    return left + right;
else if (right < 0 && left < 0 && int.MinValue - right < left)
    // Less than 0 and ok
    return left + right;
else
    throw new OverflowException();
}

Example with your own types:
public struct MyNumber
{
  public MyNumber(int value) { n = value; }

  public int n; // the value

  public static MyNumber operator +(MyNumber left, MyNumber right)
  {
    if (left == 0 || right == 0 || left < 0 && right > 0 || right < 0 && left > 0)
      // One is 0 or they are both on different sides of 0
      return new MyNumber(left.n + right.n); // int addition
    else if (right > 0 && left > 0 && int.MaxValue - right > left)
      // More than 0 and ok
      return new MyNumber(left.n + right.n); // int addition
    else if (right < 0 && left < 0 && int.MinValue - right < left)
      // Less than 0 and ok
      return new MyNumber(left.n + right.n); // int addition
    else
      throw new OverflowException();
  }

  // I'm lazy, you should define your own comparisons really
  public static implicit operator int(MyNumber number) { return number.n; }
}

As I stated earlier, you will lose performance, but gain the exceptions.

A: You could use Expression Tree & modify it to introduce Checked for math operator & execute it. This sample is not compiled and tested, you will have to tweak it little more.
   void  CheckedOp (int a, int b, Expression <Action <int, int>> small, Action <int, int> big){
         var smallFunc = InjectChecked (small);
         try{
               smallFunc(a, b);
         }catch (OverflowException oe){
               big(a,b);
         }
   }

   Action<int, int> InjectChecked( Expression<Action<int, int>> exp )
   {
          var v = new CheckedNodeVisitor() ;
          var r = v.Visit ( exp.Body);
          return ((Expression<Action<int, int>> exp) Expression.Lambda (r, r. Parameters) ). Compile() ;
   }

   class CheckedNodeVisitor : ExpressionVisitor {

           public CheckedNodeVisitor() {
           }

           protected override Expression VisitBinary( BinaryExpression be ) {
                  switch(be.NodeType){
                        case ExpressionType.Add:
                                return Expression.AddChecked( be.Left, be.Right);
                  }
                  return be;
           }
   }


text:
Q: Set On End Edit Event from a Input Box (Text Mesh Pro) while runtime I am programming a game in Unity, but I have problems with the On End Edit Event on a Input box from Text Mesh Pro. I need to define the event while runtime (in code). I have really no idea how to approch this.
Here is a picture from the event in the editor and I want it to connect to the PressedButton Method in the class PlayerConnectionManager:

Thaks for any kind of help!

A: I'm assuming that you need to call the PlayerConnectionManager.PressedButton at runtime and not via editor. If that's the case its quite easy. You just have to use addlistener. Here is a snippet.
public class TextMeshAdd : MonoBehaviour
{
    //input field object
    public TMP_InputField tmpInputField;

    // Use this for initialization
    void Start ()
    {
        //Add a listener function here
        //Note: The function has to be of the type with parameter string
        tmpInputField.onEndEdit.AddListener(TextMeshUpdated);
    }

    public void TextMeshUpdated(string text)
    {
        Debug.Log("Output string "  + text);
    }
}

Remember the function you are giving it should have a parameter with string. ie
PlayerConnectionManager.PressedButton should be of similer type mentioned above TextMeshUpdated(string text). This will allow it callback the function on end at runtime.
Another thing you have to keep in mind is that if you are using the inputfield in some other place make sure to remove the old listener before adding new listener.
You can do it by using this
    tmpInputField.onEndEdit.RemoveListener(TextMeshUpdated);
or
    tmpInputField.onEndEdit.RemoveAllListeners();
The first method will remove only specific function callback while RemoveAllListeners will remove all event listeners attached to the callback. If you dont do this and try to assign new callback it will try to call old functions, and possibly might throw some errors.


text:
Q: Как сделать рейтинг в игре? Есть игра "Найди элементы на картинке" есть две разных картинки,где нужно искать элементы.
Получается что нужно как то сделать рейтинг,но у меня не получается
Суть такова: у меня не получается посчитать их время прохождения (у таймера обратный отсчет,т.е. с 3-х минут). И тут есть проблемы. Нужно как то посчитать за какое время они нашли все предметы
и нужно запоминать каждую игру! (чтобы потом в дальнейшем выводить результат каждой игры)
Вот код всего процесса:
public Form3()
    {
        InitializeComponent();
        objects = new List<MapObject>();

        objects.Add(new MapObject()
        {
            Name = "Парусник",
            X = 180,
            Y = 34,
            Width = 27,
            Height = 37
        });

        objects.Add(new MapObject()
        {
            Name = "Пароход",
            X = 304,
            Y = 20,
            Width = 49,
            Height = 19
        });

        objects.Add(new MapObject()
        {
            Name = "Кактус",
            X = 369,
            Y = 127,
            Width = 11,
            Height = 20
        });

        objects.Add(new MapObject()
        {
            Name = "Лошадь",
            X = 336,
            Y = 80,
            Width = 18,
            Height = 18
        });

        objects.Add(new MapObject()
        {
            Name = "Дирижер",
            X = 228,
            Y = 156,
            Width = 17,
            Height = 19
        });

        objects.Add(new MapObject()
        {
            Name = "Мяч",
            X = 213,
            Y = 261,
            Width = 20,
            Height = 20
        });

    }

List<MapObject> objects;
private void Timer1_Tick(object sender, EventArgs e)
    {
        tk = --i;
        TimeSpan span = TimeSpan.FromSeconds(tk);
        string label = span.ToString(@"mm\:ss");
        label1.Text = label.ToString();
        if (i <= 0)
        {
            label9.Visible = true;
            label1.Visible = false;
            timer1.Stop();
            pictureBox1.Visible = false;
            pictureBox2.Visible = true;

        }

    }
int i;
int tk;
string c;
private void Button2_Click(object sender, EventArgs e)
    {
        button2.Visible = false;
        pictureBox1.Visible = true;
        i = 180;
        c = "3:00";

        label1.Text = c;
        timer1.Interval = 1000;
        timer1.Enabled = true;
        timer1.Start();
    }
private void PictureBox1_MouseClick(object sender, MouseEventArgs e)
    {
        int currentX = e.X;
        int currentY = e.Y;
        bool FindSome = false;
        for (int i = 0; i < objects.Count; i++)
        {
            if (currentX > (objects[i].X - objects[i].Width / 2) & currentX < (objects[i].X + objects[i].Width / 2)
            & currentY > (objects[i].Y - objects[i].Height / 2) & currentY < (objects[i].Y + objects[i].Height / 2))
            {
                MessageBox.Show("Вы нашли слово : " + objects[i].Name);
                objects[i].IsClicked = true;
                FindSome = true;
            }

        }

        if (!FindSome) TimeDec();

        if (IsAllClicked())
        {
            label8.Visible = true;
            label1.Visible = false;
            timer1.Stop();
            pictureBox1.Visible = false;
            pictureBox2.Visible = false;
        }
    }

private void TimeDec()
    {
        MessageBox.Show("Никуда не попали");

        i -= 5;

    }

private bool IsAllClicked()
    {
        bool AllObjectsClicked = true;
        foreach (MapObject item in objects)
        {
            if (!item.IsClicked)
            {
                AllObjectsClicked = false; break;
            }
        }
        return AllObjectsClicked;
    }

Вот код из класса(mapobject):
class MapObject
{
    public string Name;

    public int X;
    public int Y;

    public int Width;
    public int Height;
    public bool IsClicked = false;
}

A: Ну вот в коде место, где игрок нашел все предметы.
if (IsAllClicked())
        {
            ...

Сюда и будем добавлять логику сохранения рекорда. Эту логику я предлагаю вынести в отдельный метод, например, SaveRecord:
if (IsAllClicked())
{
    SaveRecord();
    ...

В этом методе будут все расчеты и сохранение.

Нужно как то посчитать за какое время они нашли все предметы

Это можно сделать на основе того сколько времени осталось (i):
public void SaveRecord()
{
    int timeInSeconds = 180 - i;

Пара моментов:

*

*дайте переменной более говорящее название например timeLeft;

*объявите константу для общей длины игры, чтобы не писать каждый раз 180;

*Timer к сожалению не гарантирует точность отсчета. Пока он, наверное, Вам подойдет, но готовьтесь тому что замер времени с секундомером не будет сходится с таймером Вашей игры. Если в будущем понадобятся более точные измерения посмотрите в сторону Stopwatch.

и нужно запоминать каждую игру! (чтобы потом в дальнейшем выводить результат каждой игры)

Для этого я бы создал специальный класс для хранения одного рекорда:
public class Record
{
//пользователь, установивший рекорд
public string Username {get; set;}
//время в секундах
public int TimeInSeconds {get; set;}
}

Теперь можно хранить список рекордов и в методе SaveRecord создать новый рекорд и добавить его в список:
private List<Record> records = new List<Record>();

public void SaveRecord()
{
    var record = new Record();
    record.TimeInSeconds = 180 - i;
    records.Add(record);
}

Примерно такое начало. Для наглядности можете выводить сообщение о времени в MessageBox. Далее осталось добавить остальные части условия:

*

*Сортируйте список рекордов и вставляйте рекорд на нужное место.

*Удаляйте «лишние» рекорды (если нужно отображать только ограниченное количество).

*Запрашивайте у пользователя имя и проставляйте его в записи о рекорде.

*Выводите рекорды в отдельной форме.

*Сохраняйте рекорды в файл/настройки/БД и считывайте их оттуда.

Попробуйте выполнять эти пункты по одному. Если что-то не получится, то Вы сможете задать более точные вопросы. В вопросы обязательно включайте свою попытку решения, подробно описывайте ее, расскажите что именно пошло не так. Так Вы быстрее получите ответ.
З.Ы. Вопросы вида «вот мой код допишите в него штуку» очень плохо подходят для обучения, т.к. отвечающие не понимают с чем именно у Вас возникают сложности и не знают что нужно объяснять. В результате в качестве ответа Вы можете получить код, который до конца не понимаете, и ничему при этом не научитесь.
О том, как облегчить задачу себе и окружающим: Если не знаете как написать/исправить код, то лучше не пишите его сразу в большом проекте. Вместо этого создайте новый проект, который будет выполнять только проблемную часть, и сконцентрируйтесь на ней. Если все получится, то у Вас будет код, который можно вставить в Вашу игру. Если не получится, то получится короткий пример, который можно будет опубликовать здесь как вопрос.
Например:

*

*Не знаете как посчитать время потраченное на игру? Напишите новый проект единственный смысл которого: посчитать время. В нем будет таймер, счетчик и кнопка, которая останавливает таймер.

*Не знаете как вставить новый рекорд в список? Напишите проект, который только и делает, что добавляет один готовый рекорд в один готовый список.

*Не знаете как спросить у пользователя имя? Напишите проект, который ничего не делает кроме как запрашивает имя пользователя.

*Не знаете как показать список рекордов в форме? Напишите проект, который показывает готовый список в форме.

*Не знаете как сохранять рекорды в файл? Напишите проект, который только и делает, что берет готовый список рекордов и записывает их в файл.
Так Вам легче будет разобраться в проблеме. Если в проекте 10 строк, то каждую из них можно разобрать досконально. Если в проекте нет лишнего кода, то меньше вероятность того что несколько разных ошибок «наложатся» друг на друга.
Если не разберетесь сами и захотите задать вопрос здесь, то с маленьким проектом это будет сделать гораздо легче. Не нужно будет рассказывать заново всю логику игры. Вопрос получится короче, будет лучше принят и получит больше ответов за более короткое время. Большинству отвечающих здесь не захотят дописывать за Вас игру, но при этом смогут быстро ответить на простой вопрос о стандартных классах.
Разумеется то, что эти проблемы маленькие по масштабу не означает что к ним нужно относится несерьезно. По каждому из этих вопросов нужно будет предварительно поискать информацию в интернете, попробовать несколько вариантов. При публикации вопроса обязательно нужно будет указать свою попытку.
В общем, разбивайте задачи на части и работайте с ними по одной.


text:
Q: Stop script in MySQL Workbench after error I just ran a script in MySQL Workbench 6.3 Community.
I've set it to 'Stop Script Execution on Errors'.
There were two queries that gave errors.
The errors say 'Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.'
Ok, so I missed that. No big deal.
But after that, the script simply continued as if there were no error at all, or as if I never set 'Stop Script Execution on Errors'.
As a consequence I've lost some data. (This was a test database, so no worries there.)
The script continues after the errors:

Any idea how to make it stop executing the script?

A: A colleague pointed me to Edit->Preferences, SQL Editor, SQL Execution, Continue SQL script execution on errors (by default).
Continue SQL script execution on errors (by default)
This worked after restarting Workbench.


text:
Q: Reading unusual .txt text format in pandas My question is really straight forward however I am not sure if pandas or any other library has a way of dealing with such issue. The problem is that I have a .txt file with format as bellow (including the text "This is the example..."). So, as I want to read multiple files with that format and keep appending then to one dataframe. Hence, I was wondering if there is a simple way to read it despite the uneven format without separation by commas or decimal separator.
Hope that I managed to be succinct and precise. I would really appreciate your help on this one! Suggestions of what to look up for are also welcome.
I utilized notepad C++ to open the file. I also uploaded the file here in case someone wants to test it.

A: You can treat it as a .csv file but using tabs (\t) as a delimiter opposed to commas.
pd.read_csv('txt_example.txt', sep='\t', skiprows=2) returns a beautiful dataframe for me!
Edit: as suggested below the header argument creates an even better output; we can make sure the second row is not seen as a data row:
df = pd.read_csv('txt_example.txt', sep='\t', skiprows=2, header=[0,1])
df.head()

Time    RtAxsXT1    RtAxsYT1    RtAxsZT1    RtPosXT1    RtPosYT1    RtPosZT1    YawErrT1    TIAmbT1 CtT1N01 ... WkDfVrT3N17D7   WkDfVrT3N18D7   WkDfVrT3N19D7   WkDfVrT3N20D7   W3VAmbX W3VAmbY W3VAmbZ W3VDisX W3VDisY W3VDisZ
(s) (-) (-) (-) (m) (m) (m) (deg)   (percent)   (-) ... (m/s)   (m/s)   (m/s)   (m/s)   (m/s)   (m/s)   (m/s)   (m/s)   (m/s)   (m/s)
0   0.0 0.9962  0.0 -0.08716    995.0   1000.0  90.0    0.3525  12.28   0.0 ... 0.0 0.0 0.0 0.0 5.902   -0.09767    -0.009375   5.684   -0.09767    0.00971
1   2.0 0.9962  0.0 -0.08716    995.0   1000.0  90.0    1.4390  12.17   0.0 ... 0.0 0.0 0.0 0.0 5.872   -0.16040    0.283000    5.653   -0.16210    0.30040
2   4.0 0.9962  0.0 -0.08716    995.0   1000.0  90.0    0.9589  12.00   0.0 ... 0.0 0.0 0.0 0.0 6.031   -0.11650    0.593000    5.812   -0.11820    0.61040
3   6.0 0.9962  0.0 -0.08716    995.0   1000.0  90.0    2.0930  11.96   0.0 ... 0.0 0.0 0.0 0.0 6.245   0.24430 0.733700    6.025   0.24260 0.75120
4   8.0 0.9962  0.0 -0.08716    995.0   1000.0  90.0    3.1810  12.12   0.0 ... 0.0 0.0 0.0 0.0 6.483   0.79060 0.681000    6.261   0.78890 0.69870
5 rows × 1069 columns


text:
Q: ASP.Net MVC SQLExpress Production Environment Update Scenario New to actually deploying a Asp.Net MVC web application with sqlexpress in the App_Data folder, how would I handle database updates after it is live and in use.
Here's my scenario and a few questions:
I have an Asp.Net MVC 2 Web app w/ sqlexpress databases: [myappData.mdf, aspnetdb.mdf]. I was planning on publishing this to the production server with the databases included in the App_Data folder.
Question 1
When my site is in use and users have added new data into the database and I have added some new features which require some structural database additions how would I handle publishing the new database files while keeping all the data that users have added to the database?
Question 2
Also once I start debugging my app locally I can't connect to it in sql management studio, I get a file in use error. So once it goes live on the production server and a user is having a problem can I not browse through the database using sql management studio?
Question 3
Right now I'm connecting to the db with the following web.config string, are there any issues with this in a production environment that will have sqlexpress installed?:
<add name="myAppDataEntities" connectionString="metadata=res://*/Models.MyData_DB.csdl|res://*/Models.MyData_DB.ssdl|res://*/Models.MyData_DB.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\myappData.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />

Thanks for any help in getting the hang of this.

A: These links may help you in this regard
http://www.asp.net/hosting/tutorials/strategies-for-database-development-and-deployment-cs
SQL Server 2005 - Syncing development/production databases
http://www.asp.net/hosting/tutorials/configuring-the-production-web-application-to-use-the-production-database-cs
This is paid solution to sync databses
http://www.red-gate.com/products/SQL_Comparison_SDK/case_studies/synchronizing_databases.htm


text:
Q: Функция на С для PostgreSQL Я написал функцию на С для PostgreSQL и начинаю собирать под систему с разной разрядностью (х86, х64). ОС - Windows 10. Вот краткий код
#include"postgres.h"
#include "fmgr.h"
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif

PG_FUNCTION_INFO_V1(add_one);

PGDLLEXPORT
Datum add_one(PG_FUNCTION_ARGS)
{...}

Когда я собираю для x86 у меня все проходит успешно. Когда я собираю для x64 появляется ошибка add_one redefinition; different linkage.
Для ликвидации этой ошибки я делаю так (данный код компилируется успешно и для х86)
#include"postgres.h"
#include "fmgr.h"
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif

PGDLLEXPORT Datum add_one(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(add_one);

Datum add_one(PG_FUNCTION_ARGS)
{...}

Если я поменяю порядок строк:
 PGDLLEXPORT Datum add_one(PG_FUNCTION_ARGS);
 PG_FUNCTION_INFO_V1(add_one);

На такой:
 PG_FUNCTION_INFO_V1(add_one);
 PGDLLEXPORT Datum add_one(PG_FUNCTION_ARGS);

То появляется та же ошибка.
Первый вопрос: почему для х86 платформы компилируется хорошо, а для х64 необходимо внести такие изменения.
Второй вопрос: если данный код я попробую собрать под Linux, мне нужно ли будет вносить изменения в сам код, так как PGDLLEXPORT это макроопределение для экспорта в винде.
Пишу в MSVC2017.

A: Макрос PGDLLEXPORT работает только под Windows (см. src/include/port/win32.h):
#ifdef _MSC_VER
#define PGDLLEXPORT __declspec (dllexport)
#else
#define PGDLLEXPORT
#endif
#else                           /* not CYGWIN, not MSVC, not MingW */
#define PGDLLIMPORT
#define PGDLLEXPORT
#endif

так что вреда при сборке под Linux он не принесёт.
Но вообще, если пишите кроссплатформенный код, то логичнее всего экспорт в MSVC сделать через *.def файл, а строку PGDLLEXPORT Datum add_one(PG_FUNCTION_ARGS); из исходников вообще убрать.


text:
Q: Interpret results Regression I made an ordinal regression model (first time performing regression, be merciful) and now I need to evaluate it. What would be the best way? (I use mord API for the ordinal regression)
These are the tasks I am trying to complete:

3) Build a regression model that will predict the rating score of each
  product based on attributes which correspond to some very common words
  used in the reviews (selection of how many words is left to you as a
  decision). So, for each product you will have a long(ish) vector of
  attributes based on how many times each word appears in reviews of
  this product. Your target variable is the rating. You will be judged
  on the process of building the model (regularization, subset
  selection, validation set, etc.) and not so much on the accuracy of
  the results.
4) Having the vectors from Question 3, perform
  dimensionality reduction (either PCA or NMF). Can you conclude how
  many components you can keep? Experiment with this parameter and
  justify your final conclusion.

This is my code for it:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import re
import textblob
import nltk
from pandas import ExcelWriter
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.stem.snowball import SnowballStemmer
from textblob import Word
from collections import Counter
import seaborn as sns
import mord as m
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

%matplotlib inline

df = # import dataframe from link

#Clean up Rating (whilst doing 'hand cleaning' I saw data outside of the [0,5] range; needs to be corrected; this could have been spotted by plotting the data on histogram but since I saw this while going throught the data I feel plotting it is an unnecessary step)
df.loc[df.Rating > 5, 'Rating'] = np.NaN
df.loc[df.Rating < 1, 'Rating'] = np.NaN

# Convert weights to same measure (pounds). Most of the weights I inspected seem wrong...

for i in range(0, df.weight.size-1):
    cell = df.weight[i]
    while (cell == 0 and i < df.weight.size-1):
        i += 1
        cell = df.weight[i]
    if not(isinstance(cell, float)) and  not(isinstance(cell, int)):
            number = ''.join([x for x in cell if (x.isdigit() or x=='.')])
            num = float(number)
            if bool(re.search('ounces', cell)):
                df.loc[i, 'weight'] = num * 0.0625    # Ounces to pounds conversion
            else:
                df.loc[i, 'weight'] = num            # Introduce only number (without measure type)

df.loc[:, "Review"] = df["Title"] + str(' - ') + df["Text"]
df.drop('Title', axis=1, inplace=True)
df.drop('Text', axis=1, inplace=True)
df.columns = ['Brand', 'Name', 'NumsHelpful', 'Rating', 'Weight(Pounds)', 'Review']
df['Weight(Pounds)'] = pd.to_numeric(df['Weight(Pounds)'], errors='coerce')
df['Brand'] = df['Brand'].astype(str)
df['Review'] = df['Review'].astype(str)
df['Name'] = df['Name'].astype(str)

d = {'Brand':'first',
     'NumsHelpful':'mean',
     'Rating':'mean',
     'Weight(Pounds)':'first',
     'Review':'/'.join,
    }
df = df.groupby('Name').agg(d).reset_index()

df.Rating = df.Rating.round()
df.NumsHelpful = df.NumsHelpful.round()

df['Review2'] = df['Review'].apply(lambda x: " ".join(x.lower() for x in x.split()))

df['Review2'] = df['Review2'].str.replace('[^\w\s]','')

stop = stopwords.words('english')
df['Review2'] = df['Review2'].apply(lambda x: " ".join(x for x in x.split() if x not in stop))

freq = pd.Series(' '.join(df['Review2']).split()).value_counts()[:20]

common = ['wine', 'mix', 'taste', 'drink', 'one', 'price', 'product', 'flavour', 'would', 'bitters', 'bottle', 'buy','really', 'make']
df['Review2'] = df['Review2'].apply(lambda x: " ".join(x for x in x.split() if x not in common))

freq = pd.Series(' '.join(df['Review2']).split()).value_counts()[-10:]

freq = list(freq.index)
df['Review2'] = df['Review2'].apply(lambda x: " ".join(x for x in x.split() if x not in freq))

df['words'] = df.Review2.str.strip().str.split('[\W_]+')

df['Review2'] = df['words'].apply(lambda x: " ".join([Word(word).lemmatize('v') for word in x]))

df['Review2'].str.split(expand=True).stack().value_counts()
# Create word matrix
bow = df.Review2.str.split().apply(pd.Series.value_counts)
rating = df['Rating']
df_rating = pd.DataFrame([rating])
df_rating = df_rating.transpose()
bow = bow.join(df_rating)

# Remove some columns and rows
bow = bow.loc[(bow['Rating'].notna()), ~(bow.sum(0) < 80)]

# Divide into train - validation - test
bow.fillna(0, inplace=True)
rating = bow['Rating']
bow = bow.drop('Rating', 1)
x_train, x_test, y_train, y_test = train_test_split(bow, rating, test_size=0.4, random_state=0)

# Run regression
regr = m.OrdinalRidge()
regr.fit(x_train, y_train)
scores = cross_val_score(regr, bow, rating, cv=5, scoring='accuracy')
# scores -> array([0.75438596, 0.73684211, 0.66071429, 0.53571429, 0.60714286])
# avg_score -> Accuracy: 0.66 (+/- 0.16)

# Do PCA (dimensionality reduction)
scaler = StandardScaler()
# Fit on training set only.
scaler.fit(x_train)
# Apply transform to both the training set and the test set.
x_train = scaler.transform(x_train)
x_test = scaler.transform(x_test)
# Make an instance of the Model
pca = PCA(.95)
pca.fit(x_train)
x_train = pca.transform(x_train)
x_test = pca.transform(x_test)
regr.fit(x_train, y_train)
scores = cross_val_score(regr, bow, rating, cv=10, scoring='accuracy')

What are your thoughts on the above code?
Any insight is greatly appreciated!

EDIT:
This is a link to the dataset
This is a link to a google.doc containing the source code (Python)


text:
Q: Vite define alias I have some struggles migrating my Vue 3 app to Vite.
I'm facing a problem that is caused by ~ or ~@;
So I fixed a regular @ path like:
 "@": fileURLToPath(new URL("./src", import.meta.url)),

and it works fine. But how can I define ~@ and ~ to navigate to node_modules?
I tried all of these and nothing worked:
find: /^~(.*)$/,
      replacement: '$1',
      '~': `${path.resolve(__dirname, './node_modules/')}`,
      '~@': `${path.resolve(__dirname, './node_modules/')}`,

An example from scss file:
@import "~@fortawesome/fontawesome-pro/scss/solid";

Here is my full vite.config.js
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `
                  @import "bulma/sass/utilities/functions";
                  @import "bulma/sass/utilities/initial-variables";
                  @import "bulma/sass/utilities/derived-variables";
                  @import "bulma/sass/utilities/mixins";
                  @import "@/scss/main";
            `
      },
    }
  }
});


text:
Q: Registering Spring Controllers from Child Context I have a Spring Boot application, but I want to split it up into one parent context and many smaller child contexts. Request mapping and security must be centralized, so one DispatcheServlet - having multiple servlets is not an option.
I want to create @Controllers and services in each of my child contexts, have Spring autowire child context beans into these controllers, but then have these controllers registered in parent context mappings.
Is this possible to do in Spring? I haven't been able to find a way.


text:
Q: Is "suspend-to-disk" memory dump encrypted when using FileVault2? I am conserned about cold-boot attacks on my full disc encrypted (filevault2) laptop.
Therefore I am wondering if the memory image dump to /var/vm/sleepimage is encrypted before it is saved to disk?
I notice that the suspended drive asks me for my password before unlocking so it appears this is the case, but could anyone confirm this?

A: Everything written to the volume under Filevault 2 is encrypted live and in-stream by the kernel / device drivers.
As long as there isn't a bug where data leaks to outside the core storage wrapper, you don't need to worry about someone analyzing the contents of your RAM by snooping the locked drive.


text:
Q: Is possible to send HTTP code in service? I would like to know if it was possible to return a status from a service?
Indeed in my service I have my code which allows to register but I would like to return an error if for example an account is already existing with the mail.
I tried with throw new HttpException() but it does not change anything
Here is my current code:
Controller:
@Post('/signup')
async signup(@Body() body): Promise<void> {
    return await this.accountService.signup(body);
}

Service:
async signup(body: IAccount): Promise<void> {
    const hashedPass: string = await bcrypt.hash(body.password, await bcrypt.genSalt(10));
    const account: IAccount = {
        'uuid': uuidv4(),
        'username': body.username,
        'password': hashedPass
    };
    const newAccount = new this.accountModel(account)
    newAccount.save()
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
    })
}

Thank advance

A: You don't ever return anything from the method. You should at least return the newAccount.save() so that the await can actually wait for the response from the catch if there is an error


text:
Q: How to specify multiple jars inside a directory in boot-class-path attribute of a manifest file I am using java 1.6 version. Os : Windows 7.

*

*I have a jar file and in its manifest file, I have Boot-Class-Path attribute and I have been using so many 3rd party libraries(jar files) as value. So Boot-Class-Path is completely messed up as I have to include the path for every single jar file that I use. But after reading
http://todayguesswhat.blogspot.in/2011/03/jar-manifestmf-class-path-referencing.html and [enter link description here][1]
How to use a wildcard in the classpath to add multiple jars?
articles, I came to know we can use directory name end with "/" or "/*". But in my case it is not working. FYI: my line is  . Help me on this.


text:
Q: tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: 2022-08-17 09:50:13.773944: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:975] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2022-08-17 09:50:13.775825: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:975] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2022-08-17 09:50:13.779061: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 AVX512F FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-08-17 09:50:13.782886: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:975] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2022-08-17 09:50:13.784665: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:975] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2022-08-17 09:50:13.786370: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:975] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2022-08-17 09:50:15.199944: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:975] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2022-08-17 09:50:15.201818: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:975] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2022-08-17 09:50:15.203250: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:975] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2022-08-17 09:50:15.204640: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1532] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 38268 MB memory:  -> device: 0, name: NVIDIA A100-PCIE-40GB, pci bus id: 0000:00:05.0, compute capability: 8.0
INFO:tensorflow:Using MirroredStrategy with devices ('/job:localhost/replica:0/task:0/device:GPU:0',)
I0817 09:50:17.109207 140027332416448 mirrored_strategy.py:374] Using MirroredStrategy with devices ('/job:localhost/replica:0/task:0/device:GPU:0',)
INFO:tensorflow:Maybe overwriting train_steps: 5000
I0817 09:50:17.115118 140027332416448 config_util.py:552] Maybe overwriting train_steps: 5000
INFO:tensorflow:Maybe overwriting use_bfloat16: False
I0817 09:50:17.115335 140027332416448 config_util.py:552] Maybe overwriting use_bfloat16: False
WARNING:tensorflow:From /home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/object_detection/model_lib_v2.py:563: StrategyBase.experimental_distribute_datasets_from_function (from tensorflow.python.distribute.distribute_lib) is deprecated and will be removed in a future version.
Instructions for updating:
rename to distribute_datasets_from_function
W0817 09:50:17.151397 140027332416448 deprecation.py:350] From /home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/object_detection/model_lib_v2.py:563: StrategyBase.experimental_distribute_datasets_from_function (from tensorflow.python.distribute.distribute_lib) is deprecated and will be removed in a future version.
Instructions for updating:
rename to distribute_datasets_from_function
INFO:tensorflow:Reading unweighted datasets: ['Tensorflow/workspace/annotations/train.record']
I0817 09:50:17.155634 140027332416448 dataset_builder.py:162] Reading unweighted datasets: ['Tensorflow/workspace/annotations/train.record']
INFO:tensorflow:Reading record datasets for input file: ['Tensorflow/workspace/annotations/train.record']
I0817 09:50:17.155876 140027332416448 dataset_builder.py:79] Reading record datasets for input file: ['Tensorflow/workspace/annotations/train.record']
INFO:tensorflow:Number of filenames to read: 1
I0817 09:50:17.155959 140027332416448 dataset_builder.py:80] Number of filenames to read: 1
WARNING:tensorflow:num_readers has been reduced to 1 to match input file shards.
W0817 09:50:17.156022 140027332416448 dataset_builder.py:86] num_readers has been reduced to 1 to match input file shards.
WARNING:tensorflow:From /home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/object_detection/builders/dataset_builder.py:100: parallel_interleave (from tensorflow.python.data.experimental.ops.interleave_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.data.Dataset.interleave(map_func, cycle_length, block_length, num_parallel_calls=tf.data.AUTOTUNE)` instead. If sloppy execution is desired, use `tf.data.Options.deterministic`.
W0817 09:50:17.158816 140027332416448 deprecation.py:350] From /home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/object_detection/builders/dataset_builder.py:100: parallel_interleave (from tensorflow.python.data.experimental.ops.interleave_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.data.Dataset.interleave(map_func, cycle_length, block_length, num_parallel_calls=tf.data.AUTOTUNE)` instead. If sloppy execution is desired, use `tf.data.Options.deterministic`.
WARNING:tensorflow:From /home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/object_detection/builders/dataset_builder.py:235: DatasetV1.map_with_legacy_function (from tensorflow.python.data.ops.dataset_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.data.Dataset.map()
W0817 09:50:17.187078 140027332416448 deprecation.py:350] From /home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/object_detection/builders/dataset_builder.py:235: DatasetV1.map_with_legacy_function (from tensorflow.python.data.ops.dataset_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.data.Dataset.map()
WARNING:tensorflow:From /home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/tensorflow/python/util/dispatch.py:1082: sparse_to_dense (from tensorflow.python.ops.sparse_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Create a `tf.sparse.SparseTensor` and use `tf.sparse.to_dense` instead.
W0817 09:50:24.743995 140027332416448 deprecation.py:350] From /home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/tensorflow/python/util/dispatch.py:1082: sparse_to_dense (from tensorflow.python.ops.sparse_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Create a `tf.sparse.SparseTensor` and use `tf.sparse.to_dense` instead.
WARNING:tensorflow:From /home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/tensorflow/python/util/dispatch.py:1082: sample_distorted_bounding_box (from tensorflow.python.ops.image_ops_impl) is deprecated and will be removed in a future version.
Instructions for updating:
`seed2` arg is deprecated.Use sample_distorted_bounding_box_v2 instead.
W0817 09:50:28.231675 140027332416448 deprecation.py:350] From /home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/tensorflow/python/util/dispatch.py:1082: sample_distorted_bounding_box (from tensorflow.python.ops.image_ops_impl) is deprecated and will be removed in a future version.
Instructions for updating:
`seed2` arg is deprecated.Use sample_distorted_bounding_box_v2 instead.
WARNING:tensorflow:From /home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/tensorflow/python/util/dispatch.py:1082: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.cast` instead.
W0817 09:50:29.841259 140027332416448 deprecation.py:350] From /home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/tensorflow/python/util/dispatch.py:1082: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.cast` instead.
Traceback (most recent call last):
  File "/home/thecon/Documents/AiMedia/TF-Detection/Tensorflow/models/research/object_detection/model_main_tf2.py", line 114, in <module>
    tf.compat.v1.app.run()
  File "/home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/tensorflow/python/platform/app.py", line 36, in run
    _run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef)
  File "/home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/absl/app.py", line 308, in run
    _run_main(main, args)
  File "/home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/absl/app.py", line 254, in _run_main
    sys.exit(main(argv))
  File "/home/thecon/Documents/AiMedia/TF-Detection/Tensorflow/models/research/object_detection/model_main_tf2.py", line 105, in main
    model_lib_v2.train_loop(
  File "/home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/object_detection/model_lib_v2.py", line 605, in train_loop
    load_fine_tune_checkpoint(
  File "/home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/object_detection/model_lib_v2.py", line 401, in load_fine_tune_checkpoint
    _ensure_model_is_built(model, input_dataset, unpad_groundtruth_tensors)
  File "/home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/object_detection/model_lib_v2.py", line 161, in _ensure_model_is_built
    features, labels = iter(input_dataset).next()
  File "/home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/tensorflow/python/distribute/input_lib.py", line 569, in next
    return self.__next__()
  File "/home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/tensorflow/python/distribute/input_lib.py", line 573, in __next__
    return self.get_next()
  File "/home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/tensorflow/python/distribute/input_lib.py", line 630, in get_next
    return self._get_next_no_partial_batch_handling(name)
  File "/home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/tensorflow/python/distribute/input_lib.py", line 662, in _get_next_no_partial_batch_handling
    replicas.extend(self._iterators[i].get_next_as_list(new_name))
  File "/home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/tensorflow/python/distribute/input_lib.py", line 1632, in get_next_as_list
    return self._format_data_list_with_options(self._iterator.get_next())
  File "/home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/tensorflow/python/data/ops/multi_device_iterator_ops.py", line 531, in get_next
    result.append(self._device_iterators[i].get_next())
  File "/home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/tensorflow/python/data/ops/iterator_ops.py", line 819, in get_next
    return self._next_internal()
  File "/home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/tensorflow/python/data/ops/iterator_ops.py", line 749, in _next_internal
    ret = gen_dataset_ops.iterator_get_next(
  File "/home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/tensorflow/python/ops/gen_dataset_ops.py", line 3017, in iterator_get_next
    _ops.raise_from_not_ok_status(e, name)
  File "/home/thecon/miniconda3/envs/tf/lib/python3.10/site-packages/tensorflow/python/framework/ops.py", line 7164, in raise_from_not_ok_status
    raise core._status_to_exception(e) from None  # pylint: disable=protected-access
tensorflow.python.framework.errors_impl.InvalidArgumentError: assertion failed: [[0.866666675]] [[0.673333347]]
         [[{{function_node Assert_AssertGuard_false_856}}{{node Assert/AssertGuard/Assert}}]]
         [[MultiDeviceIteratorGetNextFromShard]]
         [[RemoteCall]] [Op:IteratorGetNext]

My train process stuck here. This error came from nowhere, I just regenerate tfrecords and it appeared. Untill this error appears, the process fronzez at "Instructions for updating:
Use tf.cast instead", with process still running but fronzen. I regenerated the tfrecords because has some problems on call function paths, and now I get this errror.

A: The reason for the error was the bad assertion to csv collons for xmin, xmax, ymin, ymax, the order didn't corespond to the xml.


text:
Q: PHP submit not woking over post if (isset($_POST['button']) and $_POST['button'] == 'Join')
{
  include '../includes/db.inc.php';
  $id = mysqli_real_escape_string($link, $_POST['id']);
  $user = $_SESSION['user'];
  $start = date("d-m-Y");
  $finish = 'NULL';
  $job = 'NULL';

  $sql = "INSERT INTO userproj SET user='$user', projectid='$id', datestart='$start', datestop='$finish', job='$job'";
  if(!mysqli_query($link, $sql))
  {
    $error = 'Error joining project';
    include 'error.html.php';
    exit();
  }
}

that is supposed to fire off when this code:
<form name="form2" action="?goto=display&id=<?php htmlout($id); ?>" method="post">
<input type="hidden" name="id" value="<?php htmlout($id); ?>"/>
<input type="submit" name="button" value="Join"/>
</form>

is executed. Problem is it doesn't seem to. I have put an echo in there to see if it is firing but I got the rest of the code wrong but still nothing. It works when used as a get instead of post but then it redirects to the home page instead of the same page. I have two buttons that fail like this but every other post I have works. I can't see what I have done wrong but it all looks fine to me.
Thanks for taking the time to look.
Cheers,
Rob.

A: This is not correct: job='$job', because in job is NULL, then it will be job='NULL', but it should be job=NULL. Also the same with datestop.
Change your query to this:
$sql = "INSERT INTO userproj SET user='$user', projectid='$id', datestart='$start', datestop=$finish, job=$job";

A: Try $_SERVER['PHP_SELF'];
<form action="<?php $_SERVER['PHP_SELF'];?>?goto=display&id=<?php htmlout($id); ?>" method="post">

A: Try using different name for button
<form name="form2" action="?goto=display&id=<?php htmlout($id); ?>" method="post">
<input type="hidden" name="id" value="<?php htmlout($id); ?>"/>
<input type="submit" name="mesubmit" value="Join"/>
</form>


text:
Q: How to Write Global Functions in Postman I need help writing a common function to use across a collection of requests which will help with building a framework.
I have tried using the below format
The following function is declared in the Test tab in the first function
postman.setGlobalVariable("function", function function1(parameters)
{
  //sample code
});

I used the following in the pre-request
var delay = eval(globals.function);
delay.function1(value1);

I am getting the following error
there was error while evaluating the Pre-request script : Cannot read property 'function1'  of undefined.
Can anyone help me with how to define Global/common functions and use them across the requests?
Thanks in advance

A: Without eval:
Define an object containing your function(s) in the collection's pre-request scripts without using let, var, etc. This attaches it to Postman's global sandbox object.
utils = {
  myFunc: function() {
    return 'hello';
  }
};

Then within your request's pre-request or test script section just call the function:
console.log(utils.myFunc());

A: If you want to call pm.sendRequest in a global function, try this:

*

*Define the global function in collection pre-request, like this:
pm.globals.set('globalFunction', parameters => {
    console.log(parameters);
    pm.sendRequest('https://google.com/', function(err, resp) {
        pm.expect(err).to.not.be.ok;
    });
});

*Use function like this:
eval(globals.globalFunction)('hello world!!');
Note that, I declared function using arrow style ()=>{}. Otherwise, it wouldn't work.

A: The problem had perplexed me for a while until I found the common way mentioned above. However, it still leaves a warning icon for each eval line, which indicates "eval can be harmful" in the postman interface.
Recently, I've found another way and post it here:
Users can create a prototype object with the proper function you want in the pre-request script section, like this:
Object.prototype.sayHello = function(name){
console.log(`Hello! ${name}`);
};

and call that function everywhere after that. It just required a defined object, like this:
let obj = {};
obj.sayHello('Griffin');

Or you don't even need the declaration of the object but use some built-in objects instead, like lodash (you pretend it has the function :smile: )
_.sayHello('Griffin');

It's working on my side. I also posted it in postman forum here
https://community.postman.com/t/global-functions-via-collection-level-folder/5927/6?u=franksunnn110

A: Very easy to achieve with monkey patch on object (or whatever you want).
Option #1
On collection level pre script
Object.prototype.doSomething = (foo) => console.log(foo);

On any other place:
pm.doSomething('bar');

// or

postman.doSomething('bar');

Option #2
On collection level pre script
Utilities = {};
Utilities.getParam = (foo) => console.log(foo);

On any other place
Utilities.getParam('bar');

A: I use this little hack:
pm.globals.set('loadUtils', function loadUtils() {
    let utils = {};
    utils.reuseableFunction = function reuseableFunction() {
        let jsonData = JSON.parse(responseBody);
    }
    return utils;
} + '; loadUtils();');
tests['Utils initialized'] = true;

In another request I can reuse the global variable loadUtils:
const utils = eval(globals.loadUtils);
utils.reuseableFunction();

You can also check the developer roadmap of the Postman team. Collection-level scripts are on the near-term agenda and should be available soon until then you can use the shown method.

A: A more elegant way consists of using the global context (not variables) in the pre-request scripts.
For example, if you wish a function called myFunction to be available in any pre-request script, you can go to Edit Collection/Pre-request and set
globalThis.myFunction = function(){}

Then you can call myFunction in any pre-request script of any request inside the collection (without any stringification/evaluation of your function)

A: Edit: The following answer is still valid and you can skip ahead and read it, but I want to give a warning first: If you are trying use this in Postman, you should probably use something else than Postman, like Mocha, for your testing. Postman is OK for small to medium scale applications but very large multi-developers applications can be a nightmare to maintain with postman. The in-app editor is a mess for large files, and versioning can be problematic.
ANSWER
You can have a more readable solution and more possibility to factor your code (like calling function1() from function2() directly inside your pre-request script, or declaring packages) with the following syntax :
Initialize environment (or globals) :
postman.setEnvironmentVariable("utils", () => {
    var myFunction1 = () => {
        //do something
    }
    var myFunction2 = () => {
        let func1Result = myFunction1();
        //do something else
    }
    return {
        myPackage: {
            myFunction1,
            myFunction2
        }
    };
});

And then use your functions in a later test :
let utils = eval(environment.utils)();
utils.myPackage.myFunction1(); //calls myFunction1()
utils.myPackage.myFunction2(); //calls myFunction2() which uses myFunction1()

Bonus :
If you are calling an API and need to wait the call to finish before performing a test, you can do something like this:
postman.setEnvironmentVariable("utils", () => {
    var myFunction = (callback) => {
        return pm.sendRequest({
            // call your API with postman here
        }, function (err, res) {
            if (callback) {
                //if a callback method has been given, it's called
                callback();
            }
        });
    }

    return {
        myPackage: {
            myFunction,
        }
    };
});

and then to use it:
utils.myPackage.myFunction(function() {
    console.log("this is the callback !")
    //perform test here
});

A: You can declare a global function by assigning this function into a collection, environment or global variable as follows:

*

*Create a collection variable, i.e. global_func

*In the variable value write this code,

(number)=> { return number * number }

to reuse this function elsewhere in your collection
let numberSquared = eval(pm.variables.get('global_func'))(5)

now, numberSqaure variables has a value of 25
================================
if you need to declare a function library:
you can create a collection variable and assign it this piece of code:
({
    print:function() {
        console.log('hello Postman')
    },
    squared:function(number) {
        return number * number
    }
})

Note: the functions have been enclosed with parentheses
to reuse this library:
let lib = eval(pm.variables.get('global_func'))
lib1.print()
console.log(lib1.squared(4))

Good luck :)

A: Define functions as a global variables then access across all of your tests.
pm.environment.set("UTILS", `({ myFunction: (text) => console.log(text) })`)

Call the functions
let utils = eval(pm.environment.get("UTILS"))
utils.myFunction('Test')

A: A lot of the above examples will have issues with pm variable. In order to have access to pm variable inside your custom utils method you need to pass it inside after eval. On top of that it is nice to have some modularity for your utils. Paste this as a value for a global variable under name -> Util

(function () {
    const Util = function (pm) {
        return {
            customUtilFunction: function (customVariable) {
                pm.environment.set("customVariable", customVariable);
            }
        }
    }
    return Util
}())

And then inside your test you can call it like presented below.

const Util = eval(pm.globals.get('Util'))(pm)
Util.customUtilFunction('myCustomVariableValue')

A: pm.globals.set("compare_obj",function compare_obj(){
    return (response,outputName)=>{
  if(response !== undefined && response !== null){
    var key = response.hasOwnProperty(Object.keys(response)[0]);
    if(key === true){
       var keyName =  Object.keys(response)[0];
       delete response[keyName];
    }
    delete response.cr_dt;
    delete response.up_dt;
  }
    for(const property in response){
        const isExist = pm.globals.get(outputName).hasOwnProperty(property);
        pm.expect(isExist).to.eql(true);
        if(isExist === true){
            var val = pm.globals.get(outputName);
            pm.expect(response[property]).to.eql(val[property]);
        }
    }
};
} + ';compare_obj();');


text:
Q: Android Asynctasks , passing String between activities I am trying to pass a string(locationSet) set by a spinner from one activity to another, they both implement an Asynchtask within each class.
I am unable to pass the value from the MainActivity to my WeatherActivity. Using the log, I can see the initial value being set fine in the MainActivity, but null any time I try to pass it to the Weather Activity. If I enter the relevant string within the WeatherActivity manually, the output works as expected.
I have looked through other problems, but I am finding it difficult to apply anything I see.
MainActivity.java
public class MainActivity extends Activity {

Button searchLocation;
Spinner locationSpinner;
String locationSet = null;
String strLocation = null;
Locations arrLocation;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    searchLocation = (Button) findViewById(R.id.searchLocationButton);

    locationSpinner = (Spinner) findViewById(R.id.locationsListView);

    ArrayAdapter<CharSequence> adaptor = ArrayAdapter.createFromResource(this, R.array.location_array, android.R.layout.simple_list_item_1);
    locationSpinner.setAdapter(adaptor);

    searchLocation.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            new MyAsync().execute();

        }
    });
}

public void onBackPressed() {
    super.onBackPressed();
    this.finish();
}

class MyAsync extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        strLocation = locationSpinner.getSelectedItem().toString();

        if (strLocation.equals("Aberdeen")) {
            locationSet = arrLocation.ABERDEEN;
        } else if (strLocation.equals("Dundee")) {
            locationSet = arrLocation.DUNDEE;
        } else if (strLocation.equals("Edinburgh")) {
            locationSet = arrLocation.EDINBURGH;
        } else if (strLocation.equals("Fort William")) {
            locationSet = arrLocation.FORT_WILLIAM;
        } else if (strLocation.equals("Glasgow")) {
            locationSet = arrLocation.GLASGOW;
        } else if (strLocation.equals("Manchester")) {
            locationSet = arrLocation.MANCHESTER;
        } else if (strLocation.equals("North Berwick")) {
            locationSet = arrLocation.NORTH_BERWICK;
        } else if (strLocation.equals("Portree")) {
            locationSet = arrLocation.PORTREE;
        } else if (strLocation.equals("Ullapool")) {
            locationSet = arrLocation.ULLAPOOL;
        }

        Intent intent = new Intent(MainActivity.this, WeatherActivity.class);
        startActivity(intent);
    }
}

}
WeatherActivity.java
    public class WeatherActivity extends MainActivity {

    TextView firstDayTextView;

    String selectedLocation = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weather_activity);

        locationTextView = (TextView) findViewById(R.id.locationTextView);

        new LoginAsync().execute();
    }

    class LoginAsync extends AsyncTask<Void, Void, Void> {
        MySaxHandler myHandler;

        StringBuilder builder = new StringBuilder();

        @Override
        protected Void doInBackground(Void... params) {
            myHandler = new MySaxHandler();
            myHandler.addLocation(selectedLocation.toString());
            myHandler.get();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            ArrayList<ItemData> items = myHandler.items;

            if (null != items && items.size() != 0) {
                for (int index = 0; index < items.size(); index++) {
                    ItemData obJPost = items.get(index);
                        builder.append("\n" + obJPost.getItemTitle());
                }
            }
            firstDayTextView.setText(builder.toString());

        }
    }
}

A: You can pass your string value "locationSet" using Intent.putExtra("TAG", locationSet) while starting your weather activity. In weather activity in onCreate you can get the value using Intent.getExtra.
Code example:
Intent i = new Intent(FirstScreen.this, SecondScreen.class);
String keyIdentifer  = null;
i.putExtra("STRING_I_NEED", strName);

Then, to retrieve the value try something like:
String newString;
if (savedInstanceState == null) {
    extras = getIntent().getExtras();
    if(extras == null) {
        newString= null;
    } else {
        newString= extras.getString("STRING_I_NEED");
    }
} else {
    newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}


text:
Q: Identifier on XmlAttribute I have an XML document I'm trying to deseralize that has a attribute that is ref which in C# can not be used to declare a variable hence the below doesn't work
 [XmlAttribute()]
 public string ref;

Anyway to get this to deseralize properly? I know it is case sensitive so Ref wouldn't work.

A: You can provide a name in the attribute:
[XmlAttribute("ref")]
public string anynameyouwant;

A: You can change the attribute name in the xml file, by using the AttributeName, such as in the following example:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace soans
{

    public class Test
    {

        //problematic attribute (ref is reserved)
         [XmlAttribute(AttributeName="ref")]
         public string RefAttr {get;set;}

         //other attributes as well
         [XmlAttribute()]
         public string Field { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            string filename = ""; //use your path here

            Test original = new Test()
            {
                RefAttr = "ref",
                Field = "test"
            };
            //serialiser
            XmlSerializer ser = new XmlSerializer(typeof(Test));

            //save to file
            TextWriter writer = new StreamWriter(filename);
            ser.Serialize(writer, original);
            writer.Close();

            //read from file
            TextReader reader = new StreamReader(filename);
            var fromfile = ser.Deserialize(reader) as Test;
            if(fromfile!=null)
            {
                Console.WriteLine(fromfile.RefAttr);

            }
            reader.Close();
            Console.ReadKey();

        }
    }
}


text:
Q: Setting default webpage for shared hosting I've got a bunch of domains on a shared ip address (through bluehost, not sure if that matters). Visiting any domain works fine, but visiting the ip address just triggers a 404 error. After doing some digging, I found this super user answer. What I've found out so far is that when multiple domains are on a single address, the server figures out what domain to serve up based on a host header. Is there a way to set a default header value for my server so one domain is served up by the address unless otherwise specified by headers? (ie a request to 238.483.43.52 would return example.com instead of an apache error) Can it be done with an .htaccess file?

A: With shared hosting, your IP address is not just for you - it is shared by other customers' domains.
What happens with a URL with a 'bare' IP address is controlled by the provider, and they are unlikely to direct it to the domain of one particular customer (thereby preferring them over others).
For your desired behavior, you would need a dedicated IP address.


text:
Q: How to give overlay permission by default? Currently, I use the following code.
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);

When this code is used, a setting screen which gives overlay permission is displayed.
But I want to give overlay permission by default when the application is installed.
The target android version is 6.0 or more.
How to give overlay permission by default?


text:
Q: Strings in init are not localized I do localization of my iOS SwiftUI app and using XCode Product/Export localizations.. function to create xcloc file. Everything works fine but strings in init() are not detected in shown in xcloc. Is there any way how to add them?
Thanks

A: You should replace all relevant String types that are initialized with static string literals with LocalizedStringKey, mainly in the funcs and init()s – so for example:
struct MyStruct {

    var myVar: LocalizedStringKey

    init(var: LocalizedStringKey) {
        self.myVar = var
    }
    ...
}

Stringtypes in model data have to stay untouched.
If there are missing cases left you can add them manually to your .strings file by
"original text" = "localized text";


text:
Q: How to pass Smarty variable to PHP function? This is not a duplicate question, I couldn't solve my issue using answers from the other threads, besides my problem is different.
I'm trying to print a URL with an appended parameter using PHP in a Smarty plugin function. The software I use is WHMCS.
Below is a sample code of my function:
<?php
/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     function.aff.php
 * Type:     function
 * Name:     aff
 * Purpose:  outputs a random magic answer
 * -------------------------------------------------------------
 */
function smarty_function_aff($params, &$smarty)
    {
           $affiliateid = $params['affiliateid'];
           $refflink = 'http://example.com/aff.php?aff=' . $affiliateid .'';

           print $refflink;
    }
?>

In the template file, I use {aff} that supposed to print the whole URL including the appended parameter, however it prints the URL like that: http://example.com/aff.php?aff= as if the $affiliateid variable does not exist.
Now if I used the following ($affiliateid} directly in the template file, it will output the user affiliate ID. But I need to use it in the PHP function above. Writing it directly in PHP as $affiliateid doesn't seem to work.
What I'm missing here? Any suggestions please? Thank you.

A: You can use your function like this:
{aff affiliateid=$affiliateid}

See this link for more information: http://www.smarty.net/docsv2/en/plugins.functions.tpl
It states:

All attributes passed to template functions from the template are contained in the $params as an associative array.

an attribute (http://www.smarty.net/docsv2/en/language.syntax.attributes.tpl) is the affiliateid=$affiliateid part in my line of code above.


text:
Q: Run script after booting Alpine netboot I have download alpine netboot distribution from this url:

https://dl-cdn.alpinelinux.org/alpine/v3.16/releases/x86/alpine-netboot-3.16.1-x86.tar.gz

I have run a virtual machine with qemu this way:
qemu-system-i386 -m 256 -kernel boot/vmlinuz-lts -initrd boot/initramfs-lts -append "console=ttyS0 ip=dhcp alpine_repo=http://dl-cdn.alpinelinux.org/alpine/edge/main/"

With this command, a virtual machine is created and 22 apk pacakges are installed.
I am able to install additionnal apk packages, but i have to do it by hand (apk add command).
How can i script packages installation in qemu command line ?
Please note i can replace http://dl-cdn.alpinelinux.org/ by a local mirror. So i can also change files on the repository
Thanks

A: It's not quite "scripting" package installation, but after manually installing packages you can create an overlay file using the lbu command, and then apply that on subsequent boots. See https://wiki.alpinelinux.org/wiki/Alpine_local_backup and https://wiki.alpinelinux.org/wiki/PXE_boot for details.
For example, if I boot using your command and then subsequently run:
apk add --update curl git

I can create a local backup file by running lbu package. This will create an apkovl file in my current directory:
localhost:~# ls
localhost.apkovl.tar.gz

If I place this file somewhere on my local system where it's available via http, I can boot the image like this:
qemu-system-i386 -m 256 -kernel boot/vmlinuz-lts \
  -initrd boot/initramfs-lts \
  -append "console=ttyS0 ip=dhcp alpine_repo=http://dl-cdn.alpinelinux.org/alpine/edge/main/ apkovl=http://10.0.2.2:8080/localhost/apkovl.tar.gz"

When alpine finishes booting, I will find that curl and git are already installed.

If you want to explicitly run scripts at boot, rather than simply installing packages, you can:

*

*Enable the local service:
rc-update add local default

*Place your script(s) into /etc/local.d/<something>.start and make
sure it's executable.

*Follow the previous instructions for generating and using an
overlay.


text:
Q: In Grails, how can I override the AuditlLogEvent domain class from Audit-Logging plugin? I tried to create a domain subclass (different package) but migration plugin returned ambiguous class exception.
I tried creating a copy of that domain class (same package) but compiler returned duplicate class error.
How to override the AuditLogEvent class properly? Should I create a customized copy of that plugin?

A: We're working on a bootstrap integration of the AuditLogEvent class, so everyone got it in their project instead of the plugin integrated one. You can create it from the source branch for testing:
https://github.com/robertoschwald/grails-audit-logging-plugin/tree/feature_1.x/externalizeALE1.x
When using this 1.0.6-SNAPSHOT version in your project, you must perform "grails audit-quickstart" to create the AuditLogEvent domain class in your project. It's registered in Config.groovy. See audit-test test application setup how it works.
Would be great if you can feedback in https://github.com/robertoschwald/grails-audit-logging-plugin/issues/13


text:
Q: Bitwise negation of XMM register How to get bitwise negation of values in XMM register? As far as I know there is no such instruction. The only instruction with negation is pandn, but to use it to simply negate values in one XMM register, I would have to have another XMM register padded filled with 1.
Is there another way to negate bits in XMM register? Or is there a clever way to fill XMM register with 1 without accessing memory?

A: To load a register with all 1s, use
pcmpeqd xmm0, xmm0

After that you can simply subtract xmmX from xmm0 to get ~xmmX, or use pandn
You can also load other constants to xmm registers easily
pcmpeqd xmm0, xmm0
psrld   xmm0, 30   ; 3 (32-bit)

pcmpeqd xmm0, xmm0 ; -1

pcmpeqw xmm0, xmm0 ; 1.5f
pslld   xmm0, 24
psrld   xmm0, 2

pcmpeqw xmm0, xmm0 ; -2.0f
pslld   xmm0, 30

Read Agner Fog's optimization guide, 13.4 Generating constants - Making constants for integer vectors in XMM registers

A: Use pxor with an all-ones register.
pandn is also usable, but has zero advantages.  There are no cases where pandn with an all-ones constant lets you do anything you couldn't have done with pxor.
psubd is also usable (2's complement identity), but is even worse than pandn because it has lower throughput on some CPUs (fewer execution ports).

pcmpedq  xmm1, xmm1      ; create the all-ones.  No false dependency.

pxor     xmm0, xmm1      ; flip all the bits in XMM0. Doesn't destroy XMM1
;pandn    xmm0, xmm1      ; equivalent but no advantage.  (~xmm0) & xmm1

PXOR is nice because it's commutative.  With AVX, you can load-and-NOT with one micro-fused uop:
vpxor    xmm0, xmm1, [rdi]

You can't do that with VPANDN, because the operand that can be memory or register is the not-inverted operand.  (Without AVX, though, just movdqa or dqu load and then pxor the load result.  A reg-copy and a micro-fused load+pxor is 3 total unfused-domain uops vs. 2)

Or without AVX, if you want to destroy the all-ones constant instead of the data you're inverting, pxor wins again:
movdqa  xmm2, xmm1      ; copy the all-ones constant.  Off the critical path for latency
pxor    xmm2, xmm0

you can take a movdqa off the critical path vs. movdqa xmm2, xmm0 / pandn xmm2,xmm1.  (Only IvyBridge+ and Bulldozer-family/Ryzen have zero-latency movdqa for vector regs.)  Or if you were rematerializing the all-ones every time with pcmpeqd in the target register (maybe because of register pressure or because you're not doing it in a loop), that would be another case where you want pxor instead of pandn.

Generating an all-ones constant with pcmpeqb/w/d is special-cased to not have a false dependency on the old value (except on Silvermont where it does), but does still need an execution unit (unlike xor-zeroing on Sandybridge-family).  Still, it's cheap, and it's what compilers use for _mm_set1_epi32(-1).
Re-creating the constant every time you need it instead of copying from another register is slightly worse on IvyBridge and later, and on Bulldozer-family and Ryzen.  mov-elimination for XMM copies avoids occupying a vector execution unit / port, in case vector-ALU execution ports were your bottleneck.
But it's slightly better on Intel P6-family (Core2/Nehalem): register-read stalls can be a problem when reading too many "cold" registers in an issue group.  (See Agner Fog's microarch pdf https://agner.org/optimize/).  P6-family is obsolete but still in use in some old machines.  You might want to tune for it in the non-AVX version of your code if you have an AVX version which runs on CPUs with AVX.  (But Haswell/Skylake "pentium" / "celeron" are still a thing, and they don't have AVX, so no-AVX doesn't mean old CPU.)


text:
Q: Improve throughput of retriver in google search appliance adaptor I am developing an Adaptor for the GSA using the Adaptor framework 4.0.
The issue I am having lies in the fact that the GSA does not call the retriever method getDocContent()
I have set the hostload to max 10
the Adaptor VM itself has 6 Virtual CPUs and the number of worker threads for the adaptor has been set to 64
server.maxWorkerThreads=64

Its unclear to me why the GSA does not call the getDocContent() method untill I hit the Save button on the host load schedule section of the GSA.

A: Vinay,
It's going to depend on how you develop your connector and some basic infrastructure.
1) First, confirm that you have actually fed documents.  This can be confirmed under the Feeds section.
2) Second, if there are fed documents in the index diagnostics but your method is not called, then take one of the urls and test it in the crawl diagnostics realtime diagnostics via a manual fetch.
3) Confirm the port that your adaptor is running is not blocked via firewall.