text:
Q: Calling an custom field from theme option at the frontend I am having trouble calling a field and displaying its content at the frontend from a custom theme option page. This is the code I am using to display my custom theme option at the backend
  add_action( 'admin_init', 'theme_options_init' );
  add_action( 'admin_menu', 'theme_options_add_page' );

 /** Init plugin options to white list our options **/
  function theme_options_init(){
        register_setting( 'options', 'website_options', 'theme_options_validate' );
  }
 /** Load up the menu page **/
  function theme_options_add_page() {
        add_theme_page( __( 'Blurb Options', 'websiteBlurbs' ), __( 'Blurb Options',      'websiteBlurbs' ), 'edit_theme_options', 'theme_options', 'theme_options_do_page' );
 }

 /** Create the options page **/
  function theme_options_do_page() {
            if ( ! isset( $_REQUEST['settings-updated'] ) )
            $_REQUEST['settings-updated'] = false;
 ?>

  <?php screen_icon(); echo "
" . get_current_theme() . __( ' Page Settings', 'websiteBlurbs' ) . "
"; ?>
  <?php if ( false !== $_REQUEST['settings-updated'] ) : ?>

<?php _e( 'Options saved', 'websiteBlurbs' ); ?>

  <?php endif; ?>
  <form method="post" action="options.php">
        <?php settings_fields( 'options' ); ?>
        <?php $options = get_option( 'website_options' ); ?>

About Page

            <?php /* ABOUT */ ?>

<?php _e( 'Title Blurb', 'aboutBlurb' ); ?>

                    <input id="website_options[about]" class="regular-text" type="text" name="website_options[about]" value="<?php esc_attr_e( $options['about'] ); ?>" style="width:50%; padding:1em;" />

Our Team

            <?php /* PROPERTY */ ?>

<?php _e( 'Title Blurb', 'teamBlurb' ); ?>

                    <input id="website_options[team]" class="regular-text" type="text" name="website_options[team]" value="<?php esc_attr_e( $options['team'] ); ?>" style="width:50%; padding:1em;" />

Property Page

            <?php /* PROPERTY */ ?>

<?php _e( 'Title Blurb', 'propertyBlurb' ); ?>

                    <input id="website_options[property]" class="regular-text" type="text" name="website_options[property]" value="<?php esc_attr_e( $options['property'] ); ?>" style="width:50%; padding:1em;" />

            <input type="submit" class="button-primary" value="<?php _e( 'Save Options', 'websiteBlurbs' ); ?>" />

  </form>

  <?php
 }

 /** Sanitize and validate input. Accepts an array, return a sanitized array. **/
  function theme_options_validate( $input ) {
 // Say our text option must be safe text with no HTML tags
        $input['about'] = wp_filter_nohtml_kses( $input['about'] );
        $input['property'] = wp_filter_nohtml_kses( $input['property'] );
        $input['team'] = wp_filter_nohtml_kses( $input['team'] );
        return $input;
 }

I know how to call a field from a custom post type by using echo get_post_meta($post->ID, 'customfieldname', true); but when I try using this to call field aboutBlurb i am unable to generate the content from the field to display at the frontend. I am not receiving any errors or a reasons why I can not display it.
What am I missing to make this work correctly?

A: I'm not sure how you've decided to save your options but if I were to guess based on the code above, you're saving your 'aboutBlurb' as an index in the website_options array which I also assume you're saving in the actual WordPress Options - website_options[about].
To get that data maybe try this:
$website_options = get_option('website_options');
echo $website_options['about'];

A: Try this way, may help you. I fetch the a page 's thread then fetch associated custom field by putting its name.
     $homeInsurance= new WP_Query( 'post_type=page&page_id=7' );
        while ($homeInsurance->have_posts()) : $homeInsurance->the_post();

        $thisPageID         = get_the_id();
        $home_insurance_urdu_translation_image_path = get_post_meta($thisPageID, 'home_insurance_urdu_translation_image_path', true);

        endwhile;


text:
Q: Register varibles in Verilog by using Quartus and FPGA I wonder, how is process behind when we use reg variable in verilog. We know that, in Quartus using by any FPGA we can declare and handle many registers. Also, we know that recent-i7(64 bit) CPUs have just 16 register. When we compile and simulate our code that has more than for example 50 register, it works. These registers are stored in any memory block? If so, why do we define this variable as reg? I mean when we define variable as reg in verilog registers should(am I wrong?) be handled in CPU registers but CPU has no more than 16 register. I am confused.

A:
These registers are stored in any memory block?

No. Without spacial implementation Quartus tool use registers from logic cells.
Some ALTERA device have UFM (User flash memory). You can use it to hold data:
https://www.altera.com/en_US/pdfs/literature/an/an489.pdf
https://www.altera.com/content/dam/altera-www/global/en_US/pdfs/literature/ug/ug_alt_ufm.pdf
Sorry for My English.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Import Google Admin User report to Google Sheets I am trying to import the User Report in a Google Admin account into Google Sheets. It is straightforward to export to a Google Sheet, but I would like to run a Google script that will pull in the User Report into an existing Google Sheet.

A: Try this.
function cloneGoogleSheet(existingSheet, userReportSheet){
   //get source google sheet document
   var source = SpreadsheetApp.openById(userReportSheet);
   //get the source sheet on document
   var sourceSheet = source.getSheetByName('NameOfSheet');

   //get data range
   var dataRange = sourceSheet.getDataRange();

   // get A1 notation for the range identification
   var A1Range = dataRange.getA1Notation();

   //get data within the specified range
   var data = dataRange.getValues();

   //specify the existing spreadsheet you want to pull data to
   var target = SpreadsheetApp.openById(existingSheet);

   //target sheet on your existing document
   var targetSheet = target.getSheetByName('NameOfTargetSheet');

   //if there is already data on the target sheet, you may want to remove it
   targetSheet.clear({contentsOnly: true});

   //now you set the target range of the values you get from your user report
   targetSheet.getRange(A1Range).setValues(data);
};


text:
Q: How to create an installer for an application that uses 'Martincostello.Sqllocaldb', without having reference problems? I have tried handling SQLLocalDB with 'https://github.com/martincostello/sqllocaldb' and it works fine, but when I try to package the application to install it on another machine, it has not been possible, not even with the Visual Studio 2017-2019 installer, nor with InstallShield 2020, since they always find reference problems.
Does anyone here have or know where to locate an example setup project, using either 'Martincostello.Sqllocaldb' or some other similar resource, to make the application able to be moved from one computer to another, to work with SQLLocalDB?
For example, when the installer is being built with InstallShield 2020, it always gives a warning that it can't find the SNI.dll or some of its references. But during the installation of 'Martincostello.Sqllocaldb' with NuGet, a folder named 'Microsoft.Data.SqlClient.SNI.1.0.19235.1' was created and inside it, there are several sub folders where those files can be located, i.e. , SNI.dll.

A: put the missing .dll to the resources of your project and on startup of the project, check if the instalation path is consist of specific file like SNI.dll if it doesn't exit then include it manually using code
    If Not IO.File.Exists("SNI.dll") Then
        IO.File.WriteAllBytes(Application.StartupPath & "\SNI.dll", My.Resources.SNI)
    End If


text:
Q: How to speed up a symbolic integration I have a question about an integral. I wanna integrate this:
-((cA Log[1 + mgl^2/sa1])/(-1 + x)) + (
cA Log[-(sa1/(-mgl^2 - sa1))])/(1 - x) + (cA cF Log[-1 + 1/x])/(
1 - x) - (2 cF^2 Log[-1 + 1/x])/(1 - x) + (2 cF Log[1 - x])/(
1 - x) + 1/
2 cA (2/(-1 + x) + sa1^2/(
2 mgl^4 + 4 mgl^2 sa1 + 2 sa1^2 - 4 mgl^2 sa1 x - 4 sa1^2 x +
 2 sa1^2 x^2) - (sa1^2 x)/(
 2 mgl^4 + 4 mgl^2 sa1 + 2 sa1^2 - 4 mgl^2 sa1 x - 4 sa1^2 x +
 2 sa1^2 x^2) + (2 Log[1 + mgl^2/sa1 - x])/(-1 + x))

over x from 0 to z. Every part in the integral is real. When I do this:
Integrate[Kqq1P, {x, 0, z},
 Assumptions -> {0 < z < 1, x \[Element] Real, Kqq1P \[Element] Real}]
It seems to take years. Does anyone know how to speed up that integration. By the way Kqq1P is that expression above.
Thanks in advance!
Cheers,
Marcel

A: The "trick" which works frequently when Mathematica refuses to calculate a definite integral is to calculate first the indefinite integral, then take the limits at the ends of the integration interval and subtract the results.
Here we go.
Let the integrand be
f = -((cA Log[1 + mgl^2/sa1])/(-1 + x)) + (cA Log[-(sa1/(-mgl^2 - sa1))])/(1 - x) + (cA cF Log[-1 + 1/x])/(1 - x) - (2 cF^2 Log[-1 + 1/x])/(1 -
     x) + (2 cF Log[1 - x])/(1 - x) +
  1/2 cA (2/(-1 + x) +
     sa1^2/(2 mgl^4 + 4 mgl^2 sa1 + 2 sa1^2 - 4 mgl^2 sa1 x - 4 sa1^2 x +
        2 sa1^2 x^2) - (sa1^2 x)/(2 mgl^4 + 4 mgl^2 sa1 + 2 sa1^2 -
        4 mgl^2 sa1 x - 4 sa1^2 x +
        2 sa1^2 x^2) + (2 Log[1 + mgl^2/sa1 - x])/(-1 + x));

Now take the indefinte integral
f1 = Integrate[f, x]

(*
Out[6]= (cA mgl^2)/(4 (-mgl^2 - sa1 + sa1 x)) + cA Log[1 - x] -
 cA Log[sa1/(mgl^2 + sa1)] Log[1 - x] - cA Log[(mgl^2 + sa1)/sa1] Log[1 - x] -
  cF Log[1 - x]^2 - 1/2 cA cF Log[-1 + x]^2 + cF^2 Log[-1 + x]^2 -
 cA cF Log[-1 + x] (Log[-1 + 1/x] - Log[-1 + x] + Log[x]) +
 2 cF^2 Log[-1 + x] (Log[-1 + 1/x] - Log[-1 + x] + Log[x]) -
 1/4 cA Log[mgl^2 + sa1 - sa1 x] - cA cF PolyLog[2, 1 - x] +
 2 cF^2 PolyLog[2, 1 - x] +
 cA (Log[1 - (sa1 (1 + mgl^2/sa1 - x))/mgl^2] Log[1 + mgl^2/sa1 - x] +
    PolyLog[2, (sa1 (1 + mgl^2/sa1 - x))/mgl^2])
*)

Calculate the limit at the lower end of the interval
fi0 = Limit[f1, x -> 0]

(*
Out[23]= -(2/3) cA cF \[Pi]^2 + (4 cF^2 \[Pi]^2)/3 - (cA mgl^2)/(4 (mgl^2 + sa1)) -
 1/4 cA Log[mgl^2 + sa1] + cA Log[-(sa1/mgl^2)] Log[(mgl^2 + sa1)/sa1] +
 cA PolyLog[2, 1 + sa1/mgl^2]
*)

and similarly for the limit at the upper end of the interval
fi1 = Limit[f1, x -> z]

(*
Out[24]= -((cA mgl^2)/(4 (mgl^2 + sa1 - sa1 z))) + cA Log[1 - z] -
 cA Log[sa1/mgl^2] Log[1 - z] - cA Log[(mgl^2 + sa1)/sa1] Log[1 - z] +
 cA Log[1 + sa1/mgl^2] Log[1 - z] - cF Log[1 - z]^2 -
 cA cF Log[-1 + 1/z] Log[-1 + z] + 2 cF^2 Log[-1 + 1/z] Log[-1 + z] +
 1/2 cA cF Log[-1 + z]^2 - cF^2 Log[-1 + z]^2 +
 cA Log[1 + mgl^2/sa1 - z] Log[(sa1 (-1 + z))/mgl^2] -
 cA cF Log[-1 + z] Log[z] + 2 cF^2 Log[-1 + z] Log[z] -
 1/4 cA Log[mgl^2 + sa1 - sa1 z] + cF (-cA + 2 cF) PolyLog[2, 1 - z] +
 cA PolyLog[2, (mgl^2 + sa1 - sa1 z)/mgl^2]
*)

The difference should be the value of the definite integral:
fd = fi1 - fi0 // Simplify

(*
Out[25]= 2/3 cA cF \[Pi]^2 - (4 cF^2 \[Pi]^2)/3 + (cA mgl^2)/(4 (mgl^2 + sa1)) - (
 cA mgl^2)/(4 (mgl^2 + sa1 - sa1 z)) + 1/4 cA Log[mgl^2 + sa1] -
 cA Log[-(sa1/mgl^2)] Log[(mgl^2 + sa1)/sa1] + cA Log[1 - z] -
 cA Log[sa1/mgl^2] Log[1 - z] - cA Log[(mgl^2 + sa1)/sa1] Log[1 - z] +
 cA Log[1 + sa1/mgl^2] Log[1 - z] - cF Log[1 - z]^2 -
 cA cF Log[-1 + 1/z] Log[-1 + z] + 2 cF^2 Log[-1 + 1/z] Log[-1 + z] +
 1/2 cA cF Log[-1 + z]^2 - cF^2 Log[-1 + z]^2 +
 cA Log[1 + mgl^2/sa1 - z] Log[(sa1 (-1 + z))/mgl^2] -
 cA cF Log[-1 + z] Log[z] + 2 cF^2 Log[-1 + z] Log[z] -
 1/4 cA Log[mgl^2 + sa1 - sa1 z] - cA PolyLog[2, 1 + sa1/mgl^2] +
 cF (-cA + 2 cF) PolyLog[2, 1 - z] +
 cA PolyLog[2, (mgl^2 + sa1 - sa1 z)/mgl^2]
*)

All these calculations are done by MMA in almost no time.
It should be mentioned that, stricly speaking, we should check if the indefinite integral is a continuous function of x. If not, the result obatined may be wrong. But continuity depends of the parameters of the problem, and therefore is not easily checked.


text:
Q: Android - Cannot get custom LinearLayout view to move with TranslateAnimation I'm trying to do something simple - I have a custom LinearLayout view that I want to move across the screen using the TranslateAnimation. To test out the base case, I put the code in the constructor of my custom view to translate it as soon as it is created. But nothing happens, and the view stays put. Any idea why? I have pasted the relevant code below:
My custom LinearLayout View:
public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.my_view, this);

        mText = (TextView) findViewById(R.id.my_text);
        mImage = (ImageView) findViewById(R.id.my_picture);

        //Test simple translate animation
        TranslateAnimation translateMyView = new TranslateAnimation(10, 10, 5, 5);
        translateMyView.setFillAfter(true);
        translateMyView.setDuration(1000);
        this.startAnimation(translateMyView);

    }

The XML of this custom view:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/border">

    <TextView
        android:id="@+id/my_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Example Text"/>

    <ImageView
        android:id="@+id/my_picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"/>

</LinearLayout>

And the way I have added this view in the main activity's view:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}"
    android:id="@+id/main_view">

    <com.pratikthaker.MyView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

</RelativeLayout>

What am I missing?


text:
Q: Excel VBA: Defining variable which includes reference to other dynamic variable I am quite new to VBA and given how much time I've spent trying to resolve the following problem, I would certainly appreciate some help.
This is a simplified example of what I am trying to do. In a nutshell, I need to populate Column AA with either one static value of "*" or multiple rows extracted from another column. I keep getting a run-time 1004 error.
Sub test()
TotalBG = 2
SelBG = 1

If TotalBG = SelBG Then
Column1RowCount = 2
Column1Value = "*"
Else
Column1RowCount = Worksheets("Sheet3").Range("Q25000").End(xlUp).Row
Column1Value = Worksheets("Sheet3").Cells(Column1Loop, "Q").Value
End If

k = 2
For Column1Loop = 2 To Column1RowCount
Worksheets("Sheet3").Cells(k, "AA").Value = Column1Value
k = k + 1
Next Column1Loop

End Sub

The line which is giving the error is:
Column1Value = Worksheets("Sheet3").Cells(Column1Loop, "Q").Value

I think the reason is that I am referencing a Variable name (Column1Loop) which has not yet been defined. Seems like a Catch 22 (for me, that is) - someone please help!
Cheers,
Peter

A: You code snippet indeed contains error and will not execute properly because Column1Loop is empty pertinent to that particular statement (see the following line from your code snippet):
Column1Value = Worksheets("Sheet3").Cells(Column1Loop, "Q").Value

You may modify your code to fix this issue like shown below:
 Column1Value = Worksheets("Sheet3").Cells(Column1RowCount, "Q").Value

where Column1RowCount would be the value of Column1Loop var upon the execution of For-Next loop.
Hope this may help.


text:
Q: My jquery banner is not shrinking for responsive?what property shall I need to use here? My jquery banner is not shrinking?what property I have to use here?In my mobile.css I have used class .banner width:100%.even though It is not shrinking for width 260px.I want to know what property do i need to used.check this link. I have hosted in webserver.  http://vkacademy.in/banner/

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="slider/css/skitter.styles.css" type="text/css" media="all" rel="stylesheet" />

One

Two

Three

Four

Five

Six

My defaul.css

body {
/*background-color:#F2F2F2;*/
background-color: #FFF;
padding: 0px;
margin: 0px;
font-weight: normal;
font-family: Arial;
}
.clear {
clear: both;
}
ul, li, a, h1, h2, h3, h4, h5, h6 {
padding: 0px;
margin: 0px;
}

.banner {
width: 1000px;
height: auto;
margin: auto;
/*margin:0px 0px -4px 0px;*/
z-index: 100;
}
.banner img {
width: 100%;
height: auto;
}
my mobile.css.
@media only screen and (max-width:530px)
{
/*(common width:260px;)*/
#wrapper
{
width:260px;
}
.header
{
width:260px;
height:auto;
}
.logo
{
width:260px;
height:90px;
text-align:center;
}

.banner
{
width:100%;
}
.banner img
{
width:100%;
height:100px;
}
}

A: Your media query styles will only apply if they have higher specificity than your default styles, or same specificity but appear later in your stylesheet. One way to resolve this is to reorder your style rules. Another way is to add a second media query:
@media only screen and (min-width:531px)
{
    .banner {
        width: 1000px;
    }
}

Remove the width from the regular .banner style and let the media queries handle all the width rules.


text:
Q: Setting up pglogical over ssh tunnel, connection reset by peer I am setting up a pglogical replication between an on-premise PostgreSQL 10.14 (publisher and AWS RDS Postgresql 10.16 (subscriber), but after setting up a subscription, I only get to connection resets. Can anyone spot what I'm doing wrong?
Network setup:
On-premise postgres < jumphost > <-- ssh tunnel --> AWS RDS
internal-ip                          10.2.0.8       db01.some.tld

I have verified that the ssh tunnel is working:

*

*I can connect to the on-premise postgres from AWS using psql connecting to the tunnel

*I can even connect to the on-premise postgres from AWS RDS when using postgres_fwd

Pglogical setup:
on-premise:

*

*create node with dsn host=10.2.0.8 dbname=... user=... password=...
AWS:

*

*create node with dsn host=db01.some.tld dbname=... user=... password=...

*create subscription with dsn host=10.2.0.8 dbname=... user=... password=...
Once that is done:

*

*pglogical processes are running on both the provider and subscriber

*but I get to the following errors:
AWS:

LOG:  could not receive data from client: Connection reset by peer
LOG:  unexpected EOF on client connection with an open transaction

On-premise:

LOG:  unexpected EOF on client connection with an open transaction

I have tried fiddling around with logging parameters, but couldn't get to anything useful. Similarly I couldn't get anything helpful from the ssh tunnel logs.
Any idea what I could be doing wrong?

A: Figured it out. In this case:
The connection was fine. However, there was an issue with the schema of one table on the replica, causing the replication to die.


text:
Q: Extract numbers from string Webi BO I'm almost new to Webi BO. I need to extract numbers from string. The string looks like below:
x Y Z
where x is variable length text, Y is the required number to be extracted (also may vary in length 0, or 00 or 000 or 0.00, 00.00, or 000.0, ... and Z is a fixed length text of 5 characters.
example for string:
sodium chloride 0.9% + Potassium chloride 50 mL/hr

x is sodium chloride 0.9% + Potassium chloride
Y is 50
Z is  mL/hr
The value of Y is needed to be extracted. Is there any formula to help with this regard?
Thank you.

A: This is not possible natively in Web Intelligence. Since X is variable in length and Z is a fixed length the only way see solving this is by looking for that space in front of Y which is possible if we reverse the string. However, there is no reverse function in WebI. Could you do this in your universe or in free-hand SQL?
This is what it would look like in SQL Server...
DECLARE @MyString VARCHAR(100);
DECLARE @Length INT;
DECLARE @Y_Index INT;
DECLARE @Y_Length INT;
DECLARE @Z_Index INT;

SET @MyString = 'sodium chloride 0.9% + Potassium chloride 50 mL/hr';
-- get total string length
sET @Length = LEN(@MyString);

-- find index (starting position) of Y
SET @Y_Index = @Length - CHARINDEX(' ', REVERSE(@MyString), 7) + 2;

-- find index (starting position) of Z
SET @Z_Index = @Length - CHARINDEX(' ', REVERSE(@MyString)) + 2;

SELECT
    @MyString                                                  AS [MyString]
  , REVERSE(@MyString)                                         AS [MyStringReversed]
  , @Length                                                    AS [MyStringLength]
  , @Y_Index                                                   AS [Y Index]
  , @Z_Index                                                   AS [Z Index]
  , RTRIM(SUBSTRING(@MyString, @Y_Index, @Z_Index - @Y_Index)) AS [Y];

Here is a link see it in action.


text:
Q: Expanding my search function I am looking at trying to expand my search function for my small project.  Right now I have the ability to search using a char field but I want to add a few checkboxes.  Some projects have been flagged with the SRED checkbox and I want to be able to also search for SRED only projects.
Here is my current search setup.
models.py
class Project(models.Model):
...
proj_name = models.CharField(max_length=255, verbose_name='Project Name')
pre_quote = models.CharField(max_length=3)
quote = models.IntegerField(max_length=10, verbose_name='Quote #', unique=True)
...
SRED = models.BooleanField()
...

Views.py
@login_required
def search(request):
if request.method == 'POST':
    form = SearchProjectForm(request.POST)
    if not form.is_valid():
         return render_to_response('project/search.html', {'form': form}, context_instance=RequestContext(request))
    else:
        projects = Project.objects.filter(proj_name__icontains = form.cleaned_data["text"])
        companies = Clients.objects.filter(client_name__icontains = form.cleaned_data["text"])
        return render_to_response('project/search.html', {'form': form, 'projects':projects, 'companies': companies}, context_instance=RequestContext(request))

form = SearchProjectForm()

return render_to_response('project/search.html', {'form': form}, context_instance=RequestContext(request))

forms.py
class SearchProjectForm(forms.Form):
    text = forms.CharField(label = "Search")

search.html
<form method="POST" action="">
{% csrf_token %}
{{form}}
<input type="submit" value="Search"/>
</form>

Search Results

...

Any help would be greatly appreciated!
Thanks again
Steve

A: You need to pass project to Form constructor and then add box fields if necessary:
form = SearchProjectForm(project, request.POST)

and:
class SearchProjectForm(forms.Form):
    text = forms.CharField(label = "Search")

    def __init__(self, project, *args, **kwargs):
      form = forms.Form.__init__(self, *args, **kwargs)
      if project.has_additional_fields():
        self.fields['additional_field'] = forms.SomeField()
      if project.only_additional_fields():
        self.fields['text'].required = False

More here: http://jacobian.org/writing/dynamic-form-generation/


text:
Q: Multiple Wilcoxon Signed Rank test in R I have a question about performing multiple Wilcoxon test in R. I have 7 datasets that for each I need to compare 9 different feature extraction methods using 10 classifiers. As they are stochastic methods, I have 10 values/repetitions for each classifier. A simple example for a single dataset let's assume we have 3 methods, 3classifiers, 3 repetitions:
Method, Classifier, Accuracy
M1, C1, 2.4
M1, C1, 2.3
M1, C1, 6.4
M1, C2, 0.4
M1, C2, 1.3
M1, C2, 6.8
M1, C3, 3.4
M1, C3, 2.7
M1, C3, 2.4
M2, C1, 0.4
M2, C1, 2.8
M2, C1, 3.4
M2, C2, 7.4
M2, C2, 2.3
M2, C2, 6.5
M2, C3, 1.4
M2, C3, 2.7
M2, C3, 7.4
M3, C1, 2.0
M3, C1, 1.3
M3, C1, 7.2
M3, C2, 8.4
M3, C2, 1.3
M3, C2, 9.8
M3, C3, 3.9
M3, C3, 3.7
M3, C3, 0.9

Now, I need a way to perform the Wilcoxon test between each pair of these classifiers for different methods, i.e., M1.C1 vs M2.C1,C2,C3, M1.C1 vs M3.C1,C2,C3, and so on. Can someone suggests an appropriate way to load the data and perform the multiple tests in a simple way as I am relatively new to R. Many thanks in advance for any suggestions


text:
Q: making fields editable in row in reactjs As of now when I was clicking on the edit icon, a form was getting opened and we used to change the data and save it.
but now I have a requirement in which once user click on edit icon the same row ,other than certificateNo should be editable. and edit button should be replaced by save. and user can save data there,without going to any other page.
How to approach that? any suggestions?

     {response.map((certificate: Certificate,index:number) => {
            return (

               {certificate.certificateNo}
               {certificate.sponser}
               {certificate.protoColNo}
               {certificate.startDate}
               {certificate.endDate}
               {certificate.noOfSubjects}
               {certificate.country}
               {certificate.requestStatus}

               <button className="btn btn-sm btn-outline-secondary" onClick={()=>updateCertificate(certificate,index)}>

               </button>

A: You need some way of being able to identify the row being edited, and a place to save the current edited data. That can be achieved by using state.
When the id of an object in your data array matches the current selected row (after you've clicked the edit button) return one set of row data that includes input elements. If the id doesn't match, return normal row data.
Here's a minimal working example.

const { useState } = React;

const data = [
  { id: 1, name: 'Rita', age: 22 },
  { id: 2, name: 'Sue', age: 42 },
  { id: 3, name: 'Bob', age: 12 }
]

function Example({ data }) {

  // Have states for the data, the current selected row
  // and the data that is currently being edited
  const [ rowData, setRowData ] = useState(data);
  const [ selectedRow, setSelectedRow ] = useState(0);
  const [ editData, setEditData ] = useState({});

  // Compiles the row data
  function getRows() {

    return rowData.map((obj, i) => {

      // Get the id, name, and age from the
      // current object
      const { id, name, age } = obj;

      // If the id of the current object equals
      // the selected row return a set of row data with input
      // elements (not id though) auto-populated with the
      // information from that object
      if (id === selectedRow) {
        return (

            {editData.id}

              <input
                className="edit"
                type="text"
                name="name"
                value={editData.name}/>

              <input
                className="edit"
                type="text"
                name="age"
                value={editData.age}
              />

            <button
              data-id={id}
              data-action="Save"
            >Save
            </button>

        );
      }

      // Otherwise return a set of non-editable
      // row data
      return (

          {id}
          {name}
          {age}
          <button
            data-id={id}
            data-action="Edit"
          >Edit
          </button>

      );

    });

  }

  // When a button has been clicked
  // Note: because we're using event delegation
  // (attaching listeners to the table element instead
  // of all the rows) we need to check that element
  // we clicked on is the button
  function handleClick(e) {

    const { nodeName } = e.target;

    if (nodeName === 'BUTTON') {

      const { id, action } = e.target.dataset;

      // If the button action is edit, set the
      // selected row state, and auto-populate the
      // editData state
      if (action === 'Edit') {
        setSelectedRow(+id);
        const obj = data.find(obj => obj.id === +id);
        setEditData({...obj});
      }

      // If the action is save filter out the matching
      // object from the data state, and then update the data
      // with the filtered object, plus the object in
      // the editData state, making sure you sort by id
      // otherwise the edited row will appear at the bottom
      // Then reset the states
      if (action === 'Save') {
        const filtered = data.filter(obj => obj.id !== selectedRow);
        const updated = [...filtered, editData];
        updated.sort((a, b) => a.id - b.id);
        setRowData(updated);
        setSelectedRow(0);
        setEditData({});
      }

    }

  }

  // When an input changes
  // Again we need to check that the element
  // that has changed is an input
  function handleChange(e) {

    const { nodeName } = e.target;

    // Update the editData state using the input
    // name and value
    if (nodeName === 'INPUT') {
      const { name, value } = e.target;
      setEditData({ ...editData, [name]: value });
    }

  }

  // We attach two listeners to the table element
  // One to catch clicks from the button
  // The other to catch changes to the inputs if
  // we're in edit mode
  return (

        ID
        Name
        Age

        {getRows()}

  );
};

ReactDOM.render(
  <Example data={data} />,
  document.getElementById('react')
);
table { border: 1px solid #898989; border-collapse: collapse; }
td, input { width: 75px; text-align: center; }
td { padding: 0.2em; border: 1px solid #898989; }
.heading { background-color: #efefef; text-align: center; font-weight: 600; }
.edit { background-color: #ffffcc; }


text:
Q: iTunes: Move files off a network drive I have somehow screwed up my iTunes database such that iTunes/iTunes Music Library.xml contains network paths:
<key>Location</key><string>file://localhost/Volumes/media/Music/iTunes/iTunes%20Media/Music/Unknown%20Artist/Unknown%20Album...</string>

Most of the files are where they belong, in file://localhost/Users/Shared/..., but not all. Furthermore, all of the files are located on the local disk, e.g. /Volumes/media/Music/iTunes/iTunes Media/Music/Artis/Album/Track.mp3 has been copied into the local directory /Users/Shared/Music/iTunes/iTunes Media/Music/Artis/Album/Track.mp3.
I used File > Library > Organize Library..., and enabled the Consolidate files checkbox (along with Reorganize files in the folder "iTunes Media"), but this did not move all of the network-located files onto the local disk.
iTunes/iTunes Music Library.xml itself appears to be a write-only file, based off the contents of the binary file iTunes/iTunes Library.itl, so closing iTunes, editing iTunes/iTunes Music Library.xml to correct the paths, and restarting iTunes doesn't fix the issue.
Is there a way to update the iTunes database so that it uses local file paths instead of network paths for some of the files? (This impacts 9888 entries out of 11449 entries within iTunes.)

I have a similar/identical issue with iPhoto, in which some files are network located, and some aren't, and I don't know how to consolidate them to all be on the local machine...

A: Reset the iTunes Library
Open the iTunes music folder in Finder ( it's in your home folder / Music / iTunes) and drag iTunes Music Library.xml and iTunes Library.itl out on the desktop. This will reset iTunes next time you start it, but don't start it yet. We'll be working on the xml file, while the itl file is just there for backup.
Change the location of where iTunes keeps the music
In the iTunes preferences > Advanced, click on "change" next to the "iTunes music folder location", and select your hard disk.
Look inside iTunes Library to see what the problem is
If your iTunes library is huge, it's a good idea to use Terminal to look at the first few lines, which you can do easily with

head -n100 /Users/ME/Desktop/iTunes\ Music\ Library.xml

(you can just type "head -n100 " and drag the file onto Terminal to let OS X type out the name for you)
The output will be something along the lines of

  <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
      <key>Major Version</key><integer>1</integer>
      <key>Minor Version</key><integer>1</integer>
      <key>Date</key><date>2012-08-13T21:09:21Z</date>
      <key>Application Version</key><string>10.6.3</string>
      <key>Features</key><integer>5</integer>
      <key>Music Folder</key><string>file://localhost/Volumes/HD1T/Music/</string>
      <key>Library Persistent ID</key><string>C326B89DCF4457DF</string>
      <key>Tracks</key>
      <dict>
          <key>41557</key>
          <dict>
              <key>Track ID</key><integer>41557</integer>
              <key>Name</key><string>Fifths (Jazzanova 6 Sickth Mix)</string>
              <key>Artist</key><string>Ski</string>
              <key>Album</key><string>Jazzanova: The Remixes, 1997-2000</string>
              <key>Grouping</key><string>where:de</string>
              <key>Genre</key><string>ambient-synth-90s</string>
              <key>Kind</key><string>MPEG audio file</string>
              <key>Size</key><integer>19718194</integer>
              <key>Total Time</key><integer>482925</integer>
              <key>Disc Number</key><integer>2</integer>
              <key>Disc Count</key><integer>2</integer>
              <key>Track Number</key><integer>1</integer>
              <key>Track Count</key><integer>10</integer>
              <key>Year</key><integer>2000</integer>
              <key>Date Modified</key><date>2008-12-05T14:26:06Z</date>
              <key>Date Added</key><date>2012-07-14T07:42:37Z</date>
              <key>Bit Rate</key><integer>320</integer>
              <key>Sample Rate</key><integer>44100</integer>
              <key>Play Count</key><integer>12</integer>
              <key>Play Date</key><integer>3321087305</integer>
              <key>Play Date UTC</key><date>2009-03-28T10:15:05Z</date>
              <key>Rating</key><integer>80</integer>
              <key>Album Rating</key><integer>80</integer>
              <key>Album Rating Computed</key><true/>
              <key>Artwork Count</key><integer>1</integer>
              <key>Persistent ID</key><string>E5B52C3DE807B7DC</string>
              <key>Track Type</key><string>File</string>
              <key>File Type</key><integer>1297106739</integer>
              <key>Location</key><string>file://localhost/Users/ME/Music/iTunes/iTunes%20Media/Music/Ski/Jazzanova_%20The%20Remixes,%201997-2000/Fifths%20(Jazzanova%206%20Sickth%20Mix).mp3</string>

You need to look out for the file:// bit of the xml. Here it is telling me that it is looking into /Users/ME/Music/, i.e. my home folder instead of my external hard disk.
Use sed to fix the path and create a new xml file
sed is a nifty unix utility which you can use from Terminal. It can open a file, go through it line by line, change things on each line, and then put the result in another file.

sed 's/file:\/\/localhost\/Users\/ME\/Music\/iTunes\/iTunes%20Media\//file:\/\/localhost\/Volumes\/HD1T\//'  < /Users/ME/Desktop/iTunes\ Music\ Library.xml  > /Users/ME/Music/iTunes/iTunes\ Music\ Library.xml

Here's a breakdown of what the command does.
sed calls the sed command - it stands for Stream Editor
's/…/…./' sed will itself need instructions, which are strings hence the ' (apostrophe). s/a/b/ means "if you find an a, substitue it with b"
file:\/\/localhost\/Users\/ME… this is the string we are looking for. Note that given that forward slashes are used by sed for s/…/…/, if you need them in the string you have to escape them with backward slashes
file:\/\/localhost\/Volumes\/HD1T\/ the string we are replacing with
< /Users/ME/Desktop/iTunes\ Music\ Library.xml The less than sign means "use this file as input" - in this case, the xml file I had dragged to the Desktop
>  /Users/ME/Music/iTunes/iTunes\ Music\ Library.xml and this means "create this file as output". We are asking sed to recreate the xml library file from the one on the desktop, but changing some bits around as it does so
Create a broken iTunes library
Now this is important - if you just start iTunes now, with the new .xml file there and no .itl file there, nothing will happen. iTunes will ignore the xml file, and just reset to an empty library. But if iTunes finds a broken .itl file, it will use the .xml file we just fiddled with to recreate the .itl file. The easiest way to create a broken .itl file is from terminal:

touch ~/Music/iTunes/iTunes\ Library.itl

which will create an empty file - broken enough for iTunes.
Restart iTunes
Now iTunes will finally pay attention to the xml file - it will show a dialog saying 'Importing 'iTunes Music Library.xml'…" This may take a while, even though it isn't actually copying mp3 files around.
Source: http://gotofritz.net/blog/howto/fixing-itunes-cannot-find-music/

A: I haven't tried the much better sounding answer by @Tesujin. I'm certain his is much faster than what I did do.
This "solution" worked for me. It also consumes lots of disk space. However, as an added "benefit," it found several files which were overlooked...

*

*Click iTunes > Preferences...

*Click the Advanced tab.

*Change the iTunes Media Folder location, e.g. to another disk. Something with a path name that won't be too similar to the current path, to make grep(1) easier later.

*Click OK, and dismiss the Preferences window.

*Click File > Library > Organize Library..., enabled the Consolidate files checkbox, and click OK.
This will result in copying over your library into the new location, "fixing up" the paths as it goes. This in turn means you need enough free disk space to store two complete copies of your music library.

*Quit iTunes.

*Verify the contents of iTunes/iTunes Music Library.xml, by grepping that it doesn't contain the previous path(s):
$ grep Users/Shared 'iTunes Music Library.xml'
$ grep Volumes/media 'iTunes Music Library.xml'

What you want is no matches. What I actually got was several matches; the network mount was still being used for ~10 files, while the previous location had ~5 matches.
At this point, more investigation was warranted. As It Turns Out™, my network share had a case-sensitive filesystem, so the files which weren't copied were because of case changes, e.g. the song was actually in 'ArTist/Album/Song.mp3' while there was also an 'Artist/Album/Another Song.mp3' file; iTunes apparently doesn't like artists/albums which differ only in case, and there were ~10 of these.
Fixing these remaining issues was simple, if weird:

*

*Find the source file in Finder. (This may require copying the file via root shell on the NAS... ;-)

*Find the "bad" entry within iTunes.

*File > Get Info the entry.

*iTunes may complain that it can't find the file. Refer iTunes to the file in (1).

*Go to the File tab, and double-check the location entry. For example, the location was on my NAS.

*Click OK

*Drag the file in (1) onto iTunes. iTunes will now copy the file, thus removing the need for my NAS for this particular file.

*Verify that the location is fixed via (4) and (5).

What's funny is that if I skipped the initial steps (2)-(5), iTunes would copy the file but there would be two of the songs within iTunes, one on the NAS/wrong location, and one just added. I needed to Get Info the file first in order to "update" the file location.


text:
Q: Can a Virtual PC emulate a mac address for the network card too? Can a Virtual PC emulate a mac address for the network card too?  It probably is possible but I think the Virtual PC / VirtualBox / VMWare / Parallel, all probably won't support it as the mac address is supposed to be unique?

A: Yes, this can be done in Virtual PC, VMWare, VirtualBox and Parallels.
All the VM apps allow this, because VMs are often used to test network configurations and being able to simulate machines with specific MAC addresses can be useful.


text:
Q: How do you read .txt with tab separated items that are on one line to a list? I have this .txt:
'4  1   15  12'
It's just one long line separating its' items with tab. I need to read it into a list containing int items.
I can't seem to make pandas, csv module or open to do the trick.
This kinda works:
f = open('input.txt')
for line in f:
    memory = line.split()
for item in memory:
    item = int(item)

print(memory)

['4', '1', '15', '12']

But it gives me an error when i compare its' max value to an int:
 max_val = max(memory)
 while max_val > 0:
TypeError: '>' not supported between instances of 'str' and 'int'

A: its a TypeError you cant check if a type(str) is a type(int) because they are both different types
max_val = max(memory)
print(type(max_val))
>>> <class 'str'>

just change max_val to an int for example
max_val = max(memory)
while int(max_val) > 0:

A: It appears as though the text in the question was not tab spaced.
I have created a tab spaced file and the following works:
import pandas as pd

test_file = "C:\\Users\\lefcoe\\Desktop\\test.txt"

df = pd.read_csv(test_file, delimiter='\t', header=None)

print(df)

#%% convert to a list of ints
my_list = df.loc[0, :].values.tolist()
my_list_int = [int(x) for x in my_list]
my_list_int

#%% get the max
m = max(my_list_int)
print(m)

result:
   1  1  2  3
0  4  1  15 12

15


text:
Q: How to configure an application server in Intellij Idea 13 Ultimate SpringMVC project? I create new SpringMVC project then choose Run->EditConfiguraions then choose Defaults->TomcatServer->Local on the left, push the button "Configure..." and kinna don't know what to write in the opened dialog. Could you help me?

A: In this window you have to:

*

*Configure location of your Tomcat instance (Application server -> configure -> enter "Tomcat home").

*Then you go to "Deployments" tab and add your artifact (by clicking green cross)


text:
Q: What is the difference between ground state, excited state and transition dipole moment? I need to find a transition dipole moment of Rhodamine 6G molecule, however they provide ground state and excited state dipole moment. Are they similar or can I somehow obtain transition dipole moment from the given ones?

A: The transition dipole moment depends on which transition you are looking at. It gives you the probability of state $a$ transitioning into state $b$, and will look something like $\langle b | ...|a\rangle$, where the dots are to be replaced by the specific interaction-inducing term you are dealing with (magnetic moment, electric dipole moment, etc.).
So you should find transition dipole moments between any one state and any other state. Some of these transitions are forbidden by selection rules.


text:
Q: TryFor in Z3 does not stop checking after the given timelimit I am using the .NET API of Z3. When I instantiate a solver by calling:
Solver s = ctx.MkSolver(ctx.TryFor(ctx.MkTactic("qflia"), TimeLimit));

and give it a TimeLimit of 60 seconds (60000 milliseconds) for some models the statement
s.Check()

does not return after 60 seconds. For some models it returns a few seconds later, which in my case would not be a problem, but for some models it doesn't return at all (I cancelled the process after 3 days).
How can I force Z3 to stop checking after a given timelimit?

A: The TryFor combinator is implemented using a "cancellation" flag. The new tactics are very responsive, and terminate very quickly when the "cancellation" flag is set. Unfortunately, the general purpose tactic smt is a wrapper over a general purpose solver. This general purpose solver is not very responsive. It can get "lost" in several key places: quantifier instantiation, Simplex, etc. The qflia tactic is built on top of the smt and many other tactics. Since, you are trying to solve quantifier-free problems. I'm assuming that the smt tactic is in a loop inside of the Simplex module. The Simplex module in the smt tactic is implemented using arbitrary precision rational numbers. Thus, it may be very time consuming for non-trivial linear real/integer problems.
There is not much you can do to workaround this issue. If you really need a strong guarantee in running time, the only solution I see is to create a separate process running Z3, and kill it whenever it takes more the k seconds to solve a problem.
That being said, future versions of Z3 will have a complete new arithmetic module. This new module (like the new tactics) will terminate quickly when the cancellation flag is set.


text:
Q: Что передается в параметре конструктора? не особо понимаю эту строку, какой тип данных передается в параметрах конструктора, понятно, что "map" строка, а что такое center и zoom и почему это в квадратных скобках не понятно P.s не понимаю, что мне нужно прочитать чтобы понять что тут написано
var myMap = new ymaps.Map("map", {center: [59.943178, 30.415395], zoom: 12.5});

A: new ymaps.Map("map", {center: [59.943178, 30.415395], zoom: 12.5});

*

*"map" - строка;

*{center: [59.943178, 30.415395], zoom: 12.5} - объект

*center: [59.943178, 30.415395] - переменная объекта которая содержит массив

*[59.943178, 30.415395] - массив

*zoom: 12.5 - переменная объекта которая содержит число

*12.5 - число

Вы можете проверять тип методом typeof {center: [59.943178, 30.415395], zoom: 12.5} в консоли.

A: О смысле параметров zoom и center можно прочитать в документации:
https://tech.yandex.ru/maps/doc/jsapi/2.1/theory/index-docpage/

Для того, чтобы с картой было удобно работать, вводится понятие коэффициента  (уровня) масштабирования. На нулевом уровне весь «мир» отображается на область размером 256х256 пикселей. При увеличении коэффициента масштабирования на единицу размеры «мира» увеличиваются ровно в 2 раза и, следовательно, для уровня масштабирования z составляют 2z+8x2z+8 пикселей.

Zoom это и есть коэффициент масштабирования.
Center - это гео-координата центра экрана.


text:
Q: Nestjs - Can't resolve dependencies of service I don't know how to fix this issue. I keept trying but can't get my head arround it.
The log throws me this
Error: Nest can't resolve dependencies of the ERC20Service (?). Please make sure that the argument dependency at index [0] is available in the ERC20Module context.

import { DynamicModule, Module, Provider } from '@nestjs/common';
import { ERC20Service } from './erc20.service';
const Web3 = require("web3");

export interface ERC20ModuleOptions {
  global?: boolean;
  abi: Object,
  wsEndpoint: string,
  httpEndpoint: string
}

export const WEB3_HTTP_TOKEN = 'WEB3_HTTP_TOKEN';
export const WEB3_WS_TOKEN = 'WEB3_WS_TOKEN'

export class ERC20Module {
  static forRoot(options: ERC20ModuleOptions): DynamicModule {

    const httpProvider: Provider = {
      provide: WEB3_HTTP_TOKEN,
      useValue:new Web3(new Web3.providers.HttpProvider(options.httpEndpoint))
    };
    const wsProvider: Provider = {
        provide: WEB3_WS_TOKEN,
        useValue:new Web3(new Web3.providers.WebsocketProvider(options.wsEndpoint))
      };

    return {
      module: ERC20Module,
      providers: [httpProvider, wsProvider, ERC20Service],

      exports: [ERC20Service],
      global: options.global,
    };
  }
}

import Web3 from "web3"
import { Inject, Injectable } from '@nestjs/common';
import { WEB3_HTTP_TOKEN, WEB3_WS_TOKEN } from './erc20.module';

@Injectable()
export class ERC20Service {
    constructor(@Inject(WEB3_HTTP_TOKEN) private http: Web3,@Inject(WEB3_WS_TOKEN) private ws: Web3) {

    }
}

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from '@nestjs/config';
import { ERC20Module } from 'src/modules/erc20/erc20.module';
import { abi } from 'src/config/abi';

@Module({
  imports: [
    ConfigModule.forRoot(),
    ERC20Module.forRoot({
      global: true,
      httpEndpoint: `https://${process.env.CHAINSTACK_USER}:${process.env.CHAINSTACK_PASSWORD}@${process.env.CHAINSTACK_HTTP_ENDPOINT}`,
      wsEndpoint: `wss://${process.env.CHAINSTACK_USER}:${process.env.CHAINSTACK_PASSWORD}@${process.env.CHAINSTACK_WS_ENDPOINT}`,
      abi: abi,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

I must be blind because as far as I see it, I am doing everything the correct way when in comes to injecting, exporting and importing. Maybe someone on here can guide me along the way to solve this issue. Thank you in advance

A: Your erc20.service and erc20.module files import from each other, creating a circular dependency. Move the constants to a separate file and you should be good to go
// erc20.constants.ts
export const WEB3_HTTP_TOKEN = 'WEB3_HTTP_TOKEN';
export const WEB3_WS_TOKEN = 'WEB3_WS_TOKEN'

// erc20.module.ts
import { DynamicModule, Module, Provider } from '@nestjs/common';
import { WEB3_HTTP_TOKEN, WEB3_WS_TOKEN } from './erc20.constants';
import { ERC20Service } from './erc20.service';
const Web3 = require("web3");

export interface ERC20ModuleOptions {
  global?: boolean;
  abi: Object,
  wsEndpoint: string,
  httpEndpoint: string
}

export class ERC20Module {
  static forRoot(options: ERC20ModuleOptions): DynamicModule {

    const httpProvider: Provider = {
      provide: WEB3_HTTP_TOKEN,
      useValue:new Web3(new Web3.providers.HttpProvider(options.httpEndpoint))
    };
    const wsProvider: Provider = {
        provide: WEB3_WS_TOKEN,
        useValue:new Web3(new Web3.providers.WebsocketProvider(options.wsEndpoint))
      };

    return {
      module: ERC20Module,
      providers: [httpProvider, wsProvider, ERC20Service],

      exports: [ERC20Service],
      global: options.global,
    };
  }
}

// erc20.service.ts
import Web3 from "web3"
import { Inject, Injectable } from '@nestjs/common';
import { WEB3_HTTP_TOKEN, WEB3_WS_TOKEN } from './erc20.constants';

@Injectable()
export class ERC20Service {
    constructor(@Inject(WEB3_HTTP_TOKEN) private http: Web3,@Inject(WEB3_WS_TOKEN) private ws: Web3) {

    }
}


text:
Q: How to match data in logstash one data input from API and second from csv file on server I have tried all possible case but unable to match data between API and CSV file. my ultimate goal is read host key from REST API and matching with CSV file and print respective OS. Please suggest, Configuration as below -
    input{
  http{
      host => "*****"
      port => "****"
      type => "api_input"
     }
  file {
     path => "/etc/logstash/conf.d/Event.csv"
     start_position => "beginning"
     sincedb_path => "/dev/null"
  }
}
filter {
  csv {
      separator => ","
      skip_header => "true"
      columns => ["server", "os"]
      }
if [server] == [result][host] {
         mutate { add_field => { "OS_Name" => "%{[os]}" } }
           }

else{drop {}}
}
output {
  stdout {
    codec => rubydebug
    }
}

csv file data :-
server_1,Windows
server_2,Linux
server_3,Unix
server_4,Windows
API data :-
{"result":[{"host":"server_4","parameter":"22"}]}

A: The translate filter can do a lookup of a field in a two column CSV file.


text:
Q: has_many children and has_many parents I'm trying to figure out a complex relation between a Model.
I have a model called "Concept", which has two inheriting types called "Skill" and "Occupation". Basicly this means that each concept represents a category, but a concept can also be a skill or an occupation when going deep enough into the hierychal tree.
I'm solving this hierachy by using STI. So my schema for the Concepts table looks like this:
class CreateConcepts < ActiveRecord::Migration
  def self.up
    create_table :concepts do |t|
      t.string :uri, :null => false, :length => 255
      t.string :type, :null => true, :length => 255
      t.integer :isco_code, :null => true
      t.timestamps
    end
  end

  def self.down
    drop_table :concepts
  end
end

The type column determins whether the Concept is a real "Concept" or a "Skill"/"Occupation".
The problem now however the following relations:
EDIT:

*

*A Concept can belong to a single parent Concept

*An Occupation can belong to a single parent Concept

*A Skill can belong to multiple parent Concepts

*A skill has no children

*An occupation has no children

so basicly you'd have something like this:
>                             concept1
>                  concept2                  concept3
>        concept4       concept5        concept6     concept7    skill1
> occup1   skill2 occup2    skill5
> occup7    skill2  occup3   skill4
> occup4    skill1 occup8

I hope the picture is a bit clear what I'm trying to explain.
Currently I have created the following migration to try to solve the parent-child relation but I'm not sure how to map this with the associations...
class CreateConceptLinks < ActiveRecord::Migration
  def self.up
    create_table :concept_links do |t|
      t.integer :parent_id, :null => false
      t.integer :child_id, :null => false
      t.timestamps
    end
  end

  def self.down
    drop_table :concept_links
  end
 end

What I want to end up with is the following posssibilities:
concepta.parents => a Concept object
conceptb.children => an array of Conept objects
Occupation.parents => a Concept object
Occupation.children => []
Skill.parents => an array of Concept objects
Skill.children => []

Hope this is even possible...

A: You can model hierarchical relations in rails. You've got most of the way there with your migrations. Adding the relations below should allow you to do the method calls you'd like:
def Concept < ActiveRecord::Base
  has_many :child_links, :class_name => 'ConceptLink', :foreign_key => 'parent_id'
  has_many :children, :through => :child_links

  has_many :parent_links, :class_name => 'ConceptLink', :foreign_key => 'child_id'
  has_many :parents, :through => :parent_links
end

def ConceptLink < ActiveRecord::Base
  belongs_to :child, :class_name => "Concept"
  belongs_to :parent, :class_name => "Concept"
end

I'd also take a look at this blog posting which does a very good of explaining parent-child mappings in rails.


text:
Q: programmatically add css class to ListItem I need to produce with asp.net controls this structure, but ListItem doesn't allow add properties and classes.
What is the best way to do it?

SomeText

SomeText2

A: You can still add custom attributes:
// assuming li is your WebControl or HtmlControl:
li.Attributes.Add("class", "1");

A: You can pass-through class attribute:
<asp:BulletedList ID="BulletedList1" runat="server">
  <asp:ListItem class="1">SomeText</asp:ListItem>
  <asp:ListItem class="2">SomeText2</asp:ListItem>
</asp:BulletedList>

. . .
protected void Page_Load(object sender, EventArgs e)
{
   ListItem listItem = new ListItem("Test 3");
   listItem.Attributes.Add("class", "3");
   BulletedList1.Items.Add(listItem);
}

A: This works fine for me, but using dropdownlist and VB
    Dim ListItem As ListItem = New ListItem("All folders", 0)
    ListItem.Attributes.Add("style", "color:red;")
    DropDownListFolders.Items.Add(ListItem)

A: Dropdown in listview -- if you want to give popup window on selecting item when dropdown textsize is fixed:
protected void lstViewVehicle_ItemCreated(object sender, ListViewItemEventArgs e)
{
    try
    {
    if (e.Item.ItemType == ListViewItemType.InsertItem)
    {
        DropDownList ddl = (DropDownList)e.Item.FindControl("ddlDescription");
        if (ddl != null)
        {
            string description = exp_Type_Vehicle;
            clsBER objclsBER = new clsBER();
            DataSet ds = objclsBER.FillDropdown(description);

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                ListItem lstitem = new ListItem(dr["expense_description"].ToString(), dr["eid"].ToString());
                lstitem.Attributes.Add("title", dr["expense_description"].ToString());
                //lstitem.Attributes.Add("style", "color:blue");
                ddl.Items.Add(lstitem);
            }
            ddl.DataBind();
        }
    }
    }
    catch (Exception ex)
    {
        (new csComman()).dealWithEx(ex, Session);
        Response.Redirect("ErrorPage/ErrorPage.aspx", false);
    }
}


text:
Q: Is there such a thing as "inverse unrequited love" Is there such a thing as inverse unrequited love where someone loves you but you don't love yourself as much as they love you?
I'm thinking about a situation where it's like you're suffering from impostor syndrome in a relationship.
Does this phenomenon have a name?


text:
Q: settings to get 500 error on browsing sitecore/shell Currently on browsing sitecore/shell, I am getting 401 Error.
I want to get 500 error for this. What setting on sitecore folder or change in config file can help in this?


text:
Q: PyMySQL and Database My current school assignment is requiring us to create a library system to manage both members and books. I am using PyMySQL to create the codes in the back. I am also using Tkinter to do the front-end coding as well.
For instance, I have a membership creation feature in my library system. I know in MYSQL I would have to use the INSERT INTO TABLE VALUES (A,B,C) to insert a new entry into MYSQL. However, I am not sure how to read a user's input in PyMySQL and put that data into the database. I know what I did was wrong (in picture). I was just experimenting around.
memberid = input("Enter your member ID: ")
name = input("Enter your name: ")
faculty = input("Enter your faculty: ")
phoneNumber = input("Enter your phone number: ")
emailAddress = input("Enter your email address: ")

with connection.cursor() as cursor:
    query = "INSERT INTO Members VALUES(memberid, name, faculty, phoneNumber, emailAddress)"
    cursor.execute(query)
    print("Membership created")

Could you please help me? Thank you.

A: pymysql supports prepared statements see manual
with connection:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `members`  VALUES (%s, %s,%s, %s,%s)"
        cursor.execute(sql, (memberid, name, faculty, phoneNumber, emailAddress))


text:
Q: Get all the applications for a selected permisson Is there a way to get list of all applications that use certain permission group? For example, if I have some permissions like Location, Camera or Contacts, I want to show the list of applications that use selected permission.
Here is the example image, so basically if I click on Location I want to show every installed app that use location permissions.
Thanks.

    PackageManager packageManager = getContext().getPackageManager();
    List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(0);

    //Package name results
    ArrayList<String> packageList = new ArrayList<>();

    boolean isGranted;

    for (PackageInfo packageInfo : packageInfoList) {

        isGranted = PackageManager.PERMISSION_GRANTED == packageManager.checkPermission(Manifest.permission.ACCESS_FINE_LOCATION, packageInfo.packageName);

        if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
            //System apps
            continue;
        }

        if (isGranted) {
            packageList.add("" + packageInfo.applicationInfo.packageName);
        }
    }

    System.out.println("################# PACKAGES LIST: " + packageList);


text:
Q: QJackCtl - Alsa Unknown driver Here's my problem :
I just have installed QJackCtl on my Ubuntu 12.04 and when I start Jack I got this issue :
12:01:22.769 /usr/local/bin/jackd -dalsa -dhw:0 -r44100 -p1024 -n3 -i1 -o2
Cannot connect to server socket err = Aucun fichier ou dossier de ce type
Cannot connect to server socket
jack server is not running or cannot be started
Unknown driver "alsa"

If anyone knows the solution It would help me a lot !

A: My guess is you don't have the alsa-devel package installed, so when you compiled jackdmp it couldn't link to alsa.
Install that and recompile and I'm sure it'll work


text:
Q: SMART drive error Lenovo Y580 I have the same issue as this person, that apparently was never answered for him either.
http://forums.lenovo.com/t5/IdeaPad-Y-U-V-Z-and-P-series/I-have-problems-diagnosing-if-my-hard-drive-is-failing-or-not/td-p/1102689
I have a Lenovo Y580 with the combo SSD/HDD thing.  Mine is one terabyte his looks like the 750mb.
The disk tools show a SMART error when looking for S/N, but there is a S/N
--------------- SeaTools for Windows v1.2.0.10 ---------------
5/17/2014 10:45:30 AM
Model: ST1000LM024 HN-M101MBB
Serial Number: S2U5J9ACA16694
Firmware Revision: 2AR10001
Short DST - Started 5/17/2014 10:45:29 AM
Short DST - FAIL 5/17/2014 10:45:35 AM
SeaTools Test Code: 6C9AC2A4
Fix All Fast - FAIL 5/17/2014 10:47:20 AM
SeaTools Test Code: 6C9AC2A4
Identify - Started 5/17/2014 10:48:02 AM
Short DST - Started 5/17/2014 10:48:15 AM
Short DST - FAIL 5/17/2014 10:48:23 AM
SeaTools Test Code: 6C9AC2A4
Short DST - Started 5/17/2014 10:50:44 AM
Short DST - FAIL 5/17/2014 10:50:48 AM
SeaTools Test Code: 6C9AC2A4
SMART - FAIL 8/13/2014 7:50:00 PM
SeaTools Test Code: 6C9AC2A4

is this due to Lenovo's special combine two drive and make them act like one thing or is this a legit error?

A: what you have in hands is a damaged system array, the idea behind platter HDD+SSD is to make the SSD as 'boot device' and the HDD as 'shadow'+cache+storage, but the system relies in a faulty Lenovo OEM software for that purposes instead of your chipset manufacturer software
as IT technician i have seen this a couple of times, and every time the best shot is to use the SSD as boot and keep the HDD as storage unit
the standard procedure is doing a clean install in the SSD and then erase the HDD, run a recovery software in order to 'salvage' info on the HDD, later create partition(s) on the HDD and put back the recovered info
i suggest you, if the pc is on warranty, sent it for a checkup, and ask for a backup of your info, since the fault is in the software that came 'by default' with the pc they're in the obligation of doing it


text:
Q: Store JSON object in temp file I have a project where I'm pulling in a large amount of content from a JSON array and only showing a little bit of it at a time. The JSON array can contain video or audio files so I want to avoid loading the entire array since it will be loaded on a mobile device.
I'm hoping to load the array into a temp file or some sort of local storage so I can pre-load the content. Alternatively, if there was a way to use AJAX to quickly iterate thru each item in the stored in the array which sits on MongoDB then that would work as well.
Any suggestion on this would be greatly appreciated.

A: I guess that you need to split the json in chunks,

*

*Server-side:
client only request page 1 of info, when the info is soon gone it ask for page 2 and so on... i that way you won't have to deal with tons of info and the server won't have to give you tons of info that you may not even use.

*Client:
you could store on many files or just load the json into the page as needed.


text:
Q: CS:GO case drop limit? Hello I have been playing CS:GO all week and only gotten 1 case and 1 camo drop. I am on reduced earned xp for whatever reason if that matters. Have I reached my limit for this week or is there even a weekly limit?

A: There is a 1 weapon per week limit for dropped weapons.
http://www.counter-strike.net/operationbloodhound/

How do I earn weapon drops?
There is only one way to earn weapon drops. You can receive one weapon drop per week. You will receive this drop the first time you increase your Rank during the week. Your level progress bar will indicate when you are eligible for an earned weapon.

For crates, I receive 1-3 per week on average.
The 'week' resets on Tuesday nights.


text:
Q: Adding resolve to Angular ui-router nested views? I am trying to create a version on my Angular 1.4.12 app with nested views. The reason is that some sections of my app have a header/content/footer setup and some do not.
My index page has a single ui-view.

Into that, via ui-router, I load routes that have multiple views;  most of the time, it's a header/content/footer, such as home.html:

Using a route such as:
  angular.module('app').config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/home');
    $stateProvider.state('home', {
      url: '/home',
      views: {
        '': {
          templateUrl: 'modules/home/home.html'
        },
        'header@home': {
          templateUrl: 'modules/header/header.html'
        },
        'content@home': {
          controller: 'HomeController as hc',
          templateUrl: 'modules/home/home.content.html'
        },
        'footer@home': {
          templateUrl: 'modules/footer/footer.html'
        }
      }
    });
  });

There are links on the content html and the header html with swaps the 3 views for another stub page like home.html above with 1, 2, or all 3 subviews (header, content, and/or footer).
Not sure if this is the best way to do this, but it's working so far.
My roadblock now is trying to use resolves for the routes.  For example, let's say the HomeController needs data from a service.  In other apps, I'd use a resolve, such as:
    resolve: {
      PeopleResolve: function (MockDataFactory) {
        return MockDataFactory.query({filename: 'ds_users'});
      }
    },

However, when I try adding this to the routes.js file as shown above, the page does not load (no console errors, which is confusing, just a blank page).
    $stateProvider.state('home', {
      url: '/home',
      resolve: {
        PeopleResolve: function (MockDataFactory) {
          return MockDataFactory.query({ filename: 'ds_users' });
        }
      },
      views: {
        '': {
          templateUrl: 'modules/home/home.html'
        },
        'header@home': {
          templateUrl: 'modules/header/header.html'
        },
        'content@home': {
          controller: 'HomeController as hc',
          templateUrl: 'modules/home/home.content.html'
        },
        'footer@home': {
          templateUrl: 'modules/footer/footer.html'
        }
      }
    });

Is there something obvious I am missing here?
UPDATE 1:
Based on a comment I added this to my app.module, found here after a search:
angular.module('app', ['ui.router']).run(function ($state, $rootScope) {
$rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {
  event.preventDefault();
  console.log(error);
});

});

A: SOLUTION:
The error (thanks charlietfl) tipped me off to the fact I never injected the ngResource module, even though I linked to the angular-resource.js in my index.html.
The factory in my promise was the first use in this app of $resource, and using it broke the app -- surprisingly with no console errors until I added the run block.


text:
Q: Cannot use child input value in parent's [ngClass] logic I am attempting to pass the user input value from my input through to the parent and use this value to determine which row to highlight within my <li *ngFor... element.
I can actually pass the value through successfully so it seems, as I have set up a console.log to catch what is first emitted by the child component and then also what is caught by the parent, but I just cannot get it to be seen by my [ngClass] logic section...
The logic does work correctly if I hardcode the value of the row I wish to highlight in, but of course, I want to do this programatically.
parent.component.ts
  rowId: number;

  childToParent(val){
    console.log('received from child: ' + val);
    this.rowId = val;
  }

parent.component.html
<app-child (childToParent)="childToParent($event)"></app-child>
<li *ngFor="let item of items" attr.id="item-{{item.id}}" [ngClass]="{'active': item.id === rowId}">
  <div class="item">
   ...
</li>

child.component.ts
@Output() childToParent = new EventEmitter<String>();

  sendToParent(id){
    console.log('sending to parent: ' + id)

    this.childToParent.emit(id);
  }

child.component.html
<input [(ngModel)]="val" (input)="sendToParent(val)"/>

Stackblitz

A: are you sure item.id and rowId both are number type? you can change "===" into "==" and it will work for both string and number.

A: Maybe just parseInt val
this.rowId = parseInt(val, 10);


text:
Q: Is possible to create a foreign key without a primary key? I am creating two tables and I want to put a foreign key on the column customer_email knowing is not the primary key. So is possible to create a foreign key without a primary key? And how I use DATE()?
Here is my table customer and order:
CREATE TABLE customer(
customer_id INTEGER PRIMARY KEY NOT NULL,
customer_email VARCHAR(225)
customer_name VARCHAR(225)
customer_last_name VARCHAR(225)
);

CREATE TABLE order(
order_id INTEGER PRIMARY KEY NOT NULL
customer_email  VARCHAR(225) REFERENCES customer(customer_email)
product_1 DECIMAL(10,2)
product_2 DECIMAL(10,2)
product_3 DECIMAL(10,2)
product_4 DECIAML(10,2)
product_5 DECIAML(10,2)
order_date DATE()
);

A: Postgres' documentation for the creation of foreign keys addresses your question:

Finally, we should mention that a foreign key must reference columns that either are a primary key or form a unique constraint. If the foreign key references a unique constraint, there are some additional possibilities regarding how null values are matched.

So, you certainly can create a foreign key in the order table which references customer_email in the customer table, but there would have to be a unique constraint on the email field.  So, the following definition for the customer table should work:
CREATE TABLE customer (
    customer_id INTEGER PRIMARY KEY NOT NULL,
    customer_email VARCHAR(225),
    customer_name VARCHAR(225),
    customer_last_name VARCHAR(225),
    CONSTRAINT email_unique UNIQUE (customer_email)
);


text:
Q: How to perform simple numeric integration with odeint in C++ Can you provide me with a simple example of performing a numeric integration with odeint in C++?
I would like to use the convenient integrate function, documented as:
integrate( system , x0 , t0 , t1 , dt )

Also I'm not sure, how to pass it instead of a function or a functor, a class method, if that's possible.

A: In C++11 you can use a simple lambda function wrapping the call to your member method
Class c;
auto f = [&c]( const state_type & x , state_type &dxdt , double t ) {
    c.system_func( x , dxdt , t ); };
integrate( f , x0 , t0 , t1 , dt );

std::bind might also work, but then you have to take care if values are passed by reference of by value.
In C++03 you need to write a simple wrapper around your class method
struct wrapper
{
    Class &c;
    wrapper( Class &c_ ) : c( c_ )  { }
    template< typename State , typename Time >
    void operator()( State const &x , State &dxdt , Time t ) const
    {
        c.system_func( x , dxdt , t );
    }
};

// ...
integrate( wrapper( c ) , x0 , t0 , t1 , dt );

(Boost.Bind will not work correctly with more then two arguments).

A: You mean examples in addition to the ones provided online?
#include <iostream>
#include <boost/array.hpp>

#include <boost/numeric/odeint.hpp>

using namespace std;
using namespace boost::numeric::odeint;

const double sigma = 10.0;
const double R = 28.0;
const double b = 8.0 / 3.0;

typedef boost::array< double , 3 > state_type;

void lorenz( const state_type &x , state_type &dxdt , double t )
{
    dxdt[0] = sigma * ( x[1] - x[0] );
    dxdt[1] = R * x[0] - x[1] - x[0] * x[2];
    dxdt[2] = -b * x[2] + x[0] * x[1];
}

void write_lorenz( const state_type &x , const double t )
{
    cout << t << '\t' << x[0] << '\t' << x[1] << '\t' << x[2] << endl;
}

int main(int argc, char **argv)
{
    state_type x = { 10.0 , 1.0 , 1.0 }; // initial conditions
    integrate( lorenz , x , 0.0 , 25.0 , 0.1 , write_lorenz );
}

And regarding the system, you can provide anything where the following expression is valid:
sys( x , dxdt , t ) // returning void

Check the user's guide (and more examples) online.


text:
Q: Streets and Intersections Data Structure I am writing a program that is supposed to emulate a city, and one of the problems I am running into is how to store a large amount of interconnected data. For instance, each Street has a direction enumeration (NORTH_ONE_WAY, EAST_WEST, etc.) and other attributes. The most important attribute is that each street has a list of intersections (a map of the street that it intersects with along with the block number at which it intersects). From this data structure, I should be able to parse it and create a visualization (that comes later and is not part of this question).
The question is: what is the best type of data structure to use for this? Obviously a relational database would be a good choice, but if I am writing in C++ (not a constraint for this question, but C++ implementation would be a plus), should I be using that? What other data structures may work for this?

A: The data structure you describe is a graph. See, e.g., Boost's BGL for a generic library operating on graphs. Note, that this doesn't mean you won't use a database: the storage of data and the in-memory representation tend to be rather different. The actual representation tends to depend on what you want to do with the data.

A: Just do not maintain relations in each local object. Have a 'meta' object evaluating the relation, it may cache these.
Some elaboration:
A street should know it lanterns and nice gardens and the intersections, of course. But it is an intersection to whatever (it does not matter). The street might have a single lane or a a double lane at the intersection (for left turns). The intersection is maintained by some higher instance.
(An apology to left lane drivers)


text:
Q: JavaScript create box with emails from array I have code like this:
function getEmails() {
    var search_in = document.body.innerHTML;
    string_context = search_in.toString();
    emails = string_context.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
    for(var i=0; i<emails.length; i++){
        console.log(emails[i]);
    }
}

Instead of console.log, I need a box to appear with the list of emails from this array and a checkbox next to every email (checkbox is checked by default) and a button Save.
When I click the Save button, all selected emails should be saved to a txt file.
How do I do this?

A: You're practically there,  I suggest your create an element in the markup and then create a string you'll append to it later, for example :
var string='';
for(var i=0; i<emails.length; i++){
string += "
<input type='checkbox'>" +emails[i]+ "
";
}

and when you're done with your string, you can append it to the element of choice in the markup.


text:
Q: Create Linear System from derivatives of variables and solve it I have the following simply function:
f[x_, y_, z_] = (x - A)^2 + (y - B)^2 + (2*z - C)^2 + (5 + z + x -
     D)^2 + (y - 2 + 2*x)^2 + (y - z + F)^2

I am looking for a simple way to have mathematica take the derivatives w.r.t to x,y,z, set them to zero, create a system of 3 equations with the three unknowns where the unknowns are moved to the left, and the constants to the right (I need to see the system outputted before it is solved). I know how to do this the standard way where I write things down one step at a time, but I was wondering if there is simpler way to do it, because I have to deal with a messier function.


text:
Q: filtering records based on n:m table criteria I have table product
 ID int
 name nvarchar()

 dummy data: (1,'car'), (2,'bike')

I have table parameters
 ID int
 name nvarchar()

 dummy data: (1,'abs'), (2,'audio'), (3,'eps'), (4,'air conditioning')

and finally I have n:m table product_parameters which holds information about parameters for product.
 ID int
 id_product int
 id_parameter int

 dummy data:

 (id,product,parameter)
 (1, 1, 1),
 (2, 1, 2),
 (3, 1, 3),
 (4, 2, 1)

How do I create select which:

*

*shows everything is parameters is not defined in search

*shows car and bike because they both have parameter abs

*shows only car because it searches for abs, eps, audi

Is it possible?
UPDATE
I created only 3 parameters but think of it like unlimited number, whether 10, 20 or 30 or more ... basically is there a way how to build select in such a way that it will query one parameter if needed or 20 parameters if needed.

A: First:
SELECT * FROM product PR
JOIN product_parameters PP ON PR.ID=PP.id_product
JOIN parameters PA ON PP.id_parameter=PA.ID

Second:
SELECT PR.* FROM product PR
JOIN product_parameters PP ON PR.ID=PP.id_product
JOIN parameters PA ON PP.id_parameter=PA.ID
WHERE PA.name = 'abs'

Third:
SELECT PR.* FROM product PR
WHERE EXISTS (SELECT * FROM product_parameters PP JOIN parameters PA ON PP.id_parameter=PA.ID WHERE PP.id_product=PR.ID AND PA.name='abs')
AND EXISTS (SELECT * FROM product_parameters PP JOIN parameters PA ON PP.id_parameter=PA.ID WHERE PP.id_product=PR.ID AND PA.name='eps')
AND EXISTS (SELECT * FROM product_parameters PP JOIN parameters PA ON PP.id_parameter=PA.ID WHERE PP.id_product=PR.ID AND PA.name='audi')


text:
Q: Compare data from query result to different table data in PostgreSQL STEP 1
Select data1,name,phone,address from dummyTable limit 4;

From above query, I will get the following result for example:
 data1 | name | phone | address

 fgh   | hjk  | 567...| CA
 ghjkk | jkjii| 555...| NY

Now, after having the above result I am suppose to match data1 records that I got from above query to existing another table in a database called existingTable which has a same column called data1 in it. If the result above gives data1 value as 'fgh' so I take that 'fgh' and compare with that existingtable column called data1.
STEP 2
Next, after I am finished comparing, I need to apply some condition as follows:
if((results.data1.value).equals(existingTable.data1.value))
then count --
else
count++

So by above condition I am trying to explain, that if the value I got from the result is matched then I do count decrement by 1 and if not then count is incremented by 1.
Summary
I basically wanted to achieve this in one single query, is it possible using PostgreSQL?

A: I think you can translate that to a simple query:
SELECT d.data1, d.name, d.phone, d.address
     , count(*) - 2 * count(e.data1)
FROM  (
   SELECT data1, name, phone, address
   FROM   dummytable
   -- ORDER BY ???
   LIMIT  4
   ) d
LEFT   JOIN existingtable e USING (data1)
GROUP  BY d.data1, d.name, d.phone, d.address;

The major ingredient is the LEFT [OUTER] JOIN. Follow the link to the manual.
count(*) counts all rows from dummytable.
count(e.data1) only counts rows from existingtable where a matching data1 exists (count() does not count NULL  values). I  subtract that twice to match your formula.
About ORDER BY: There is no natural order in a database table. You need to order by something to get predictable results.
If there can be duplicates in existingtable but you want to count every distinct data1 only once, eliminate dupes before you join or use an EXISTS semi-join:
SELECT data1, name, phone, address
      , count(*) - 2 * count(EXISTS (
                          SELECT 1 FROM existingtable e
                          WHERE  e.data1 = d.data1) OR NULL)
FROM  (
   SELECT data1, name, phone, address
   FROM   dummytable
   -- ORDER BY ???
   LIMIT  4
   ) d
GROUP BY data1, name, phone, address;

The last count works because (TRUE OR NULL) IS TRUE, but (FALSE OR NULL) IS NULL.


text:
Q: Decrypt Java AES/CBC/PKCS5Padding with CryptoJS I have some problem decrypting text with CryptoJS that has been encrypted with Java. The decryption should be done with AES/CBC/PKCS5Padding. The encrypted string is base64 encoded and I decode it before trying to decrypt the string.
This is how the Java code looks like:
private static byte[] doAES(int mode, byte[] dataToEncrypt, String secretKey, String salt) throws Exception {
        byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        IvParameterSpec ivspec = new IvParameterSpec(iv);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKeySpec secretKeySpec = new SecretKeySpec(tmp.getEncoded(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(mode, secretKeySpec, ivspec);

        return cipher.doFinal(dataToEncrypt);
}

And this is how I attempt to decrypt it in CryptoJS. SharedSecretKey is both the secretKey and the salt value in Java.
let decoded = Buffer.from(encodedString, 'base64')
console.log("Result: " + CryptoJS.AES.decrypt({
  ciphertext: CryptoJS.enc.Hex.parse(decoded.toString().substring(32))
}, CryptoJS.enc.Hex.parse(CryptoJS.SHA1(sharedSecretKey).toString().substring(0,32)),
  {
    iv: CryptoJS.lib.WordArray.create(Buffer.alloc(16)),
  }).toString(CryptoJS.enc.Utf8))

Where decoded is the decoded Base64-string that I want to decrypt. However, this does not work and I get the error 'Error: Malformed UTF-8 data'. I am not sure if there is anything I have missed, any help is very much appreciated.

A: In the CryptoJS code the key derivation with PBKDF2 is missing. CryptoJS uses SHA1 for this by default.
The ciphertext can be passed Base64 encoded and will be implicitly converted to a CipherParams object:

var encodedString = "0O15lUg8sE1G0+BjO5N2j8AjVKXV4J+18z5DinbM6tYjoILhL0WDTFWbcTiN+pG/";
var key = CryptoJS.PBKDF2(
  "my passphrase",
  "my salt",
  {
    keySize: 256 / 32,
    iterations: 65536
  }
);
var decryptedData = CryptoJS.AES.decrypt(encodedString, key,
  {
    iv: CryptoJS.enc.Utf8.parse("\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"),
  }
);

console.log("Result: " + decryptedData.toString(CryptoJS.enc.Utf8));
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>

The ciphertext in the above example was previously generated with the posted Java code.
Note that a static IV is insecure. The IV is usually randomly generated for each encryption and passed along with the ciphertext (typically concatenated). Analogously for the salt, it is randomly generated for each key derivation and passed together with ciphertext and IV, e.g. salt|iv|ciphertext. Both, IV and salt, are not secret and need not be encrypted.
In addition, the encoding should be specified in the Java code when encoding with getBytes() and decoding with  new String(), otherwise cross-platform problems may occur.


text:
Q: Identity element for `numpy.hstack` How can I create an empty array wich I can then hstack with another array to fill with values?
For example in Matlab, I can do the following:
a = [];
b = [10 20];
a = [a b];

and would get
a =

      10    20

I am looking for something similar in numpy. I tried
a = np.array([]);
b = np.array([10, 20]);
a = np.hstack((a, b)); # should be equal to `b`

But that gives

ValueError: all the input array dimensions except for the concatenation axis must match exactly

A: You can resize the dimension of a to match the shape of b and fill in the missing values. This will change the size of a and fill it with the default value, for np.floats this is 0.0
a = np.array([])
b = np.array([10, 20])
a.resize(b.shape)

np.hstack((a, b))

A: Using np.array([]) with hstack works for me.
In [11]: a = array([], dtype=int)

In [12]: b = array([10, 20])

In [13]: c = array([30, 40])

In [14]: a = hstack((a,b))

In [15]: a
Out[15]: array([10, 20])

In [16]: a = hstack((a,c))

In [17]: a
Out[17]: array([10, 20, 30, 40])

For vstack, the shape of the initial a needs some tweaking to make it have shape (0,2):
In [22]: a = array([], dtype=int).reshape(-1,2)

In [23]: a
Out[23]: array([], shape=(0, 2), dtype=int64)

In [24]: b
Out[24]: array([10, 20])

In [25]: c
Out[25]: array([30, 40])

In [26]: a = vstack((a,b))

In [27]: a
Out[27]: array([[10, 20]])

In [28]: a = vstack((a,c))

In [29]: a
Out[29]:
array([[10, 20],
       [30, 40]])

Note that I've used dtype=int when creating the initial value of a. Without this, it uses the default dtype of float, and then when a is hstacked or vstacked with b, the result is upcast to float.


text:
Q: How to draw a Fibonacci indicator automatically in MQL4? I wish to analyze a chart using Fibonacci indicator. Are there any methodologies ( or libraries ) that can draw of a Fibonacci indicator automatically on a chart with MQL4?

A: Use the MQL4 "Object Functions" ( Ref. to GUI Objects' manipulations )
Among many graphical elements, MetaTrader Terminal 4 can place also the few of Fibonacci based technical indicators ( let's go ahead with the Fibonacci retracement tool, other are similar in the use and can apply the same to them ).
First, one has to create such object, using:
ObjectCreate( chart_ID,                           // ref. doc
              anInterimObjNAME,                   //      a name to be used
              OBJ_FIBO,                           //      a type of GUI-obj to draw
              0,                                  //      sub-window
              time1, price1,                      //      where to start
              time2, price2                       //      where to finish
              );

Next, one can adapt many attributes of the already created object - colour, line-type / line-thickness, texts and also the starting time, starting price, ending time, ending price - to such values that are pleasing one's taste.
//--- set how many levels you want to paint
      ObjectSetInteger( chart_ID,
                        anInterimObjNAME,
                        OBJPROP_LEVELS,
                        levels
                        );

//--- set the properties of each of the level
   for (  int i = 0; i <  levels; i++ )
   {      ObjectSetDouble(  chart_ID, anInterimObjNAME, OBJPROP_LEVELVALUE, i, values[i] ); // level value
          ObjectSetInteger( chart_ID, anInterimObjNAME, OBJPROP_LEVELCOLOR, i, colors[i] ); // level color
          ObjectSetInteger( chart_ID, anInterimObjNAME, OBJPROP_LEVELSTYLE, i, styles[i] ); // level style
          ObjectSetInteger( chart_ID, anInterimObjNAME, OBJPROP_LEVELWIDTH, i, widths[i] ); // level width
          ObjectSetString(  chart_ID, anInterimObjNAME, OBJPROP_LEVELTEXT,  i, DoubleToString( 100 * values[i], 1 ) ); // level description
          }


text: Q: The choice of abbreviation "TF" and "TN" in EGA II I am a native French speaker, yet I cannot guess what the abbreviations "TF" and "TN" stand for in page 39 (where they define them). I assume that the F stands for some kind of Finite and N for some kind of Nul, but I can't figure out the T. Does anyone know? That would be a really fun fact to know.


text:
Q: Blazor WASM publish on IIS => memory access out of bounds , Error loading ICU asset Since the last Visual Studio Preview update to 16.9.0 Preview 1.0 I get the following error from the IIS-Server in our local network:

On my local machine everything works fine with the IIS Express integrated in Visual Studio. But when I publish the blazor.server project to the IIS-Server in our network I get this message when I try to access the page. So it doesn't start at all
When I jump to the rows mentioned in the message I get the following code snipets

Client-Project-File

Server-Project-File
Any Idea what could be the cause?
Update 07.12.20 21:40: I just tried to access the webpage directly on the server using "localhost" or "127.0.0.1" and it works without any problems.
If I try to access the page from the same browser-instance using the IP-Address "192.168.50.3" I get the same error as from remote clients


text:
Q: What will happen if I don't response RTSP GET_PARAMETER command? I'm developing a RTSP Server and UDP works fine, but there's 1 issue when it's goes to TCP which is the VLC only can view streaming about 30 minutes, from the packet I see that I didn't response the RTSP GET_PARAMETER command, is this command matters and what will happen is I don't response this command?

A: According to the specification, GET_PARAMETER is optional for servers and clients to implement.


text:
Q: How to compute the Second and higher order Betti numbers of a graph? I know that the zeroth Betti number is the number of connected components of a graph, and the first one is computed using Euler characteristics. However, I am not sure if we can compute the higher order Betti numbers.

A: The nth Betti number is the rank of the nth homology of your graph. Using cellular homology, the Betti numbers of any graph are 0 if $n>1$.


text:
Q: Function using iterators to perform a object operation Assuming I have an std::array<SomeType, N> and I'd like to call a function which uses iterators to work with the objects in the std::array but without knowing about the container being a std::array.
SomeType is a class which has a public member function doSomething()
For example a function might be:
template<typename Iterator>
void action(Iterator &beg, Iterator &end) {
  for (; beg != end; ++beg)
    beg->doSomething();
}

Calling this function is possible by:
int main() {
  std::array<SomeType, 10> a;

  action<std::array<SomeType, 10>::iterator>(a.begin(), a.end());
}

But I'm wondering if this is the way to do it? Especially because the template could be used for each class. Is there a way to restrict the function to SomeType without letting the function know that the container is an std::array?

A: *

*Fix your code: You should not require lvalue arguments. In fact, iterators are meant to be copyable efficiently.
template<typename Iterator>
void action(Iterator beg, Iterator end)
//          ^^^^^^^^^^^^  ^^^^^^^^^^^^

*Let template argument deduction do its job:
action(a.begin(), a.end());

A: Note that the standard library already has a number of algorithms that cover the general case of "doing the same thing over some range in some container":
#include <array>
#include <vector>
#include <algorithm>
#include <numeric>
#include <iterator>

struct SomeType
{
  void doSomething();

  SomeType mutatedCopy() const;

  int someValue() const;
};

int add_value(int i, const SomeType& st) {
  return i + st.someValue();
}

void call_something(SomeType& st) { st.doSomething(); }
auto mutate_copy(SomeType const& st) { return st.mutatedCopy(); }

int main() {
  std::array<SomeType, 10> a;
  std::vector<SomeType> b;

  std::for_each(a.begin(), a.end(), call_something);
  std::for_each(b.begin(), b.end(), call_something);

  std::transform(a.begin(), a.end(), a.begin(), mutate_copy);
  std::transform(b.begin(), b.end(), b.begin(), mutate_copy);

  auto tot = std::accumulate(a.begin(), a.end(), 0, add_value)
           + std::accumulate(b.begin(), b.end(), 0, add_value);

  // you can even transform into dissimilar containers:

  std::transform(a.begin(), a.end(), std::back_inserter(b), mutate_copy);

}


text:
Q: Why is fetch_assoc returning false? $stmt = $mysqli->prepare("SELECT username, email, password, code FROM temp_users WHERE code = ?");
$stmt->bind_param('s', $code);
$stmt->execute();
$stmt->store_result();
//if SELECT statement returns 1, grab data.
if ($stmt->num_rows === 1) {
    echo "Got Row";

    $result = $stmt->get_result();
    var_dump($result);

    while ($row = $result->fetch_assoc()) {

        $username = $row['username'];
        $email = $row['email'];
        $password = $row['password'];
    }

This is really weird, the query must be going through because the script is echoing "Got Row", and I have no errors up to that point. But when I try to use $result->fetch_assoc() I get an error,and $result is spitting out false, so why is that? Please excuse how dumb this question may seem, I'm still learning how to use mysqli. :)

A: Your question is neither dumb nor weird. You are simply confused by store_result() and get_result().
Both of these functions fetch the whole record set from the database. Once the data is fetched you can't fetch it again. Therefore, you can't use both of these functions at the same time!
We can fix your code in two ways.
With store_result():
$stmt = $mysqli->prepare("SELECT username, email, password, code FROM temp_users WHERE code = ?");
$stmt->bind_param('s', $code);
$stmt->execute();
$stmt->store_result();
//if SELECT statement returns 1, grab data.
if ($stmt->num_rows === 1) {
    echo "Got Row";

    $stmt->bind_result($username, $email, $password);
    while ($stmt->fetch()) {
        // use the data here
        var_dump($username);
    }
}

with get_result():
$stmt = $mysqli->prepare("SELECT username, email, password, code FROM temp_users WHERE code = ?");
$stmt->bind_param('s', $code);
$stmt->execute();
$result = $stmt->get_result();
//if SELECT statement returns 1, grab data.
if ($result->num_rows === 1) { // <--- !!! We are using the result object here
    echo "Got Row";

    foreach ($result as $row) {
        $username = $row['username'];
        $email = $row['email'];
        $password = $row['password'];
    }
}


text:
Q: Specify a generic value argument as a parameter of an object initialization call I have a struct Event that gets initialized with a time and a value.
The value property's type is decided at the time the event is created. It can be one of either an Int or Double primitive.
How should I implement this in Swift?
I want to be able to create a new Event object like so:
let event = Event(time: Date.init(), value: EventValue<Double>(40.3467))

I found this but I can't make it out.
I have experimented with so many permutations of this and the best I can do is
struct Event {
  let time: Date
  var value: EventValue? // This line 'requires arguments in <...>'
}

struct EventValue <T> {
  let value: T?
}

A: Add generic parameter to your Event struct too and then use this type for parameter of EventValue
struct Event<T> {
    let time: Date
    var value: EventValue<T>?
}

then just initialize EventValue without specifing type, since compiler allows you to pass just value corresponding to generic parameter constraint. And since your parameter has no constraints, it is equal to Any, so you can pass any type
let event = Event(time: Date.init(), value: EventValue(value: 40.3467))

A: Since EventValue is generic, it can't be used directly as the type of a property.* You have to either directly specify the type parameter, which gives you a container that always has a particular variety of EventValue:
struct DoubleEvent {    // Please pick a better name, though
    let time: Date
    var value: EventValue<Double>?
}

Or make the container generic as well:
struct Event<T> {
    let time: Date
    var value: EventValue<T>?
}

In either case, you don't have to explicitly give the type when creating an Event: let event = Event(time: Date(), value: EventValue(value: 40.3467)) Type inference will fill it in when the Event itself is generic.
(Aside: note that you have no formal restriction for T to be only Double or Int. For example, let event = Event(time: Date(), value: EventValue(value: "123abc")) is possible as well. If you do want to strictly avoid that, Martin R's answer gives one solution.)

*Without getting into too much detail, it's more like a "thing that creates a type" than a type itself.

A: If the intention is to have a (single) Event type with an EventValue property which can hold either an integer or a double value, then an enum with associated values would serve that purpose:
enum EventValue {
    case ival(Int)
    case dval(Double)
}

struct Event {
    let time: Date
    let value: EventValue
}

let event1 = Event(time: Date(), value: .dval(40.3467))
let event2 = Event(time: Date(), value: .ival(1234))

A: If you want to support various kinds of EventValue under the same Event type (i.e. no generics for Event), you can store a protocol reference for EventValue:
protocol EventValueProtocol {
    var time: Date { get }
    var value: SomeCommonGroundProtocolOrClass
}

struct Event {
    let time: Date

    // note that the generics information is lost
    // when using the protocol
    var value: EventValueProtocol

    init<T>(time: Date, value: EventValue<T>) {
        self.time = time
        self.value = value
    }
}

struct EventValue <T>: EventValueProtocol {
    let value: T?
}

The downside of the "type eraser" protocol is that you loose the type information used for the generic argument of EventValue, however it might be that you'll be able to work around this via some helper methods in the protocol. For example you can use a common denominator for all T generic arguments in order to access the common functionality (you kinda need this unless you want to switch over all possible types T can take).


text:
Q: smearing in Linux, but not in Windows I must have a Linux library out of wack since the following image has "smears" on the colors.  Is there a better term?  On my Windows 7 RStudio it works fine.  this image is from a Ubuntu 16.04 LTS and the following are the libraries:
library(ggplot2)
library(ggmap)
library(maps)
library(mapdata)

the code that generates this image is:
ggplot(data = world2) +
  geom_polygon(aes(x = long, y = lat, fill = region, group = group), color
    = "white") +
  coord_fixed(1.3) +
  guides(fill=FALSE)


text:
Q: selectpicker doesnt show data after choosing email Hope somebody could help me. As I am really  new to php and mysql. Here is my code-
https://www.codepile.net/pile/bmwgqlmd
https://www.codepile.net/pile/W3N7DjP1
The problem is-when I choose email from selectpicker it doesnt connect  to the table and doesnt show selected data.
Can anyone help figure it out how to connect them so it shows selected data?
Thanks.


text:
Q: Why table variable SQL doesn't return values in R Markdown? Can't understand why R Markdown doesn't return values for table variable SQL? I use notebook in R Studio.
For example:
declare @CountriesTable as TABLE (countries varchar(2))
        insert into @CountriesTable values ('us'), ('gb'), ('de'), ('fr')

 select * from @CountriesTable

in MSSMS returns

In R Markdown I get 0 Rows:

A: *

*Your statement "does not work with non-numeric data" is quite wrong, DBI (with SQL Server) supports SQL Server's bit, integer, float variants, datetimeoffset variants, char/varchar/nchar/nvarchar variants, etc.

*Suggested here, add SET NOCOUNT ON.
Demonstration:
---
title: Why table variable SQL doesn't return values in R Markdown?
---

```{r setup}
library(DBI)
con <- DBI::dbConnect(odbc::odbc(), ...) # redacted
```

```{sql connection=con}
set nocount on
declare @CountriesTable as TABLE (countries varchar(2))
insert into @CountriesTable values ('us'), ('gb'), ('de'), ('fr')
select * from @CountriesTable
```

Ultimately, I believe the issue is that DBI does not deal with with multiple result-sets. While I had expected that odbc's PR 345 would have addressed this in odbc-1.3.0, it does not seem to deal correctly with the first resultset (4, number of rows inserted) and the second (four rows of data).