text:
Q: Using extern in C++ to share vairables I have looked online at using extern with examples however when I have applied it to my project it either says that the variable has been defined multiple times within the project or the variable is out of scope
main.cpp
#include <SimPre.h>

void setup() {
  example();
  simController.println("Test");
}

void loop() {
  example();
}

SimPre.h
#include <SoftwareSerial.h>

#ifndef SIM_PRE
#define SIM_PRE

extern SoftwareSerial simController(7, 8);

void example();

#endif

SimPre.cpp
#include <Arduino.h>
#include "SimPre.h"

void example() {
  simController.println("Test");
}

The above code shows me trying to access the simController variable from the main.c and it should also be accessible from SimPre.c however I get an error:
libraries/SimPre/SimPre.cpp.o:(.bss.simController+0x0): multiple definition of `simController'
sketch/DilshadSIM.ino.cpp.o:(.bss.simController+0x0): first defined here
collect2: error: ld returned 1 exit status

A: In SimPre.h declare it as:
extern SoftwareSerial simController;


text:
Q: asp.net viewstate errors - "Invalid length for a Base-64 char array or string." and "The input is not a valid Base-64 string" My .Net application is recording some errors that I have tracked to the viewstate. I've read quite a bit on this, and found some information that simply hasn't helped me to get to the root of the problem. The errors are:

*

*Invalid length for a Base-64 char array or string.

*The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

These errors happen somewhat infrequently, and often to the same small subset of users. Often, simply redirecting the user to the same page again does not result in the same error
In an attempt to resolve these errors, I implemented two different solutions. In each solution, I attempted a string replace for blank spaces as well as attempted to ensure that the viewstate string was an appropriate length by appending "=" characters. Additionally, in one test I compressed the viewstate as well. Code for each of those attempts is below.
Compressed Viewstate
Public Class baseCompressor
    Inherits System.Web.UI.Page
    Protected Overrides Function LoadPageStateFromPersistenceMedium() As Object
        Dim viewState As String = Request.Form("__VSTATE")
        viewState = viewState.Replace(" ", "+")

        Dim mod4 As Integer = viewState.Length Mod 4
        If mod4 > 0 Then
            viewState += New String("=", 4 - mod4)
        End If
        Dim bytes As Byte() = Convert.FromBase64String(viewState)
        bytes = compressor.Decompress(bytes)
        Dim formatter As New LosFormatter()
        Return formatter.Deserialize(Convert.ToBase64String(bytes))
    End Function

    Protected Overrides Sub SavePageStateToPersistenceMedium(viewState As Object)
        Dim formatter As New LosFormatter()
        Dim writer As New StringWriter()
        formatter.Serialize(writer, viewState)
        Dim viewStateString As String = writer.ToString()
        Dim bytes As Byte() = Convert.FromBase64String(viewStateString)
        bytes = compressor.Compress(bytes)
        ScriptManager.RegisterHiddenField(Me, "__VSTATE", Convert.ToBase64String(bytes))
    End Sub

End Class

Public NotInheritable Class compressor
    Private Sub New()
    End Sub

    Public Shared Function Compress(data As Byte()) As Byte()
        Using output As New MemoryStream()
            Using gzip As New GZipStream(output, CompressionMode.Compress, True)
                gzip.Write(data, 0, data.Length)
                gzip.Close()
                Return output.ToArray()
            End Using
        End Using
    End Function

    Public Shared Function Decompress(data As Byte()) As Byte()
        Using input As New MemoryStream()
            input.Write(data, 0, data.Length)
            input.Position = 0
            Using gzip As New GZipStream(input, CompressionMode.Decompress, True)
                Dim output As New MemoryStream()
                Dim buff As Byte() = New Byte(4096) {}
                Dim read As Integer = -1
                read = gzip.Read(buff, 0, buff.Length)
                While read > 0
                    output.Write(buff, 0, read)
                    read = gzip.Read(buff, 0, buff.Length)
                End While
                gzip.Close()
                Return output.ToArray()
            End Using
        End Using
    End Function
End Class

Uncompressed Viewstate
Public Class baseNonCompressor
    Inherits System.Web.UI.Page
    Protected Overrides Sub SavePageStateToPersistenceMedium(viewState As Object)
        Dim formatter As New LosFormatter()
        Dim writer As New StringWriter()
        formatter.Serialize(writer, viewState)
        Dim viewStateString As String = writer.ToString()
        Dim bytes As Byte() = Convert.FromBase64String(viewStateString)
        ScriptManager.RegisterHiddenField(Me, "__VSTATE", Convert.ToBase64String(bytes))
    End Sub

    Protected Overrides Function LoadPageStateFromPersistenceMedium() As Object
        Dim viewState As String = Request.Form("__VSTATE")
        viewState = viewState.Replace(" ", "+")

        Dim mod4 As Integer = viewState.Length Mod 4
        If mod4 > 0 Then
            viewState += New String("=", 4 - mod4)
        End If
        Dim bytes As Byte() = Convert.FromBase64String(viewState)
        Dim formatter As New LosFormatter()
        Return formatter.Deserialize(Convert.ToBase64String(bytes))
    End Function
End Class

The results have still left me with the original two errors as well as a new error:

*

*Unable to read beyond the end of the stream.

The new error occurs on the Deserialize call. Can anyone point me to what the problem might be? While my code is in VB, C# solutions are also welcomed.

A: First you should take the Base64 string and be sure it is valid.
There are many online tools.
These might be wrong:
Dim mod4 As Integer = viewState.Length Mod 4
If mod4 > 0 Then
    viewState += New String("=", 4 - mod4)
End If

From your code I sense you already know why. It's just wondering if it really behaves well in all cases, for example you shouldn't pad with four ==== if the modulo is 0.
Second, consider if this goes through a GET. The HTTP protocol has hard limits on the status line's maximum length.
In other words: if you set it as a parameter in the URL's query string, and the data is big (next to 1K) I'd recommend strongly to prefer a POST instead of a GET.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i use Retry pattern in Azure functions? I have created a task scheduler in azure function and wanted to implement retry policy if Proxy url returns some error message.

A: When a Timer Triggered (Scheduled) Azure Function raises an uncaught exception, retry policies are evaluated.
It should catch all exceptions in the code and can implement the retry policy for that which is a best practice.
You can apply either of the two strategies like Fixed delay and Exponential backoff.
Refer to Scheduled Azure Functions - Retry Policies for more information.


text:
Q: How to execute a cascading JPA/toplink batch update Background
I have a problem with a JPA cascading batch update that i need to implement.
The update will take some 10000 objects and merge them into the database at once.
The objects have an average depth of 5 objects and an average size of about 3 kb
The persistance provider is Oracle Toplink
This eats a large amount of memory and takes several minutes to complete.
I have looked around and i see 3 possibilities:
Looping through a standard JPA merge statement and flushing at certain intervals
Using JPQL
Using Toplink's own API (Which i have no experience with whatsoever)
So i have a couple of questions
Will i reduce the overhead from the standard merge by using JPQL instead? If i understand correctly, merge causes to entire object tree to be cloned before being invoked. Is it actually faster? Is there some trick to speeding up the process?
How do i do a batch merge using to Toplink API?
And i know that this is subjective but: Does anyone have a best practice for doing large cascading batch updates in JPA/Toplink? Maybe something i didn't consider?
Related questions
Batch updates in JPA (Toplink)
Batch insert using JPA/Toplink

A: Not sure what you mean by using JPQL?  If you can express your update logic in terms of a JPQL update statement, it will be significantly more efficient to do so.
Definitely split your work into batches.  Also ensure you are using batch writing and sequence pre-allocation.
See,
http://java-persistence-performance.blogspot.com/2011/06/how-to-improve-jpa-performance-by-1825.html


text:
Q: Codeigniter RESTful API I have a mysql database with a table which contains several brands of cars. I need to create an API for all, so right now I have something like this :
<?php

require(APPPATH.'libraries/REST_Controller.php');

class carcollection extends REST_Controller{

// AUDI
public function audi_get()
{
    $this->load->database();
    $sql = "SELECT car_id, car_brand, car_model FROM `cars` WHERE car_brand LIKE 'Audi' LIMIT 10";
    $query = $this->db->query($sql);
    $data = $query->result();

}

// BMW
public function bmw_get()
{
    $this->load->database();
    $sql = "SELECT car_id, car_brand, car_model FROM `cars` WHERE car_brand LIKE 'BMW' LIMIT 10";
    $query = $this->db->query($sql);
    $data = $query->result();

}

...etc..etc.

This works fine so far, when I for example enter http://localhost/myprojects/cars/index.php/api/carcollection/audi my console/browser gives me the correct data in JSON format. When I enter http://localhost/myprojects/cars/index.php/api/carcollection/ - I get the error {"status":false,"error":"Unknown method."} - but I would like to know how I could do this so that I get all data for once? with the URL shown before without basically changing the SQL queries...
Any help is appreciated...

A: You need to include an index route:
public function index_get() {
    $this->load->database();
    $sql = "SELECT car_id, car_brand, car_model FROM `cars` LIMIT 10";
    $query = $this->db->query($sql);
    $data = $query->result();
}


text:
Q: why $(2,3)$ is closed subset 0f Y ??? This  is the  section 17  of munkre topology...example 5 ???
EXAMPLE 5. Consider the following subset of the real line:
$Y = [0, 1] ∪ (2, 3),$
in the subspace topology. In this space, the set $[0, 1]$ is open, since it is the intersection of
the open set $(−1/2, 3/2)$ of $R$ with $Y$ . Similarly, $(2, 3)$ is open as a subset of $ Y$ ; it is even open
as a subset of R. Since $[0, 1] $and $(2, 3)$ are complements in Y of each other, we conclude
that both $[0, 1]$ and $(2, 3)$ are closed as subsets of $Y $.
Now  my question    is that  why $(2,3)$ is  closed  subset   0f $Y$ ???

A: This is exactly because of the comment in your question: "Since $[0,1]$ and $(2,3)$ are complements in Y of each other".
Sometimes we call such sets "clopen" sets.
Basically, the concept of "open" and "closed" are not exclusive, "closed set" is defined as a sets whose complement set is "open", and thus you could find a set that is open and closed at the same time.


text:
Q: Hello, I'm new at mysql. please help me to solve mysql error logs I get occasional error establishing database connection error on wp site. It happens regularly. To prevent it from happening again, I need to fix it, after the error I checked MySQL error logs and they are something like this
[ERROR] mmap(137363456 bytes) failed; errno 12
[ERROR] Cannot allocate memory for the buffer pool
[ERROR] Plugin initialization aborted with error Generic error
[ERROR] Failed to initialize DD Storage Engine
[ERROR] Data Dictionary initialization failed
[ERROR] Aborting

How do I know what causes it and how can I fix it?


text:
Q: Unable to carry edited data to DB in jqgrid inline editing I'm developing a web based application using bootstrap.
I'm trying to implement inline editing in my grid on page load but when I click on edit button on the grid, all the cells become editable text and later i click on save button it shows the text I am typing in the particular cell.but on the onclick of save button i unable to call a function which performs updation of data in DB.
Here is my code :
  $(document).ready(function () {
    var GetUrl = Web_Path + '/Test/TestHandler/GetTestData/' + AjaxHandlerName;

                jQuery("#jqGrid-container").jqGrid({
                    url: GetUrl,
                    datatype: 'json',
                    mtype: 'POST',
                    postData: { SearchInfo: function () { return getSearchPostData() } },
                    colNames: [' ', 'ID', 'Name', 'ContactNo', 'EmpId', 'MailId', 'RoleName'],
                    colModel: [
                    { name: 'myac', index: '', width: 80, fixed: true, sortable: false, resize: false,
                        formatter: 'actions',
                        formatoptions: {
                            keys: true,
                            delOptions: { recreateForm: true, beforeShowForm: beforeDeleteCallback }
                        }
                    },
                                { name: 'Id', index: 'Id', hidden: true, editable: true },
                                { name: 'Name', index: 'Name', validation: { required: true }, sortable: true, editable: true, editoptions: { size: "40", maxlength: "50"} },
                                { name: 'ContactNo', index: 'ContactNo', sortable: false, editable: true, editoptions: { size: "20", maxlength: "30"} },
                                { name: 'EmpId', index: 'EmpId', sortable: false, editable: true, editoptions: { size: "20", maxlength: "30"} },
                                { name: 'MailId', index: 'MailId', sortable: false, editable: true, editoptions: { size: "40", maxlength: "50"} },
 {name: 'RoleName', index: 'RoleName', sortable: false }
  ],
                    jsonReader: {
                        id: 'Id',
                        repeatitems: false
                    },
                    height: "100%",
                    pager: '#jqGrid-pager',
                    rowNum: 10,
                    rowList: [10, 20, 30],
                    sortname: 'Id',
                    sortorder: 'desc',
                    viewrecords: true,
                    caption: "JQ grid data",
                    loadComplete: function () {
                        var table = this;
                        updatePagerIcons(table);
                    }
                });
});

 function getSearchPostData() {
            var searchData = {};
            searchData.Id=1;

            return JSON.stringify(searchData);
        }
 function updatePagerIcons(table) {
            var replacement =
                    {
                        'ui-icon-seek-first': 'icon-double-angle-left bigger-140',
                        'ui-icon-seek-prev': 'icon-angle-left bigger-140',
                        'ui-icon-seek-next': 'icon-angle-right bigger-140',
                        'ui-icon-seek-end': 'icon-double-angle-right bigger-140'
                    };
            $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
                var icon = $(this);
                var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

                if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
            })
}

I have used jquery.jqGrid.min.js.
when i try to save, unable to carry the data to DB.. Please help me out.

A: You need to use editurl properties of jqgrid which basically is the controller URL of your server. When save action is triggered , editurl is called upon.
While calling editurl following data is sent to the server according to jqgrid documentation ,
How is the data organized
When the row is edited and the input elements are created we set the following rules:

*

*the table row becomes attribute editable="1"

*the array savedRow (option in the grid) is filled with the values
before the editing. This is a name:value pair array with additional
pair id:rowid

*Hidden fields are not included

*The id of the editable element is constructed as 'rowid_'+ the name
from the colModel array. Example if we edit row with id=10 and the
only editable element is 'myname' (from colModel) then the id becomes
10_myname.

*The name of the editable element is constructed from the name of the
colModel array - property - name after the row is saved or restored
the editable attribute is set to "0" and the savedRow item with
id=rowid is deleted

What is posted to the server?
When the data is posted to the server we construct an object {} that contain(s):

*

*the name:value pair where the name is the name of the input element
represented in the row (this is for all input elements)

*additionally we add a pair id:rowid where the rowid is the id of the
row

*if the extraparam parameter is not empty we extend this data with the
posted data

So, you need to setup the Server side to get the value sent from the jqGrid on edit/save action.


text: Q: Complete rings and modules(topologically) In the a-adic topology, if M,N are A-modules, and N is the homomorphic image of M, can we prove that N is complete whenever M is? in other words, does completeness carries over to homomorphic images.


text:
Q: Eval on a certain array part Ok I been looking online for a few hours and i'm confused how eval() can be used in my situation so I know eval is evil but I need
and I want to use eval still for personal reasons so how can I get the variable $part to work properly like this.
$numbers= array($part);

Which means this
$numbers= array(4,6,2,22,11);

but it is not working so how can I do this with eval? and this is my failed code.
<?php

$part= eval(4,6,2,22,11);

$numbers= array($part);

sort($numbers);

$arrlength=count($numbers);

$output='';

for($x=0;$x<$arrlength;$x++) {
$output .= $numbers[$x].'<br>';
}

echo $output;

?>

and this is the error I am getting
Parse error: syntax error, unexpected ',' in C:\path\example.php on line 3

A: Eval only run string as php code and your use is wrong because 2,4,6 is not code in php language. How documentation says

eval - Evaluate a string as PHP code

This will work.
$stringNumbers = "4,6,2,22,11";

$part= eval("return array(\".$stringNumbers.\");");

$numbers= $part;


text:
Q: Cannot publish app targeting to Android 12 Getting an error on uploading an app to the Google Play store
You uploaded an APK or Android App Bundle which has an activity, activity alias, service or broadcast receiver with intent filter, but without the 'android:exported' property set. This file can't be installed on Android 12 or higher. See: developer.android.com/about/versions/12/behavior-changes-12#exported
All activities, activity alias, services, or broadcast receivers that have intent-filter are marked with android:exported.
The app installs to device and emulator running Android 12 without errors. Also, Android Studio doesn't report any error on merged AndroidManifest file.
Any ideas what could be wrong when there are no errors on the development environment but Google Play store still complains? How this can be resolved?

A: I think mentioned link in your question answers itself.
In simple words, if your app is responding to system or by other apps and if that is intended then you need set android:exported=true else false. I mean if your app activity gets opened by any other app or your app listens to other apps broadcasts or your app starts any service by other apps then this case is involved.
Doing this will resolve your issue on play store while publishing app. This assessment is done as part of behaviour changes when targeting android 12
https://developer.android.com/about/versions/12/behavior-changes-12#exported
Update : Add below tag in all your activities, services, broadcasts etc.
android:exported="false/true" based on above explanation.
E.g.
<service android:name="com.example.app.backgroundService"
         android:exported="false">
    <intent-filter>
        <action android:name="com.example.app.START_BACKGROUND" />
    </intent-filter>
</service>

A: Dexguard can be the cause of this issue. Add rule -keepresourcexmlattributenames manifest/** to your Dexguard/Proguard file.
The original answer found https://stackoverflow.com/a/70703375/1474153


text:
Q: Best practices for JDBC accessor class I am working on a small restaurant management app that will keep track of food orders. I am making a class that will handle all the SQL querying (for ease of use for my other teammates) and I want to know some of the best practices for doing so. The class will handle connecting/disconnecting/inserting and querying very specifically and will only take in basic parameters. I have the following design problems: Exception handling (should the user have to handle them, I prefer they do not), connecting (should the connection be re-established and closed on every query or just when a set of queries is done), and displaying results (how should I most elegantly convert a ResultSet, which can throw exceptions, do a stable finalized set of results).
TLDR;
What is the best design for a wrapper MySQL class that will make it so that the user of the class only needs to use built-in methods.

A: In 2013, we have enough frameworks that make database access simpler than plain JDBC.
Please have a look at jOOQ for a bare-bones Active Record-like API or at Hibernate for something more complex. And if you want a taste of the future, have a look at Spring Data.

A: Given your requirements, I would suggest that you use the Hibernate framework. It has all the features that you have mentioned built into it. Additionally it also helps in directly mapping the tables to simple POJOs.
Using Hibernate, you can set the properties that you want in an xml configuration file and then you can change it at will to get what you want. Exception handling is something the user should never have to do - Hibernate provides features for this. Since it maps the tables to POJOs, the ResultSet can be easily processed.

A: I will try to provide a roll your own answer.
Make methods throwable in your api, it is a common api practice.
A ResultSet is just like a List<HashMap<String, dataType>> :

Create a List, and each record that is returned is populated into a
  HashMap where the fieldName is the key and the data returned is the
  value then add the HashMap to the List. For each record, create a new HashMap and repeat.

You can use metaData on a resultSet to get the number of Columns returned and the name of the columns returned.
    //rs is a ResultSet
    rs.getMetaData().getTableName(int Column);
    rs.getMetaData().getColumnCount();

Example Code for Select Query:
   private List<HashMap<String,Object>> selectQuery(sql) throws SqlException {
        //assumption that connection is a global
        List<HashMap<String, Object>> results = new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> record = null;
        PreparedStatement pStmt = conn.prepareStatement(sql);
        ResultSet rs = pStmt.executeQuery();
        while (rs.next() {
            record = new HashMap<String, Object>();
            for (int i : rs.getMetaData().getColumnCount()) {
                record.put(rs.getMetaData().getTableName(i), rs.getString(i));
            }
            results.add(record);
        }
        rs.close();
        return results;
    }

Connection
  -

Keep the connection open until they close it. The developer should
  know well enough that you should always close your connections else
  create a leak.

A: Here's my take:

The class will handle connecting

You should use a connection pool to acquire and manage connections.

disconnecting

The connections should be acquired by services for each unit of work/use case.  The service is responsible for acquiring the connection from the pool closing the connection in a finally block, and committing or rolling back transactions.

inserting and querying

easy to do.

very specifically and will only take in basic parameters

has to take in whatever data is needed.  you don't know basic.

I have the following design problems: Exception handling (should the
  user have to handle them, I prefer they do not),

persistence exceptions should never bubble out of the service layer.  It should inform the user as to what happened, but not by sending exceptions.  user friendly messages are preferred.

connecting (should the connection be re-established and closed on
  every query or just when a set of queries is done),

connections should be open in the narrowest scope possible.  associate them with a unit of work/transaction.  the pool amortizes the cost.

and displaying results (how should I most elegantly convert a
  ResultSet, which can throw exceptions, do a stable finalized set of
  results).

ResultSet should never, ever leave the persistence tier.  responsibility for closing it will be lost.  you should map all result sets into an object or collection of objects and return that.
Look at Spring JDBC template.  It's already sorted much of this out.
I would not recommend Hibernate.


text:
Q: Mysql - оптимизация select * Во всех гайдах предупреждают не использовать выборки select * по причине лишних нагрузок.
Цитата из офф руководства
Вместо использования 'SELECT *' всегда указывайте столбцы в предложении SELECT, чтобы повысить производительность MySQL. Поскольку ненужные столбцы создают дополнительную нагрузку на базу данных, замедляя ее работу, а также весь системный процесс.
Листая офф доки оптимизации наткнулся на момент "если таблица содержит строковые столбцы, но многие запросы не извлекают эти столбцы, рассмотрите их вынесение в отдельную таблицу и вызов соединения внешнего ключа по мере необходимости. Извлекая любое значение строки, mysql считывает блок данных со всей строкой всех столбцов, а возможно и другие соседние строки. Так вы сократите ввод-вывод и использование памяти к общим запросам. Сохранение каждой строки небольшой, с использованием только наиболее часто используемых столбцов позволяет большему количеству строк поместиться в каждый блок данных"
О чем речь? О ситуациях с hdd? О размере таблицы распределения 1-2-4-8-16-32kb любого диска?


text:
Q: Copy the latest version of an artifact from a Maven repository I am trying to copy a war file from my company's Nexus repository to a specific location. I am using maven-dependency-plugin in the following way:
    <plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-dependency-plugin</artifactId>
  <version>2.1</version>
  <executions>
   <execution>
    <id>copy-to-output</id>
    <phase>prepare-package</phase>
    <goals>
     <goal>copy</goal>
    </goals>
   </execution>
  </executions>
  <configuration>
           <artifactItems>
             <artifactItem>
               <groupId>com.mycompany</groupId>
               <artifactId>myproduct</artifactId>
               <version>2.3.0</version>
               <type>war</type>
               <overWrite>false</overWrite>
             </artifactItem>
           </artifactItems>
           <outputDirectory>${basedir}/src/main/output</outputDirectory>
         </configuration>
 </plugin>

The problem arise when I am trying to use <version>RELEASE</version> instead of a specific version (or no version at all) in order to get the latest release version (although not best practice, in this case it is safe) - it doesnt work. Any thoughts?

A: Brian Fox (who wrote the dependency plugin) explained in this answer that the unpack and copy goals do NOT support ranges (nor the LATEST or RELEASE) - he didn't implement this feature - and suggests to use the xxx-dependencies goals instead.

A: I wonder if this has been fixed in a later version of Maven; we're using 3.0.3 and maven-dependency-plugin:copy goal is working using <version>LATEST</version


text:
Q: How to iterate over a vector and compare the elements without using a clone to prevent a borrow error This is my working code where things is a Vec<[u8 ; 32]>
let t_copy = tx.things.clone();

for (index, value) in tx.things.into_iter().enumerate() {
    if tx.id == value {
        return Err(CustomError);
    }
    if t_copy[index].max(t_copy[index+1]) == t_copy[index]  {
        return Err(CustomError);
    }

}

I use into_iter rather than iter as I compare the values here:  tx.id == tx_parent
The above works but only because I clone the vector first which doesn't seem ideal to me. Is there a better way to achieve my goal here? Without the clone.
The purpose of the above code is to check the elements are in a certain order.

A: Use iter, not into_iter, the former returns iterator that iterates over existing vector by borrowing it, the latter consumes data - takes ownership of the object, and directly turns it into iterator, which is not what you want.


text:
Q: JavaScript and CSS minifier not working in Servicestack In the latest version of Servicestack, minifier was introduced. So, tried them in project. I am able to minify razor pages but not the javascript or css file I am adding into them.
I have copy pasted the code
public override List<IVirtualPathProvider> GetVirtualPathProviders()
{
    var existingProviders = base.GetVirtualPathProviders();
    var memFs = new InMemoryVirtualPathProvider(this);

    //Get existing Local FileSystem Provider
    var fs = existingProviders.First(x => x is FileSystemVirtualPathProvider);

    //Process all .html files:
    foreach (var file in fs.GetAllMatchingFiles("*.html"))
    {
        var contents = Minifiers.HtmlAdvanced.Compress(file.ReadAllText());
        memFs.AddFile(file.VirtualPath, contents);
    }

    //Process all .css files:
    foreach (var file in fs.GetAllMatchingFiles("*.css")
      .Where(file => !file.VirtualPath.EndsWith(".min.css"))) //ignore pre-minified .css
    {
        var contents = Minifiers.Css.Compress(file.ReadAllText());
        memFs.AddFile(file.VirtualPath, contents);
    }

    //Process all .js files
    foreach (var file in fs.GetAllMatchingFiles("*.js")
      .Where(file => !file.VirtualPath.EndsWith(".min.js"))) //ignore pre-minified .js
    {
        try
        {
            var js = file.ReadAllText();
            var contents = Minifiers.JavaScript.Compress(js);
            memFs.AddFile(file.VirtualPath, contents);
        }
        catch (Exception ex)
        {
            //As JSMin is a strict subset of JavaScript, this can fail on valid JS.
            //We can report exceptions in StartUpErrors so they're visible in ?debug=requestinfo
            base.OnStartupException(new Exception("JSMin Error {0}: {1}".Fmt(file.VirtualPath, ex.Message)));
        }
    }

    //Give new Memory FS the highest priority
    existingProviders.Insert(0, memFs);
    return existingProviders;
}

And while debugging it I found out that. It is indeed minifying the files but some how it is not getting there in out put.
I have also tried debug and release and even with deployed version. But JavaScript and CSS that are I am adding there as reference are still in beutified format only.
Am I doing something wrong?


text:
Q: 'No tests found in your file:' when using Before Hook in Cypress I'm attempting to use a Before Hook to run some commands however I keep being presented with 'No tests found in your file:'
describe("Test hook", function ()

{before("Before", function(){cy.log("Testing")})})

This is all I have in my .js, Cypress is able to find the .js file no problem and will run my code as expected when I'm not trying to use a before hook.
What am I missing here? Thanks.


text:
Q: mysql vs mongodb cache/load balancing I have a system where users can 'like' content. There will likely be many hundreds of these likes going on at once. I'd like it to be AJAX driven so you get an immediate response.
At the moment I have a mysql table of likes which contains the post_id and user_id and I have a 'cached' counter on the posts table with the total number of likes - simple so far.
Would I benefit in any way, from storing any of this information in mongodb to take the load off of mysql?
At the moment, I click like, and two mysql queries run - and INSERT into likes and an UPDATE on posts. If I'm in a large-scale environment in heavy read/write situation what would be the best way to go?
Thanks in advance :)


text:
Q: Using javascript to manipulate string into dom elements I have a string of text that is populated dynaimcally. In every string, there is one common word : "type". Given a string stored as a variable, I would like to use javascript to find the word "type" and place a dive before it, and then a closing div after the string.
Like so:
var string = "Here is some text that contains the word type and more text after";

I would like the end result to be like so:
Here is some text that contains the word
type and more text after

How can I go about this?
Current Code is below:
var wod = $("#wod a").attr("title");
    var newwod = wod.replace("Copyright 2012, GB Blanchard - Learn Spanish: www.braser.com","");
    //get ride of example and everythign after it
    var finalwod = newwod.split("Example")[0];
    var newstring = finalwod.replace(/(type.+)/,"
$1
");

   $("#wod span").append(newstring);

A: Just use replace:
string = string.replace(/(type.+)/,"
$1
");

Please note that this isn't the best approach when you're trying to modify HTML that consists of more complicated structures than a single text node, but it will do for this specific case.
As Jack has pointed out, you don't need to use a capturing group here since the entire match is already available using $&.
string = string.replace(/type.+/,"
$&
");

A: Is this really the only way you have available?
Asad has a good example of a regex, however, he also points out that your approach is not best practice.
Why can't you just have some structure?
var returnedData = { "type": "div", "text": "I like best practice" };
//Might need error checking in future
var newElement = document.createElement(returnedData.type);
newElement.innerHTML = returnedData.text;
$("#wod span").append(newElement);


text:
Q: Return a manipulated mutable Python object passed by reference Is it good practice to return an object that is passed by reference and manipulated in a function?
Which of these two approaches is more pythonic? Not returning a manipulated object in place or to return it:
def append42(mylist: list) -> None:
    mylist.append(42)

def append42(mylist: list) -> list:
    mylist.append(42)
    return mylist

The latter looks nicer to me, but it is ambiguous as the function can be used in two different ways to get the same result, e.g.:
mylist = [1, 2, 3]
append42(mylist)
print(mylist)
>>> [1, 2, 3, 42]

or
mylist = [1, 2, 3]
stillmylist = append42(mylist)
assert stillmylist == mylist
print(stillmylist)
>>> [1, 2, 3, 42]


text:
Q: Angular Grid Validation on cell value How would I highlight a cell be colored red if gender == "male" instead of a row. This code currently highlights the whole row, but I want it to highlight only a particular cell. This code is taken from this UI Grid tutorial.
var app = angular.module('app', ['ngAnimate', 'ngTouch', 'ui.grid', 'ui.grid.importer', 'ui.grid.rowEdit', 'ui.grid.edit']);

app.controller('MainCtrl', ['$scope', '$http', '$interval', '$q', function ($scope, $http, $interval, $q) {
  $scope.data = [];
  $scope.gridOptions = {
    enableGridMenu: true,
    importerDataAddCallback: function(grid, newObjects) {
      $scope.data = $scope.data.concat(newObjects);
    },
    onRegisterApi: function(gridApi) {
      $scope.gridApi = gridApi;
      gridApi.rowEdit.on.saveRow($scope, $scope.saveRow);
    },
    data: 'data'
  };

  $scope.saveRow = function(rowEntity) {
    // create a fake promise - normally you'd use the promise returned by $http or $resource
    var promise = $q.defer();
    $scope.gridApi.rowEdit.setSavePromise(rowEntity, promise.promise);

    // fake a delay of 3 seconds whilst the save occurs, return error if gender is "male"
    $interval(function() {
      if (rowEntity.Gender === 'male') {
        promise.reject();
      } else {
        promise.resolve();
      }
    }, 3000, 1);
  };

  var handleFileSelect = function(event) {
    var target = event.srcElement || event.target;

    if (target && target.files && target.files.length === 1) {
      var fileObject = target.files[0];
      $scope.gridApi.importer.importFile( fileObject );
      target.form.reset();
    }
  };
};

import.json
[
  {"name":"John Smith", "gender":"male", "company":"TestIcon"},
  {"name":"Jane Doe", "gender":"female", "company":"FastTruck"}
]

A: If you just want to dynamically highlight a cell, regardless of any validation stuff, you can provide a function to the cellClass property on your column definition:
{
  field: 'gender',
  cellClass: function (grid, row, col, rowIndex, colIndex) {
    var val = grid.getCellValue(row, col);
    if (val === 'male') {
      return 'blue';
    }
    else if (val === 'female') {
      return 'pink';
    }
  }
}

There's a plunker for this specific example: http://plnkr.co/edit/kbZfVKkSTKGuD9XiDz1f?p=preview, and a longer write-up if you want more information: http://brianhann.com/customize-ui-grid-with-dynamic-cell-classes/


text:
Q: Accessing Data from Archive / Repository (FTP?) I'm trying to write a script in MATLAB to pull down the data from this website: https://data.cresis.ku.edu/data/rds/2010_Antarctica_DC8/CSARP_standard/20101120_03/
which includes the accessing of subsequent ".mat" files present.
I'm not super familiar with data acquisition and I'm not sure if this is FTP or whatnot.
Question statement:
How do you conclude what type of protocol to access the data, and in what syntax is this accomplished in MATLAB?
I've begun to experiment with the method found here: http://www.mathworks.com/help/matlab/ref/ftp.mget.html


text:
Q: URLLoader Error#2032 issues in Air 3.8 I am looking for some help to address the below mentioned issue;
Ever since I upgraded the Adobe air version from 3.7 to 3.8 in my mobile (S4), my Android App started getting URL stream error #2032 when trying to contact an INTRANET URL (web service endpoint which is NOT open to internet). But works perfectly when trying to access URL's which are open to internet.Again if I downgrade the Air version in the mobile to 3.7 then everything works perfect.

*

*This 2032 stream error happens only when I tried deploying the app to an actual android device (S4 / Jelly Bean) and use it.

*No issues when trying  to access same URL through the emulator (Flash Builder).

*The android device which I used for testing is SUCCESSFULLY (authentication successful) connected to the intranet network through WIFI.

*I am using Flash Builder 4.7 and Apache Flex 4.10 SDK to develop the app.

This is how I use URLLoader to call web services;
var urlRequest:URLRequest = new URLRequest();
urlRequest.contentType = "text/xml; charset=utf-8";
urlRequest.method = "POST";
urlRequest.requestHeaders.push(new URLRequestHeader("SOAPAction",""));
urlRequest.requestHeaders.push(new URLRequestHeader("Connection", "Keep-Alive"));
urlRequest.url = "https://example.com/services/abcWebService"; //Intranet- NOT OPEN TO INTERNET
urlRequest.data = "I have my soap request xml here";
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE,resultHandlerFunction);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, **ioErrorHandlerFunction**);
urlLoader.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS, responseHandlerFunction);
urlLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, statusHandlerFunction);
urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandlerFunction);
urlLoader.load(urlRequest);

All the times UrlLoader ends up in the ioErrorHandlerFunction  with stream error #2032
The HTTPStatusEvent.HTTP_Status doesn't give much information either, the status code is 0.
Should I make any changes to the way I use URLLoader?
The same code works good with Air 3.7

A: This appears to be a bug in AIR 3.8 related to SSL.  Try changing your URL to http.  I realize that may not be a solution, but it may help us diagnose it.


text:
Q: DecoderFailure in cardano-cli I'm facing some issues with cardano-cli. I'm using the Daedalus socket and trying to query the testnet.
When running this command cardano-cli query tip --testnet-magic 1097911063 it returns the following:
cardano-cli: DecoderFailure (LocalStateQuery HardForkBlock (': * ByronBlock (': * (ShelleyBlock (ShelleyEra StandardCrypto)) (': * (ShelleyBlock (ShelleyMAEra 'Allegra StandardCrypto)) (': * (ShelleyBlock (ShelleyMAEra 'Mary StandardCrypto)) ('[] *))))) Query (HardForkBlock (': * ByronBlock (': * (ShelleyBlock (ShelleyEra StandardCrypto)) (': * (ShelleyBlock (ShelleyMAEra 'Allegra StandardCrypto)) (': * (ShelleyBlock (ShelleyMAEra 'Mary StandardCrypto)) ('[] *))))))) ServerAgency TokQuerying QueryHardFork GetCurrentEra) (DeserialiseFailure 3 "EraIndex: invalid index 4")

However when executing cardano-cli get-tip --testnet-magic 1097911063 it works fine.
What could be causing this? Any thoughts on what I might be missing?

A: Okay so I ran into this issue too and I was able to solve the issue by upgrading the cardano-cli
confirmed that this version of the cli:
cardano-cli --version
cardano-cli 1.30.1 - linux-aarch64 - ghc-8.10
git rev 0fb43f4e3da8b225f4f86557aed90a183981a64f

works with this version of the node:
cardano-node --version
cardano-node 1.34.1 - linux-aarch64 - ghc-8.10
git rev 73f9a746362695dc2cb63ba757fbcabb81733d23


text:
Q: Using log4j2 property substitution with properties defined in another file I'm working on a project using log4j2, and have some values in my log4j2.properties which are configurable. This project will also include a configuration file for other components. Ideally, I'd like to keep all my configuration in one place so I'd like to be able to set those configurable values for log4j in that same file, so that I don't have two different places where config values are subject to change (including environment variables, for example).
The ways I've found around this are less than ideal, like having other parts of my project read the values from the main config file and put them into system variables to be picked up by log4j, since I'd like to avoid writing code to set up log4j outside of its own properties file.
Is there any way to directly reference values defined in other properties files in log4j2.properties? If not, it this possible in one of the configuration file formats log4j2 can use, like XML or JSON?
To clarify, I'm aware of the various ways lookup methods available in log4j2 but since I'm storing these values in a different file none of them are as "clean" as being able to reference that file directly.

A: The Log4j2 configuration has a properties section, and if all keys are known in advance, you can get each of the values from another lookup, like the system properties lookup or a custom lookup.
It may be a good idea to suggest getting Log4j2 configuration properties from an external properties file as a new feature request on the Log4j2 JIRA issue tracker.


text:
Q: Ext-js: How to resize / close browser window? Does Ext-js come with functionality to manipulate the browser window?
Specifically, I want to resize and close the current browser window.
(Browser window, the browser's native window, as opposed to Ext-js' widgets).
It it possible or must I resort to plain old javascript?

A: As far as I know Ext JS does not have any functionality to support changing the browser window.  Ext JS what originally designed run on top of other frameworks like jQuery and Prototype, so when run by its self it does not contain many non-widget methods.
You would have to default to using window.resizeTo or window.close.
If you need to let Ext JS know that you have changed the size of the window you can register an event using Ext.EventManager.onWindowResize.  Take a look the method documentation on the ExtJS site: http://dev.sencha.com/deploy/dev/docs/?class=Ext.EventManager


text:
Q: Why this multiple queries are not getting executed. Only pincode is showing output. Rest is showing Notice: llTrying to access array offset in php I am trying to execute multiple select query one after another with different variables. Out all queries only query used for Pincode is showing result rest is showing - Notice: Trying to access array offset on value of type null in
I am new to PHP. Thank you to guide me in advance
<?php
include 'connection.php';
include 'eMembersHome.php';
include 'common.php';

$muname = $_SESSION['muname'];

$sql = "Select * from membersprofile where muname = '$muname'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($result);

$mfname = $row['mfname'];
$mlname = $row['mlname'];
$ftname = $row['ftname'];
$mdob = $row['mdob'];
$maddress = $row['maddress'];
$muname = $row['muname'];
$mpassword = $row['mpassword'];
$marea = $row['marea'];
$mlandmark = $row['mlandmark'];
$mcity = $row['mcity'];
$mstate = $row['mstate'];
$mpincode = $row['mpincode'];
$mcountry = $row['mcountry'];

$sql4 ="select cname from country where sno = '$mcountry'";
$res4=mysqli_query($con,$sql4);
$data4=mysqli_fetch_assoc($res4);

$sql1 = "select sname from states where ssno = '$mstate'";
$res1=mysqli_query($con,$sql1);
$data=mysqli_fetch_assoc($res1);

$query = "select ctname from cities where ctsno = '$mcity'";
$rescity=mysqli_query($con,$query);
$datacity=mysqli_fetch_assoc($rescity);

$sql3 = "select pincode,area from pincode where psno = '$mpincode'";
$res3=mysqli_query($con,$sql3);
$data2=mysqli_fetch_assoc($res3);

?\>


text:
Q: How to stop our document to be scroll, once a perticular section of of our document comes inside our view port in React.js? What I am trying to achieve:
I Have three sections on my webpage first page, second page, and third page (those are section names, all three have 100vh and 100vw so they are cover our entire screen) and I want that once the second page comes in the viewport so the document should not be scrollable any more (i mean once our second page comes in viewport we can't scroll anymore to the third page it should stop scrolling)
what I tried in codepen.
https://codepen.io/Adarsh04/pen/yLvppBK
rootElement

CSS
  body{
  -ms-overflow-style: none;
  scrollbar-width: none;
}

*::-webkit-scrollbar {
  /* width: 4px;
  cursor: pointer; */
  display: none;
}

.firstPage,.secondPage,.thirdPage{
  border:1px solid red;
  width:95vw;
  margin:atuo;
  height:95vh;
  display:flex;
  align-items:center;
  justify-content:center;
  font-size:64px;
}

.firstPage{
  background-color:red;
}

.secondPage{
  background-color:blue;
}

.thirdPage{
  background-color:yellow;
}

App.js
    const App = () => {
  React.useEffect(()=>{
    const handleEvent = () => {
      const bounding = document
        .getElementById("secondPage")
        .getBoundingClientRect();
      if (
        bounding.top >= 0 &&
        bounding.left >= 0 &&
        bounding.right <=
          (window.innerWidth || document.documentElement.clientWidth) &&
        bounding.bottom <=
          (window.innerHeight || document.documentElement.clientHeight)
      ) {
        console.log("Element is in the viewport!");
        document.body.style.overflow = "hidden";
      } else {
        console.log("Element is NOT in the viewport!");
      }
    };
    window.addEventListener("scroll", handleEvent, { passive: true });

    return () => {
      window.removeEventListener("scroll", handleEvent), { passive: true };
    };
  },[])
  return(

First.

Second.

Third

  );
}

ReactDOM.render(<App />,
document.getElementById("root"))

here the problem is only that when I scroll fastly that the second page is not stopped but if I scroll slowly its works and I want it should work regardless of how fast or slow I scroll


text:
Q: ProgressDialog problem during Activiy onCreate():void in Android Solution:
Okay,I've found the solution from your answers since your answers are not completely working
First we need to use Handler to post a Runnable to main/UI thread to run UpdateDisplay() and but define ProgressDialog under UIThread not other threads which was also crucial.
Here is the final code :
public final String RSSFEEDOFCHOICE = "http://www.deals2buy.com/rssgen/tech.xml";

public final String tag = "RSSReader";
private RSSFeed feed = null;
private Handler handler = new Handler();
private ProgressDialog dialog;

/** Called when the activity is first created. */

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    dialog = ProgressDialog.show(RSSReader.this, "Loading",
            "Loading, please wait..");
    Thread t = new Thread() {
        public void run() {
            feed = getFeed(RSSFEEDOFCHOICE);
            handler.post(new Runnable() {
                public void run() {
                    dialog.dismiss();
                    UpdateDisplay();
                };
            });
        }
    };

    t.start();
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Problem :
When Android application first load, this is what happens :

*

*Retrieving RSS content from Url and parse it into RSSFeed feed instance variable via getFeed(String url).

*Showing these feeds to users in ListView via UpdateDisplay() method.

When these are happening, I wanted to show a ProgressDialog to users to notify them about system are retriving content like "Loading, please wait..." Once getFeed(String Url):RSSFeed is done, ProgressDialog will be dismissed and UpdateDisplay():void will be invoked.
So this is my first attempt :
public final String RSSFEEDOFCHOICE = "somewhere.xml"; //coming from http
public final String tag = "RSSReader";
private RSSFeed feed = null;
/** Called when the activity is first created. */

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    ProgressDialog dialog = ProgressDialog.show(RSSReader.this, "Loading...", "Loading, please wait");
    feed = getFeed(RSSFEEDOFCHOICE);
    dialog.dismiss();
    UpdateDisplay();
}

And it doesn't show the ProgressDialog so it didn't work the way I want. Since I belived it is because ProgressDialog is continues progress, it should be handled by another Thread.
Here is my second attempt :
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    Thread t = new Thread()
    {
        public void run()
        {
            ProgressDialog dialog = ProgressDialog.show(RSSReader.this, "Loading...", "Loading, please wait");
            feed = getFeed(RSSFEEDOFCHOICE);
            dialog.dismiss();
        }
    };

    UpdateDisplay();
}

It was okay till UpdateDisplay() since this method was handled by main thread and it wasn't waiting anything so I thought maybe I should have put it under t Thread after dialog.dismiss().
So I did this :
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    Thread t = new Thread()
    {
        public void run()
        {
            ProgressDialog dialog = ProgressDialog.show(RSSReader.this, "Loading...", "Loading, please wait");
            feed = getFeed(RSSFEEDOFCHOICE);
            dialog.dismiss();
                    UpdateDisplay();
        }
    };
}

But then debugger said at run-time : only the main thread which handles onCreate():void can reach and use View objects because it creates them.
Now, I am so messed up and feel like quitting programming.
Some one can help me :/
Thanks in advance.

A: You could use AsyncTask, thats exactly what its for. Since onPostExecute(Long result) is done on the UI thread, it wont crash when looking for View objects.
Here is a example taken from the asyncTask reference
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

What you want to do is obtain the RSS feed in doInBackground(), and then update the UI in onPostExecute.
In your onCreate() method, invoke the asyncTask.
new DownloadFilesTask().execute(url1, url2, url3);

A: Okay,I've found the solution from your answers since your answers are not completely working
First we need to use Handler to post a Runnable to main/UI thread to run UpdateDisplay() and but define ProgressDialog under UIThread not other threads which was also crucial.
Here is the final code :
public final String RSSFEEDOFCHOICE = "http://www.deals2buy.com/rssgen/tech.xml";
public final String tag = "RSSReader";
private RSSFeed feed = null;
private Handler handler = new Handler();
private ProgressDialog dialog;

/** Called when the activity is first created. */

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    dialog = ProgressDialog.show(RSSReader.this, "Loading",
            "Loading, please wait..");
    Thread t = new Thread() {
        public void run() {
            feed = getFeed(RSSFEEDOFCHOICE);
            handler.post(new Runnable() {
                public void run() {
                    dialog.dismiss();
                    UpdateDisplay();
                };
            });
        }
    };

    t.start();
}

A: You have to run your request in another thread than the progressdialog. So try with
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
ProgressDialog dialog = ProgressDialog.show(RSSReader.this, "Loading...", "Loading, please wait");
Thread t = new Thread()
{
    public void run()
    {
        feed = getFeed(RSSFEEDOFCHOICE);
        dialog.dismiss();
        UpdateDisplay();
    }
};
}

And depending on what you do in update display you should run it in the UI thread.

A: Actually the best way would be to use AsyncTask.
However as a quick workaround you could do smth like this:
private Handler handler = new Handler();

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    Thread t = new Thread()
    {
        public void run()
        {
            ProgressDialog dialog = ProgressDialog.show(RSSReader.this, "Loading...", "Loading, please wait");
            feed = getFeed(RSSFEEDOFCHOICE);
            dialog.dismiss();
            handler.post(new Runnable() {
                public void run() {
                    UpdateDisplay();
                }
            });
        }
    };

}


text:
Q: OpenERP Server Error When Click New Module Install I just now installed Odoo and it shown local modules with install button. I clicked install but no module is installed and always displayed with following error message.
I searched for answers with query "odoo arch mes_type" odoo module install error and many possible variations but not going anywhere.
In one thread it was told to upgrade with sudo apt-get install python-passlib but that didn't change anything.
    Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 500, in _handle_exception
    # We need then to manage http sessions manually.
  File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 517, in dispatch
    return super(JsonRequest, self)._handle_exception(exception)
  File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 283, in _call_function
  File "/usr/lib/python2.7/dist-packages/openerp/service/model.py", line 113, in wrapper
    return f(dbname, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 280, in checked_call
    # Backward for 7.0
  File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 733, in __call__
    # but we only store controllers directly inheriting from Controller
  File "/usr/lib/python2.7/dist-packages/openerp/http.py", line 376, in response_wrap
    routing = kw.copy()
  File "/usr/lib/python2.7/dist-packages/openerp/addons/web/controllers/main.py", line 975, in call_button
    def call_button(self, model, method, args, domain_id=None, context_id=None):
  File "/usr/lib/python2.7/dist-packages/openerp/addons/web/controllers/main.py", line 963, in _call_kw
  File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 237, in wrapper
    return old_api(self, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/openerp/addons/base/module/module.py", line 450, in button_immediate_install
    return self._button_immediate_function(cr, uid, ids, self.button_install, context=context)
  File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 237, in wrapper
    return old_api(self, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/openerp/addons/base/module/module.py", line 498, in _button_immediate_function
    registry = openerp.modules.registry.RegistryManager.new(cr.dbname, update_module=True)
  File "/usr/lib/python2.7/dist-packages/openerp/modules/registry.py", line 341, in new
    openerp.modules.load_modules(registry._db, force_demo, status, update_module)
  File "/usr/lib/python2.7/dist-packages/openerp/modules/loading.py", line 358, in load_modules
    loaded_modules, update_module)
  File "/usr/lib/python2.7/dist-packages/openerp/modules/loading.py", line 263, in load_marked_modules
    loaded, processed = load_module_graph(cr, graph, progressdict, report=report, skip_modules=loaded_modules, perform_checks=perform_checks)
  File "/usr/lib/python2.7/dist-packages/openerp/modules/loading.py", line 182, in load_module_graph
    _load_data(cr, module_name, idref, mode, kind='data')
  File "/usr/lib/python2.7/dist-packages/openerp/modules/loading.py", line 118, in _load_data
    tools.convert_file(cr, module_name, filename, idref, mode, noupdate, kind, report)
  File "/usr/lib/python2.7/dist-packages/openerp/tools/convert.py", line 907, in convert_file
    convert_sql_import(cr, fp)
  File "/usr/lib/python2.7/dist-packages/openerp/tools/convert.py", line 997, in convert_xml_import
    xml_filename = xmlfile.name
  File "/usr/lib/python2.7/dist-packages/openerp/tools/convert.py", line 858, in parse
    for n in de.findall('./data'):
  File "/usr/lib/python2.7/dist-packages/openerp/tools/convert.py", line 771, in _tag_record
    id = self.pool['ir.model.data']._update(cr, self.uid, rec_model, self.module, res, rec_id or False, not self.isnoupdate(data_node), noupdate=self.isnoupdate(data_node), mode=self.mode, context=rec_context )
  File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 237, in wrapper
    return old_api(self, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/openerp/addons/base/ir/ir_model.py", line 1060, in _update
    res_id = model_obj.create(cr, uid, values, context=context)
  File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 237, in wrapper
    return old_api(self, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/openerp/addons/base/ir/ir_ui_view.py", line 322, in create
    context=context)
  File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 237, in wrapper
    return old_api(self, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 332, in old_api
    result = method(recs, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/openerp/models.py", line 3979, in create
  File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 235, in wrapper
    return new_api(self, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 464, in new_api
    result = method(self._model, cr, uid, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/openerp/models.py", line 4170, in _create
    cr.execute('select parent_left from '+self._table+' where id=%s', (parent,))
  File "/usr/lib/python2.7/dist-packages/openerp/api.py", line 235, in wrapper
    return new_api(self, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/openerp/models.py", line 1271, in _validate_fields
    errors.append(
ParseError: "ValidateError
Field(s) `arch` failed against a constraint: Invalid view definition

Error details:
Field `mes_type` does not exist

Error context:
View `product.template.common.form`
[view_id: 332, xml_id: n/a, model: product.template, parent_id: n/a]" while parsing /usr/lib/python2.7/dist-packages/openerp/addons/product/product_view.xml:46, near
<record id="product_template_form_view" model="ir.ui.view">
            <field name="name">product.template.common.form</field>
            <field name="model">product.template</field>
            <field name="mode">primary</field>
            <field name="arch" type="xml">
                <form string="Product">
                    <field name="is_product_variant" invisible="1"/>
                    <field name="product_variant_count" invisible="1"/>
                    <sheet>
                        <field name="id" invisible="True"/>

                            <field name="image_medium" widget="image" class="oe_avatar oe_left"/>

<field name="name" class="oe_inline"/>

                                        <field name="sale_ok"/>

                        <notebook>
                            <page string="Information">
                                <group colspan="4">
                                    <group>
                                        <field name="type"/>
                                        <field name="uom_id" on_change="onchange_uom(uom_id,uom_po_id)" groups="product.group_uom"/>
                                        <field name="list_price"/>
                                    </group>
                                    <group>
                                        <field name="active"/>
                                    </group>
                                </group>
                                <group colspan="4">
                                    <field name="company_id" groups="base.group_multi_company" widget="selection"/>
                                </group>
                                <field name="description" placeholder="describe the product characteristics..."/>
                            </page>
                            <page string="Procurements" groups="base.group_user">
                                <group name="procurement">
                                    <group name="general">
                                        <field name="standard_price"/>
                                    </group>
                                    <group name="procurement_uom" groups="product.group_uom" string="Purchase">
                                        <field name="uom_po_id"/>
                                    </group>
                                </group>
                                <separator string="Suppliers"/>
                                <field name="seller_ids"/>
                                <separator string="Description for Suppliers"/>
                                <field name="description_purchase" placeholder="This note will be displayed on requests for quotation..."/>
                            </page>
                            <page string="Inventory">
                                <group name="inventory">
                                     <group name="status" string="Status">
                                        <field name="state"/>
                                        <field name="product_manager"/>
                                    </group>
                                    <group name="weight" string="Weights" attrs="{'invisible':[('type','=','service')]}">
                                        <field digits="(14, 3)" name="volume"/>
                                        <field digits="(14, 3)" name="weight"/>
                                        <field digits="(14, 3)" name="weight_net"/>
                                    </group>
                                </group>
                                <group name="packaging" string="Packaging" attrs="{'invisible':[('type','=','service')]}" groups="product.group_stock_packaging" colspan="4">
                                    <field name="packaging_ids" string="Configurations" context="{'tree_view_ref':'product.product_packaging_tree_view_product', 'form_view_ref': 'product.product_packaging_form_view_without_product'}"/>
                                </group>
                            </page>
                            <page string="Sales" attrs="{'invisible':[('sale_ok','=',False)]}" name="sales">
                                <group name="sale">
                                    <group name="sale_condition" string="Sale Conditions" colspan="3">

                                            <field name="warranty" class="oe_inline"/> months

                                    </group>
                                    <group groups="product.group_uos" string="Unit of Measure">
                                        <field name="uos_id"/>
                                        <field name="uos_coeff"/>
                                        <field name="mes_type"/>
                                    </group>
                                </group>
                                <group name="website_and_pos" col="2">
                                </group>
                                <separator string="Description for Quotations"/>
                                <field name="description_sale" placeholder="note to be displayed on quotations..."/>
                            </page>
                        </notebook>
                    </sheet>

                        <field name="message_follower_ids" widget="mail_followers"/>
                        <field name="message_ids" widget="mail_thread"/>

                </form>
            </field>
        </record>

A: Like as per @Danish said, he has problem of wkhtmltopdf problem and solved by blow step.
So here is solution.
Thanks


text:
Q: Can't manage to extract or convert SWF file because they seem to be corrupted So I've extracted from a website a bunch of swf file which are photos.
What I was intending to do is converting them using swf tool.
However whatever I'm trying on thoose I'm ending up with :

./503141211.swf is not a valid SWF file or contains errors.

For exemple I've tried to render them with :
swfrender 2773003.swf -o test.png
Any idea why this is happening?
You can find one of the file there if you want :
Link to file
Otherwise do you have a solution to extract an image from this link?

A: Your SWF files are already in JPEG format.
Solution: Try renaming them from .swf to .jpg.
Extended version:
If you ever suspect some file corruption, then first check the bytes with a hex-editor. Correct SWF beginning bytes are 43 57 53 (CWS) or sometimes begins with bytes 46 57 53 (FWS).
Your linked SWF file begins with FF D8 FF which is usually expected in JPEG files.
Also seeing JFIF signature confirms that this is a JPEG image file (not a Flash SWF file).

So after renaming from 3503270035.swf to 3503270035.jpg we get this result in image viewer:


text:
Q: Organic Group, og details block link in lightbox I have used organic grouop(og) in my website, and i have a block of group details where group content creation link are appearing. now i want to open those link in lightbox. or in popup how can we do this.

A: You can either use the popup API - http://drupal.org/project/popups
or
Thickbox - http://drupal.org/project/thickbox


text:
Q: DurandalJS and jQuery not adding to Select I am creating a SPA in DurandalJS with MVC, and have jQuery loading a <select> with options loaded from a database. Setting breakpoints i was able to follow the stack all the way down the chain and verify that all of my ajax loading and jQuery calls were occuring, but when I go to check the select box, it is empty, including the inner html of the tag and the dropdown elements themselves.
What's weird though is that the items will load if I navigate to another page and then come back to the original page (since this is an ajax-ified single page application it doesn't actually navigate in the traditional sense.
Why is this happening and how can I fix it?
Code to load the data:
function addProjectSelectorOptions(projects) {
        $('#project-picker').empty();
        for (var i = 0; i < projects.length; i++) {
            console.log(projects[i]);
            $('#project-picker').append(new Option(projects[i]["Name"], projects[i]["Id"]));
        }
    }

    function loadData() {

        $.ajax({
            url: '/ClubhouseData/GetProjects',
            type: 'GET',
            cache: false,
            success: function (results) {
                console.log(results);
                addProjectSelectorOptions(results);
            }
        });

    };

    loadData();

A: Solved:
I wrapped loadData() in a jQuery onDocumentLoad call and it fixed the problem.


text:
Q: Unable to create table in local dynamoDB I have locally running DynamoDB and create a table using the shell( localhost:8000/shell/).
Can confirm with the following code:
var params = {
  ExclusiveStartTableName: 'STRING_VALUE',
  Limit: 10
};
dynamodb.listTables(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

outputs
{"TableNames":["myTable"]}

However when I call getItem/PutItem from PHP code it throws the following error

[Mon Dec 14 11:22:48.266930 2015] [:error] [pid 12] [client
  10.0.2.2:58042] PHP Fatal error:  Uncaught Aws\DynamoDb\Exception\ResourceNotFoundException: AWS Error Code:
  ResourceNotFoundException, Status Code: 400, AWS Request ID:
  8de599f1-7aa6-4147-b2f8-b3acc74b09da, AWS Error Type: client, AWS
  Error Message: Cannot do operations on a non-existent table,
  User-Agent: aws-sdk-php2/2.8.24 Guzzle/3.9.3 curl/7.35.0
  PHP/5.5.9-1ubuntu4.14\n  thrown in
  /opt/lib/aws/sdk/vendor/aws/aws-sdk-php/src/Aws/Common/Exception/NamespaceExceptionFactory.php
  on line 91

And this is how I create the client
$this->client = DynamoDbClient::factory(array(
    'key' => 'YOUR_KEY',
    'secret' => 'YOUR_SECRET',
    'profile' => 'default',
    'region'  => 'us-west-2',
    //'version' => '2012-08-10',
    'endpoint'=> 'http://localhost:8000',
    //'debug'   => true
));

If the endpoint were wrong, client creation itself would have thrown error but in this case tables are not getting created as per PHP
echo "List of tables";
$iterator = $this->client->()->getIterator('ListTables');
foreach ($iterator as $tableName) {
    echo $tableName . "\n";
}

prints nothing.

A: I have just answered a similar question here: https://stackoverflow.com/a/40806393/1061798
Check how you are starting dynamoDB. You need to add a -sharedDb flag as described in my answer in the link above


text:
Q: Disable Scrolling in SwiftUI List/Form Lately, I have been working on creating a complex view that allows me to use a Picker below a Form. In every case, the Form will only have two options, thus not enough data to scroll downwards for more data. Being able to scroll this form but not Picker below makes the view feel bad. I can't place the picker inside of the form or else SwiftUI changes the styling on the Picker. And I can't find anywhere whether it is possible to disable scrolling on a List/Form without using:
.disable(condition)

Is there any way to disable scrolling on a List or Form without using the above statement?
Here is my code for reference
VStack{
        Form {
            Section{
                Toggle(isOn: $uNotifs.notificationsEnabled) {
                    Text("Notifications")
                }
            }
            if(uNotifs.notificationsEnabled){
                Section {
                    Toggle(isOn: $uNotifs.smartNotifications) {
                        Text("Enable Smart Notifications")
                    }
                }.animation(.easeInOut)
            }
       } // End Form
            .listStyle(GroupedListStyle())
            .environment(\.horizontalSizeClass, .regular)
        if(!uNotifs.smartNotifications){
                GeometryReader{geometry in
                    HStack{
                        Picker("",selection: self.$hours){
                            ForEach(0..<24){
                                Text("\($0)").tag($0)
                            }

                        }
                            .pickerStyle(WheelPickerStyle())
                            .frame(width:geometry.size.width / CGFloat(5))
                            .clipped()
                        Text("hours")
                        Picker("",selection: self.$min){
                            ForEach(0..<61){
                                Text("\($0)").tag($0)
                            }

                        }
                            .pickerStyle(WheelPickerStyle())
                            .frame(width:geometry.size.width / CGFloat(5))
                            .clipped()
                        Text("min")
                    }

A: Here it is

Using approach from my post SwiftUI: How to scroll List programmatically [solution]?, it is possible to add the following extension
extension ListScrollingProxy {
    func disableScrolling(_ flag: Bool) {
        scrollView?.isScrollEnabled = !flag
    }
}

and the use it as in example for above demo
struct DemoDisablingScrolling: View {
    private let scrollingProxy = ListScrollingProxy()

    @State var scrollingDisabled = false
    var body: some View {
        VStack {
            Button("Scrolling \(scrollingDisabled ? "Off" : "On")") {
                self.scrollingDisabled.toggle()
                self.scrollingProxy.disableScrolling(self.scrollingDisabled)
            }
            Divider()
            List(0..<50, id: \.self) { i in
                Text("Item \(i)")
                    .background(ListScrollingHelper(proxy: self.scrollingProxy))
            }
        }

    }
}

A: You can use the .scrollDisabled(true) modifier on the component (Form or List) to accomplish this behavior.


text:
Q: No privileges on phpMyAdmin I'm trying to follow a udemy course and in order to complete it I need to have proper working phpMyAdmin CP.
I am running through WAMP 2.4, I went to localhost/phpmyadmin and "logged in" (username is admin, password is blank") and went to complete the first step which is to create a database.
But I see a red x and "no priveleges" where I should see the database creation input.
I tried going back to the home of phpMyAdmin and changing my password to not be blank but I get an error message when I try that too.
Create database:
No Privileges

A: User you are connecting to phpmyadmin has no privileges set for it to be able to create database.
Edit config File on phpmyadmin setup and set a user with more permissions root user for mysql can be good since this is for a course?

A: The actual solution is to use the correct MySQL user account to login.
By default ALL MySQL installs come with ONE pre configured Userid and that is root it comes with no password.
So when phpMyAdmin asks you to login use :-
Username = root
password = (leave this blank)
Then press the Go button.
You should really now add a password to this account as it is the SUPER User account. Add the same password to all 3 of the root user accounts. Yes all 3, there are rooot@localhost and root@127.0.0.1 and root@::1
Remember that a MySQL user account is domain specific, in other words you can create user1 that is allowed to login from a specific ip address or many specific ip address's


text:
Q: pandas rename columns then assign to a new dataframe python 2.7 - I want to create a new dataframe with renaming columns from a different dataframe
for example x is a pandas DF and I want to rename the columns and save it into y
this example returns NONE
x=pd.read_excel(r'C:\hm.xlsx')
y=x.rename(columns={'Zip': 'Zipcode'},inplace='False')
print y

however if I do
x=pd.read_excel(r'C:\hm.xlsx')
x.rename(columns={'Zip': 'Zipcode'},inplace='True')
print x

this correctly renames it -- what do I need to do

A: Try This
x = pd.read_excel(r'C:\hm.xlsx')
y = x.copy()
y.rename(columns={'Zip': 'Zipcode'},inplace='True')
print(y)

x.rename() is a function that does not return anything but rather alters x.
By setting y = x.rename() you are therefore setting y to NoneType.
y = x.copy() is necessary to create a deep copy rather than a pointer to x, so you can alter y without altering x


text:
Q: issue with  and using basename Unable to get basename to work in C++, I am trying to just get the code to compile.
This is for a school assignment and I have tried to see if it is my stdlib having issues -- however, it seems that the problem is that
'''c++
#include<iostream>
#include<cstring>
#include<libgen.h>
int main(){
  const char *ch = "asdfasdf/asdf.cpp";
  std::cout<<basename(ch) << std::endl;
  std::cout<<dirname(strdup(ch)) << std::endl;
  return 0;
}

I was supposed to print out the output of ch, however, instead I get the error message:
test.cpp:8:14: error: no matching function for call to 'basename'
  std::cout<enter code here
/usr/include/libgen.h:40:7: note: candidate function not viable: 1st argument ('const char *') would lose const qualifier
char    *basename(char *);
         ^
1 error generated.

A: basename's argument is char*, so this function may modify passed data. You cannot pass const char* - pointer to only-read data into basename because it would let basename modify const data - not allowed.
Create your input as modifiable array:
char ch[] = "asdfasdf/asdf.cpp";


text:
Q: Como gerar novo código a partir do DBO Tenho uma tabela com o nome Produtos em que eu inseri 3 produtos para testes. Agora estou montando o formulário de cadastro de produtos e preciso que sempre gere um código de produto sequencial a partir do último id já cadastrado + 1.
O código que fiz é esse, segui a minha lógica mas n está funcionando.
    private void GerarNovoCodigo()
    {
        string strCon = "Data Source=MEUPC; Initial Catalog=MEUDB; Integrated Security=SSPI";
        SqlConnection sqlCon = new SqlConnection(strCon);
        SqlCommand sqlCom = new SqlCommand();
        sqlCom.Connection = sqlCon;
        sqlCon.Open();

        sqlCom.CommandText = "Select max(prod_codigo) + 1  from Produtos";

        txt_prod_cod.Text = Convert.ToString(sqlCom.ExecuteNonQuery());
    }

A: O problema específico é que o método usado retorna o número de linhas afetadas e não o código gerado. O certo é usar o ExecuteScalar().
Em casos onde há acesso concorrente (quase sempre tem) pegar um código assim é problemático. Tem que mandar gravar os dados e aí gerar um novo código, caso contrário tem uma condição de corrida.
Além disso parece que a aplicação tem bastante código repetido. Não é uma boa ideia enxugar depois, mas isso é com você.

A:
Elaborei essa resposta apenas para englobar e tentar sanar todas as dúvidas que encontrei na pergunta sobre SQL, inclusive.

Vamos falar sobre SQL primeiro...
O que você quer o próprio banco de dados já faz. Para isso, basta marcar o campo da Key como Auto Increment (Identity). Feito isso, você não precisa inserir o código no INSERT, que o banco faz tudo automático para você.
Um exemplo seria:
CREATE TABLE Produtos
(
 Id int IDENTITY(1,1),
 Nome varchar (100)
);

INSERT INTO Produtos VALUES ('Produto1')
INSERT INTO Produtos VALUES ('Produto2')

Feito isso, o banco irá salvar os dados como:
Id  | Nome
----------------
1   | Produto1
2   | Produto2

Caso queira saber qual será o próximo código, você pode utilizar o código abaix:
SELECT isnull(IDENT_CURRENT('Produtos') + IDENT_INCR('Produtos'),1)

Esse código irá buscar o último id IDENT_CURRENT() e somar com o valor incremental, com o IDENT_INCR().
Em seu exemplo você está aumentando mais 1, mas se fosse 2, 3, etc... O IDENT_INCR() obtém esse valor da Key automaticamente.
Solução do problema...
Como já apontado nas demais respostas, basta alterar o ExecuteNonQuery() pelo ExecuteScalar() que resolverá o seu problema.
Caso queira entender um pouco mais a diferença entre os métodos, este link explica um pouco sobre eles.

A: O método que você está utilizando para executar o SQL (ExecuteNonQuery()) é um método utilizado para inserts e updates e o retorno dele é a quantidade de linhas afetadas conforme descrito na documentação.
Utilize o método ExecuteScalar(), que o mesmo irá retornar o que você deseja.
Deverá ficar desta forma:
txt_prod_cod.Text = Convert.ToString(sqlCom.ExecuteScalar());

Documentação do ExecuteScalar().
Isto pode resolver o seu problema, mais conforme sugerido pelo Maniero essa não é uma boa prática, e provavelmente você deve estar repetindo muito código em sua aplicação, seria bom assim que possível reavaliar a forma de trabalho e verificar melhorias.


text:
Q: Serve ASP.NET Webforms content on Ubuntu 16.04 from 2 different root directories using one XSP4 child process? We  would like to serve ASP.NET Webforms content on Ubuntu 16.04 from 2 different root directories using  one XSP4 child process.
In /etc/mono-server4, I created debian.webapp specifying root directory /var/www/firstaspnet and seconddebian.webapp specifying root directory /var/www/secondaspnet. I thought that would be sufficient . Yet I get this runtime exception:
 System.Web.HttpException
    The resource cannot be found.

    Description: HTTP 404.The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

    Details: Requested URL: /hello.aspx
    Exception stack trace:
      at System.Web.Compilation.BuildManager.AssertVirtualPathExists (System.Web.VirtualPath virtualPath) <0x40e88650 + 0x00197> in <filename unknown>:0
      at System.Web.Compilation.BuildManager.Build (System.Web.VirtualPath vp) <0x40e883f0 + 0x00033> in <filename unknown>:0
      at System.Web.Compilation.BuildManager.GetCompiledType (System.Web.VirtualPath virtualPath) <0x40e880a0 + 0x00093> in <filename unknown>:0
      at System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath (System.Web.VirtualPath virtualPath, System.Type requiredBaseType) <0x40e87f50 + 0x00033> in <filename unknown>:0
      at System.Web.UI.PageParser.GetCompiledPageInstance (System.String virtualPath, System.String inputFile, System.Web.HttpContext context) <0x40e87bb0 + 0x000bb> in <filename unknown>:0
      at System.Web.UI.PageHandlerFactory.GetHandler (System.Web.HttpContext context, System.String requestType, System.String url, System.String path) <0x40e87b70 + 0x00027> in <filename unknown>:0
      at System.Web.HttpApplication.GetHandler (System.Web.HttpContext context, System.String url, Boolean ignoreContextHandler) <0x40e7ccb0 + 0x002de> in <filename unknown>:0
      at System.Web.HttpApplication.GetHandler (System.Web.HttpContext context, System.String url) <0x40e7cc80 + 0x0001b> in <filename unknown>:0
      at System.Web.HttpApplication+<Pipeline>c__Iterator1.MoveNext () <0x40e65a50 + 0x02aab> in <filename unknown>:0

I am running only one instance of mod-mono-server4.exe spawned by my systemd apache2.service during system reboot as shown below by ps -ef:
  148:www-data  1090     1  0 16:42 ?        00:00:00 /usr/bin/mono /usr/lib/mono/4.5/mod-mono-server4.exe --filename /tmp/.mod_mono_server4 --nonstop --appconfigdir /etc/mono-server4

Could someone venture a hypothesis about what I am missing or did wrong?
Any help is greatly appreciated.


text:
Q: Can´t type open brace or backslash in cygwin I have been using Cygwin without trouble on a separate computer, and I do not recall having any trouble typing certain symbols. I just starting using Cygwin on a computer with a Spanish keyboard, and noticed that when I type "{" or "\" nothing happens.
Is there some issue with Cygwin so that it would not recognize characters from a European keyboard? For reference, the version number is "2.7.0(0.306/5/3)."


text:
Q: CallBack Functions in React Native Swift I'm trying to create a native swift module with a function I can call in my javascript code. Currently I have my module.swift file, my module.m file, and the bridging header.
Here's MyModule.swift:
import Foundation

@objc(MyModule)
class MyModule: NSObject {

  @objc func callbackMethod(callback: RCTResponseSenderBlock) -> Void {
     let resultsDict = [
     "success" : true
     ];

    callback([NSNull() ,resultsDict])
  }

}

Here's MyModule.m:
import Foundation

@objc(AskPermissions)
class AskPermissions: NSObject {

  @objc func callbackMethod(callback: RCTResponseSenderBlock) -> Void {
    let resultsDict = [
     "success" : true
   ];
   print("GLARGH!")
  callback([NSNull() ,resultsDict])
  }

}

Here's the bridging header:
#import React/RCTBridgeModule.h

#import React/RCTEventEmitter.h

Finally, here's my call in javascript:
const { MyModule } = require('NativeModules');
MyModule.callbackMethod((err,r) => console.log(r));

The problem is that whenever I run the project, it causes an error:
Exception 'callbackMethod:(RCTResponseSenderBlock)callback is not a recognized Objective-c
 method.'

However, I can't find anything wrong with the documentation. Could someone please provide some help?

A: Try to add underscore:
callbackMethod(_ callback: RCTResponseSenderBlock)


text:
Q: AS3 keeping score I'm making a game where my character passes an object and when doing so the score counts up by one. The object is part of an array, and when I pass the first object the score counts up continuously. Here is what I have so far:
if (beardman.x >= tubes[i].x)
{
 score++;
}

How would I re-write it so that the score just counts up by one?

A: What you could do is have a similar array and remove from that list like so:
//assume you have a copy of the tubes array called activeTubes.
if (beardman.x >= activeTubes[i].x)
{
    score++;
    activeTubes.splice( i, 1 );
}

Edit: I wanted to add that splice is known to be a fairly expensive operation as it shifts how the indices are stored in memory. That being said, if you are searching through a fairly large list a optimization to make would look like this:
//assume you have a copy of the tubes array called activeTubes.
if (activeTubes[i] && beardman.x >= activeTubes[i].x)
{
    score++;
    activeTubes[i] = null;
}

Or even from a for loop perspective:
var i:int;
for ( ; i < activeTubes.length; i++ ) {
    //check if the index is null, if so continue.
    if ( !activeTubes[i] ) { continue; }

    if (beardman.x >= activeTubes[i].x)
    {
        score++;
        activeTubes[i] = null;
    }
}


text:
Q: Segmentation Fault from Split String Function I am required to write a function that splits a string into individual words.
My first parameter is a string.  We assume that the words in the string are separated by single spaces, with no spaces before the first word or after the second word. Punctuation like spaces for example is part of a word. My second parameter is an address of an integer in which the function gives it the value of the number of words in the string. The return value is a pointer that points of an array of strings containing the individual words in the sentence. I need to allocate it memory from the heap and have one word in each index of the array. The strings are copies of the original words, not pointers. Here is my code :
char** splitString(char theString[], int *arraySize) {
  *arraySize = countSpaces(theString) + 1; //Points to the number of words in the string.
  char** pointerToArrayOfStrings = malloc(*arraySize * sizeof(char *)); //Allocated memory for '*arraySize' character pointers
  int characters = 0;
  for (int i = 0; i < *arraySize; i++) {
    while (theString[characters] != ' ' || theString[characters] != '\0') {
      characters++;
    }
    characters++;
    pointerToArrayOfStrings[i] = (char *)malloc(characters);
    pointerToArrayOfStrings[i][characters] = '\0';
  }
  for (int word = 0; word < *arraySize; word++) {
    int ch = 0;
    while (ch < strlen(pointerToArrayOfStrings[word])) {
      pointerToArrayOfStrings[word][ch] = theString[ch];
    }
    ch+=2;
  }
  return pointerToArrayOfStrings;
}

This is immediately giving me segmentation faults. I am very new to pointers, so my method is to first allocate the array with the amount of memory for "numberOfWords" character pointers. Then I allocated each character pointer with the size of the corresponding word. After, I filled the slots with the characters from the original string. I don't know what I'm missing.

A: The comments have already addressed your questions about seg-faults etc. But since you did not say it was required how you split the string, I wanted to suggest looking at another approach.
Consider these steps:
1) Walk through string counting occurrences of white space (words) and track longest word found.
2) Knowing count, and longest word, you have what you need to allocate memory.  Do it.
3) In a for loop, use strtok() with the delimiters of: , \n, \t etc. to tokenize the string.
4)  Using strcpy() (also in the loop) to transfer each token into the string array.
5) Return array. Use array.  Free all allocated memory.
Example code to do these steps:
char** splitString(const char theString[], int *arraySize);
char ** create_str_array(int strings, int longest) ;

int main(void)
{
    int size;
    char ** string = splitString("here is a string", &size);

    return 0;
}

char** splitString(const char theString[], int *arraySize)
{
    *arraySize = strlen(theString) + 1; //Points to the number of words in the string.
    char *tok;
    char *dup = strdup(theString);//create copy of const char argument

    char** pointerToArrayOfStrings = NULL;
    int characters = 0;
    int len = 0, lenKeep = 0, wordCount = 0, i;

    /// get count of words and longsest string
    for(i=0;i<*arraySize;i++)
    {
      if((!isspace(theString[i]) && (theString[i])))
      {
          len++;
          if(lenKeep < len)
          {
              lenKeep = len;
          }
      }
      else
      {
        wordCount++;
        len = 0;
      }
    }

    /// create memory. (array of strings to hold sub-strings)
    pointerToArrayOfStrings = create_str_array(wordCount, lenKeep);
    if(pointerToArrayOfStrings)// only if memory creation successful, continue
    {
        /// parse original string into sub-strings
        i = 0;
        tok = strtok(dup, " \n\t");
        if(tok)
        {
            strcpy(pointerToArrayOfStrings[i], tok);
            tok = strtok(NULL, " \n\t");
            while(tok)
            {
                i++;
                strcpy(pointerToArrayOfStrings[i], tok);
                tok = strtok(NULL, " \n\t");
            }
        }
    }

    /// return array of strings
    return pointerToArrayOfStrings;
}

char ** create_str_array(int strings, int longest)
{
    int i;
    char ** a = calloc(strings, sizeof(char *));
    for(i=0;i<strings;i++)
    {
        a[i] = calloc(longest+1, 1);
    }
    return a;
}


text:
Q: Entity Framework is throwing "System.Data.Entity.Core.OptimisticConcurrencyException" for some users I am trying to delete user tables and user config table,it is working fine most of the time,but for some users, it is throwing an OptimisticConcurrencyException with this message:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.

This is my code:
var context = UnitOfWork._context;

var userToRemove = context.Users.Where(<some_condition>).ToList();

var userConfigurationsToRemove = (some_condition_with_users_join_on_userConfig).ToList();

if (userToRemove != null && userToRemove.Any())
{
    context.Users.RemoveRange(userToRemove );

    if (userConfigurationsToRemove != null && userConfigurationsToRemove.Any())
    {
        context.userConfigurations.RemoveRange(userConfigurationsToRemove );
    }

    context.SaveChanges();
}

My question is: users table is a child table and userConfigurations is parent table, can I do save changes twice; one after context.Users.RemoveRange(userToRemove ); and other after context.userConfigurations.RemoveRange(userConfigurationsToRemove), or is there anything else that can be done?
This issue is coming once in a day for some anonymous users.


text:
Q: How to exclude weeks based on Year and Week columns? I have a [Year/Week] column, based on which I want to have a window of 12 weeks inclusive of current week. For example: If current week is Week 5, I want to show my window from Week 5 to Week 16, regardless if the current day is Monday or Friday.
I have tried setting some numbers to adjust this window in the code below, but I believe there must be a better way.
CREATE TABLE #DATES ([Year/Week] VARCHAR(MAX))

INSERT INTO #DATES ([Year/Week]) VALUES
('2019/W01'),('2019/W02'),('2019/W03'),('2019/W04'),('2019/W05')
,('2019/W06'),('2019/W07'),('2019/W08'),('2019/W09'),('2019/W10')
,('2019/W11'),('2019/W12'),('2019/W13'),('2019/W14'),('2019/W15')
,('2019/W16'),('2019/W17'),('2019/W18'),('2019/W19'),('2019/W20')
,('2019/W21'),('2019/W22'),('2019/W23'),('2019/W24'),('2019/W25')
,('2019/W26'),('2019/W27'),('2019/W28'),('2019/W29'),('2019/W30')
,('2019/W31'),('2019/W32'),('2019/W33'),('2019/W34'),('2019/W35')

SELECT DISTINCT
CONVERT(INT, LEFT([Year/Week], 4)) AS [Year]
,CONVERT(INT, RIGHT([Year/Week], 2)) AS [Week]
,dateadd (week, CONVERT(INT, RIGHT([Year/Week], 2)), dateadd (year,
CONVERT(INT, LEFT([Year/Week], 4))-1900, 0)) - 4 -
       datepart(dw, dateadd (week, CONVERT(INT, RIGHT([Year/Week], 2)),
dateadd (year, CONVERT(INT, LEFT([Year/Week], 4))-1900, 0)) - 4) + 1  AS
[Week Date]

FROM #DATES
WHERE dateadd (week, CONVERT(INT, RIGHT([Year/Week], 2)), dateadd (year,
CONVERT(INT, LEFT([Year/Week], 4))-1900, 0)) - 4 -
       datepart(dw, dateadd (week, CONVERT(INT, RIGHT([Year/Week], 2)),
dateadd (year, CONVERT(INT, LEFT([Year/Week], 4))-1900, 0)) - 4) + 1
BETWEEN GETDATE() - 3 AND GETDATE() + 81

ORDER BY [Year], [Week]

A: I suggest you to have Calendar table for reporting purposes.
After that you can easily get same result with small query
select Year, Week
from Auxiliary.Calendar
where Date between GetDate() and DATEADD(MONTH, 4, GetDate())

Here is DBFiddle

A: It looks like you're using ISO weeks. You should be able to perform the comparison "alphabetically" with something like this:
select [Year/Week] from #DATES
where [Year/Week] between
    format(getdate() -  3, 'yyyy/\W') + format(datepart(iso_week, getdate() -  3), '0#') and
    format(getdate() + 81, 'yyyy/\W') + format(datepart(iso_week, getdate() + 81), '0#')
order by [Year/Week];

Make sure the week numbers match with yours.
Unfortunately I didn't think of a way to avoid repeating the date expression. Perhaps there's even something a bit more compact. An expression like this will probably be better at using an index on your Year/Week column.


text:
Q: Call a function inside firebase ListenerForSingleValueEvent I am using firebase ListenerForSingleValueEvent and trying to get a list of Address class and put them into an arraylist but this thing is not working.. i tried to call a function or something but it didnt work
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            for (DataSnapshot postSnapshot: dataSnapshot.child("addresses").getChildren()) {

               Adress adress = new Adress(postSnapshot.getValue(Adress.class));
                adresses.add(adress);

            }

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

I have no idea how to solve it and i didnt find anyone has the same problem as me
Please help,Thanks
edit1:
the problem is i cant add the address class to the arraylist using anything
it's just like i cant do it inside the listener, i checked that everything is ok .. also when i check the adresses arraylist size inside the lister it increases then out of the listener it returns to 0.. like the adresses.add function worked only at the listener itself or something like that