text:
Q: ¿Cómo obtener la correlación entre las variables de objeto de un marco de datos? Tengo un marco de datos con 49 columnas. La mayoría de ellas son de objeto tipo d. Intenté trazar el mapa de calor de la correlación de Pearson y ver la correlación de las variables independientes, pero parece que sólo se tienen en cuenta las variables numéricas.
En efecto, cuando intento
#Using Pearson Correlation
cor = df1.corr()

mask = np.zeros_like(cor, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
plt.figure(figsize=(12,10))
sns.heatmap(cor,
            vmin=-1,
            cmap='coolwarm',
            annot=False,
            mask = mask);

obtengo:

Esto es un extracto de mi base de datos:
>>> df1.head(3)
    Sexe    date_naissance  Groupe_dage     ville   Statut_marital  Niveau_de_scolarite     Situation_professionnelle   Autre_situation_professionnelle     Revenu_mensuel  Si_connexion_internet   Canal_acces_info    Autre_canal_acces_info  Si_situtation_ville_degradee    Si_intention_emigration     Besoin_Sante    Besoin_Education    Besoin_Conditions_de_vie    Besoin_Lutte_contre_criminalite     Besoin_Emploi   Besoin_Lutte_contre_corruption  Besoin_Eau_potable  Besoin_Infrastructures  Besoin_Culture_art  Besoin_Amelioration_services_publics    Besoin_Acces_logement   Besoin_Autres_besoins   Non_declaration_besoins     Autres_besoins  Si_connait_president_commune    Si_connait_parlementaires   Si_inscrit_LE   Si_vote_2016    Intention_vote_2021     Consentement    Langue_du_questionnaire     region  id_reg  status  nbr_app     adherent
0   Une femme   1964-04-15  Entre 45 et 54 ans  Al Hoceima  Marié et je n'ai pas encore d'enfants à charge    1er cycle universitaire / Licence   Je suis independent     NaN     5,000-7,499 DHS     Oui     Internet    NaN     Je suis d'accord    Je ne suis pas d'accord     True    False   True    False   True    False   False   False   False   False   False   False   False   NaN     Oui     Oui     Oui     Oui     Je sais déjà pour qui je vais voter en 2021   J'accepter d'être recontacté  Arabe   Tanger-Tetouan-Al Hoceima   1.0     Qualifié   3.0     True
1   Une femme   NaN     Entre 18 et 24 ans  Tétouan    Célibataire    1er cycle universitaire / Licence   Je suis journalier, je travaille de temps à a...   NaN     1-2,499 DHS     Non     Internet    NaN     Je suis d'accord    Je suis d'accord    True    True    False   False   True    False   False   False   False   False   False   False   False   NaN     Oui     Non     Non     NaN     Je ne voterai pas en 2021   Non     Arabe   Tanger-Tetouan-Al Hoceima   1.0     NaN     NaN     NaN
2   Un homme    NaN     Entre 25 et 34 ans  Khenifra    Marié et j'ai des enfants à charge    Niveau lycée   Je suis journalier, je travaille de temps à a...   NaN     Je préfére ne pas répondre   Non     Télévision    NaN     Je suis d'accord    Je suis d'accord    True    False   True    False   True    False   False   False   False   False   False   False   False   NaN     Oui     Non     Non     NaN     Je vais voter en 2021 mais je ne sais toujours...   J'accepter d'être recontacté  Arabe   Beni Mellal-Khenifra    5.0     Na veut pas répondre   2.0     NaN

El mio intento
Siguiendo esta guía sobre la codificación categórica intenté lo siguiente:
# for each column where dtype is object
for column in df1.columns:
    if df1[column].dtypes == np.object:
        df1[column] = df1[column].cat.codes

Sin embargo, obtuve la siguiente salida:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-187-5f3d03cb1581> in <module>
      2 for column in df1.columns:
      3     if df1[column].dtypes == np.object:
----> 4         df1[column] = df1[column].cat.codes

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
   5268             or name in self._accessors
   5269         ):
-> 5270             return object.__getattribute__(self, name)
   5271         else:
   5272             if self._info_axis._can_hold_identifiers_and_holds_name(name):

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\accessor.py in __get__(self, obj, cls)
    185             # we're accessing the attribute of the class, i.e., Dataset.geo
    186             return self._accessor
--> 187         accessor_obj = self._accessor(obj)
    188         # Replace the property with the accessor object. Inspired by:
    189         # http://www.pydanny.com/cached-property.html

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\arrays\categorical.py in __init__(self, data)
   2510
   2511     def __init__(self, data):
-> 2512         self._validate(data)
   2513         self._parent = data.values
   2514         self._index = data.index

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\arrays\categorical.py in _validate(data)
   2519     def _validate(data):
   2520         if not is_categorical_dtype(data.dtype):
-> 2521             raise AttributeError("Can only use .cat accessor with a 'category' dtype")
   2522
   2523     def _delegate_property_get(self, name):

AttributeError: Can only use .cat accessor with a 'category' dtype


text:
Q: Adding the figures to a `draft` pdf Suppose you have a draft pdf, and the only difference with a desired final version of it is the lack of figures. And suppose too you have the original figures, but not the source code of the document.
What would be your best trick to achieve the document with its figures on place?

A: Example with two images tiger.pdf and flowers.eps from TDS:doc/generic/pstricks/images/:
\documentclass[a5paper]{article}
\usepackage[hmargin=10mm,vmargin={10mm,20mm}]{geometry}
\usepackage[draft]{graphicx}
\usepackage{lipsum}
\begin{document}
\lipsum[11]
\begin{center}
  \includegraphics[width=.5\linewidth]{tiger}%
\end{center}
\lipsum[2]
\begin{center}
  \includegraphics[width=.5\linewidth]{flowers}%
\end{center}
\end{document}

Then I have measured the positions of the image boxes (using gv, ...):
\newcommand*{\imglist}{%
  \img{1}{118bp}{306bp}{301bp}{498bp}{tiger}%
  \img{1}{118bp}{65bp}{301bp}{204bp}{flowers}%
}

The first argument of \img is the page number, then the coordinates of the lower left corner and of the upper right corner follows. The following example will use the coordinate system of PDF (gv) with horizontal values from the left and vertical values from the bottom.
The last argument contains the image file name.
Then first a white box is put in the image area to clear the frame and image file name of option draft. Then the image is placed. It is assumed that the image is not distorted.
Package atbegshi is used to put the images on the foreground of the output pages. Package picture extends the picture environment. Also lengths values can be used instead of factors for \unitlength. Package pdfpages includes the original PDF file without images. And package color is needed for the white box.
Example file:
\documentclass{article}
\usepackage{pdfpages}
\usepackage{atbegshi}
\usepackage{picture}
\usepackage{color}

\newcommand*{\imglist}{%
  \img{1}{118bp}{306bp}{301bp}{498bp}{tiger}%
  \img{1}{118bp}{65bp}{301bp}{204bp}{flowers}%
}

\newcommand*{\img}[6]{%
  \ifnum#1=\value{page}%
    \AtBeginShipoutUpperLeftForeground{%
      \put({\dimexpr(#2)\relax},{-\dimexpr\paperheight-(#3)\relax}){%
        \rlap{%
          \textcolor{white}{%
            \rule{\dimexpr(#4)-(#2)\relax}{\dimexpr(#5)-(#3)\relax}%
          }%
        }%
        \includegraphics[%
          width=\dimexpr(#4)-(#2)\relax,
          height=\dimexpr(#5)-(#3)\relax,
        ]{#6}%
      }%
    }%
  \fi
  \ignorespaces
}
\AtBeginShipout{%
  \imglist
}

\begin{document}
  \includepdf[pages=-,fitpaper]{t.pdf}% PDF file without images
\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: ModRewrite statement redirect to user profile I need to write simple Apache mod_rewrite statement, which redirect user urls to a script:
**http://mydomain.com/username -> http://mydomain.com/user.py?uname=username**
mydomain.com/username -> http://mydomain.com/user.py?uname
mydomain.com/username -> http://mydomain.com/user.py?uname

The following lines don't work:
RewriteEngine on
RewriteRule ^[a-z]{5,}$  /user.py?username=$1 [L]

Looking forward for your help

A: Try:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ /user.py?uname=$1 [L]

This makes it so when someone requests http://mydomain.com/username, they will get served the content at http://mydomain.com/user.py?uname=username.


text:
Q: JSTL iterate list I have this class:
public class Orders{

    private Integer id;
    private String name;

    //getters/setters

}

In controller I pass a List<Orders> to jsp:
@RequestMapping(value = "/orders")
public ModelAndView orders(){

    List<Orders> orders = ...//get list from db

    //print list in console
    orders.forEach(e -> System.out.println(e.getId() + " - " + e.getName()));
    //print -> 1 - name1 ; 2 - name2

    return new ModelAndView("orders", "orders", orders);

}

In jsp use it like this:
${orders.size()}
<c:forEach items="${orders}" var="order">
    <c:out value="${order.getId()}"></c:out>
</c:forEach>

In browser at inspect(html code) looks like this:
"2"
<c:foreach items="[com.web.entity.Orders@21e16dd6,
                   com.web.entity.Orders@52a33913]" var="order">
    <c:out value=""></c:out>
</c:foreach>

I tested in controller by printing list in console and everything is right.
Why in jsp is not printed?

A: Could you please provide more details (controller code, html page tags ...).
Still I've some point to share with you :

*

*Use always a toString method in your Entity/POJO.

*Use order.id instead of order.getId()

*Make sure you have JSTL core tag in the top of your HTML page :

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

*

*Try to have a simple c:out tag:

<c:out value="${order.id}"/>


text:
Q: Read AppSettings from MEF plugin I would like to access the values in the ConfigurationManager.AppSettings object from a MEF plugin which has its own app.config file.
However, the keys from the app.config file are not present in AppSettings after the plugin is loaded.
The keys from the application loading the plugin are still present.
I noticed that using a Settings.settings file allows this behaviour, via the app.config file, so the file must be being loaded somehow.
My plugin looks like:
[Export(IPlugin)]
public class Plugin
{
    public Plugin()
    {
        // reads successfully from app.config via Settings object
        var value1 = Settings.Default["Key1"];

        // returns null from app.config via ConfigurationManager
        var value1 = ConfigurationManager.AppSettings["Key2"]
    }
}

The app.config looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="applicationSettings" type="..." >
      <section name="Plugin.Settings" type="..." />
    </sectionGroup>
  </configSections>

  <appSettings>
    <add key="Key2" value="Fails" />
  </appSettings>

  <applicationSettings>
    <Plugin.Settings>
      <setting name="Key1" serializeAs="String">
        <value>Works</value>
      </setting>
    </Plugin.Settings>
  </applicationSettings>
</configuration>

I can manually load the app.config file with:
var config = ConfigurationManager.OpenExeConfiguration("Plugin.dll");
var value = AppSettings.Settings["Key2"].Value

but this seems more like a workaround than a solution.
Is there a way to access a MEF plugin's <appSettings> directly, from inside the plugin?
If not, what is recommended?

A: By default the ConfigurationManager loads the .config for the entry assembly, i.e. the assembly that started the currently executing process.
The correct way to do this would be something like this:
[Export(IPlugin)]
public class Plugin
{
    public Plugin()
    {
        var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
        var value = config.AppSettings.Settings["Key2"].Value;
    }
}

This would make the plugin automatically open the .config for the DLL it was compiled in, and fetch values from there.

A: I'd recommend you to use a dependency injection tool like Unity, in order to provide to your plug-ins the configuration they required. By proceeding in this way, your plug-ins will no longer need to reference System.Configuration.dll.


text:
Q: android.app.ServiceConnectionLeaked: Activity ...MainActivity has leaked ServiceConnection ...MainActivity$1@e794142 that was originally bound here its failing @ below line -
bindService(intent, m_serviceConnection, Context.BIND_AUTO_CREATE);

Below is the trace....
Activity com.example.alwaysrunningprocesswithcallanswertap.MainActivity has leaked ServiceConnection com.example.alwaysrunningprocesswithcallanswertap.MainActivity$1@e794142 that was originally bound here
android.app.ServiceConnectionLeaked: Activity com.example.alwaysrunningprocesswithcallanswertap.MainActivity has leaked ServiceConnection com.example.alwaysrunningprocesswithcallanswertap.MainActivity$1@e794142 that was originally bound here
    at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1077)
    at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:971)
    at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1774)
    at android.app.ContextImpl.bindService(ContextImpl.java:1757)
    at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
    at com.example.alwaysrunningprocesswithcallanswertap.MainActivity.onCreate(MainActivity.java:48)
    at android.app.Activity.performCreate(Activity.java:5990)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
    at android.app.ActivityThread.access$800(ActivityThread.java:151)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

MainActivity.class
public class MainActivity extends Activity
{
    CallNotifierService m_service;
    boolean isBound = false;

    private ServiceConnection m_serviceConnection = new ServiceConnection()
    {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service)
        {
            m_service = ((CallNotifierService.MyBinder)service).getService();
            Toast.makeText(MainActivity.this, "Service Connected", Toast.LENGTH_LONG).show();
            isBound = true;
            Intent intent = new Intent(MainActivity.this, CallNotifierService.class);
            startService(intent);
        }

        @Override
        public void onServiceDisconnected(ComponentName className)
        {
            Toast.makeText(MainActivity.this, "Service Dis-connected", Toast.LENGTH_LONG).show();
            m_service = null;
            isBound = false;
        }
    };

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

        Intent intent = new Intent(this, CallNotifierService.class);
        bindService(intent, m_serviceConnection, Context.BIND_AUTO_CREATE);
    }

    .
    .
    .

}

A: You need to add this in your code.
@Override
protected void onDestroy() {
    super.onDestroy();
    unbindService(m_serviceConnection);
    Toast.makeText(MainActivity.this, "Service Un-Binded", Toast.LENGTH_LONG).show();
};

A: Another good practice to do this could be adding a flag to know when the service was added.
private boolean m_serviceBound = false;
private ServiceConnection m_serviceConnection = new ServiceConnection()
{
    ...
};

@Override
protected void onCreate(Bundle savedInstanceState)
{
    ...
    Intent intent = new Intent(this, CallNotifierService.class);
    bindService(intent, m_serviceConnection, Context.BIND_AUTO_CREATE);
    m_serviceBound = true;
    ...
}

@Override
protected void onDestroy() {
    ...
    if (m_serviceBound) {
        unbindService(m_serviceConnection);
        m_serviceBound = false;
    }
    ...
};

This is useful if you bind and unbind the service in different segments of the app's life cycle.

A: onStop()
is another place where you can unbind a service in your activity.

This approach is quite preferable when you want to interact with a
service only when your Activity is in the foreground. See official Android Developer guide suggestion

Override
protected void onStop() {
   super.onStop();
   unbindService(m_serviceConnection);
};

In this case, prefered way to bind service is in the onStart() method of the Activity.


text:
Q: Prevent laravel mix from converting "const" and "let" to "var" I am using LaravelMix to compile my project.
And I want to prevent LaravelMix from converting const and let to var
I tried to update babel to latest version and tried alot of solutions on stackoverflow with no success.
This is my webpack.mix.js
const mix = require("laravel-mix");

mix.webpackConfig({
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: [
              [
                "@babel/preset-env",
                { targets: "defaults, not ie 11, not ie_mob 11" },
              ],
            ],
            plugins: ["@babel/plugin-proposal-class-properties"],
          },
        },
      },
    ],
  },
});

mix
  .js("./app.js", "./assets/js")
  .postCss("./app.css", "./assets/css", [
    require("tailwindcss"),
    require("autoprefixer"),
  ]);

And this is my package.json
{
...

"dependencies": {
    "laravel-mix": "^6.0.34",
    "quicklink": "^2.2.0"
  },
  "devDependencies": {
    "@babel/core": "^7.16.0",
    "@babel/plugin-proposal-class-properties": "^7.16.0",
    "@babel/preset-env": "^7.16.0",
    "autoprefixer": "^10.4.0",
    "babel-loader": "^8.2.3",
    "browser-sync": "^2.27.5",
    "browser-sync-webpack-plugin": "^2.3.0",
    "postcss": "^8.3.11",
    "tailwindcss": "^2.2.19",
    "webpack": "^5.62.1"
  },
  "browserslist": [
    "defaults, not ie 11, not ie_mob 11"
  ]

...
}

Any help?


text:
Q: Linux distros for EC2 advice? I'm using Centos right now as it seemed like the most popular choice, but even the most recent 5.5 has a lot of truly ancient software like Ruby 1.8.5 (that's 2006!).
Ubuntu doesn't suffer from this, but it's concept of user accounts (no root at all), seem to be quite incompatible with EC2's (root for everything), and I'm wondering if it will cause any problems.
Any advice?

A: Ubuntu is a pretty good choice for Amazon EC2 usage. It is quite up to date and stable. They do even have their very own AMI release cycle http://uec-images.ubuntu.com/lucid/current/
Ubuntu's concept of user account (no root at all) is IVMHO the way to go.
Amazon EC2 does not force you to use root for anything indeed. They do only force you to log into the box using the ssh keypair they provide during the first login into and instance booted from an AMI that you did not create.
Once you have created your own AMI, you can include your own ssh public keys or LDAP service or whatever you prefer using configuration management tools (chef, puppet, etc).
Just my 2 cents.


text:
Q: How to name worker? I tired to use a GenServer as a worker:
defmodule CSVServer do
    use GenServer

    def start_link(_opts \\ []) do
        GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
    end

    def process!(csvs_params), do: GenServer.call(__MODULE__, %{csvs_params: csvs_params})

    def handle_call(%{csvs_params: csvs_params}, _from, state) do

    ...

    end

And at my app:
def start(_type, _args) do
    import Supervisor.Spec, warn: false

    children = [
      # Start the endpoint when the application starts
      supervisor(MyApp.Endpoint, []),

      # Start the Ecto repository
      supervisor(MyApp.Repo, []),

      worker(CSVServer, [], name: "CSVServer"),
    ]

The question is, do I have to explicitly name the worker? at:
worker(CSVServer, [], name: "CSVServer"),

isn't it already named at the GenServer as:
GenServer.start_link(__MODULE__, %{}, name: __MODULE__)

?
EDIT
In the generated myapp.ex I can see this:
# Here you could define other workers and supervisors as children
# worker(MyApp.SomeWorker, [], name: SomeWorker),


text:
Q: How can I create array database row then find if value exist in array? I am trying to search for a given value in a array from a DB row -
$path = '1.jpg';

$result = mysqli_query("SELECT * FROM table WHERE myname='$myuser'");
$mypath = array();
while($row = mysqli_fetch_assoc($result)){
    $mypath[]= $row['path'];
}

if(array_search($path, $mypath)) {
    echo 'image exist';
}else{
    echo 'image not found in array';
}

But this wont work, what am I doing wrong?
Thanks!

A: Why do you build up an array and use array search when a better SQL statement could probably do the job faster?
If you change the query to this, it will only select the rows where name and path match:
$path = '1.jpg';

$result = mysqli_query("SELECT * FROM table WHERE myname='$myuser' AND path='$path'");
if(mysqli_fetch_assoc($result)){
    echo 'image exist';
}else{
    echo 'image not found';
}

This should do the same job without the array overhead.
However, note that the code is prone to SQL injections as it is now, if the path or the name are user-provided and go into the query unchecked. Therefore you should escape these values with mysqli_real_escape_string() before using them in the query.


text:
Q: marklogic client api conbine with other module We are using XQuery for MarkLogic query before. And we want to replace with Java as it more widely used.
Everything is fine before I meet with the module query.
import module namespace ent = "http://xxx.xx/model/entitlements" at "/Entitlements/entitlements.xqy";
And in the Xquery, we are using below.
let $final-query := ent:query($query, $cvUserId)
let $docs := cts:search(/, $final-query)
return $docs

ent:query(xx,xx) is in our Linux server which we can't get the source code.
As the name side, this query will do entitlement check when execute the search.
I have write below Java code to get the result.
QueryManager queryManager = markLogicClient.newQueryManager();
StringQueryDefinition queryDef = queryManager.newStringDefinition("OPTIONS");
queryDef.setCriteria("Title:test");
XMLDocumentManager dManager = markLogicClient.newXMLDocumentManager();
DocumentPage docs = dManager.search(queryDef, 1, new DOMHandle());
dManager.search(queryDef, 1);

It works well for my test, but without the entitlement check.
Is there any to apply my own query ent:query(xx,xx) with Java ?
Marklogic-8 & marklogic-client-api-4.0.4

A: Java and XQuery API's in MarkLogic are not comparable, they fill different use cases, and in fact the Java API ends up calling XQuery.
XQuery (and JavaScript) runs within the server,  Java API runs outside the server and calls the REST API which then invokes XQuery in the server.  If you have perfectly good XQuery it makes little sense to rewrite that with Java -- at best, performance will suffer. Instead, you can invoke your XQuery from Java API either as an 'ad hoc' expression or as a stored module.  This allows you to expose a Java API for the parts of your app that benefit from a java API but keep the existing code.  For new code, where it makes sense to do so, the Java API is quite good, but for the cases where you find it does not fill you needs you can apply the same technique as above and still provide the the same integration to your app.
You can see some examples of various ways to invoke ML using the Java API as well as performance bench marks here:  https://github.com/DALDEI/mlperf

A: Keep your existing XQuery code and create beautiful RESTful Web Services using simple XQRS functions to hook it all up.


text:
Q: Running a meteor app on Nodejitsu Deployed a meteor app to a Nodejitsu trial environment but failed to get it to run. Upon executing jitsu deploy from my meteor app directory I get the following error: ReferenceError: Meteor is not defined.
If you have gotten a meteor app up and running on Nodejitsu, please highlight the steps you took and dependencies I might be missing. I will use your suggestions and try to get my app to run. Thanks.
// package.json contents
{
  "name": "test123-meteor",
  "subdomain": "user123.test123-meteor",

/*
* Really not sure about this line here...
*/
  "scripts": {
    "start": "node client/controllers/GeneralController.js"
  },
  "version": "0.0.1-2",
  "engines": {
    "node": "0.8.x"
  }
}

A: I tried this today and didn't have a problem when using demeteorizer.  I wrote the following small article about it on Meteorpedia which includes my custom build script which greatly simplifies deployment.
http://www.meteorpedia.com/read/Nodejitsu

A: Meteor won't run on nodejitsu until this bug is fixed: node-fibers won't build on SmartOS. If you want it, you should star the bug or even look into fixing it. (Naively, it looks like the kind of thing that needs more persistence than brilliance; a build issue on just that one OS for a package which builds unmodified on over 5 other OSs.)


text:
Q: I need get specific columns I have a model but i need get specific columns so i wrote native query
public interface HndAllOrgWipProdViewRepository  extends JpaRepository<HndAllOrgWipProdViewModel, Long> {
    @Query( value = "SELECT Transaction_Date, Class_Code, Start_Quantity, Transaction_Quantity,Fm_Department_Code from HND_ALL_ORG_WIP_PROD_VIEW where TRANSACTION_DATE  BETWEEN '01-Aug-2019' and '30-Aug-2019' AND CLASS_CODE = 'WORK WEAR'" , nativeQuery = true )
    List<HndAllOrgWipProdViewModel> fetchProcessPerformance();
}

Above query return array of arrays
[

 [
    "2019-07-31T19:00:00.000+0000",
    "WORK WEAR",
    500,
    83,
    "T5"
  ] ,
 [
    "2019-07-31T19:00:00.000+0000",
    "WORK WEAR",
    500,
    83,
    "T5"
  ]
]

but i need array of objects eg:
[

{
  Transaction_Date: "2019-07-31T19:00:00.000+0000" ,
  Class_Code : "WORK WEAR" ,
  Start_Quantity : "500" ,
  Transaction_Quantity : "83",
  Fm_Department_Code : "T5"

},
{
  Transaction_Date: "2019-07-31T19:00:00.000+0000" ,
  Class_Code : "WORK WEAR" ,
  Start_Quantity : "500" ,
  Transaction_Quantity : "83",
  Fm_Department_Code : "T5"

}
]

Please also suggest is this a right approach or it there any other standardized method to do this.

A: In HndAllOrgWipProdViewModel model there is Array object, Just make it simple Object. problem will be solved.


text:
Q: Array returns first element blank in my Rails(3.2.11) multi-select When I selected multiple values from select list then array returns the first value empty.
= f.select :assignedto, options_from_collection_for_select(User.all, 'name', 'name',f.object.assignedto),{}, { :multiple => true}

I tried with {:include_blank => false} and {:include_hidden => false} but this is not working for rails 3.2.11. I have many solutions to handle this empty value in the controller but I want to stop adding empty value in the array.

A: Properly because the second arg is 'name' instead of 'id'.
Try
options_from_collection_for_select(User.all, 'id', 'name', f.object.assignedto)


text:
Q: Userscript to Click a "Refresh" button every minute except when there is input? I'm trying to create a Tampermonkey script that would click the page's "Refresh" button every so often, preferably every minute.
It would be even better if it could pause while you are performing other actions on the site like typing but that's more optional.
Reason for this is that we are using a website at work that needs us to keep track of incoming customer requests in a timely manner but the site only has an integrated refresh button that needs to be clicked manually and doesn't refresh automatically.
There are browser plugins which kinda do what I need but they refresh the whole webpage which causes it to loose important information or settings that have been done before. (this does not happen with the refresh button on the site).
So what i have found was the setInterval and the .click function.
What i setup was the following which sometimes worked and sometimes didn't.
But every time it did work it wouldn't stop even when disabling Tampermonkey.
// ==UserScript==
// @name         Ticket System - Auto Refresh
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://my*******.***.****mand.com/*
// @grant        none
// ==/UserScript==

setInterval(function () {document.getElementById("buttonOcLMZKwM8KoKda967hf2B0_11").click();}, 10000);

//end

I probably have some significant flaws in what i did above but as i said i have no experience with javascript. Also the time used was to test in order to quickly see if it works or not.
As you probably can see i already got stuck at the refresh part, so the stopping part when typing isn't even remotely done.
I also used
document.getElementById("buttonOcLMZKwM8KoKda967hf2B0_11")

and it is very likely target to fail as the website tends to change this ID when you login again. So i tried to do it by using instead:
document.querySelector('[title="Refresh"]');

but that didn't seem to work at all even though the title of the button is Refresh.
This is the full button HTML on the site:
<button type="button" id="buttonOcLMZKwM8KoKda967hf2B0_11" data-sap-ui="buttonOcLMZKwM8KoKda967hf2B0_11"
data-sap-automation-id="OcLMZKwM8KoKda967hf2B0" title="Refresh" role="button"
aria-disabled="false" tabindex="0" class="sapUiBtn sapUiBtnIconOnly sapUiBtnLite sapUiBtnS width-button-form sapUiBtnStd">
</button>

I would really appreciate any help i can get.

A: To start and stop polling, or interval clicking, etc.; merely:

*

*Store the value of the setInterval() call.
EG: var myTimer = setInterval (someFunction, 1000);

*Pass that value to clearInterval() to stop the loop.
EG: clearInterval (myTimer);
Of course, the user interface is the hardest part.  I like to:

*

*Put a status and control button in the upper-right of the screen.

*Bind a keyboard shortcut to be able to toggle the loop without needing the mouse.

The following userscript does all of the above, plus:

*

*Clicks the "Refresh" button on every iteration of the loop.

*Stops/Restarts the loop when the control button is clicked.

*Stops/Restarts when F9 is pressed (depending on where the focus is).

*Stops the loop when one of the form controls is selected or typed into.

*Restarts the loop when the "Refresh" button is clicked.

Here is a complete working userscript (It's just the part above the ****** block.).
To see it in action, Run the code snippet.

// ==UserScript==
// @name     _Click button regularly, with start/stop controls
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==

//--- Initialize the refresh button loop and controls.
var rfrshBtnSel = 'button[title="Refresh"]';  //  jQuery selector for the refresh
var rfrshTmr    = LoopManager (clickRefreshButton, 1000);  //  1000 ms == 1 second.
var loopStBtn   = LoopButtonManager (rfrshTmr.toggle);

rfrshTmr.setCallbacks (loopStBtn.start, loopStBtn.stop, loopStBtn.error);
rfrshTmr.start ();  //  Start looping the refresh btn click.

$(window).keydown (keyboardShortcutHandler);

//--- On use of certain form controls, stop the refresh timer:
$("body").on (
    "click keydown focus paste scroll", "input, textarea, select", rfrshTmr.stop
);
//--- On click of the refresh button, (re)start the refresh timer:
$("body").on ("click", rfrshBtnSel, rfrshTmr.start);

function clickRefreshButton () {
    var refreshBtn = $(rfrshBtnSel);
    if (refreshBtn.length === 1)  clickNode (refreshBtn);
    else loopStBtn.error ("Refresh button not found!");
}
function keyboardShortcutHandler (zEvent) {
    if (zEvent.which == 120) {  //  On F9, Toggle the Loop state.
        rfrshTmr.toggle ();
        return false;
    }
    return true;
}
function clickNode (jNode) {
    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    jNode[0].dispatchEvent (clickEvent);
}

function LoopManager (callbackFnc, intrvlMillisec, bAutoStart, ...optParams) {
    var _thisInterval = null;
    var _startCB = null, _stopCB = null, _errorCB = null;
    if (bAutoStart)  _start ();

    function _start () {
        if ( ! _thisInterval) {
            _thisInterval = setInterval (callbackFnc, intrvlMillisec, ...optParams);
        }
        if (_startCB)  _startCB ();
    }
    function _stop () {
        clearInterval (_thisInterval);
        _thisInterval = null;
        if (_stopCB)  _stopCB ();
    }
    function _toggle () {
        if (_thisInterval)  _stop ();
        else                _start ();
    }
    function _setCallbacks (startCB, stopCB, errorCB) {
        _startCB = startCB; _stopCB = stopCB; _errorCB = errorCB;
    }
    return {
        start: _start,  stop: _stop,  setCallbacks: _setCallbacks,  toggle: _toggle
    };
}
function LoopButtonManager (clickCB) {
    var _btnNode = $('#tmStartStopBtn');
    if (_btnNode.length === 0) {
        _btnNode = $( `
            <button id="tmStartStopBtn" type="button" class="tmRefreshRunning">
                TBD (F9)
            </button>
        ` ).appendTo ("body");
    }
    var _spanNode = _btnNode.find ("span");

    _btnNode.click (clickCB);

    function _start () {
        setButtonDisplay ("Running", "tmRefreshRunning");
    }
    function _stop () {
        setButtonDisplay ("Stopped", "tmRefreshStopped");
    }
    function _error (errMess) {
        console.error ("TM: " + errMess);
        setButtonDisplay ("See console!", "tmError");
    }
    function setButtonDisplay (btnText, btnClass) {
        _spanNode.text (btnText);
        _btnNode.removeClass ();
        if (btnClass)  _btnNode.addClass (btnClass);
    }
    return { start: _start,  stop: _stop,  error: _error };
}
GM_addStyle ( `
    #tmStartStopBtn {
        position:           absolute;
        top:                0;
        right:              0;
        font-size:          18px;
        margin:             5px;
        opacity:            0.9;
        z-index:            1100;
        padding:            5px 20px;
        color:              black;
        cursor:             pointer;
    }
    .tmRefreshRunning { background: orange; }
    .tmRefreshStopped { background: lime; }
    .tmError { background: red; }
` );

/********************************************************************
******* Everything below this block is simulated target page. *******
******* It's NOT part of the userscript.                      *******
********************************************************************/
$('button[title="Refresh"]').click ( function () {
    $(this).attr ("id", 'spelunk' + Math.random () );
    $("#StatusNd").text ("Refreshed: " + (new Date() + '').replace (/\s*\(.+\)/, "") );
} );
div {
    margin: 0 0 1ex 1em;
    width: 20em;
    padding: 0.5ex 1em 0 1em;
    border: 1px solid darkgreen;
    border-radius: 1ex;
}
label { margin: 0 0 0 2em; }
label[for="Bar"] { display: inline-block;  vertical-align: top; }
button, #StatusNd { margin: 0 0 1ex 2em; }

This userscript will click the "Refresh" button every second,
 unless typing in an input.

Some inputs:

    Foo: <input type="text" id="Foo">

<button type="button" id="some_random_ID" title="Refresh">Refresh</button>


text:
Q: UIPickerView didSelectRow issue iPhone I have three labels, which I want to fill with selected row from pickerview. Like if 1st label is already filled then the second should be filled with the selected row value and if 1st and second both are already filled then the third should be filled.
I am trying this code but it is assigning value only to the first label.
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
      inComponent:(NSInteger)component
{

    NSString *selectedReward = [self.rewards objectAtIndex:row];

    if ([reward1.text isEqualToString:selectedReward]) {

        if ([reward2.text isEqualToString:selectedReward]) {

            reward3.text = selectedReward;
        }

        reward2.text = selectedReward;
    }
    else  {

        reward1.text = selectedReward;
    }

}

A: I think it's because you always select the different row, and the row text is different. Then the selected value is always different with the first lable's text, so the function will set the label1's text.
I think you should test the text length.
if ([reward1.text length] == 0) {reward1.text = selectedReward;} // and so on

A: In your code you are checking label's text with selectedReward.
So, if you select each time different picker component then it will just updated the first label(will enter in else part of your code), but if you select same picker component(as you selected for first label) then it will enter in if part.
You can proceed with what @loser1089906 suggested.

A: try check UILabel by comparing its length.
if ([label1.text length]==0){
   //set label 1
}
else if ([label2.text length]==0){
   //set label 2
}
else{
   //set label 3.
}


text:
Q: Forbidden You don't have permission to access / on this xampp server while hosting laravel app in heroku I try to deploy my laravel app to heroku but while running heroku after completing all steps it show the following error

My ht access file is
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

A: Creating a Procfile
By default, Heroku will launch an Apache web server together with PHP to serve applications from the root directory of the project.
However, your application's document root is the public/ subdirectory, so you need to create a Procfile that configures the correct document root:
On terminal of project directory, perform following (for Windows)
  echo web: vendor/bin/heroku-php-apache2 public/ > Procfile

then do Git add, Commit, Push
 -Source Heroku Documentation

A: I think the problem is here:
access here, or in any related virtual host.
<Directory />
    Options FollowSymLinks
    AllowOverride All
    Require all denied
 </Directory>

 <Directory /usr/share>
    AllowOverride None
    Require all granted
 </Directory>

 <Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride all
    Require all granted
 </Directory>

The key point is
Require all denied

You should change the denied to granted

A: Did you deploy the app on Heroku correctly? Can you check whether you did the following things?

*

*Create Heroku App

*Create Procfile On Root Directory Of Project

*Modify composer.json

*Get Your Project Files Up-to-date

*Add Your Project Files To Heroku

*Setup Database Connections *

If you have missed any step, do it and try again. The complete guidance to Deploy, Build, Run, and Operate Laravel Applications On Heroku Cloud Application Platform is included in the following blog article with all the steps and information you need.
Read: Laravel: Deploy Laravel Projects On Heroku
https://www.ashenlive.com/blog/laravel-deploy-laravel-projects-on-heroku

A: I got the same issue and found a solution. It is about Heroku can't find an index file (index.php,index.html) in the directory.
For example, if you can't reach files under the root directory, you should add an index file there. In my case, I had a root directory and had an index.php file so I could reach the files in it. But also there was another folder under the root directory which I couldn't enter. So I created an empty index.html file there too.
Then the issue was solved.

A: in Procfile you have edit it and replace the code to
web: heroku-php-apache2 public/

now update your Procfile by this commend in cmd

*

*git status

*git add -A

*git commit -m "Add Procfile and make use of Apache2"

*git push heroku master

I hope it will be fixed


text:
Q: how to put quote inside a quote javascript I have a problem when I try to render out a table cell after a successful ajax call.
How can I put an id in function deleteServiceIdFromInput()?
I tried:
deleteServiceIdFromInput('"+ id +"');

I also tried adding \" \", but it still didn't work.
Any suggestion would be great, thanks.
$.ajax({
          type: "POST",
          url: "./OTTProductMapServIDAjaxSubmit.do",
          dataType: 'json',
          cache: false,
          data: {"productID":productID,"serviceID":serviceID, "method":"searchSerivceById"},
          success: function(data){

            document.getElementById("listOfServiceID").value;
            if (data != null){
            var table = document.getElementById("serviceMappingTable");
            var row = table.insertRow(1);
            row.align="center";
            row.onmouseover = function(){this.bgColor = '#C0C0C0';};
            row.onmouseout = function(){this.bgColor = '#FFFFFF';};

            var cell1 = row.insertCell(0);

            cell1.innerHTML= 'Delete';
            insertServiceIdToInput(data.serv_id);

        }

the end result I am looking for as it will rendered in HTML as (below) :
href="javascript:deleteServiceIdFromInput(' id ')"

and for solution i have tried, redered in HTML as :
href="javascript:deleteServiceIdFromInput( id )"  <-- quote is missing

A: You can use
cell1.innerHTML= 'Delete'

A: Since you are using jQuery, why not use the .html() function?
I tested with this following code and it works:
HTML:

JavaScript:
var id = '123';
var htmlContent = "Delete";

$('#cell1').html(htmlContent);

Here's a jsfiddle: http://jsfiddle.net/nkwn390u/

A: This works, Thank you all for helping !
cell1.innerHTML= 'Delete'


text:
Q: understanding CPU step by step journey of learning process hello
I want to learn how cpu works from scale of bit level to assembly level
could somebody tell me ?
which one would be better?
top-down learning or bottom-up learning?
and what am I suppose to do first?
assembly language? or computer architecture?
what sort of book, site, method would be good?
I am interested in computer science/Artificial Intelligence but I have no compass to know how to get there efficiently
your reply would be very thankful and helpful
welcome your experienced story
thanks

A: You probably do well reading something like this in combination with the Intel/AMD Instruction manuals, of course this is biased to x86, but other vendors/architectures should have similar publications.
This does go very in-depth, but that can only serve to help in my opinion.
Also, if your interests are AI and CS, this could be considered a waste of time, as it'll add to neither (remember CS is not about programming, its about the art of programming and programatic problem solving).


text:
Q: How can I control the column order using 'annotate', 'values' and 'union' in Django? I have 2 models:
class Hero(models.Model):
    name = models.CharField(max_length=50)
    age = models.PositiveSmallIntegerField()
    identity = models.TextField(max_length=50)

class Villain(models.Model):
    villain_name = models.CharField(max_length=50)
    age = models.PositiveSmallIntegerField()
    identity = models.TextField(max_length=50)

and I create some test instances:
Hero(name="Superman", age=30, identity="Clark Kent").save()
Hero(name="Iron Man", age=35, identity="Tony Stark").save()
Hero(name="Spider-Man", age=18, identity="Peter Parker").save()

Villain(villain_name="Green Goblin", age=45, identity="Norman Osborn").save()
Villain(villain_name="Red Skull", age=38, identity="Johann Schmidt").save()
Villain(villain_name="Vulture", age=47, identity="Adrian Toomes").save()

Since the Villain model doesn't have a name field, we use annotation before doing a union.
Then, using them in a union produces results where the columns aren't all where they should be:
>>> from django.db.models import F
>>> characters = Hero.objects.all().values('name', 'age', 'identity').union(Villain.objects.all().annotate(name=F("villain_name")).values('name', 'age', 'identity'))
>>> for character in characters:
...     print(character)
{'name': 38, 'age': 'Johann Schmidt', 'identity': 'Red Skull'}
{'name': 45, 'age': 'Norman Osborn', 'identity': 'Green Goblin'}
{'name': 47, 'age': 'Adrian Toomes', 'identity': 'Vulture'}
{'name': 'Iron Man', 'age': 35, 'identity': 'Tony Stark'}
{'name': 'Spider-Man', 'age': 18, 'identity': 'Peter Parker'}
{'name': 'Superman', 'age': 30, 'identity': 'Clark Kent'}

Looking at the raw sql queries, we see this:
>>> str(Hero.objects.all().values('name', 'age', 'identity').query)
'SELECT "myapp_hero"."name", "myapp_hero"."age", "myapp_hero"."identity" FROM "myapp_hero"'

>>> str(Villain.objects.all().annotate(name=F("villain_name")).values('name', 'age', 'identity').query)
'SELECT "myapp_villain"."age", "myapp_villain"."identity", "myapp_villain"."villain_name" AS "name" FROM "myapp_villain"'

The auto-generated sql contains columns that aren't in the same order for the two queries.
How can I make these in the same order, so that the resulting queryset of my union isn't messed up?
PS. Yes, this is very similar to the question asked here, but after a long explanation of why it happens, the end result of the answer to that question was:

please make sure that the ordering of fields in generated SQL is always correct

which helps, but doesn't answer the question of how to fix it.

A: From the docs on union

Passing different models works as long as the SELECT list is the same in all QuerySets (at least the types, the names don't matter as long as the types are in the same order)

When you add the annotation to values() it always comes after the non-annotated columns, however since the names don't matter and you only need the columns to be in the same order you can discard this annotation
Hero.objects.values(
    'name', 'age', 'identity'
).union(Villain.objects.values(
    'villain_name', 'age', 'identity'
))


text:
Q: How to parse json using Retrofit I am fairly new to android and using retrofit and realm. I am having a hard time getting this json string from the url to parse properly.
Here is what i have done so far.
My Interface:
package com.example.stephen.traveland.Rest;
import android.database.Observable;
import com.example.stephen.traveland.Models.Country;
import java.util.List;
import retrofit.http.GET;

public interface TravelAnDInterface {
    @GET("/index-updated.json/")
    Observable<List<Country>> getAllCountries();
}

This java class is where i am using the interface to pull the string from the url.
package com.example.stephen.traveland.Rest;
import android.content.Context;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.okhttp.OkHttpClient;

import io.realm.RealmObject;
import retrofit.RestAdapter;
import retrofit.android.AndroidLog;
import retrofit.client.OkClient;
import retrofit.converter.GsonConverter;

public class TravelAnD {
    private static final String URL = "http://data.international.gc.ca/travel-voyage/";
    private final static Gson gson = new GsonBuilder()
        .setExclusionStrategies(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes f) {
                return f.getDeclaringClass().equals(RealmObject.class);
            }

            @Override
            public boolean shouldSkipClass(Class<?> clazz) {
                return false;
            }
        })
        .create();

    private static TravelAnDInterface sTravelAnDSvc;

    public static TravelAnDInterface getCountries() {

        if (sTravelAnDSvc == null) {
            RestAdapter restAdapter = new RestAdapter.Builder()
                    .setEndpoint(URL)
                    .setClient(new OkClient(new OkHttpClient()))
                    .setConverter(new GsonConverter(gson))
                    .setLogLevel(RestAdapter.LogLevel.FULL)
                    .setLog(new AndroidLog("RETROFIT"))
                    .build();

            sTravelAnDSvc = restAdapter.create(TravelAnDInterface.class);
        }

        return sTravelAnDSvc;
    }
}

This is one of my object classes so you can see how i am trying to accomplish.
package com.example.stephen.traveland.Models;

import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;

public class Country extends RealmObject {

    @PrimaryKey
    private int country_id;
    private String country_iso;
    private String country_in_english;
    private String country_in_french;
    private int advisory_state;
    private RealmList<DatePublished> datePublished;
    private int advisory_warning;
    private int regional_advisory;
    private int content;
    private String recent_update_type;
    private RealmList<English> english;
    private RealmList<French> french;

    public Country() { super(); }

    public Country(int country_id, String country_iso, String     country_in_english, String country_in_french,
               int advisory_state, int advisory_warning, int regional_advisory, int content) {
        this.country_id = country_id;
        this.country_iso = country_iso;
        this.country_in_english = country_in_english;
        this.country_in_french = country_in_french;
        this.advisory_state = advisory_state;
        this.advisory_warning = advisory_warning;
        this.regional_advisory = regional_advisory;
        this.content = content;

    }

    public int getAdvisory_state() { return advisory_state; }

    public void setAdvisory_state(int advisory_state) { this.advisory_state = advisory_state; }

    public int getAdvisory_warning() { return advisory_warning; }

    public void setAdvisory_warning(int advisory_warning) { this.advisory_warning = advisory_warning; }

    public int getContent() { return content; }

    public void setContent(int content) { this.content = content; }

    public int getCountry_id() { return country_id; }

    public void setCountry_id(int country_id) { this.country_id = country_id; }

    public String getCountry_in_english() { return country_in_english; }

    public void setCountry_in_english(String country_in_english) { this.country_in_english = country_in_english; }

    public String getCountry_in_french() { return country_in_french; }

    public void setCountry_in_french(String country_in_french) { this.country_in_french = country_in_french; }

    public String getCountry_iso() { return country_iso; }

    public void setCountry_iso(String country_iso) {this.country_iso = country_iso; }

    public RealmList<DatePublished> getDatePublished() { return datePublished; }

    public void setDatePublished(RealmList<DatePublished> datePublished) { this.datePublished = datePublished; }

    public RealmList<English> getEnglish() { return english; }

    public void setEnglish(RealmList<English> english) {this.english = english;}

    public RealmList<French> getFrench() { return french; }

    public void setFrench(RealmList<French> french) { this.french = french; }

    public String getRecent_update_type() { return recent_update_type; }

    public void setRecent_update_type(String recent_update_type) { this.recent_update_type = recent_update_type; }

    public int getRegional_advisory() { return regional_advisory; }

    public void setRegional_advisory(int regional_advisory) { this.regional_advisory = regional_advisory; }

}
I have created the Classes to store the data, but having a problem because the string itself is weird and challenging to work with. I was hoping to get some guidance to what I am doing wrong. Any help would be greatly appreciated.
@EDIT
No longer using Realm for any of my objects and the previous code has been altered quite a bit, because the data is too large to be storing on the phone. It would be too much information for one device.
But, a new problem or same problem just in a different situation. My retofit call is grabbing the data fine, just when i place them into the object, the object is null when i want to pull data from it. Here is some small snippets of of my code.
public void gatherData() {

    final ProgressDialog progress = new ProgressDialog(this);
    progress.setTitle("Please wait...");
    progress.setMessage("Loading data...");
    progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    progress.setIndeterminate(false);
    progress.show();

    bossModel1 = new BossModel();

    Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES)
            .create();

    RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint("http://data.international.gc.ca/travel-voyage")
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .build();

    Api service = restAdapter.create(Api.class);

    service.listRepos(new Callback<BossModel>() {
        @Override
        public void success(BossModel bossModel, Response response) {
            bossModel1 = bossModel;

            Log.i("SUCCESS", "" + bossModel1.getData());

            for (Field field : bossModel1.getData().getClass().getDeclaredFields()) {
                if (!Modifier.isStatic(field.getModifiers())) {
                    Log.i("ahlsdkjha: ", field.getName());
                    countryISO.add(field.getName());
                }
            }

            progress.dismiss();
        }

        @Override
        public void failure(RetrofitError error) {

        }
    });
}

public void gatherVPData(final String countryIso) {
    vpModel1 = new VPModel();

    Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES)
            .create();

    RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint("http://data.international.gc.ca/travel-voyage")
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .build();

    Api service = restAdapter.create(Api.class);

    service.getCountry(countryIso, new Callback<VPModel>() {

        @Override
        public void success(VPModel vpModel, Response response) {
            vpModel1 = vpModel;
            Log.d("SUCCESS2: ", "" + vpModel1.getData());
        }

        @Override
        public void failure(RetrofitError error) {

        }
    });
}

API
public interface Api {
    @GET("/index-updated.json")
    void listRepos(Callback<BossModel> callback);

    @GET("/countries/cta-cap-{country}.json")
    void getCountry(@Path("country") String countryIso, Callback<VPModel> callback);
}

Here is where i am trying to fill a list of new objects with the data pulled by gatherVPData. This doesn't fill because the data is null for some reason.
public void populateCountryList(int id) {

    for (int i = 0; i < countryISO.size() - 1; i++) {
        gatherVPData(countryISO.get(i));
        if (vpModel1.getData().getAdvisoryState() == id) {
            countries.add(new Country(
                    vpModel1.getData().getCountryIso(),
                    vpModel1.getData().getAdvisoryState(),
                    vpModel1.getData().getHasAdvisoryWarning(),
                    vpModel1.getData().getHasRegionalAdvisory(),
                    vpModel1.getData().getHasContent(),
                    vpModel1.getData().getUpdateMetadata(),
                    vpModel1.getData().getEng(),
                    vpModel1.getData().getFra()
            ));
        }
    }
}

A: I would go like this:
a/ Declare the result of getAllCountries to be a JsonObject:
JsonObject getAllCountries();

b/ When you call the method, tranform it to get the content:
JsonObject json = <your adapter here>.getAllCountries();
Map<String, Country> countries = gson.fromJson(jsonResponse.getAsJsonObject("data"),
                    new TypeToken<Map<String, Country>>() {
                    }.getType());

Basically you get the object in "data", which is a JsonObject, and parse it as a Map of String>Country.


text:
Q: How to use the multiroot to compute the MLEs? I want to write an R-code to compute the MLEs of (µ; σ2; λ) with the Newton-Raphson algorithm and try initial values λ = 0.5、.... I'm trying to run the following code in R, but I'm getting an error I'm not sure what part of the formula is incorrect. Any help would be greatly appreciated.
library(rootSolve)
head(y)
[1] 0.15 0.09 0.18 0.10 0.05 0.12
obs.loglik2 = function(y,theta)
{
  mu=theta[1]
  sig2=theta[2]
  lambda = theta[3]
  n = length(y)
  loglik = -0.5*n*log(2*pi)-0.5*n*log(sig2)-
    sum(((y^lambda-1)/lambda-mu)^2)/(2*sig2)+(lambda-1)*sum(log(y))
  return(loglik)
}
multiroot(obs.loglik2,c(1,1,0.5))

Error:
#Error in f(x, ...) : argument "theta" is missing, with no default


text:
Q: Mongo Aggregation With Projection Given the following document
{
 "Id": "MyNormalObjectId",
 "CompanyId" : 1234,
 "User" :
    {
         "UserId":4567,
         "FirstName":"Tester",
         "Lastname":"McCtesterson"
    }
}

How do I write my aggregate query to return a list of all unique users in a given company (including first and last name)?
FilterDefinitionBuilder<MyDoc> builder = Builders<MyDoc>.Filter;
var filter = builder .Eq(t => t.CompanyId, companyId);

var aggregate = _col.Aggregate();

aggregate.Match(filter).GroupBy(t=>t.User.UserId, ?????? )

Desired result would be a HashSet of UserMetadata. I've seen a lot of people go straight to BSon for what they need and I can if I HAVE to. Strongly typed is always better.

A: You can make use of the $addToSet operator inside the $group pipeline stage
to get the desired output.
db.collection.aggregate([
  {
    "$match": {
      "CompanyId": 1234  // Find Conditions go here
    }
  },
  {
    "$group": {
      "_id": "$CompanyId",
      "Users": {
        "$addToSet": "$User",
      },
    },
  },
])


text:
Q: Why can I not recieve serial data using Rust? I've been trying to read serial data from a Feather M0, but for some reason I can't read the data into a buffer. This device is for sure outputting serial data, and both PlatformIO and the Arduino IDE show serial data in their respective serial monitors. However, it will timeout when I'm reading it in Rust, every single time, no matter what timeout value I have it set to. Here is my code:
// First, find the serial port
let port_info = find_receiver();

// If we didn't find a port, then we can't continue
if port_info.is_none() {
    panic!("Could not find a serial port");
}

let mut port = serialport::new(port_info.unwrap().port_name, 9600)
    .timeout(Duration::from_millis(1000))
    .open()
    .expect("Could not open serial port");

let mut serial_buf: Vec<u8> = vec![0; 8];
loop {
    let n = port.read_exact(serial_buf.as_mut_slice()).unwrap();

    println!("Buffer is {:?}", serial_buf);
}

The find_reciever() function simply scans the open ports and returns the one that I want to connect to. I'm on Windows, so in this case it's usually COM9 or COM12. I would like this to be a cross-platform application, so I'm not using the open_native() function that serialport provides.
I've tried varrying the size of the buffer from 1 byte to 1000, I've trying different versions of read into the port, I've tried skipping over timeout errors, and I've tried directly outputting the read bytes to io::Stdout. Any ideas on what to do?

A: Apparently, the serialport crate that I was using requires you to set the command
port.write_data_terminal_ready(true);

in order for it to start reading data. On Linux this works perfectly fine without it. Rip 4 hours trying to change what IO reader I was using.


text:
Q: Vanishing product of polynomials over finite fields $(x_1-x_2-x_3+x_4)(x_2-x_4-x_3+x_1)(x_3-x_1)(x_4-x_2)\equiv 0$ over $\mathbb F_3$.
Take polynomials $p_1,\dots,p_n$ over variables $x_1,\dots,x_n$ such that $p_i$ does not depend on $x_i$ and $\Pi_{i=1}^n (x_i+p_i) \equiv 0$ over $\mathbb F_q$.
It is easy to see that one can take $n=q$ and $p_i=i+\sum_{j\ne i} x_j$ to satisfy this equation.
If each $p_i$ can depend on only a bounded number of variables, then it follows from the Local Lemma that this is not possible.
It is not that hard to show that for $n=2^{q-1}$ there are polynomials such that each $p_i$ depends on only one $x_j$ with $j<i$; see the example in the first line for $q=3$.
In general, have such polynomials been studied in number theory?
My motivation comes from that this is an equivalent reformulation of the Hat Guessing Number of graphs.
To decide whether such polynimials exists such that their dependency graph is degenerate, would solve an interesting open problem. This graph is defined on $n$ vertices such that $ij\in E$ if $p_i$ depends on $x_j$ or $p_j$ depends on $x_i$. A graph is $d$-degenerate if its vertices can be ordered such that from each vertex $v_i$ there are at most $d$ edges to vertices coming after $v_i$ in this ordering. In our problem $d$ can be any constant, compared to which $q$ and $n$ can be arbitrary.


text:
Q: How do you update a w2ui grid summary cell? I have a grid where I need to show the sum of all the numbers in one column.  The numbers are editable in the grid, and the sum needs to be updated as the numbers change (before a Save).  I am having multiple issues. The relevant code is shown below and here is a jsfiddle if you'd like to poke around with a functioning program.
$(function() {
    $('#grid').w2grid({
        name: 'grid',
        columns: [{
            field: 'recid', caption: 'ID', size: '50px', sortable: true, attr: 'align=center'}, {
            field: 'lname', caption: 'Last Name', size: '150px', sortable: true },
            {field: 'amount', caption: 'Amount', size: '100px', render: 'money', editable: { type: 'money' }},
        ],
        records: [{
            recid: 1, fname: 'Jane',  amount: 1000.00}, {
            recid: 2, fname: 'Stuart', amount: 1000.00}, {
            recid: 3, fname: 'Jin', amount: 1000.00}, {
            recid: 's-1', fname: '', amount: 0, w2ui: {summary: true}}
        ]
    });
    w2ui.grid.on('change', function(event) {
        event.done(function () {updateTotal(); });
    });
    w2ui.grid.on('refresh', function(event) { updateTotal(); });
    w2ui.grid.on('render', function(event) {updateTotal(); });
});

function updateTotal() {
    var total = 0.0;
    for (var i = 0; i < w2ui.grid.records.length; i++) {
        if (typeof w2ui.grid.records[i].amount == "number") {
            total += w2ui.grid.records[i].amount;
        }
    }
    w2ui.grid.get('s-1').amount = total;
    w2ui.grid.refreshCell('s-1','amount');
    document.getElementById("gridtotal").innerHTML = '' + w2ui.grid.summary[0].amount  + '<br>w2ui.grid.records[0].amount = ' + w2ui.grid.records[0].amount;
}

First issue -- updates to the summary row are not being displayed. I have onChange, onRefresh, and onRender handlers. They wrap a call to updateTotal(), which adds the 'amount' in every record and stores the result in the summary record's amount field. I call refreshCell after the amount has been changed. But none of the handlers are called when the initial display of the grid happens - so the summary record shows 0. What call should be made to update the summary amount when the grid is initially displayed?
Second issue -- updateTotal() displays results in the wrong cell. Click the button to execute updateTotal(). The sum of 3000 is correct for the table in its initial state. You can see from the line that updates the innerHTML that the summary record ('s-1') gets updated with the correct value in its 'amount' field, and that we call refreshCell('s-1','amount'). But on the grid, the 'amount' cell for recid 1 gets updated to show 3000 (and note that it gets rendered left-justified rather than right-justified).   Why did this happen? What call should I make to update the 'amount' cell in the summary row?
Third  issue -- as a user makes changes to the 'amount' cells (double-click to change the amount), the onChange event occurs which causes a new total to get calculated. But the changes made by the user are not available in the grid records. The changes are saved in a different location. So the newly calculated total does not correspond to the numbers the user sees on the grid. The new values are not available in the records (records[i].amount) until after updates are saved. But I need to access the amounts displayed in the grid before the changes are saved.  How do I  access the changed values?

A: To modify an existing record, you need to use the set method - with get you do not get a reference, but a copy!
 w2ui.grid.set('s-1', {amount: total});

About your first issue: You are assigning a render callback after the grid is already rendered. You will need to assign the callback in the constructor:
  $('#grid').w2grid({
      onRender: ....
  });

Your second issue should no longer be an issue when you use set instead of get.
About your third issue: until you save the changes, the changes are stored in record.w2ui.changes - so either call grid.save() or get the amount from the changes, not from the original record.
Updated fiddle:
http://jsfiddle.net/pfq20gnu/14/


text:
Q: Server is open SyntaxError: Unexpected token = in /home/michael/DemoApp/views/posts.ejs while compiling ejs Server is open

SyntaxError: Unexpected token = in /home/michael/DemoApp/views/posts.ejs while compiling ejs

const express = require("express");
const app = express();
const port = process.env.PORT || 4000

app.set('views', './views');
app.set('view engine', 'ejs');

app.get("/posts", function(req, res){
var posts = [
{title: "Once upon a time", author: "Richard"},
{title: "The Way", author: "Ikoro"},
{title: "I Love Critics", author: "Emmanuel"},
{title: "Adorable Bunny", author: "Christian"}
]
res.render("posts.ejs", {posts: posts});
});

app.listen(port, function(){
console.log("Server is open");
});

// The Codes for posts.ejs

<% for(var = i; i < posts.length; i++){ %>

    <%= posts[i].title %> - <%= posts[i].author
    %>

<% } %>

Server is open

SyntaxError: Unexpected token = in /home/michael/DemoApp/views/posts.ejs while compiling ejs

A: Please I have seen the error the fault is from me

A: In your code you have var = i - this is the error. It should be:
<% for(var i = 0; i < posts.length; i++){ %>

    <%= posts[i].title %> - <%= posts[i].author
    %>

<% } %>


text:
Q: Time-series analysis, resetting time to 0 I am currently working on a time-based dataset. I have cleaned the dataset by removing zeros at the beginning and end of my dataset. Now instead of starting from 0, the time for my dataset starts at 7000s - 400000s. I would like to make the starting time (7000s) to 0 and from then increases.
Any thoughts?


text:
Q: How to get React to resolve index.ts as root of folder? Just started a new React project and I'm wondering how I can get my project to resolve the index.js file as the folder being imported in another component.
Expected:
No error
// src/pages/router.tsx
import HomePage from './home-page`

export const Router: FC = () => {
  return (
    <Routes>
      <Route path="/">
        <HomePage />
      </Route>
    </Routes>
  )
}

// src/pages/home-page/home-page.tsx/index.ts
export { HomePage as default } from './home-page'

Actual:
Cannot find module './home-page' or its corresponding type declarations.ts(2307)
The index.ts doesn't show up as a possible import either.

A: Your screenshot is cutoff, but that's not where the file is:

That image shows your index.ts is actually in home-page/home-pa... (which is truncated in your screenshot.
You either need to move the .ts files to the correct directory, or change you import to:
import HomePage from './home-page/home-page-or-whereever-this-is'


text:
Q: having issue with updating label asynchronously I am trying a simple ajax form where it will update a label on button click.
I get the below error:

Microsoft JScript runtime error:
  Sys.WebForms.PageRequestManagerParserErrorException: The message
  received from the server could not be parsed.

at below function on line : "throw error;"
function Sys$WebForms$PageRequestManager$_endPostBack(error, executor, data) {
    if (this._request === executor.get_webRequest()) {
        this._processingRequest = false;
        this._additionalInput = null;
        this._request = null;
    }
    var handler = this._get_eventHandlerList().getHandler("endRequest");
    var errorHandled = false;
    if (handler) {
        var eventArgs = new Sys.WebForms.EndRequestEventArgs(error, data ? data.dataItems : {}, executor);
        handler(this, eventArgs);
        errorHandled = eventArgs.get_errorHandled();
    }
    if (error && !errorHandled) {
        ***throw error;***
    }
}

Here is my form code:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Test Form
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<form id="form1" runat="server">

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
               <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

               <asp:Button ID="Button1" runat="server" onclick="Button1_Click" style="margin-left: 66px" Text="Button" Width="176px" />

            </ContentTemplate>
        </asp:UpdatePanel>

</form>

</asp:Content>

Am I missing something?

A: I inserted the code above into empty aspx page, removed reference to masterpage and asp:Content and it worked for me. The label changed its text.
If it still doesn't work for you you may use Firefox+Firebug to see the actual server response after clicking on a button. It may contain detailed exception that will give you a hint.


text:
Q: Recreate this chart in python - what type of chart is it? I'm trying to recreate the chart from this post on Reddit. How would I recreate a chart like this in python? What would you even call this type of chart?
The chart looks like this:

I tried this similar approach, but a bubble chart isn't quite what I'm looking for. Here's a simplified version of my data:
Date,Asleep,Awake
3/31,12:00 AM,5:00 AM
3/31,6:00 AM,8:30 AM
3/31,12:00 PM,2:45 PM
3/31,5:30 PM,8:30 PM
3/31,11:00 PM,11:59 PM
4/1,12:00 AM,4:30 AM
4/1,6:00 AM,9:00 AM
4/1,11:30 AM,2:00 PM
4/1,5:00 PM,9:00 PM
4/1,10:45 PM,11:59 PM
4/2,12:00 AM,2:30 AM
4/2,3:00 AM,8:00 AM
4/2,10:30 AM,2:00 PM
4/2,5:00 PM,10:00 PM
4/3,12:00 AM,8:30 AM
4/3,11:00 AM,3:00 PM
4/3,6:00 PM,9:00 PM
4/3,10:30 PM,11:59 PM
4/4,12:00 AM,9:00 AM
4/4,10:30 AM,12:00 PM
4/4,3:30 PM,5:00 PM
4/4,8:00 PM,10:30 PM
4/4,11:00 PM,11:59 PM

A: This gets you part of the way...
Convert to proper types
df['Date'] = pd.to_datetime(df.Date.radd('2020/'), format='%Y/%m/%d')
df['Asleep'] = pd.to_datetime(df.Asleep) - pd.Timestamp('now').normalize()
df['Awake'] = pd.to_datetime(df.Awake) - pd.Timestamp('now').normalize()

vlines
import matplotlib.pyplot as plt

plt.vlines(df.Date, df.Asleep, df.Awake)

From here, you need to figure out how to format the axes and thicken the lines.  That's more matplotlib than I want to deal with this morning.


text:
Q: WebBrowser click element  I have an application that does some posts on a blog. The blog went through change and where was the <href> passed to <button type = "submit" value = "Post" class = "btn btnD medBtn MFSM touchable"
And the code that used no longer works, follows my code;
var links = br.Document.GetElementsByTagName("A");
foreach (HtmlElement link in links)
{

    if ((link.InnerText != null) && ((link.InnerText.Contains("Publicar"))||(link.InnerText.Contains("Discussão")  )))
    {
        link.InvokeMember("click");

    }
}

I've tried to search the button element but does not work;
HtmlElementCollection classButton = br.Document.All;
foreach (HtmlElement element in classButton)
{
    if (element.GetAttribute("class").Contains("btn btnD medBtn MFSM touchable"))
    {
        element.InvokeMember("click");
    }
}


text: Q: How to clear all states in redux store when user logs out? If not clear all states, the dirty datas may be rendered to the components when a new user logs in, Obviously it's a bug. I find a simple solution that reloads the page when the route jumps to '/#/login' after a click on logout button. Is anyone have a more elegant solution? Thanks.


text:
Q: Refreshing KendoUI Grid - pager broken I have created a simple Kendo UI grid with paging. Now I want to refresh my grid with some new data. Im using the setDatasource to attach the new data to the grid and then refresh to refresh the grid. Works fine except that the pager stops working. It will just give me a no-items-in-the-grid message.
I created a jsFiddle to demonstrate what I mean:
http://jsfiddle.net/DXgYu/
And here is the code I use to refresh the grid:
var grid = $("#grid").data("kendoGrid");
var ds = setds();
grid.setDataSource(ds);
grid.refresh();

In my example I wont be changing the data but that doesn't matter. If you click the button it will not refresh the pager the correct way and I have no clue how to get the pager to update too. Hopefully someone can help me! It's probably something small but I just can't find anywhere how to access the grid pager.
Thanks in advance.

A: The Grid's .setDataSource() function expects an actual kendo.data.DataSource not just an object. Change your .setds() function to return a DataSource:
function setds() {
    return new kendo.data.DataSource({
        ...
    });
}


text:
Q: pysnmp : AttributeError: 'module' object has no attribute 'NotificationOriginator' I am working on pysnmp where my script acts as SNMP listener and forwarder. I am able to receive SNMP traps and I can see the mibs. I am getting an error with the sendPdu function of ntforg.NotificationOriginator(). I am using python 2 on centos.
here is error snippet:
Traceback (most recent call last):
File "/tmp/akhil.py", line 65, in <module>
snmp_engine.transportDispatcher.runDispatcher()
File "build/bdist.linux-x86_64/egg/pysnmp/carrier/asyncore/dispatch.py", line 50, in runDispatcher
pysnmp.error.PySnmpError: poll error: Traceback (most recent call last):
;  File "build/bdist.linux-x86_64/egg/pysnmp/carrier/asyncore/dispatch.py", line 46, in runDispatcher
    use_poll=True, map=self.__sockMap, count=1)
;  File "/usr/lib64/python2.7/asyncore.py", line 220, in loop
    poll_fun(timeout, map)
;  File "/usr/lib64/python2.7/asyncore.py", line 201, in poll2
    readwrite(obj, flags)
;  File "/usr/lib64/python2.7/asyncore.py", line 123, in readwrite
    obj.handle_error()
;  File "/usr/lib64/python2.7/asyncore.py", line 108, in readwrite
    obj.handle_read_event()
;  File "/usr/lib64/python2.7/asyncore.py", line 449, in handle_read_event
    self.handle_read()
;  File "build/bdist.linux-x86_64/egg/pysnmp/carrier/asyncore/dgram/base.py", line 170, in handle_read
    self._cbFun(self, transportAddress, incomingMessage)
;  File "build/bdist.linux-x86_64/egg/pysnmp/carrier/base.py", line 70, in _cbFun
    self, transportDomain, transportAddress, incomingMessage
;  File "build/bdist.linux-x86_64/egg/pysnmp/entity/engine.py", line 152, in __receiveMessageCbFun
    self, transportDomain, transportAddress, wholeMsg
;  File "build/bdist.linux-x86_64/egg/pysnmp/proto/rfc3412.py", line 433, in receiveMessage
    PDU, maxSizeResponseScopedPDU, stateReference)
;  File "build/bdist.linux-x86_64/egg/pysnmp/entity/rfc3413/ntfrcv.py", line 115, in processPdu
    contextName, varBinds, self.__cbCtx)
;  File "/tmp/akhil.py", line 54, in cbFun
    ntf_org = ntforg.NotificationOriginator()
;AttributeError: 'module' object has no attribute 'NotificationOriginator'
caused by <type 'exceptions.AttributeError'>: 'module' object has no attribute 'NotificationOriginator'
e here

My code :
from pysmi.codegen import PySnmpCodeGen
from pysmi.parser import SmiStarParser
from pysmi.reader import FileReader
from pysmi.searcher import PyFileSearcher, PyPackageSearcher, StubSearcher
from pysmi.writer import PyFileWriter
from pysnmp.carrier.asyncore.dgram import udp
from pysnmp.carrier.error import CarrierError
from pysnmp.entity import config, engine
from pysnmp.entity.rfc3413 import ntforg, ntfrcv
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.hlapi import *
from pysnmp.proto.api import v2c
from pysnmp.smi import builder, compiler, view
from pysnmp.smi.error import MibNotFoundError
from pysnmp.smi.rfc1902 import ObjectIdentity, ObjectType

# snmpTrapAddress, SCALAR, not-accessible, IpAddress, 1.3.6.1.6.3.18.1.3.0

# Create SNMP engine with autogenernated engineID and pre-bound
# to socket transport dispatcher
snmp_engine = engine.SnmpEngine()

# UDP over IPv4
config.addTransport(
    snmp_engine,
    udp.domainName,
    udp.UdpTransport().openServerMode(("0.0.0.0", 162))
)

config.addTransport(
        snmp_engine,
        udp.domainName + (2,),
        udp.UdpTransport().openClientMode()
)

# SNMPv1/2c setup
config.addV1System(snmp_engine, "my-area", "public")

config.addTargetParams(snmp_engine, "distant_agent_auth", "public", "noAuthNoPriv", 1)

config.addTargetAddr(snmp_engine, "distant_agent", udp.domainName + (2,),("100.80.97.21", 162), "distant_agent_auth", retryCount=0)

def cbFun(snmp_engine, state_reference, context_engine_id, context_name, var_binds, cb_ctx):
    execContext = snmp_engine.observer.getExecutionContext("rfc3412.receiveMessage:request")
    trap_pdu = v2c.TrapPDU()
    v2c.apiTrapPDU.setDefaults(trap_pdu)
    v2c.apiTrapPDU.setVarBinds(trap_pdu, var_binds)
    source_ip_address = execContext["transportAddress"][0]
    print "got traps from : {}".format(source_ip_address)
    var_binds_dict = {name.prettyPrint(): None if val.prettyPrint() == "" else val.prettyPrint() for name, val in var_binds}
    print var_binds_dict
    print "sending traps to destination 100.80.97.21"
    ntf_org = ntforg.NotificationOriginator()
    ntf_org.sendPdu(snmp_engine, "distant_agent", None, "", trap_pdu)

# Register SNMP Application at the SNMP engine
ntfrcv.NotificationReceiver(snmp_engine, cbFun)

snmp_engine.transportDispatcher.jobStarted(1)  # this job would never finish

# Run I/O dispatcher which would receive queries and send confirmations
try:
    snmp_engine.transportDispatcher.runDispatcher()
except:
    snmp_engine.transportDispatcher.closeDispatcher()
    raise
finally:
    snmp_engine.transportDispatcher.closeDispatcher()
    snmp_engine.transportDispatcher.jobFinished(1)

version details :

>>> pysnmp.__version__
'4.4.9'

>>> pysmi.__version__
'0.3.4'

Am I missing anything ?

A: I don't know exactly 'why', but if you want to import something from hlapi try to import the specific module that you want to use. Thus avoid doing from pysnmp.hlapi import *. So if you remove that piece of code your system will probably work properly.


text:
Q: Cannot connect to the MySQL database server, there are error messages but I do not know what the problem is and how to solve it I get the below error messages and think that I have more than one problem:

The first one is common:

mysql-bin.index' not found (Errcode: 13)

and I want to solve it by
chgrp -R mysql /usr/local/mysql/data && chown -R mysql /usr/local/mysql/data
But I got another error message:

chown: /usr/local/mysql/data/.DS_Store: Operation not permitted

I do not know how to solve these...
2020-09-12T04:15:42.843047Z 0 [System] [MY-010116] [Server] /usr/local/mysql-8.0.21-macos10.15-x86_64/bin/mysqld (mysqld 8.0.21) starting as process 1012
2020-09-12T04:15:42.849049Z 0 [Warning] [MY-010159] [Server] Setting lower_case_table_names=2 because file system for /usr/local/mysql-8.0.21-macos10.15-x86_64/data/ is case insensitive
2020-09-12T04:15:42.855324Z 0 [ERROR] [MY-010119] [Server] Aborting
2020-09-12T04:15:42.855495Z 0 [System] [MY-010910] [Server] /usr/local/mysql-8.0.21-macos10.15-x86_64/bin/mysqld: Shutdown complete (mysqld 8.0.21)  MySQL Community Server - GPL.

These are other error messages. Can anyone figure out the problem and the solution for me?

A: File '/etc/mysql/var/log-bin.index' not found (Errcode: 13). Doesn't mean it's not there; Error 13 means "Permission denied" Which If there is no .index file, and no binlogs mysql will just start over from scratch Remove any files in that directory.
Option 1:
service mysqld stop

Copy the log files including the .index file to new location.
 cp mysql-bin.log* /path/to/binlogs
 cp mysql-bin.index /path/to/binlogs

Do Changes in the /etc/my.cnf file.
[mysqld]
log-bin=/path/to/newdirecory/mysql-bin
log-bin-index=/path/to/newdirectory/mysql-bin.index
service mysqld start

Option 2:
Use this utiltiy to relocate binary logs:
mysqlbinlogmove --binlog-dir=/server/data /new/binlog_dir


text:
Q: Code to check 30 days trial for my application Hi everyone I have developed an application using c# and I wish to restrict its use to 30days and after 30 days the user should not be able to use the application.I got the following code online.What code should I add in elseif(days<30) to restrict its use
#region Using directives
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
#endregion

namespace Coder24
{
    class TrialTimeManager
    {
        /// <summary>
        /// A Temporary variable.
        /// </summary>
        private string temp = "";

        /// <summary>
        /// The constructor.
        /// </summary>
        public TrialTimeManager()
        {

        }

        /// <summary>
        /// Sets the new date +31 days add for trial.
        /// </summary>
        public void SetNewDate()
        {
            DateTime newDate = DateTime.Now.AddDays(31);
            temp = newDate.ToLongDateString();
            StoreDate(temp);
        }

        /// <summary>
        /// Checks if expire or NOT.
        /// </summary>
        public void Expired()
        {
            string d = "";
            using (Microsoft.Win32.RegistryKey key =
                Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Test"))
            {
                 d = (String)key.GetValue("Date");
            }
            DateTime now = DateTime.Parse(d);
            int day = (now.Subtract(DateTime.Now)).Days;
            if (day > 30){}
            else if (0 < day && day <= 30){
                 string daysLeft = string.Format("{0} days more to expire", now.Subtract(DateTime.Now).Days);
                 MessageBox.Show(daysLeft);
            }
            else if (day <= 0){
                /* Fill with more code, once it has expired, what will happen nex! */
            }
        }

        /// <summary>
        /// Stores the new date value in registry.
        /// </summary>
        /// <param name="value"></param>
        private void StoreDate(string value)
        {
            try
            {
                using (Microsoft.Win32.RegistryKey key =
                    Microsoft.Win32.Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Test"))
                {
                    key.SetValue("Date", value, Microsoft.Win32.RegistryValueKind.String);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

A: This depends entirely on what you want to have happen when a trial expires.
You probably want to immediately end the program. You could also give them the option of visiting your website to purchase a license. Maybe something like this:
if (day > 30)
{
    if (MessageBox.Show("Trial expired. Visit site to purchase license?",
        "Trial Expired!", MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
        Process.Start("http://www.yourwebsite.com");
    }

    Environment.Exit(0);
}

If you have something else in mind, or other requirements, update your question with more details.


text:
Q: Сравнение строк двух разных датафреймов pandas по нескольким условиям Есть два датафрейма, нужно сравнить данные по нескольким условиям столбцов в нужной строке и вписать данные одного датафрейма в другой.
Я решил это с помощью вложенных циклов
for i in range(df_mi.shape[0]):
    for j in range(df_pz.shape[0]):
        if (df_mi.iloc[i].A == df_pz.iloc[j].A) and (df_mi.iloc[i].C >= df_pz.iloc[j].C) and (df_mi.iloc[i].D <= df_pz.iloc[j].D) :
            df_mi.iloc[i].new = df_pz.iloc[j].J

Но способ очень медленный.
Есть ли идеи как сделать быстрее?

A: Обычно в Pandas всё можно сделать без циклов. Вот вам пример приближенный к вашему:
import pandas as pd
import numpy as np

df1 =  pd.DataFrame(np.random.rand(1000,5))
df2 =  pd.DataFrame(np.random.rand(1000,5))
df1.columns = list('ABCDJ')
df2.columns = list('ABCDJ')

cond = (df1.C <= df2.C) & (df1.D >= df2.D)
df1.loc[cond, 'new'] = df1.loc[cond, 'J']

Основное, что нужно иметь в виду:

*

*Условия выборки обязательно нужно писать в скобках и соединять между собой через побитовые операции & и | (а не через логические and и or), условий можно писать сколько угодно

*В новый столбец данные можно записать только через индексную нотацию ['new'], а как вы написали через точку .new так запись в новый столбец не работает, это сработает только если такой столбец уже есть, тогда Pandas сделает всё что нужно за вас и обеспечит доступ

*Размер Series слева и справа от знака присваивания должен быть одинаковый, поэтому я заранее создаю битовую маску, сохраняю её в переменную и использую .loc[] нотацию с этой маской с обеих сторон =

A: Судя по всему, вы хотите сравнить строки двух разных датафреймов и вписать данные одного датафрейма в другой, если выполнено несколько условий на столбцы. Один из способов ускорения вашего кода состоит в том, чтобы использовать метод apply для применения функции к каждой строке датафрейма. Этот метод обычно работает быстрее, чем циклы, так как он использует векторизованные операции вместо последовательных операций над каждым элементом.
Ниже приведен пример того, как это может выглядеть:
def compare_rows(row):
    for i in range(df_pz.shape[0]):
        if (row.A == df_pz.iloc[i].A) and (row.C >= df_pz.iloc[i].C) and (row.D <= df_pz.iloc[i].D):
            return df_pz.iloc[i].J
    return row.new

df_mi['new'] = df_mi.apply(compare_rows, axis=1)

Обратите внимание, что в функции compare_rows мы используем текущую строку датафрейма df_mi, которая передается в качестве аргумента функции. Мы сравниваем эту строку с каждой строкой датафрейма df_pz, и если все условия выполнены, мы возвращаем значение из столбца J датафрейма df_pz. Если ни одно из условий не выполнено, мы возвращаем значение из столбца new датафрейма df_mi.
Метод apply применяет функцию compare_rows к каждой строке датафрейма df_mi и возвращает результат в виде нового столбца new.
Этот код должен работать быстрее, чем ваш исходный код с вложенными циклами, так как он использует векторизованные операции вместо последовательных операций над каждым элементом.
Есть еще несколько способов, которые могут ускорить ваш код. Один из них состоит в том, чтобы использовать метод merge для слияния датафреймов df_mi и df_pz по нужным условиям. Этот метод обычно работает быстрее, чем циклы, так как он использует внутренние алгоритмы Pandas для слияния датафреймов.
Ниже приведен пример того, как это может выглядеть:
df_merged = df_mi.merge(df_pz, on=['A', 'C', 'D'], how='inner')
df_mi['new'] = df_merged['J']

Метод merge сливает датафреймы df_mi и df_pz по столбцам A, C и D, и возвращает результат в виде нового датафрейма df_merged. Затем мы присваиваем значения из столбца J датафрейма df_merged столбцу new датафрейма df_mi.


text: Q: How can I remove Chrome app (not Chrome itself)? Once I've installed Postman app for Chrome. Then they deployed native mac os app and Chrome version was deprecated. The problem is that I don't have Postman in the list of installed apps in Chrome so now I have no idea how to remove it. Both native app and Chrome version now is shown in my Spotlight


text:
Q: Find the value of $p$ such that $\cos(P \sin x)=\sin(P\cos x)$
Find the smallest positive value of $P$ for which the equation
  $$\cos(P \sin x)=\sin(P\cos x)$$
  is true, where $x\in[0^{\circ},360^{\circ}]$.

A: Hint:
$$\cos (P \sin x) \equiv \sin \left(\frac{\pi}{2} - P \sin x\right)$$
So your problem reduces to
$$\sin \left(\frac{\pi}{2} - P \sin x\right) = \sin (P \cos x)$$
What can you conclude from this? Perhaps take the inverse sine of both sides?


text:
Q: Saving an sqllite3 database as csv file in Ruby on Rails 5 I am currently working on a project and I want to know how to save an sqllite database in rails as a csv file. I want it when you click the button, the current database on the system download. Can anybody help me? Thanks!

A: Your problem isn't really specific to Rails. Instead, you're mostly dealing with an administrative issue. You should write a script to export your database as csv, something like this:
#!/bin/bash
./bin/sqlite3 ./my_app/db/my_database.db <<!
.headers on
.mode csv
.output my_output_file.csv
select * from my_table;
!

This script exports a single table. If you have additional tables, you'll want to add them to your script.
The only Rails related issue is the matter of calling that script. Save the script within your application structure; I'd suggest my_app/assets or some similar location.
Now you can run that script using system(command) where command is the absolute path for your script, within a set of double-quotes.


text:
Q: QT: QPainter.drawText() into QPixmap crashes under OSX Lion, not Leopard Solved!
I cross compiled for Windows, and got my hint: The windows version crashed even before main -- so it had to be basic allocation issues. And it was. I had made a large static allocation and recently made it even larger (something the program requires, not optional or temporary); changed array[size] to array=calloc(etc,etc) and bingo, the windows version ran, and the crash deep in the bowels of OSX/Lion went away, everything runs fine again.
So, lesson learned: large static allocations, no good -- neither windows or OSX is particularly able to accommodate them.

I get a paint event. I have a QPixmap, standalone, that I will be drawing on a QWidget frame. Within the paint event call, I create a painter for the QPixmap, which lives in the class definition. I set colors; brushes, pens. I fill, I draw lines. rects. gradients. text. ellipses. it all works fine under Snow Leopard and Leopard. Under Lion, 10.7.anything, any drawText() call on this same QPixmap fails many call levels within OSX, and five levels deep in com.apple.ColorSync. Doesn't matter what font I use, or size. Both drawText() and drawStaticText() fail the same way.
The failure occurs prior to any attempt to actually draw the QPixmap -- it's during the render of the drawText() that it blows up. All I've done to that point is fill with black (works), fill with a gradient (works), draw some filled rects (works) and draw a grid (works) and then I go to draw this text. Which doesn't work, but blows out the main thread (0) (which is doing the drawing during the paint event) with EXC_BAD_ACCESS SIGSEGV.
Qt has no color management as far as I can tell. OSX has no way to turn off colorsync to the display.
For the moment, I've special cased the OS level and simply don't draw text (in the beta) if running under Lion but this is a horrible workaround.
Anyone have any ideas at all why Apple's 10.7 colorsync would get its knickers in a knot over drawText() to a perfectly vanilla QPixmap with valid size, text, rectangle, and within-bounds drawing task?


text:
Q: Best way to tunnel RMI over HTTP I'm looking for a secure way to tunnel RMI traffic.
In My application(java Webstart) i must assume that the only port that is open is port 80.
I have the looked att socketfactories for rmi but do i really need a proxy then.
I need to do all my tunneling on the client side.
The only firewall i am trying to get past is on the client side.
I'm not able to open 1099 with port ranges above.
Would be nice to see some implementations.
Thanks!

A: Port 1099 was reserved for RMI at IANA in about 1995. There is no reason for it not to be open for outbound access in the client-side firewall.
RMI can be made to use fixed port numbers by supplying a port number when constructing (super(port)) or exporting (exportObject(object, port)). Better still, if you create the Registry within the server JVM via LocateRegistry.createRegistry(), all subequently exported remote objects will use that port unless they specify a different port or they use a server socket factory.
BUT ... RMI already includes HTTP tunneling 'out of the box'. No external solution required. You have to deploy the RMI-Servlet provided with the JDK, at the server end.

A: (a)
although not the newest fashion, exposing remote services with Hessian and Burlap seems to be a simple solution to avoid problem working across firewalls: http://hessian.caucho.com/doc/
see sample code for the server and client side:
http://www.javatpoint.com/spring-remoting-by-hessian-example
(b) or consider using Spring HttpInvokder (see some sample code here: http://www.javatpoint.com/spring-remoting-by-http-invoker-example)
HttpInvokder provides more customization options through the RemoteInvocationFactory, RemoteInvocationExecutor and HttpInvokerRequestExecutor strategies (for example, to add custom context information (such as user credentials) to the remote invocation, or using java's built-in object serialization etc.), see:
http://docs.spring.io/spring-framework/docs/2.0.x/api/org/springframework/remoting/support/RemoteInvocationFactory.html


text:
Q: How to add topLinks to a cms page in magento The answer is probably out there as a combination of several posts but I am not very good at Magento yet so I have to ask anyway:
I would like to have the topLinks inserted into a cms page.
I tried <?php echo $this->getChildHtml('topLinks') ?> but that does not work, it just shows the code as text on the page.
I tried {{block type="core/template" name="top.Links" as="topLinks" template="page/template/links.phtml"}} but nothing shows up.
I did successfully add the search form to the cms page with {{block type="core/template" name="top.search" as="topSearch" template="catalogsearch/form.mini.phtml"}} so I figured I probably just have the block type wrong or something.
What did I do wrong?

A: TL;DR: Well...You can't.
Why?:The topLinks block is a "container" block of type page/template_links. This is just added in the layout, but other layout handles or blocks add links to it. For example this part of xml in the customer.xml layout file
<reference name="top.links">
        <action method="addLink" translate="label title" module="customer">My Account<url helper="customer/getAccountUrl"/><title>My Account</title><prepare/><urlParams/><position>10</position></action>
    </reference>

adds the My account link to it. There are others.
In conclusion the topLinks block does not have meaning on it's own. It is just a placeholder that can e modified by other blocks.
When a cms page is rendered the layout is already loaded parsed, so the block you add cannot be modified anymore by other blocks or layout files.

A: You can hardcode put top links in your cms pages like this..

<a href="<?php echo $this->getUrl('customer/account')?>">My Account

<a href="<?php echo $this->getUrl('wishlist')?>">My Wishlist

<a href="<?php echo $this->getUrl('checkout/cart')?>">My Cart

<a href="<?php echo $this->getUrl('checkout')?>">Checkout

<a href="<?php echo $this->getUrl('customer/account/login')?>">Log In

A: @Marius Thanks, I learned something new there. I am still struggling with understanding the intricate details of Magento's structure but I'm working on it.
@chirag I tried that but php does not work directly in cms pages so it tries to link to http://mymagentopage/<?php echo $this->getUrl('customer/account')?>. I can of course link directly to http://mymagentopage/customer/account but for a few links I would miss functionality:
"Login" changing to "Logout" when logged in and logging the customer out instead of going to the account screen.
"Cart" changing to "Cart(2)" when product is added to the cart.
etc (I don't use wishlist)
Is there a way to regain this functionality?
I found this snippet that does it but it's php which won't work in cms pages:
<?php if (Mage::getSingleton('customer/session')->isLoggedIn()==0): ?>
<a href="<?php echo $this->getUrl('customer/account/login') ?>"><?php echo $this->__('Log In') ?>
<?php else: ?>
<a href="<?php echo $this->getUrl('customer/account/logout') ?>"><?php echo $this->__('Log Out') ?>
<?php endif ?>I would also be happy with a solution to enable me to use php in cms pages, I am the only admin anyway.
EDIT
I found a working solution:
I created a new phtml file containing the above mentioned snippet. I created a new folder 'customphp' in my template folder and saved it there as test.phtml.
In the cms page I added a block: {{block type="core/template" name="whatever_unique-name-i-want" template="customphp/test.phtml"}}
Tada!
This is where I got the idea: http://www.magentocommerce.com/boards/viewthread/439880/