text:
Q: Codeigniter internal server error load model I have this model
<?php
class Votante_model extends CI_Model{
    var $departamento = '';
    var $municipio = '';
    var $puesto = '';
    var $direccion_puesto = '';
    var $fecha_inscripcion = '';
    var $mesa = '';

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }

    function getVotanteJSON($cedula){
        $retorno = '';
        $this->db->save_queries = true;

        $this->db->select('nom_dpto, nom_mpio, nom_puesto, mesa');
        $this->db->join('divipol', 'censo.cod_dpto = cod_dpto');
        $this->db->join('divipol', 'censo.cod_mpio = cod_mpio');
        $this->db->join('divipol', 'censo.cod_puesto = cod_puesto');
        $this->db->where('censo.cedula = ',$cedula);

        $query = $this->db->get('censo');

        if ($query->num_rows() > 0){
            $row = $query->row_array();

            $departamento = $row['nom_dpto'];
            $municipio = $row['nom_mpio'];
            $puesto = $row['nom_puesto'];
            $direccion_puesto = '';
            $fecha_inscripcion = '';
            $mesa = $row['mesa'];

            $retorno = '{"error":"", "codigo": 1,"departamento": "'.$departamento.'", "municipio": "'.$municipio.'", "puesto": "'.$puesto.'", "direccion": "Cll 64A", "fecha": "19910825", "mesa": '.$mesa.'}';
        }else{
            $retorno = '{"error": "No hay datos", "codigo": -1}';
        }

        return $retorno;
    }
   }

and this controller
<?php
class Datos extends CI_Controller{

public function __construct(){
parent::__construct();
}

public function index(){
echo "
" . $this->db->last_query(); . "
";
echo "
" . $this->db->_error_message() . "
";
}

Public function votante($cedula){
$this->load->model('votante_model');
$data['json']= $this->Votante->getVotanteJSON($cedula);
$this->load->view('json_view',$data);

}

}

and this view
<?php

$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo $json;
?>

when I call a controller throws this error: 500 Internal Server Error  and no error on logs neither apache logs. What's wrong??
Htaccess is ok, Deny from all
Thanks in advance

A: You need to call the model:
$data['json']= $this->votante_model->getVotanteJSON($cedula);
// not this:
$data['json']= $this->Votante->getVotanteJSON($cedula);

As it is now, you're calling the method from within the method.


text:
Q: Is .NET Remoting really deprecated? Everyone is saying how .NET Remoting is being replaced by WCF, but I'm wondering just how accurate that is. I haven't seen any official word that Remoting is being deprecated, and it seems to me there are certainly scenarios where Remoting makes more sense than WCF. None of the Remoting-related objects or methods have been deprecated, even in version 4.0 of the framework. It is also my understanding that System.AddIn in the 3.5 and 4.0 frameworks use Remoting.
Does anyone have any official word to the contrary?
In the article, Choosing Communication Options in .NET (for 3.0, as that's the latest version of that article), it states:

8 Cross-application domain communications
If you need to support communication between objects in different application domains within the same process, you must use .NET remoting.

Now, that, of course, isn't accurate, as WCF can certainly be used to cross appdomain boundaries, but is it giving the official recommendation for that scenario?
Update: I sent Clemens Vasters (who was on the team that owns Remoting and WCF) this question:

Clemens, I understand you're on the team that owns both remoting and wcf, and I have a couple of questions that I believe I need to go to the source for.
First, I have a question about whether remoting is going away. Specifically, we have a rather large application that uses remoting extensively for in-process cross-appdomain communication, and I was wondering if this usage of remoting is considered "legacy". If so, will AppDomain.CreateInstance and friends be replaced with something else?

This is his reply:

Remoting is part of the .Net Framework and as such it isn't going away. COM has been in Windows since Windows NT 3.5/Windows 95 and hasn't gone away and I don't see that going away anytime soon, either.
That said, there is very minimal development investment going into Remoting. WCF is the successor of Remoting and supplants COM/DCOM for managed code.
For in-process, cross-appdomain communication Remoting is the CLR's native way of communicating. If you are seeing performance issues pumping larger amounts of data or very many messages in short time, you should take a serious look at WCF and the NetNamedPipeBinding.

A: If you like to migrate to .NET Core you have to find another solution for
Remoting anyway:

.NET Remoting was identified as a problematic architecture. It's used for cross-AppDomain communication, which is no longer supported. Also, Remoting requires runtime support, which is expensive to maintain. For these reasons, .NET Remoting isn't supported on .NET Core, and we don't plan on adding support for it in the future.

Source: https://learn.microsoft.com/en-us/dotnet/core/porting/libraries#remoting

A: Calling it a legacy technology is a more accurate description.
http://msdn.microsoft.com/en-us/library/72x4h507%28VS.85%29.aspx

This topic is specific to a legacy
  technology that is retained for
  backward compatibility with existing
  applications and is not recommended
  for new development. Distributed
  applications should now be developed
  using the  Windows Communication
  Foundation (WCF).

Update: WCF doesn't distinguish between inter/intra/process/inter/intra-appdomain. If you are using single machine communication in WCF you use named pipes- using it should give good performance in virtually all realistic scenarios.
For a performance comparison of various distributed communication technologies see here.

A: Clemens Vasters, the Technical Lead for the Microsoft .NET Service Bus (that means both Remoting as well as WCF) talks about WCF vs. Remoting in this forum post. To summarize the post he ends up recommending WCF over Remoting.
I'm not sure if .NET 4.0 uses remoting internally but you could try sending Clemens the question... I'm sure he knows the answer.

A: I think that now (2015) it's quite clear even for cross application
domains:
https://msdn.microsoft.com/en-us/library/vstudio/ms180984(v=vs.100).aspx

Remoting Cross AppDomains
  This topic is specific to a legacy
  technology that is retained for backward compatibility with existing
  applications and is not recommended for new development. Distributed
  applications should now be developed using the Windows Communication
  Foundation (WCF).

Then WCF should be used for cross application domains too.

A: Yes. Remoting is deprecated...and it's official from Microsoft. Here's the link:
.NET Remoting
The first line in the article says in bold:

This topic is specific to a legacy technology that is retained for backward compatibility with existing applications and is not
  recommended for new development. Distributed applications should now
  be developed using the Windows Communication Foundation (WCF).

I thought the verbiage was 'deprecated' but apparently they refer to it as 'legacy'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pyspark monitoring metrics not making sense I am trying to understand the spark ui and hdfs ui while using pyspark.
Following are my properties for the Session that I am running
pyspark --master yarn --num-executors 4 --executor-memory 6G --executor-cores 3 --conf spark.dynamicAllocation.enabled=false --conf spark.exector.memoryOverhead=2G --conf spark.memory.offHeap.size=2G --conf spark.pyspark.memory=2G

I ran a simple code to read a file (~9 GB on disk) in the memory twice. And, then merge the two files and persist the results and ran a count action.
#Reading the same file twice
df_sales = spark.read.option("format","parquet").option("header",True).option("inferSchema",True).load("gs://monsoon-credittech.appspot.com/spark_datasets/sales_parquet")
df_sales_copy = spark.read.option("format","parquet").option("header",True).option("inferSchema",True).load("gs://monsoon-credittech.appspot.com/spark_datasets/sales_parquet")
#caching one
from pyspark import StorageLevel
df_sales = df_sales.persist(StorageLevel.MEMORY_AND_DISK)

#merging the two read files
df_merged = df_sales.join(df_sales_copy,df_sales.order_id==df_sales_copy.order_id,'inner')
df_merged = df_merged.persist(StorageLevel.MEMORY_AND_DISK)
#calling an action to trigger the transformations
df_merged.count()

I expect:

*

*The data is to first be persisted in the Memory and then on disk

*The HDFS capacity to be utilized at least to the extent that the data persist spilled the data on disk

Both of these expectations are failing in the monitoring that follows:
Expectation 1: Failed. Actually, the data is being persisted on disk first and then in memory maybe. Not sure. The following image should help. Definitely not in the disk first unless im missing something

Expectation 2: Failed. The HDFS capacity is not at all used up (only 1.97 GB)

Can you please help me reconcile my understanding and tell me where I'm wrong in expecting the mentioned behaviour and what it actually is that I'm looking at in those images?

A: Don't use persist to disk until you have a really good reason.(You should only performance tune when you have identified a bottle neck)  It takes way longer to write to disk than it does to just proceed with processing the data.  for that reason persist to disk should only be used when you have a reason.  Reading data in for a count is not one of those reasons.
I humbly suggest that don't alter the spark launch parameters unless you have a reason.(And you understand them.)  Here your not going to fit your data into memory because of your spark launch configuration. (You split the space into 2 Gig allocations which means you'll never fit 9 gigs into the 6 gigs you have)  I think that you should consider removing all your configuration and see how that changes what's used in memory. Playing with these launch configuration will help you learn what each parameter does.  That might help you learn more.
Really it's hard to really provide more advice because there is a lot to learn and explain.  Perhaps you'll get luck and someone else will answer your question.


text:
Q: How to save the results from nltk function "most_informative_features" to a txt file in Python Sorry if this is a noobie question! I am carrying out sentiment analysis on python using nltk. It has a function which returns the most informative features but whenever i try and save the results to a  text file, i get the following error 'TypeError: must be str, not list'. the code i am using is as follows
classifier.most_informative_features(100)

str(information)
saveFile = open('informationFile.txt', 'w')

saveFile.write(information)
saveFile.close()

any ideas what i am doing wrong?

A: You need to assign the conversion from list to string to something, or do in place...
saveFile.write(''.join(information))

Applying str to a variable generates a value, but doesn't change the variable (unless you assign it)
>>> bar
['a', 'b', 'c']
>>> str(bar)
"['a', 'b', 'c']"
>>> bar
['a', 'b', 'c']
>>> ', '.join(bar)
'a, b, c'
>>> bar
['a', 'b', 'c']
>>> bar = ', '.join(bar)
>>> bar
'a, b, c'


text:
Q: ADF Refresh page jsf with page fragments jsff after set session variable I have a template which includes a button that let you select a profile, you push the button and appear the available profiles, choose one and push accept. After that I set a variable session successfully.
I have a "First" jsf page with two jsff page fragments from a View Link. The view link is composed by a headerView and detailView. The headerView had a bind variable. What I need is that parameter (bindVariableParameter) can be set by the session variable of the template.
This is what I get:
I am in a home page (separate Application Module), I push the template button before I load de "First" jsf page and after that I go to the "First" jsf page the information is loaded successfully. What I do in the Application Module is something like that:
protected void prepareSession(Session session) {
Map sessionScope = ADFContext.getCurrent().getSessionScope();
String company = (String)sessionScope.get("compId");
System.out.println("Default Comapny in BC is: " + company);
super.prepareSession(session);
this.getSession().getUserData().put("Company", company);
System.out.println("After setting value in userData map of BC");
}

And in the bind variable expression of the headerView I use:
adf.userSession.userData.Company

It works great!!!! But!!!!
When I press the button again and I choose another profile, the info is not updated. Neither in the headerView neither in the detailView.
Also, when I go to the "First" jsf page (without previously push the template button), I got no info, which is right, because I don't have any session variable. After that I push the template button and select the profile, but the page is not refreshed.
I tried several ways to to this but I'm lost.
Could you help me?
Regards.

A: You have two options for this:

*

*Option one: tune your AM as follows:
jbo.doconnectionpooling=true
jbo.txn.disconnect_level = 1
This will ensure prepareSession() method is being called before each operation. This happens to be a best practice in ADF productions systems, increasing scalability (see here )

*Option two: Better than using prepareSession(), you can pass the Http Session data to ADF BC  through a custom DataControlFactory.
You can find an example here: http://andrejusb.blogspot.co.uk/2012/05/solution-for-sharing-global-user-data.html


text:
Q: Ajax and MVC 4 ( post request) I want to send a simple string ( which is xml ) to a controller. I don't know why the breakpoint in Visual Studio is not hit.
Here is the jQuery code :
$.ajax({
            type: "POST",
            url: "BasicWizard/show",
            data: "xml="+xmlResult,
            success: function (data) {
                console.log("Oh yeah !");
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(textStatus, errorThrown);
            }

            });

And here is my method in the controller:
    [HttpPost]
    public ActionResult show(string xml)

   {
       try
       {
           ViewBag.xml = xml;
           return PartialView("showXML");
       }
       catch (Exception)
       {
           return Content("error");
       }

    }

I have just a 500 error in the console.

A: try this :-
data: "{'xml':'" + xmlResult+ "'}",

A: The post data isn't properly formatted. Try passing in encodeURIComponent(xmlResult) instead of just xmlResult. This will escape out the = and other characters that won't work properly in a post value.


text:
Q: Can't find "Use .NET Standard" when creating a Xamarin.Forms project with Visual Studio for Mac I am trying this tutorial as I want to create a simple Xamarin.Forms project to plugin to my other project. The parent tutorial is here. In the parent tutorial it stated:

You can see most of this code is boilerplate - and it's the only thing
you really need to do in the MacOS project. All of your app's UI and
business logic code can happily reside in the shared Xamarin.Forms
project. Xamarin.Forms code in a shared project simply points to a
start page with minimal XAML, like so:

It gives sample code. That was why I was trying to setup a project with Xamarin.Forms. But when creating this XAML project, in the tutorial is shows:

Yet in my Visual Studio for Mac all I see is:

It is missing the Use .NET Standard options. Ultimately I want to create a simply XAML form so I can use it with the other project. And I am wanting to run this GUI on MacOS.

Update
If I go ahead a create a empty project then, and add it as a referenced project, I still don't know how to get my appDelegate file to fire up an instance of that xaml window:


text:
Q: getView() of ArrayAdapter not getting called I am doing Flickr integration and using Json parsing..I am able to fetch data  but its not displaying because getView() method of adapter is not getting called..However constructor of adapter class is called as i checked using Toast messages..I have no clue why getView() is not getting called...I have checked other questions with almost similar issue but unable to find solution that solves my problem
public class FlickrImagesList extends Fragment
{
    private FragmentActivity myContext;

    ArrayList<Flickr> flickrList;

    private static final String photo = "photo";
   private static final String id = "id";
    private static final String owner = "owner";
    private static final String secret = "secret";
    private static final String server = "server";
    private static final String farm = "farm";
    private static final String title = "title";
    private static final String ispublic = "ispublic";
    private static final String isfriend = "isfriendt";
    private static final String isfamily = "isfamily";

ImageLoader imageLoader;
  FlickrListAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {

        View rootView = inflater.inflate(R.layout.flickr_main_list, container, false);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
  //      imageLoader = ImageLoader.getInstance();
//        imageLoader.init(ImageLoaderConfiguration.createDefault(myContext));
        rootView.setFocusableInTouchMode(true);

        flickrList= new ArrayList<Flickr>();
            new JSONAsyncTask().execute("https://api.flickr.com/services/rest?method=flickr.groups.pools.getPhotos&api_key=xyz&format=json&group_id=2058557@N24&nojsoncallback=1");
        ListView listview = (ListView)rootView.findViewById(R.id.listflickr);
      adapter = new FlickrListAdapter(getActivity().getApplicationContext(), R.layout.flickr_list_single,flickrList);

    listview.setAdapter(adapter);

        return rootView;
    }
    class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

        ProgressDialog dialog;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();

            dialog = new ProgressDialog(getActivity());
            dialog.setMessage("Loading, please wait");
            dialog.setTitle("Connecting server");
            dialog.show();
            dialog.setCancelable(false);
        }

        @Override
        protected Boolean doInBackground(String... urls)
        {
            try
            {

                HttpGet httppost = new HttpGet(urls[0]);
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httppost);

                int status = response.getStatusLine().getStatusCode();
                Log.e("status","status");
                if (status == 200) {
                    Log.e("status2","status2");
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);
                    entity.consumeContent();
                    JSONObject jsono = new JSONObject(data);
                    JSONArray jarray = jsono.getJSONArray("photos");

                    for (int i = 0; i < jarray.length(); i++)
                    {
                        Log.e("status3","status3");
                        JSONObject c = jarray.getJSONObject(i);

                            JSONObject ph = c.getJSONObject(photo);

                        Flickr actor = new Flickr();
                        if(ph.has(id)) {
                            actor.setId(ph.getString(id));
                        }
                        if(ph.has(owner)) {
                            actor.setOwner(ph.getString(owner));
                        }
                        if(ph.has(secret))
                        {
                            actor.setSecret(ph.getString(secret));
                        }
                        if(ph.has(server)) {
                            actor.setServer(ph.getString(server));
                        }
                        if(ph.has(farm)) {
                            actor.setFarm(ph.getString(farm));
                        }
                        if(ph.has(title)) {
                            actor.setTitle(ph.getString(title));
                        }
                        if(ph.has(ispublic)) {
                            actor.setIspublic(ph.getString(ispublic));
                        }
                        if(ph.has(isfriend)) {
                            actor.setIsfriend(ph.getString(isfriend));
                        }
                        if(ph.has(isfamily)) {
                            actor.setIsfamily(ph.getString(isfamily));
                        }
                        Log.e("actor.getServer()", actor.getServer());
 flickrList.add(actor);
                    }
                    return true;
                }

                //------------------>>

            }
            catch (ParseException e1)
            {
                e1.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            catch (JSONException e)
            {
                Log.e("exception", e.getMessage());
                e.printStackTrace();
            }
            return false;
        }

        protected void onPostExecute(Boolean result)
        {

            dialog.cancel();
           adapter.notifyDataSetChanged();

        }

    }

}

FlickrListAdapter
public class FlickrListAdapter extends ArrayAdapter<Flickr> {
    ArrayList<Flickr> flickrList;
    LayoutInflater vi;
    int Resource;
    ViewHolder holder;
    DisplayImageOptions options;

    public FlickrListAdapter(Context context, int resource, ArrayList<Flickr> objects)
    {
        super(context, resource, objects);
        Toast.makeText(context,"FlickrListAdapter",Toast.LENGTH_LONG).show();
        vi = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Resource = resource;
        flickrList = objects;
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(android.R.color.transparent)
                .showImageForEmptyUri(android.R.color.transparent)
                .showImageOnFail(android.R.color.transparent)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {    Toast.makeText(getContext(),"getView",Toast.LENGTH_LONG).show();
        // convert view = design
        View v = convertView;
        if (v == null)
        {
            holder = new ViewHolder();
            v = vi.inflate(Resource, null);
            holder.imageview = (ImageView) v.findViewById(R.id.flickr_image);

            v.setTag(holder);
        }
        else
        {
            holder = (ViewHolder) v.getTag();
        }

        holder.imageview.setImageResource(R.drawable.logo_icon);

        ImageLoader.getInstance().displayImage("https://farm" + flickrList.get(position).getFarm() + ".staticflickr.com/" + flickrList.get(position).getServer() + "/"
                + flickrList.get(position).getId() + "_" + flickrList.get(position).getSecret() + ".jpg",holder.imageview, options);

    }

    static class ViewHolder
    {
        public ImageView imageview;
        public TextView textview;
        public TextView textview2;
    }

}

If i add
@Override
    public int getCount () {
        return 1;
    }

then app crashes showing error on ImageLoader
  java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

A: Your adapter´s getView() is not called because the list flickrList that you get from your JSONAsyncTask() is empty.
in fact you are getting this exception:
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

According  to your .json response
http://www.mocky.io/v2/548b349c9739deb61372aecf
The problem is your parser, this will fix your problem:
                JSONObject jsono = new JSONObject(data);
                JSONObject jb = jsono.getJSONObject("photos");
                JSONArray jarray = jb.getJSONArray("photo");

        for (int i = 0; i < jarray.length(); i++){
                    Log.e("status3","status3");
                    JSONObject ph = jarray.getJSONObject(i);

                    Flickr actor = new Flickr();

A: Problem was where I am creating JSONObject thats why size of list is zero since jarray was zero..I resolved it by changing to..
 JSONObject jsono = new JSONObject(data);
                        JSONObject c = jsono.getJSONObject(photos);
                        JSONArray jarray = c.getJSONArray(photo);

                for (int i = 0; i < jarray.length(); i++){
                    Log.e("status3","status3");
                    JSONObject ph = jarray.getJSONObject(i);

                    Flickr actor = new Flickr();


text:
Q: CodePipeline fails every time in CodeDeploy stage CodePipeline fails every time in CodeDeploy stage.
Every time I push code to CodeCommit CodePipeline successefully fetching it but it's always fails in CodeDeploy stage.
Here is error message:
The overall deployment failed because too many individual instances failed deployment, too few healthy instances are available for deployment, or some instances in your deployment group are experiencing problems.
appspec.yml:
version: 0.0
os: linux
files:
- source: /
 destination: /home/ec2-user/app

permissions:
- object: /
   pattern: "**"
   owner: ec2-user
   group: ec2-user

hooks:
ApplicationStop:
   - location: scripts/app-stop
     timeout: 10
     runas: ec2-user

AfterInstall:
   - location: scripts/install-npm
     timeout: 1200
     runas: ec2-user

ApplicationStart:
   - location: scripts/app-start
     timeout: 60
     runas: ec2-user

scripts:
app-start:
#!/bin/bash
forever start /app/index.js

app-stop:
#!/bin/bash
forever stopall

install-npm:
#!/bin/bash
cd app && npm install

A: For code deploy, you've to make sure that your instance has the codedeploy agent installed on it, else it will give you an error like "

The overall deployment failed because of too many individual instances
  failed deployment, too few healthy instances are available for
  deployment or some instances in your deployment group are
  experiencing problems"

you can follow this URL to install codedeploy agent on your EC2 instance.
https://docs.aws.amazon.com/codedeploy/latest/userguide/codedeploy-agent-operations-install.html


text:
Q: Dynamically created controls causing Null reference I am trying to dynamically create controls and give them properties during run time.
I have put my code inside the Page_Init event, when I run my website I can see my controls but when I click on the submit button an error occurrs saying "Object reference not set to an instance of an object".
Here is the code I have used:
    //Creates instances of the Control
    Label FeedbackLabel = new Label();
    TextBox InputTextBox = new TextBox();
    Button SubmitButton = new Button();
    // Assign the control properties

    FeedbackLabel.ID = "FeedbackLabel";
    FeedbackLabel.Text = "Please type your name: ";
    SubmitButton.ID = "SubmitButton";
    SubmitButton.Text = "Submit";
    InputTextBox.ID = "InputTextBox";
    // Create event handlers
    SubmitButton.Click += new System.EventHandler(SubmitButton_Click);

    // Add the controls to a Panel
    Panel1.Controls.Add(FeedbackLabel);
    Panel1.Controls.Add(InputTextBox);
    Panel1.Controls.Add(SubmitButton);
}

protected void SubmitButton_Click(object sender, EventArgs e)
{
    // Create an instance of Button for the existing control
    Button SubmitButton = (Button)sender;
    // Update the text on the Button
    SubmitButton.Text = "Submit again!";

    // Create the Label and TextBox controls
    Label FeedbackLabel = (Label)FindControl("FeedbackLabel");
    TextBox InputTextBox = (TextBox)FindControl("InputTextBox");
    // Update the controls
    FeedbackLabel.Text = string.Format("Hi, {0}", InputTextBox.Text);

How can I fix this error?
This Is the Stack Trace

[NullReferenceException: Object reference not set to an instance of an object.]
     _Default.Page_PreInit(Object sender, EventArgs e) in c:\Users\bilalq\Documents\Visual Studio 2010\WebSites\WebSite3\Default.aspx.cs:31
     System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
     System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
     System.Web.UI.Page.OnPreInit(EventArgs e) +8876158
     System.Web.UI.Page.PerformPreInit() +31
     System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +328

A: As FindControl is not recursive, you have to replace this code :
Label FeedbackLabel = (Label)FindControl("FeedbackLabel");
TextBox InputTextBox = (TextBox)FindControl("InputTextBox");

by this code :
Label FeedbackLabel = (Label)Panel1.FindControl("FeedbackLabel");
TextBox InputTextBox = (TextBox)Panel1.FindControl("InputTextBox");

However, according other answers, you should move the declaration (not the instantiation) outside the method (at class level) in order to easily get an entry for your controls.

A: try to put your code in the Page_Load instead of Page_Init and also, check for null before  using objects returned by FindControl.
I suspect the object InputTextBox is null and it crashes when you try to print its Text.
as a general rule just check for null and also for type when casting results of FindControl to something else.

A: The FindControl is failing because it can't find the control and causing a null reference.
Just reference it directly using FeedbackLabel as you already have it in your class. Just move the scope outside of your 'Init' method.
private Label feedbackLabel = new Label();
private TextBox inputTextBox = new TextBox();
private Button submitButton = new Button();

public void Page_Init(EventArgs e)
{
    feedbackLabel.ID = "FeedbackLabel";
}

protected void SubmitButton_Click(object sender, EventArgs e)
{
    feedbackLabel.Text =...;
}

A: I suggest that you declare your controls outside the page_int and do your initialization in the init then use them with their name instead of find control.

A:     protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        //-- Create your controls here
    }


text:
Q: NightwatchJS how to emit html5 drag drop Maybe someone knows how to drag elements which have implemented html5 drag&drop.
I need this in e2e test using nightwatchjs.
I tried:
        browser.useCss()
        .moveToElement("div.test-dragbtn-row",10,10)
        .mouseButtonDown(0)
        .moveToElement('div.test-container-root',50,50)
        .mouseButtonUp(0).pause(3000);

In browser I can see that element is pressed, but second move not works, moreover it holds mouse down on element until I enter physically with mouse into browser window.
Maybe someone done test with nightwatchjs for drag and drop, and knows how to overcome this?

A: I created a custom command and it is working in chrome and firefox
dragAndDrop.js:
module.exports.command = function(source, dest, callback) {
  var self = this;

  this.moveToElement(source,  10,  10)
  .mouseButtonDown(0)
  .pause(500)
  .moveToElement(dest,  10,  10)
  .mouseButtonUp(0);

  return this;
};

A: I got a similar issue resolved by using this package - https://www.npmjs.com/package/html-dnd
It simulates a drag and drop by dispatching dnd events, no mouse involved. It is not ideal, as you may be relying on mouse events to make other stuff happen, but it did the trick for me.


text:
Q: Display an add-in command button only if there are attachments I try to make an add-in command button to only be visible when there are attachments. Is it possible?
I expected I could add a "Rule" node to the "Control" node but it cannot be done:
<Control xsi:type="Button" id="hButton2">
    <Label resid="hButton2Label" />
    <Supertip>
        <Title resid="hButton2SupertipT" />
        <Description resid="hButton2SupertipD" />
    </Supertip>
    <Icon>
        <bt:Image size="16" resid="h-button2-icon-16" />
        <bt:Image size="32" resid="h-button2-icon-32" />
        <bt:Image size="80" resid="h-button2-icon-80" />
    </Icon>
    <Action xsi:type="ShowTaskpane">
        <SourceLocation resid="hSourceLocation2"/>
    </Action>
    <Rule xsi:type="ItemHasAttachment" /> <-------------------- won't work
</Control>

A: The Rule element is only applicable to the CustomPane extension point and can't be defined in a Control element: https://dev.office.com/docs/add-ins/outlook/manifests/define-add-in-commands.  See also: https://dev.office.com/docs/add-ins/outlook/manifests/activation-rules


text:
Q: Does *BSD have the ability to encrypt a system partition with full disk encryption? Does FreeBSD, NetBSD, or OpenBSD have an encryption feature like Linux's dm-crypt?
And will it work for a system partition?

A: Indeed, as jdeBP says, this is documented in the handbook:
https://www.freebsd.org/doc/handbook/disks-encrypting.html
And although gbde is mentioned first, geli is generally more recommended. The installer actually will even help you set this up, there's a prompt for it.

A: OpenBSD has softraid(4), which allows you to use an encrypting discipline on a block device. Setting up disk encryption is not supported by the installer (as of September 2020), but can be configured by hand during an operating system installation. OpenBSD FAQ has a section dedicated to Full Disk Encryption which can be used as a reference for setting up disk or partition encryption.

A: NetBSD can indeed be run with an encrypted root filesystem, via a kernel module called cdgroot (though it still needs an unencrypted partition to boot from).
See the following for some comments on the concept and configuration:
NetBSD Root Filesystem Encryption


text:
Q: Using .htaccess mod_rewrite to insert a script name at the start of the path I have a problem with an htaccess url rewrite, that works fine at localhost but doesn't work on my hosting (anhosting).
I need to redirect all the request to my index.php page.
Here's an example: i would to redirect
http://mydomain.com/this/is/a/page

to
http://mydomain.com/index.php/this/is/a/page

This is my .htaccess:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

on the hosting i always get redirected to the index.php file, but the $1 parameters results always blank, so my custom framework cannot handle the request correctly.
What could be the problem?
Sorry for my bad english, i hope i have been clear enough...

A: It sounds like the remote server has AcceptPathInfo turned off. That setting is responsible for the effect you are using.
Try a manual request to
http://mydomain.com/index.php/this/is/a/page

if this/is/a/page vanishes, then that option is definitely turned off, and you can't use this method on the remote server (unless you can change its configuration).
In that case, I would change the rule to
RewriteRule ^(.*)$ index.php?path=$1 [L,QSA]

and change the framework to listen for $_GET["path"] instead of $_SERVER["PATH_INFO"].

A: Did you enable the mod-rewrite in the Apache configuration files.
sudo nano /etc/apache2/sites-available/default
sudo nano /etc/apache2/sites-enabled/000-default

Here's a site that shows you a few ways. I have done my mod-rewrites by modifying the above files but I think there are other ways.
http://drupal.org/node/134439


text:
Q: Best practice to create Python class with hardcoded dictionary I am new to Python. I have a function like below which returns a dictionary.
def get_my_class_object(self, input):
    return {
            "foo": {"test": {}}, // this is hard-coded
            "var": "FIRST" // real code computes var using the input
        }

I'd like to define a class for the return type so I can enable the type using Pyre.
What is the best practice to create a python class for above structure?
I tried below class and changed the function signature to return MyClassObject.
class MyClassObject(NamedTuple):
    foo: Dict
    var: str

def get_my_class_object(self, input) -> MyClassObject:
// create MyClassObject from input and return the object

But Dict is not allowed by Pyre as it is too generic. I can't change "foo": {"test": {}} due to backward compatibility.

A: There are a few things you might be able to do in this case. Without any context, it is quite hard to know what might be best for you.
But, using a more specific type-hint might work:
Here, instead of a NamedTuple, it might also be best to use a DataClass
@dataclass
class MyData:
    foo: dict[str, dict]
    var: str

Here, foo is typed as dict[str, dict] which may be specific enough for Pyre. If you know what the type of the "innermost" dictionary should be, you can type-hint that here too. For example, let's say the innermost dictionary will eventually be used to map a string to an int, you could type-hint it as:
dict[str, dict[str, int]]

It may also be more clear to use type aliases. Check out the python documentation for more info, but that could look something like:
# Defining type aliases
TestData = dict[str, int]  # Here I'm assuming this inner dictionary maps strings to ints
Test = dict[str, TestData]

@dataclass
class MyData:
    foo: Test  # here we can just use the alias to make the code cleaner
    var: str

You might need to change the names of these to better fit your purpose.
Also note, I'm using python 3.9+ syntax for type-hinting, if you are using a lower version, you'll need to import the Dict type from the typing module.


text:
Q: Access Secure variable from unit test on Azure pipeline maven build I'm trying to create a Azure DevOps pipeline for one of Java application using maven and in the unit test I have 2 secrets which needs to access the value from environment variables.
String key = System.getenv().get("MY_KEY");
String secret = System.getenv().get("MY_SECRET");

I have added 2 values under pipeline variables from the browser and mark them as "Keep this value secret" so that values will be kept as secret.

In the pipeline I have added required variables and substitute the value with configured variables.
variables:
  MY_KEY: $(MY_KEY_VAL)
  MY_SECRET: $(MY_SECRET_VAL)

However, when I run the build pipeline, it fails with unit test due to null values on both 'key' and 'secret' values.
How can I fix this? Am I doing anything wrong on the configurations?
UPDATE
As Ben mentioned below, it is not possible to set environment variable on hosted agents. In order to run all unit tests during the build pipeline and still keep the key & secret secure, I have modified the unit tests to read the key and secret from a file on the project root. Instead adding the file containing key & secret to git repo, it was added as a Secure File on the pipeline library and was given permission to access by pipeline.
On the Pipeline I was able to download the secure file using 'DownloadSecureFile' task.
- task: DownloadSecureFile@1
  displayName: Download API secrets
  name: configfile
  inputs:
    secureFile: 'service_api_keys'

Moved the file to project root using bash.
- bash: mv $(configfile.secureFilePath) ./

Run the build the process which will read the secrets on unit test execution.

A: System.getenv() reads the system environment variables of the machine which runs the java code. And the variables defined in pipeline is in agent scope not machine scope.Maybe that is why the unit test cannot get the variables.
There is probably no direct way to achieve this. As Ben Smith mentioned, you can refactor your code to get the key/secret from a json files and add a Set Json Property task to update the json files with the variables you defined in the pipeline before maven task run the unit test. Check here for detailed usage of this task.
As another workaround,You can run your pipeline on a self-hosted linux agent, and try to add a bash script task to set the environment variables for the your linux agent(I tested and found set environment variables is not workable for shared-hosted agent). Check here for how to set environment variable for linux.
Check here to instructions to create a self-hosted linux agent.
Hope you will find above helpful!

A: You need to substitute the values within your Java files. The variable substitution you have detailed above i.e.
variables:
  MY_KEY: $(MY_KEY_VAL)
  MY_SECRET: $(MY_SECRET_VAL)

will only replace the values in your pipeline YAML file.
You can substitute your variables in your Java files using the "Replace Tokens" task e.g.
- task: replacetokens@3
    inputs:
      targetFiles: "yourJavaFile.java"
      encoding: "auto"
      writeBOM: true
      verbosity: "detailed"
      actionOnMissing: "warn"
      keepToken: false
      tokenPrefix: "#{"
      tokenSuffix: "}#"
    displayName: Perform variable substitution in java file

And in your java file you would write the variables to be replaced as e.g.
String key = System.getenv().get("#{MY_KEY}#");
String secret = System.getenv().get("#{MY_SECRET}#");


text:
Q: Spotipy - Adding songs to a new playlist I am pulling songs from one playlist to sort them by year and then place the songs in a new playlist based on the year. Here is my code:
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
from spotipy.oauth2 import SpotifyOAuth
import json

scope = 'playlist-modify-private'

# grab credentials for API authorization
credentials = json.load(open('Authorization.json'))
client_id = credentials['client_id']
client_secret = credentials['client_secret']
redirect_uri = credentials['redirect_uri']
username = credentials['username']
playlists = json.load(open('Playlists.json'))

# Construct Spotify API to read in data
client_credentials_manager = SpotifyClientCredentials(client_id=client_id,client_secret=client_secret)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

# Grab tracks from a playlist
def get_playlist_tracks(username,playlist_id):
    results = sp.user_playlist_tracks(username,playlist_id)
    tracks = results['items']
    while results['next']:
        results = sp.next(results)
        tracks.extend(results['items'])
    return tracks

# list of songs which will be added to each respective playlist
songs = {'20' + str(yy) : [] for yy in range(14,23)}

# aggregate songs by year
for item in playlist_tracks_data:
    added_stamp = item['added_at']
    added_year = added_stamp[:4]
    track_info = item['track']
    track_uri = track_info['uri']

    if added_year == '2014':
        songs['2014'].append(track_uri)
    elif added_year == '2015':
        songs['2015'].append(track_uri)
    elif added_year == '2016':
        songs['2016'].append(track_uri)
    elif added_year == '2017':
        songs['2017'].append(track_uri)
    elif added_year == '2018':
        songs['2018'].append(track_uri)
    elif added_year == '2019':
        songs['2019'].append(track_uri)
    elif added_year == '2020':
        songs['2020'].append(track_uri)
    elif added_year == '2021':
        songs['2021'].append(track_uri)
    elif added_year == '2022':
        songs['2022'].append(track_uri)
    else:
        print("Unidentified year")

# Construct Spotify API to write to new playlists
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, username=username, scope=scope))

# this part of the code where I add the playlist goes on forever
for idx, year in enumerate(songs.keys()):
        uri = playlists[idx]['uri']
        playlist_id = uri.split(':')[2]
        sp.playlist_add_items(playlist_id, songs[year])

The problem I am facing is that the code runs forever when attempting to add songs to my playlist. Whenever I ran the code, I authorized the access permissions to my account so I do not believe this is the issue (otherwise the code should throw an error instead of running forever).The credentials appear to be correct as I am able to read the songs from playlist with no problems. The songs dictionary is nonempty and contains the correct URI codes to each song. My guess is that the issue lies in the Authorization Code Flow as my understanding of this process is minimal.


text:
Q: create new MYSQL database from R script I am trying to create new MYSQL database from R script to save the new resulted tables from sampling function on it. The function takes the connection information from user, do the sampling on the specified table, then return the table after sampling.
a snapshot of my function is shown below to illustrate the idea more clearly.
`
SQLRowRandomSampling <- function(username,passwords,databaseName,TableName,
                                 SamplingSize){
  #' establish the connection with the selected database
  ConnectedDb <- dbConnect(RMariaDB::MariaDB(), user=username,
                           password=passwords, dbname=databaseName,
                           host='localhost')
  #' checking if the entered table exist in the selected database
  x <- tryCatch({
      dbframe <- dbReadTable(ConnectedDb,TableName)},
    error = function(e){
      #' if not stop the function
      stop('Table does not exist! Try again please.')
      }
    )
  #' get number of rows in the selected table
actualRowNumber <- nrow(dbframe)
  # check if the entered sampling size is valid
if(SamplingSize<1){
    stop("Entered sampling size must be a valid number")}
  else if (SamplingSize >=  actualRowNumber){
    stop("You should eneter a sampling size that is less than the rows number
         of the selected table")}

   # start row random sampling
  RandomRowSmpling<- sample_n(dbframe, SamplingSize)
    # return the result
return(RandomRowSmpling)}

the returned table "RandomRowSmpling" should be saved in new created MYSQL database to be used later on.
I know how to create new SQLite database as follow:
 #' create new database named Sampling_Database
    ConnectedCreatedDb <- dbConnect(drv = RSQLite::SQLite(),
                             dbname= 'Sampling_Database')

However, for my project proposes it should be MYSQL not SQLite. any idea how to create new MYSQL database to save the resulted table on it ?
Also, i know i can add the created table to my original MYSQL database by using the following command:
dbWriteTable(conn = ConnectedDb, name = "RandomRowSmpling"
                            , value = RandomRowSmpling)

But, unfortunately I can not alter the given database.
Thank you for any help !

A: Temporary Tables
Two methods:

*

*Manual creation of the temp table, requires knowing all of the fields and field-types:
DBI::dbExecute(maria, "create temporary table mytemp (myint int, mychr varchar(16))")
# [1] 0
DBI::dbWriteTable(maria, "mytemp", data.frame(myint=1L, mychr="hello world"), append = TRUE)
DBI::dbGetQuery(maria, "select * from mytemp")
#   myint       mychr
# 1     1 hello world

*Use temporary=TRUE in the table creation:
DBI::dbWriteTable(maria, "mytemp2", data.frame(myint2=2L, mychr2="hello world again"), create=TRUE, temporary=TRUE)
DBI::dbGetQuery(maria, "select * from mytemp2")
#   myint2            mychr2
# 1      2 hello world again

For both of these, this is a temporary table: it is dropped when the current connection is dropped.
DBI::dbDisconnect(maria)
maria <- DBI::dbConnect(RMariaDB::MariaDB(), user="example-user", password="my_cool_secret", host="localhost", db = "mydb")
DBI::dbGetQuery(maria, "select * from mytemp")
# Error: Table 'mydb.mytemp' doesn't exist [1146]
DBI::dbGetQuery(maria, "select * from mytemp2")
# Error: Table 'mydb.mytemp2' doesn't exist [1146]

Reproducibility: I'm using docker with mariadb. You won't need this, since you already have an instance of MariaDB up and running somewhere.
From the shell:
$ docker run -p 3306:3306 --detach  --name some-mariadb --env MARIADB_USER=example-user --env MARIADB_PASSWORD=my_cool_secret --env MARIADB_ROOT_
PASSWORD=my-secret-pw  mariadb:latest
3babf14f7a8f2010e844a5244475d69ac4dd0856017d190bf531c5187c3e178f

$ docker exec -it  some-mariadb mariadb  -uroot -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 6
Server version: 10.9.3-MariaDB-1:10.9.3+maria~ubu2204 mariadb.org binary distribution

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> create database mydb;
Query OK, 1 row affected (0.001 sec)

MariaDB [(none)]> grant all on mydb.* to 'example-user'@'%';
Query OK, 0 rows affected (0.002 sec)

In R, the connect can be formed with:
maria <- DBI::dbConnect(RMariaDB::MariaDB(), user="example_user", password="my_cool_secret", host="localhost", db="mydb")


text:
Q: pointCounts error using MKOverlay I have problem with custom overlay. The problem is I cant identify error code, its occurs randomly
Maybe someone will be able to help me basic on this stack. What is pointCount?
2012-07-30 02:02:01.187 MyApp[454:8107] -[MyRegionOverlay pointCount]: unrecognized selector sent to instance 0x5d7dab0
2012-07-30 02:02:01.190 MyApp[454:8107] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MyRegionOverlay pointCount]: unrecognized selector sent to instance 0x5d7dab0'
*** Call stack at first throw:
(
    0   CoreFoundation                      0x016c15a9 __exceptionPreprocess + 185
    1   libobjc.A.dylib                     0x01815313 objc_exception_throw + 44
    2   CoreFoundation                      0x016c30bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
    3   CoreFoundation                      0x01632966 ___forwarding___ + 966
    4   CoreFoundation                      0x01632522 _CF_forwarding_prep_0 + 50
    5   MapKit                              0x008186c4 _ZL20createPathForPolygonP9MKPolygon10MKMapPoint + 55
    6   MapKit                              0x00818817 -[MKPolygonView createPath] + 95
    7   MapKit                              0x0081d715 -[MKOverlayPathView drawMapRect:zoomScale:inContext:] + 79
    8   MapKit                              0x00838328 -[MKOverlayClusterView drawLayer:inContext:] + 1450
    9   QuartzCore                          0x00472b5e -[CALayer drawInContext:] + 143
    10  QuartzCore                          0x00489283 _ZL18tiled_layer_renderP16_CAImageProviderjjjjPv + 1648
    11  QuartzCore                          0x003d1eb2 _ZL21CAImageProviderThreadPjb + 475
    12  libSystem.B.dylib                   0x91bce781 _pthread_wqthread + 390
    13  libSystem.B.dylib                   0x91bce5c6 start_wqthread + 30
)

A: What the error means is that there is an MKPolygonView in your overlay. The polygon property of the MKPolygonView is set to an instance of MyRegionOverlay. Unfortunately MyRegionOverlay is not a subclass of MKPolygon as it is supposed to be. So when the pointCount message is sent to the MyRegionOverlay you get a run time error "unrecognized selector" since MyRegionOverlay apparently does not respond to pointCount.


text:
Q: What does incompatible pointer to integer mean? I want to have a function that creates an array contain multiplication values of int num, and another function that prints the array out. However, I can't seen to figure out these errors.
My code:
.c file
#include "multiplication.h"
#include <stdio.h>
int main(){
int arr=multiplication(4);
printArray(4,arr);

}

int multiplication(int num){
 /* initialize array and build*/
    int arr[num][num];
    for(int i=0; i<num;i++){
        printf("row number: %d ",i);
         for(int j=0;j<num;j++){
             printf("column number: %d", j);
            arr[i][j]= (i+1)*(j+1);
         }
    }
    return arr;
    }

    void printArray(int num,int arr[num][num]){

    int i;
    for(i=0;i<num;i++){
        for(int j=0;j<num;j++){
            printf("%d ",arr[i][j]);
        }

    }
    }

.h file:
int multiplication(int num);
void printArray(int num,int arr[num][num]);

The errors:
multiplication.c:6:14: warning: incompatible integer to pointer conversion passing 'int' to parameter of type 'int (*)[*]' [-Wint-conversion]
printArray(4,arr);
             ^~~
./multiplication.h:4:29: note: passing argument to parameter 'arr' here
void printArray(int num,int arr[num][num]);
                            ^
multiplication.c:22:12: warning: incompatible pointer to integer conversion returning 'int [num][num]' from a function with result type 'int' [-Wint-conversion]
    return arr;
           ^~~
multiplication.c:22:12: warning: address of stack memory associated with local variable 'arr' returned [-Wreturn-stack-address]
    return arr;
           ^~~

                    ^
multiplication.c:25:33: note: declared here
    void printArray(int num,int arr[num][num]){
                            ^

A: Your code is one big Undefined Behaviour.
int mulitpication(int num)

*

*You want to return a pointer to int. But it is declared int not int *. When you try to return the pointer, the compiler warns you about incompatible conversion

*Even if you declare it as returning pointer you return a pointer to an automatic variable which ceases to exist when the function returns (warning about stack variable).

void printArray(int num,int arr[num][num])

*

*sizeof returns the size of the pointer not the size of the array

main function.

*

*arr is a single integer and you try to pass to print function. You need to make it int *

A: This is what I regard as the code you need:
#include <stdio.h>

static void multiplication(int num, int arr[num][num]);
static void printArray(int num, int arr[num][num]);

int main(void)
{
    int arr[4][4];
    multiplication(4, arr);
    printArray(4, arr);

    return 0;
}

static void multiplication(int num, int arr[num][num])
{
    for (int i = 0; i < num; i++)
    {
        //printf("row number: %d ", i);
        for (int j = 0; j < num; j++)
        {
            //printf("column number: %d", j);
            arr[i][j] = (i + 1) * (j + 1);
            printf("arr[%d][%d] = %d\n", i, j, arr[i][j]);
        }
    }
}

static void printArray(int num, int arr[num][num])
{
    int i;
    for (i = 0; i < num; i++)
    {
        for (int j = 0; j < num; j++)
        {
            printf("%d ", arr[i][j]);
        }
        putchar('\n');
    }
}

The output from running that is:
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[0][3] = 4
arr[1][0] = 2
arr[1][1] = 4
arr[1][2] = 6
arr[1][3] = 8
arr[2][0] = 3
arr[2][1] = 6
arr[2][2] = 9
arr[2][3] = 12
arr[3][0] = 4
arr[3][1] = 8
arr[3][2] = 12
arr[3][3] = 16
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16

You can ring the changes in main(), for example getting a size from the user and creating an array of that size and passing the info to the functions:
int size;
if (scanf("%d", &size) == 1 && size > 0 && size < 100)
{
    int other[size][size];
    multiplication(size, other);
    printArray(size, other);
}


text:
Q: what is the best way to initialize my global data in shared library? I have a single class which does all the required initialization.
currently i have declared a global object of this class type, which is being instantiated on library load.
I've seen other ways, like delaring
BOOL APIENTRY DllMain

entry point for the shared library, and does the actual initialization on process attach.
does this differ from letting the implicit global initialization to its job? which way is better?

A: This is what happens during C++ DLL startup:

*

*System calls DLL's entry point, generated by you compiler

*Entry point calls DllMainCRTStartup (name may differ), which initializes C/C++ runtimes and instantiates all global objects.

*DllMainCRTStartup then calls user-defined DllMain.

I personally prefer DllMain, because this way I can explicitly control order of initialization. When you use global objects in different compilation units, they will be initialized in random order which may bring some unexpected surprises 10 minutes before the deadline.
DllMain also let's you do per-thread initialization, which you can not achieve with global objects. However, it is not portable to other platforms.
P.S. You do NOT need mutex in DllMain, as all calls to it are already serialized under process-global critical section. I.e. it is guaranteed two threads will not enter it at the same time for any purpose. This is also the reason why you should not communicate with other threads, load other libraries etc. from this function; see MSDN article for explanation.

A: A couple of things that should never be done from DllMain:

*

*Call LoadLibrary or LoadLibraryEx (either directly or indirectly). This can cause a deadlock or a crash.

*Synchronize with other threads. This can cause a deadlock.

*Acquire a synchronization object that is owned by code that is waiting to acquire the loader lock. This can cause a deadlock.

*Initialize COM threads by using CoInitializeEx. Under certain conditions, this function can call LoadLibraryEx.

*Call the registry functions. These functions are implemented in Advapi32.dll. If Advapi32.dll is not initialized before your DLL, the DLL can access uninitialized memory and cause the process to crash.

*Call CreateProces. Creating a process can load another DLL.

*Call ExitThread. Exiting a thread during DLL detach can cause the loader lock to be acquired again, causing a deadlock or a crash.

*Call CreateThread. Creating a thread can work if you do not synchronize with other threads, but it is risky.

*Create a named pipe or other named object (Windows 2000 only). In Windows 2000, named objects are provided by the Terminal Services DLL. If this DLL is not initialized, call to the DLL can cause the process to crash.

*Use the memory management function from the dynamic C Run-Time (CRT). If the CRT DLL is not initialized, calls to these functions can cause the process to crash.

*Call functions in User32.dll or Gdi32.dll. Some functions load another DLL, which may not be initialized.

*Use managed code.

A: You need a static boolean initialization variable and a mutex.  Statically initialize "initialized" to 0.  In your DllMain(), make a call to CreateMutex().  Use bInitialOwner=0 and a unique name for lpName that's unique to your application.  Then use WaitForSingleObject() to wait for the mutex.  Check if initialized is non-zero.  If not, do your initialization, and then set initialized to 1.  If initialized is non-zero, do nothing.  Finally, release the mutex using ReleaseMutex() and close it using CloseHandle().
Here's some pseudo-code, with error and exception handling omitted:
initialized = 0;

DllMain()
{
    mutex = CreateMutex(..., 0, "some-unique-name");
    result = WaitForSingleObject(handle, ...);
    if (result == WAIT_OBJECT_0) {
        if (!initialized) {
            // initialization goes here
            initialized = 1;
        }
    }
    ReleaseMutex(mutex);
    CloseHandle(mutex);
}

A: hi i would recommend u to prefer a signleton class where u can only create a single object of a class and use it. Sigleton class can be created with a private constructor. Now suppose ur class A is a singleton class its object can be used in a constructor of each Class which u want to initialize. Please give us some sample code so other may help u better.


text:
Q: I'm getting an error message while trying to run serve -s build I was working on my first react project and now trying to deploy it in Netlify so I ran npm install -g serve then serve -s build after running npm run build
but I'm getting the following error message while I ran serve -s build
what is the problem here
serve : File C:\Users\Akhlak Hossain Jim\AppData\Roaming\npm\serve.ps1 cannot be loaded because running scripts is disabled on this system. For more
information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ serve -s build
+ ~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

A: Now your PowerShell is preventing you from executing "possibly" harmful scripts, therefore, you have to change your execution policy, simply type this:
Set-ExecutionPolicy Unrestricted
May be you will need to start your terminal as an administrator in order to do this

A: I faced the same problem while trying to serve my react app using terminal of visual code. I just switched from the terminal of visual code to command prompt and it worked. But you have to install serve package in that folder(where your app currently resides) running command "npm install -g serve" first then run "serve -s build".


text:
Q: elasticsearch group by inside group by I have a table which contains 2 IDs. The first one is userid and the second one dealid. I want to have a group by inside a group by. I tried doing this:
"query": {"match_all": {}},
  "aggs": {
    "group_by_userid": {
      "terms": {
        "field": "userid"
      }
    },
    "aggs": {
      "group_by_dealid": {
        "terms": {
          "field": "dealid"
        }
      }
    }
  }

This doesn't work, because group_by_dealid isn't using group_by_userid. The output I need is that each user has a array of all the Deals he entered. The User can enter the same Deal multiple times.
Is there a way of doing this?


text:
Q: How to Export Crystal Report to Excel using CrystalReport Object and TableAdapter? I am using TableAdapter method of dataset file to get data from database,
and Crysral report object to create report instead of CrystalReport file itself.
(Basically I don't want to use Physical CrystalReport File)
Here, sample of my Code
DataTable dtRpt = new DataTable();
CrystalReportViewer crv = new CrystalReportViewer();
using (uspRptComplainReceiptTableAdapter _adpSales = new uspRptComplainReceiptTableAdapter())
{
    dtRpt = _adpSales.GetData(Convert.ToByte(bolObj.CompId), bolObj.ComplainId) as DataTable;
    if (dtRpt != null && dtRpt.Rows.Count > 0)
    {
         crptComplainReceipt rpt1 = new crptComplainReceipt();
         rpt1.SetDataSource(dtRpt);
         crv.ReportSource = rpt1;
         crv.PrintReport();
    }
    else
         MessageBox.Show("Record not found.", "Report", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

Now, I want to Export my report to Excel File using this method (CrystalReport Object).
Please, help me for this problem...

A: Try This:
 CrystalDecisions.CrystalReports.Engine.ReportClass rpt=new ReportClass();
 rpt.ExportToDisk(ExportFormatType.Excel, "FilePath");

BTW do not forget to add the references.


text:
Q: rails4 migration for a column of two dimensional arrays to postgres What is the correct syntax in a migration to create a column capable of storing two dimensional arrays in postgres with rails4? I know how to do a single dimensional column
t.float :vami, array: true, default: []

but not sure how to do multidimensional. Some of the tutorials on using arrays seem to suggest it's possible, but they don't outline how to specify it in the migration. Thanks


text:
Q: AJAX read JSON data from twitter search not work I use jquery to retrieve search result from twitter but it does not work, can you address mistake in my code?
Here is form search:
Enter keyword: <input type="text" id="keyword" name="keyword" size="50" autocomplete="off"/>
    <input type="button" name="btnsearch" id="btnsearch" value=" Search " />

and here is jquery code:
$(document).ready(
        function(){
            $("#keyword").focus();
            $("#btnsearch").click(function(){
                var keyword = $("#keyword").val();
                if(keyword == null || keyword == "") return;
                $("#results").html("");
                $.ajax({
                    url:'http://search.twitter.com/search.json?q='+keyword+'&rpp=50',
                    dataType:'json',
                    success:function(json){
                        $("#results").remove();
                        alert("Successfull");
                    },
                    error:function(){
                        alert("cant search");
                    }
                });
            });
        }
    );

I just test if it work or not, and when I press Search button, it alerts "Cant search"!
Any help?

A: This is because you are not using dataType: 'jsonp'; which is a code to be added when you are accessing cross domain data
below is the working code (i have tried it)
$(document).ready(
function(){
$("#keyword").focus();
$("#btnsearch").click(function(){
var keyword = $("#keyword").val();
if(keyword == null || keyword == "") return;
$("#results").html("");
    $.ajax({
    type: 'GET',
    dataType: 'jsonp',
    contentType: "application/json; charset=utf-8",
    url:'http://search.twitter.com/search.json',
    data: 'q='+keyword+'&rpp=50',
    success:function(json){
    $("#results").remove();
    alert("Successfull");
    },
error:function(){
alert("cant search");
}
});
});
}
);

A: Demo :  http://jsfiddle.net/cAVsS/1/
Callback should be JSONP:  https://dev.twitter.com/docs/api/1/get/search

A: It seems that you are trying to access Twitter API from your own webpage. Unfortunately, this kind of access is not allowed by browser for security reason.
You cannot access an API on another server with Ajax/JSON.
For example, assume your web page is hosting on www.myserver.com.  You can access APIs ONLY if they come from www.myserver.com. You cannot access APIs that come from twitter.
This is called "same origin policy".
The solution is creating a proxy on your server with a server-side language such as PHP/Python/Perl. Just google "ajax proxy" for some solutions.

A: Use the following jQuery code. It does work for me in production
$.getJSON('http://search.twitter.com/search.json?q=' + keyword + '_de&callback=?', function(json) {
    alert(JSON.stringify(json));
});

You have to specify the &callback=? parameter in order to let jQuery consume the JSON.
Maybe just adding the &callback=? will help in your example, but above is how I did it.


text:
Q: desktop ruby file run a script that connects with a rails application I've use irb and console to write lots of scripts and have switched to writing single .rb files in textmate and then command+r to run it. This is really cool because I can keep all my code in one spot and just hit command+r.
So now I want it to get data from a rails app which of course has a sqlite3 database. How can I do this?

A: Rails includes a console, which is an IRB session pre-wired to load the models and make your DB connection, among other things. It makes it easy to do adhoc what-if's without having to manually require the needed Rails modules and perform the DB connection.
Also, Rails has a "script runner" called, amazingly enough, rails runner. It lets you run code within the context of your Rails app, without having to add the routines inside the controller or a model. It's great for utility scripts that shouldn't be part of the main app stack, but still need to access to the models and database. See rails runner -h from your Rails' app directory.
SO has some other questions about runner that might help.

A: I think the easiest way to access the database from outside Rails is to use the sqlite3-ruby gem.  Find documentation here.
Here is some example code copied from the link above on GitHub:
require "sqlite3"

# Open a database
db = SQLite3::Database.new "test.db"

# Find a few rows
db.execute( "select * from numbers" ) do |row|
  p row
end


text:
Q: sed capture everything until pattern using variable as string I have the a bunch of text that is represented similar to xml.
<File>
    <abc1>
        <Hex>
            <item>
                <data>AB CD 34 43</data>
            </item>
         </Hex>
    </abc1>
</File>

I use an application (ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, not stripped) which takes a file as an argument and decodes it.
I can successfully run:
./application /tmp/file and it decodes correctly

I can also capture everything up to and including the line that contains the hex below (this works well, but of course, cannot enter in data everything into file and then run it - need to do it with a variable dynamically:
./application /tmp/file | sed '/AB CD 34 43/q'

But what I am unable to do is pass a variable instead of the hex string
./application /tmp/file | sed '/`echo -n "$value"`/q'

I don't mind what I use, sed/awk/grep.
My main aim is to extract everything up to the hex address then run another command to copy the same in the other direction, that I am left with mostly one complete "frame" if you will. Then I can just tail it for the frame size so it contains just one complete frame.

A: ./application /tmp/file | sed "/$value/q"

Research quoting in shell and difference between single and double quotes.
For parsing XML files use XML aware tools, like xmlstarlet. Do not parse XML with regex.
Do not use ` backticks - use $(...) instead.

A: Your command substitution (backticks) is inside hard (single) quotes ('), so the shell won't expand it. You don't need echo, either, just the variable itself. You must still use soft (double) quotes ("), for the variable to be expanded.
hex='AB CD 34 43'

./application /tmp/file | sed "/$hex/q"

When using shell variables in sed addresses, just remember that it's a regular expression, not a string, and sed doesn't have an option like grep's -F (nor would such an option help with sed's //{}; etc - the only option is to escape, beforehand). For hex it's fine, as it's only alphanumeric and space characters.
Also, as you said, sed will print up to the line containing the pattern. So any text after the pattern, on the same line, will be included. Perhaps this is fine for your requirements, but I'll include a few methods of printing up to (and including) the pattern exactly, but no further.
sed
sed -E "/$hex/{s/($hex)(.*)/\1/;q}"

awk
awk -v RS="$hex" '{print($0 RS); exit}'

Note: POSIX says RS should be a single character, but many implementations accept a regex*
shell
decoded=$(./application /tmp/file)
truncated=${decoded%%"$hex"*}
echo "$truncated"

This copies all the data to memory first, and can be slow for very large data, but fast for small data, b/c pure shell. Quoting $hex treats it as a string instead of a pattern.
* From https://www.gnu.org/software/gawk/manual/html_node/gawk-split-records.html

RS as a regular expression [is a gawk extension]

mawk has allowed RS to be a regexp for decades. As of October, 2019, BWK awk also supports it.

If pattern $hex occurs more than once, these all print up to the first occurrence of $hex (including it), but can be easily modified to print to up to the last occurrence.
Finally, when doing stuff like this, remember that the hexdump utility can use printf like format strings to control output format. Eg hexdump -ve '1/1 "%02x "' mybinfile; echo to dump a space delimited list of bytes in mybinfile, in hex.


text:
Q: Multiple Projects on a single VCS root causing pending I've got 2 entirely separate projects that both rely on the the same base project and shared nuget packages. For that reason I have little choice but to have a single VCS root that will ensure I have all the files needed.
I've managed to configure each project in TeamCity to work with the needed csproj files and trigger correctly. However if I commit something for Project A that Project B doesn't care about it will still show as 'Pending(x)' even though they will never get triggered with that project's configuration.
It goes away when I commit something that Project B -does- care about, but it is annoying to look at. So is there a way to configure it to not even look at changes in files from Project A?

This is the trigger for project A:
-:root=SVN:.
+:Web/**
+:Library/**

And this is the trigger for project B:
-:root=SVN:.
+:Client/**
+:Library/**

I'm using Subversion for my VC if that would make any difference to help in configuring.

A: Have a single VCS root, but configure checkout rules instead of VCS triggers. If you edit the build configuration and go under VCS settings select "view checkout rules". For the first project enter:
+:Web/**
+:Library/**

This will then mean the build doesn't know anything about /Client and can't tell you changes are pending. If you make this change, you no longer need to restrict the VCS trigger as it will be pre-filtered to only look at these folders.
You will need to make a similar change to the second build configuration to achieve the same.


text:
Q: Is closing ImageInputStream enough, if I do not use readers directly? I read BufferedImage from Internet Connection, using ImageIntputStream. I close ImageIntputStream creating it in the try header.
try(ImageIntputStream is = new ImageIntputStream(connection)) {
    BufferedImage img = ImageIO.read(is);
} catch(IOException readException) {
    readException.printStackTrace();
}

I thought, it is enough for safety. But reading posts about work with readers/writers, such as here or here or here, I see, that I should flush something, dispose of something, close something, and put null to something, and these things are sometimes different, If I use reader separately. Seeing such insistent destroying of the reader and stream or anything that is connected to them, I feel ashamed of my weak and primitive measures for safety.
If I do not use this ImageReader, what else have I to flush, dispose, null, close, shut down, shoot, kill, annihilate, degrade, silence, maim or offend in some other way after I got my image?

A:
I feel ashamed of my weak and primitive measures for safety.

TLDR;
Don't be. You are good.

Long version:
You are using the try-with-resources statement, that automatically invokes close() on the resource in an "implicit" finally after the try is done. The ImageInputStream is the only resource you create, thus it's the only resource that is your responsibility to dispose of.
The ImageIO.read method will handle internal housekeeping, like disposing the ImageReader instances etc. itself. This is not your responsibility (you don't even have access to these objects, so you couldn't even if you really wanted to).
To release the memory of the returned BufferedImage it's enough to just assign the null reference or let it pass out of scope. The garbage collector will clean things up for you, as with any normal Java object. You may also invoke flush() to release native/display memory associated with the image, if any. It doesn't hurt. If you don't, the memory will be freed anyway, so don't worry.

Longer version:
The posts you refer to in your question, is mostly unrelated to your code. Two of them are about writing images, using an ImageWriter directly. In this case, you should always close() the ImageOutputStream and dispose() the ImageWriter instance after use.
The last (ok, the middle one) of the posts you refer to, is about drawing to a BufferedImage using a Graphics context. In this case, you should always dispose() the Graphics/Graphics2D after use.
It is also possible to read images using an ImageReader directly (similar to the writing examples). In this case, you should always close() the ImageInputStream and dispose() the ImageReader instance.
These are, however, different use cases from what you are doing in the code sample in the question. I'm just adding it here for completeness.
Finally, a word of advice: Don't let yourself be confused by reading random Google results. If in doubt, go to the source. Either literally, by reading the Java libraries source code, or read the API doc. ;-)

Further reading:

*

*Java2D tutorial, Lesson: Working with Images

*ImageIO.read API doc

*BufferedImage API doc

*Image.flush API doc

A: You do not need to flush any reader or whatever that wraps an input stream.  Flushing is for output.
However, closing the reader is safe, and (IMO) clean.  And it does guard against the hypothetical possibility that some releasable resources are held at the reader level; e.g. if you or someone else had reason to change your application to use a different reader class.
For example, a FileCacheImageInputStream will cache the input stream in a temporary file.  The cache file is only deleted when the FileCacheImageInputStream is closed.  So in that case, just closing the base stream may leak files and/or file descriptors.


text:
Q: adding a drop pin button I'm creating a button that will place a pin on users current location. But when ever I press it, instead is is placed in the middle of the global map, around Africa, I believe this is because in the original tutorial where I got this from, they created a void method with "didUpdateUserLocation" but I can figure a way to add this to the IBAction , here's what am working with. Has anyone ever had trouble with this?
This is the zooming in code but notice the didUpdateUserLocation down there vvvv
-(void)mapView: (MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
     MKCoordinate region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate,
     800,800);
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:NO];
}

`
Now here is the IBAction that when tapped, drops pin around Africa or the center of the global map. I figured it's because it is missing the didUpdateUserLocation
-(IBAction)addAnnotation;
{
   MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate,
     800,800);
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:NO];

   MKPointAnnotation *point = [[MKPointAnnotation Alloc] init];
   point.coordinate = myLocation.coordinate;
   point.title = @"Test";
   point.subtitle = @"Text";
   [self.mapView addAnnotation:point];
}

So if anybody would know how to, what i figure is the solution, didUpdateUserLocation to the IBAction, please let me know, appreciate it!

A: Try this...
- (void)mapView:(MKMapView *)aMapView didUpdateUserLocation:(MKUserLocation *)aUserLocation
{
    MKCoordinateRegion region;

    CLLocationCoordinate2D location;
    location.latitude = aUserLocation.coordinate.latitude;
    location.longitude = aUserLocation.coordinate.longitude;

    region.span = aMapView.region.span;
    region.center = location;
    [self.objMapView setRegion:region animated:FALSE];

    showCurrentLoc = FALSE;
}

-(IBAction)addAnnotation;
{
    MKCoordinateRegion region;
    region.span = self.mapView.region.span;
    region.center = location;
    [self.mapView setRegion:region animated:FALSE];

    MKPointAnnotation *point = [[MKPointAnnotation Alloc] init];
    point.coordinate = self.mapView.userLocation.coordinate;
    point.title = @"Test";
    point.subtitle = @"Text";
    [self.mapView addAnnotation:point];
}


text:
Q: How can I select / insert / update data from another table into a new table I have a table for categories like this - nid is an identity column:
TB_Categories

nid
name

1
Brochure

2
stamp

A specific number can be ordered for each category, such as:
id is identity
TB_numbercategories

id
nid
number

1
1
10

2
1
50

3
1
100

4
2
100

5
2
500

6
2
1000

I have another table for countries - cid is an identity column:
TB_Countries

cid
name

1
Germany

2
Netherland

3
Slovakia

So far I have the contents and everything is fine.
The problem I have is that shipping costs vary for each issue of each category for each country.
For example: the order of the brochure is 100 different for Germany and Slovakia.
Or any other number for any other country.
I need a query that displays the data for me as follows:

nid
country
number
transport_cost

1
Germany
10

1
Germany
50

1
Germany
100

1
Netherland
10

1
Netherland
50

1
Netherland
100

1
Slovakia
10

1
Slovakia
50

1
Slovakia
100

I need a select query to display the information and just enter the shipping cost field.
I do this operation with Gridview .NET.
Thank you for your help in writing query for select and insert, update

A: Schema:

create table TB_Categories(nid    int, name varchar(20));
insert into TB_Categories values(1,'Brochure');
insert into TB_Categories values(2,'stamp');

create table TB_numbercategories (id  int, nid    int, number int);
insert into TB_numbercategories values(1,   1,    10);
insert into TB_numbercategories values(2, 1,  50);
insert into TB_numbercategories values(3, 1,  100);
insert into TB_numbercategories values(4, 2,  100);
insert into TB_numbercategories values(5, 2,  500);
insert into TB_numbercategories values(6, 2,  1000);

create table TB_Countries (cid    int, name varchar(20));
insert into TB_Countries values(1,    'Germany');
insert into TB_Countries values(2,    'Netherland');
insert into TB_Countries values(3,    'Slovakia');

Query:

select tc.nid,tbc.name country ,number,'' Transport_cost from TB_Categories tc inner join TB_numbercategories tnc on tc.nid=tnc.nid
cross join TB_Countries tbc
where tc.name='Brochure'
order by tbc.name,number
GO

Output:

nid
country
number
Transport_cost

1
Germany
10

1
Germany
50

1
Germany
100

1
Netherland
10

1
Netherland
50

1
Netherland
100

1
Slovakia
10

1
Slovakia
50

1
Slovakia
100

db<>fiddle here


text:
Q: Script to disable a text box on selecting a radio button I have two radio buttons

                @Html.RadioButtonFor(model => model.ReceiveCopyOrders, "true") Yes

                @Html.RadioButtonFor(model => model.ReceiveCopyOrders, "false", new { @id = "mailForOrder_no" }) No

and a text box

                @Html.TextBoxFor(m => m.OrderEmail, new { @class = "form-control",@id="

mailForOrder" })

If the radio NO is checked I want the textbox to be disabled.
I tried the script below


text:
Q: How to Check the cell from excel which has formula using python I Want to access the cell which has formula from the excel workbook.Actually my python script is working fine only to read the data from excel, but i need that only the cell which has formula and to print that cells only
An example would be really appreciated..........

A: Two things that could help you solve the problem:

*

*There's a typo: HasForumla instead of HasFormula

*e is a string, not a cell object, so e.HasFormula won't work.

You probably want to use
e = sheet.cell(row,17)

to access the Cell object at that position. I'm not sure where you got your HasFormula attribute from, though - couldn't find it in the docs.
Edit:
I just looked at the README for the current distribution where it's stated that

xlrd will safely and reliably ignore any of these if present in the
  file:

*

*[...]

*Formulas (results of formula calculations are extracted, of course).

*[...]


text:
Q: Cast const int pointer to int, in a switch case node In my STM32 code i have an
#define USART1              ((USART_TypeDef *) USART1_BASE)

and i would like to have
switch((uint32_t)ptr)
{
  case USART1: return 1;
(...)

But gcc-arm (6.3.1) give me an error

error: reinterpret_cast from integer to pointer

I found an information that i can use
  case __builtin_constant_p(USART1): return 0;

but this is only gcc solution? Is there something more generic?

A: There is UART1_BASE which is just the sum of a couple of unsigned integer constants. See the machine header:
#define PERIPH_BASE           0x40000000U
#define APB2PERIPH_BASE       (PERIPH_BASE + 0x00010000U)
#define USART1_BASE           (APB2PERIPH_BASE + 0x1000U)

So should be able to use
switch((unsigned int)ptr) {
    case USART1_BASE: return 1;
}

A: You forgot to cast pointer to integer in the case statement as well.
Example from my working code:
switch ((uint32_t)gpio) {
    case (uint32_t)GPIOA:
        EXTI_cfgr = 0b0000;
        break;
    case (uint32_t)GPIOB:
        EXTI_cfgr = 0b0001;
        break;
    case (uint32_t)GPIOC:
        EXTI_cfgr = 0b0010;
        break;
    default:
        break;
    }

A: USART1_BASE is a number in the header files of the STM32 development environment. You can compile your code when you decided what type shall be used in the switch. I recommend uint32_t:
switch((uint32_t)ptr)
{
  case USART1_BASE: return 1;
  (...)

If you like more readability you can try to remove the cast from the switch:
uint32_t ptr_value = (uint32_t)ptr;

switch(ptr_value)
{
  case USART1_BASE: return 1;
  (...)


text:
Q: Berry-Esseen type bounds for functions of almost Gaussian random variables Suppose that I have $n$ dependent random variables $X_1,\ldots,X_n$ with $\mathbb{E}[X_i]=0, \mathbb{E}[X_i^2]=1$, where we have the following bounds on the Kolmogorov distance from a normal distribution:
$$|P(X_i\leq x)-\Phi(x)|\leq \rho(x)\text{ for all }i=1,\ldots,n.$$
Here $\rho(x)$ is a generic function of $x$ that goes to zero as $|x|\to \infty$ and $\Phi$ is the CDF of the standard normal distribution.
Now what can we say about the distribution of the functions of $X_i$? For example, suppose that we have a Lipschitz function $f(X_1,\ldots,X_n) = \sqrt{\sum_{i=1}^n X_i^2}$, let $Z_i$ be standard Gaussian distributions such that $\mathbb{E}[Z_iZ_j]=\mathbb{E}[X_iX_j]$. What can we say about
\begin{align}|P(f(X_1,\ldots,X_n)\leq x)- P(f(Z_1,\ldots,Z_n)\leq x)|\quad ?\hspace{20mm}(1)\end{align}
The continuous mapping theorem tells us that as $\rho\to 0$, the above quantity also converges to $0$. However I am interested in trying to find explicit convergence rates for $(1)$. Stein's method most likely plays a big role here, but most papers I've found are concerned with limiting distributions, eg. https://arxiv.org/pdf/1507.08688.pdf.
A similar question can be found in: Berry-Esseen bound in 2 dimensions for linear combinations, but I am hoping for a better answer/references if possible.


text:
Q: Nested div-container gets bigger then parent element I just tried to create nested elements, but the inner element (subcategory) gets always bigger, then the parent element (category).
Please have a look at this JSFiddle:
JSFiddle: http://jsfiddle.net/d7vhpcmt/
HTML:

Category

Subcategory

CSS:
.category {
    background-color: #f8f8f8;
    padding: 20px;
    margin-bottom: 10px;
    width: 100%;
    max-width: 1600px;
    float: left;
    margin-right: 10px; }
    .category a {
        color: #262626;
        text-decoration: none;
        border-bottom: 0;
        background-color: transparent;
        display: block;
        width: 100%; }
    .category h1 {
        font-size: 2.0em;
        margin: 0 0 0.5em 0;
        font-weight: 300;
        line-height: 1em;
        color: #262626;
        letter-spacing: -1px; }

.box_1 {
    background-color: #E9E9E9;
    margin-top: 5px;
    border: 1px solid #E2E2E2;
    display: block;
    width: 100%; }
    .box_1:hover {
        background-color: #eee; }
    .box_1 header {
        padding: 5px 0 0 50px; }
    .box_1 .content {
        background-color: #f2f2f2;
        height:100%;
        padding: 0.2em 0 0 0;  }
        .box_1 .content p { margin: 0.5em 0.8em; }
        .box_1 .content h3 {
            font-size: 1.2em !important;
            margin-left: 0.3em; }
        .box_1 .content .box_1 {
            margin: 5px; }

A: It's because you have given .box_1 it a width of 100% and .content .box_1 and margin of 5px;  this means your box is going to be 100% + 10px - instead of using margin try add padding to the parent container, this way you don't need to keep adding 5px margin to all it's children:
.box_1 .content {
    background-color: #f2f2f2;
    height:100%;
    padding: 0.2em 5px 0 5px;
}

Example

A: If you are not worry about IE8 then use calc in your box_1 class.
.box_1 {
background-color: #E9E9E9;
margin-top: 5px;
border: 1px solid #E2E2E2;
display: block;
width: calc(100% - 10px);
}

DEMO

A: The problem is in this piece of code:
.box_1 .content .box_1 {
    margin: 5px;
}

You are applying a margin around the entire section containing the Subcategori. Just edit in this way:
.box_1 .content .box_1 {
    margin: 5px 0;
}

In order to remove the margin right and left.
Here is the JSFiddle.


text:
Q: CSS-only push nav won't hide I'm using a css-only push nav. It works great, however I can't figure out how to make the menu hide away when a nav link is clicked. You have to manually click the menu icon for the menu to go back into hiding. However, when a link is clicked and the site jumps to a section, I want the menu to slide into hiding automatically.
Here's a fiddle of it:
http://jsfiddle.net/ex7jthnn/28/
html:
<input type="checkbox" id="menu" name="menu" class="menu-checkbox">

Toggle

ABOUT

PROCESS

WORK

CONTACT

CSS:
label{
cursor: pointer;
&:focus;
outline: none;
}

.menu{
position: fixed;
top: 0;
left: 0;
background-color: rgba(111, 206, 204, 0.7);
width: 240px;
height: 100%;
z-index: 10;
}

label.menu-toggle{
position: absolute;
right: -60px;
width: 75px;
height: 90px;
line-height: 0px;
display: block;
margin-top: 30px;
margin-right: -50px;
padding: 0px 0px 0px 20px;
text-indent: -9999px;
background: 50% 50% / 45px 32px no-repeat;
background-image:url(../images/menu.png);
}

a, label{
display: block;
text-align: center;
line-height: 50px;
text-decoration: none;
}

.menu-checkbox{
display: none;
}

.menu .menu label.menu-toggle{
background: none;
}

.menu-checkbox:checked + .menu{
transform: translate3d(0, 0, 0);
-webkit-transition: translate3d(0, 0, 0);
}enter code here

A: Try to add this piece of code into your website, it should make the job done.
$('ul.mainnav > li > a').on('click', function(e){
   $('#menu').prop('checked', false);
});


text:
Q: How do I check if it returns a null? i should check whether there is some values based on this condition. if there is some, then i should do one action or else do a different action.
i work on rails, mysql and xp
this is not working @test.nil? suggest me a alternate way
@test=Model.find(:all,:conditions=>"id=@someid")thanks in advance

A: @test.nil? should work fine. It's probably not working because your find method is wrong. Try this instead:
@test = Model.find_by_id(@someid)

An alternative syntax is:
@test = Mode.find(@someid)

—Which will raise a RecordNotFound exception if the record doesn't exist.


text:
Q: How to link boost using cmake on windows the StackOverFlow community!
I'm trying to link up boost libraries and there's an error of linking up the 'boost_system' static library.
I use cmake 2.8, the MinGW compiler and the 1.55.0 boost.
Judging by the logs, cmake doesn't see the pathway to the libraries.
 Here's the error:
Unable to find the requested Boost libraries.

Boost version: 1.55.0

Boost include path: c:/local/boost_1_55_0

Could not find the following static Boost libraries:

      boost_system

No Boost libraries were found.  You may need to set BOOST_LIBRARYDIR to the
directory containing Boost libraries or BOOST_ROOT to the location of
Boost.
Call Stack (most recent call first):

 Here's the cmake code:
cmake_minimum_required(VERSION 2.8)
project(test)

if (WIN32)

set(BOOST_ROOT "c:/local/boost_1_55_0")
set(BOOST_LIBRARYDIR ${BOOST_ROOT}/stage/lib/)
set(Boost_USE_STATIC_LIBS ON)
set(Boost_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)

find_package(Boost 1.55 COMPONENTS system REQUIRED)
add_definitions(${Boost_LIB_DIAGNOSTIC_DEFINITIONS})

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libgcc -static-libstdc++")

include_directories(${Boost_INCLUDE_DIR})

set(SOURCE_FILES main.cpp)
add_executable(test ${SOURCE_FILES})

target_link_libraries(test ${Boost_LIBRARIES})

endif (WIN32)

I receive logs like this with the declared set(Boost_DETAILED_FAILURE_MSG on)
status** Boost Include: c:/local/boost_1_55_0
status** Boost Libraries:
status** Boost Libraries:

A: For me worked setting hint variables CMAKE_INCLUDE_PATH & CMAKE_LIBRARY_PATH. BOOST_ROOT & BOOST_LIBRARYDIR were not working also.
Another hint variables are Boost_COMPILER, Boost_NAMESPACE, Boost_ARCHITECTURE they help to define how your library is named to boost search script.
Using SET(Boost_DEBUG 1) helped me a lot do diagnose a problem -as it prints Boost path suffixes=  and  _boost_LIBRARY_SEARCH_DIRS_RELEASE
For example
SET(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "D:/boost/boost_1_70_0")
SET(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "D:/boost/boost_1_70_0/stage/gcc/x64/lib")

SET(Boost_COMPILER ${Boost_COMPILER} "-mgw73")
SET(Boost_NAMESPACE ${Boost_NAMESPACE} "libboost")
SET(Boost_ARCHITECTURE "-x64")

Or
SET(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "D:/boost/boost_1_70_0")
SET(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "D:/boost/boost_1_70_0/stage/lib")
SET(Boost_COMPILER ${Boost_COMPILER} "-vc142")


text:
Q: Checking through an expression I am writing a code that manipulates expressions that contains functions with an arbitrary number of arguments.  An example expression is
expr = x f[a, b, c, d] - 4 f[b, a, d] + z f[] + f[a, b, d] - f[a]f[b,d]

What I would like to do is to make my code to be a little user-friendly by making it throw a message if the expression is invalid.  Basically, the only symbols allowed to appear in f are allowedList={a,b,d}, and so I probably need to somehow use Scan to check through expr.  (The above example should yield an 'error' since the first term has a c in it.)
To make answering easier, please assume that the input expr will be such that all arguments will have Head = Symbol.  But please allow for the possibility that multiple fs could be multiplied together.

A: This function yields True if the expression expr is valid, otherwise it yields False:
validExpressionQ[ expr_, allowedList_List] :=
  Union @ Cases[ Variables[expr], f_[x___] :> x, Infinity] == Union @ allowedList

now we have, e.g.
validExpressionQ[ x f[a, b, d] - 4 f[b, a, d] + z f[] + f[a, b, d] - f[a] f[b, d],
                  {a, b, d}]

True

validExpressionQ[ x f[a, b, c, d] - 4 f[b, a, d] + z f[] + f[a, b, d] - f[a] f[b, d],
                  {a, b, d}]

False

A: A possibility is to define a support function:
EDIT: Thanks to Simon Woods' comment: .. instead of __
check[(a | b | d) ..] := 1;
check[___] = Indeterminate;

The substitution
expr /. f-> check

contains Indeterminate if f has arguments not allowed.
Concluding:
If[FreeQ[expr /. f -> check, Indeterminate], "ok", "error"]

returns "error" for your example and "ok" if the arguments are acceptable.

A: Since it seems that evaluation of the expression is specifically permitted let's leverage that:
check[expr_, f_, pat_] := FreeQ[expr /. f[pat ...] -> 1, _f]

check[expr, f, a | b | d]
check[expr, f, a | b | c | d]

False

True

I used Alternatives instead of List to make this cleaner, but you can always Apply Alternatives if needed.
If for some reason you don't like the method above, here is my take on Artes's method:
check2[expr_, f_, args_] :=
  {} === Complement[Cases[expr, f[x___] :> x, -2], args]

check2[expr, f, {a, b, d}]
check2[expr, f, {a, b, c, d}]

False

True


text:
Q: volver al menu no funciona -lenguaje C estoy haciendo un menú de opciones el cual está contenido en una función menu(); pero cuando verifico si alguien quiere volver al menú (volver a ejecutar la función menu) el programa finaliza, no hay errores pero simplemente finaliza el programa
int main(int argc, char *argv[]) {

system("COLOR 02");
//bienvenida();
menu();
return 0;
}
int menu(){
   int opcion;
   char vAM;
   //MENU
   printf("\n\t\t\t\t**********Bienvenido a Cinematic***********\n\n\nBienvenido al menú de
   opciones\n\n1) COMPRAR BOLETOS\n2) CONSULTAR BOLETOS COMPRADOS\n3) VER CARTELERA \n");
   printf("\n¿Introduzca el número de la acción que desea hacer? ");
   scanf("%d", &opcion);
   printf("\n");

   if(opcion == 1)
   {

       comprarBoleto();

       return 1;
   }
   if(opcion == 2)
   {
       consultarUsuario();
   }
   if(opcion == 3)
   {

       consultarCartelera();
       printf("\n¿Desea volver al menu? (s/n)");
       scanf("%c", sn);
       if(sn=='s'){
           menu();
       }

   }
}

A: scanf("%c", sn);

Debería ser
scanf("%c", &sn);
//          ^ importante

Por otro lado, quizás deberías considerar la posibilidad de usar un bucle en vez de llamadas recursivas a la función:
char sn='s';
do
{
   printf("\n\t\t\t\t**********Bienvenido a Cinematic***********\n\n\nBienvenido al menú de
   opciones\n\n1) COMPRAR BOLETOS\n2) CONSULTAR BOLETOS COMPRADOS\n3) VER CARTELERA \n");
   printf("\n¿Introduzca el número de la acción que desea hacer? ");
   scanf("%d", &opcion);
   printf("\n");

   if(opcion == 1)
   {
       // ...
   }
   if(opcion == 2)
   {
       consultarUsuario();
   }
   if(opcion == 3)
   {
       consultarCartelera();
       printf("\n¿Desea volver al menu? (s/n)");
       scanf("%c", &sn);
   }
} while (sn == 's');

A: Has probado a utilizar, ya que las opciones son limitadas y están definidas, usar "switch" y "cases"?
Soy muy, muy nuevo en ésto, pero si el programa finaliza sin marcar errores, seguramente la sinstaxis esté bien y sea un problema de control de flujo.
Al ser una condición anidada, aunque no sea dentro de un ciclo, puede que el comando "goto" te pueda servir también.
Por último:
if(opcion == 3)
{
   consultarCartelera();
   printf("\n¿Desea volver al menu? (s/n)");
   scanf("%c", sn);
   if(sn=='s'){
       menu();
   }

(A éste bloque podría añadirle algo como...
char primeracadena= "s";
char segundacadena= "n";
   if(sn == primeracadena) bla, bla, bla


text:
Q: Java on Mac OS X Server: game over? As a developer currently working on a Web app that uses a Java/Tomcat backend, the recent announcement by Apple to deprecate Java is causing me some consternation. Mainly because I'm planning on hosting this Web app on Mac OS X Server (already on 10.5, soon to be on 10.6).
From http://www.appleoutsider.com/2010/10/22/java/:

Since the Intel transition, building a server VM for Darwin is almost trivial.

Is this actually true? Is there a document somewhere that describes how to build a headless Java VM for Mac OS X Server?

A: You should be able to build OpenJDK on Mac OS X without much trouble. It only has Windows and X11 frontends but since you are asking for a headless JVM, this should not be a problem for you.
Pre-built binaries of OpenJDK are also available for Mac OS X. See the SoyLatte project (a Java Research License may be required):

*

*http://landonf.bikemonkey.org/static/soylatte/#get
Note that SoyLatte has recently become part of the OpenJDK BSD-Port project:

*

*http://openjdk.java.net/projects/bsd-port/

A: Build instructions for OpenJDK on OS X Snow Leopard can be found at http://wikis.sun.com/display/OpenJDK/BSDPort. Apparently. Tomcat runs fine with OpenJDK, so you shouldn't have any real problems (even if Oracle never step up and provide an "official" JDK).