text:
Q: Poco library PUT method not working as expected although host, method, content-type are set correctly I have the following code in C++ with Poco Library that should perform a PUT on localhost with a body like {"name" : "sensorXXX", "totalLots" : 50, "occupied": 5}
string url = String("http://localhost:3000/cam1111");
URI uri(url);
HTTPClientSession session(uri.getHost(), uri.getPort());

// prepare path
string path(uri.getPathAndQuery());
if (path.empty()) path = "/";

// send request
HTTPRequest req(HTTPRequest::HTTP_PUT, path, HTTPMessage::HTTP_1_1);
req.setContentType("application/json");

string body = string("{\"name\" : \"Parking Sensor developed by aromanino\", \"totalLots\" : 50, \"occupied\": 5}");
// Set the request body
req.setContentLength( body.length() );

// sends request, returns open stream
std::ostream& os = session.sendRequest(req);
cout<<"request sent to " <<uri.getHost()<<endl;
cout<<"port "<<uri.getPort()<<endl;
cout<<"path "<<uri.getPathAndQuery()<<endl;
cout<<"body:\n"<<body<<endl;

HTTPResponse res;
cout << res.getStatus() << " " << res.getReason() << endl;

return 0;

It is supposed to PUT on a local middleware done in NodeExpress.
I get 200 as response so it should be ok.
However the middleware is receiving something (so the host and port are correct) but it is not executing the end point which I am expecting which is:
router.put("/:dev", function(req, res){
    //console.log(req.params.dev);
    /*Check if request contains total and occupied in the body: If not reject the request.*/
    var stat;
    var body_resp = {"status" : "", "message" : ""};;
    console.log(req.body);
    ....
});

and it is not captured also by router.all('*', ...).
The same host, body, content-type are working as expected on Postman.
What am I supposed to set more in the Poco library to perform a correct PUT request.

A: You are not actually sending the body with the HTTP request, as in:
std::ostream& os = session.sendRequest(req);
os << body;

Furthermore, you must also receive the server response after sending the request with the body - simply declaring the HTTPResponse object is not sufficient.
HTTPResponse res;
std::istream& is = session.receiveResponse(res);

So, the complete snippet should be:
string url = string("http://localhost:3000/cam1111");
URI uri(url);

HTTPClientSession session(uri.getHost(), uri.getPort());

string path(uri.getPathAndQuery());
if (path.empty()) path = "/";

HTTPRequest req(HTTPRequest::HTTP_PUT, path, HTTPMessage::HTTP_1_1);
req.setContentType("application/json");

string body = string("{\"name\" : \"Parking Sensor developed by aromanino\", \"totalLots\" : 50, \"occupied\": 5}");
req.setContentLength(body.length());

std::ostream& os = session.sendRequest(req);
os << body;

HTTPResponse res;
std::istream& is = session.receiveResponse(res);
cout << res.getStatus() << " " << res.getReason() << endl;


text:
Q: Does alarm/reminder get automatically deleted when its event is deleted? I create a calendar event with HAS_ALARM set to 1 as follows:
contentResolver.insert(
    Uri.parse("content://com.android.calendar/calendars"),
    contentValuesOf(
        CalendarContract.Events.CALENDAR_ID to calendarId,
        CalendarContract.Events.TITLE to event.title,
        CalendarContract.Events.EVENT_LOCATION to event.location,
        CalendarContract.Events.DESCRIPTION to event.description,
        CalendarContract.Events.DTSTART to event.startTimeInMillis,
        CalendarContract.Events.DTEND to event.endTimeInMillis,
        CalendarContract.Events.EVENT_TIMEZONE to event.zoneName,
        CalendarContract.Events.HAS_ALARM to 1
    )
)

Then I create a reminder for the event created above as follows:
contentResolver.insert(
    Uri.parse("content://com.android.calendar/reminders"),
    contentValuesOf(
        CalendarContract.Reminders.EVENT_ID to it,
        CalendarContract.Reminders.METHOD to CalendarContract.Reminders.METHOD_ALERT,
        CalendarContract.Reminders.MINUTES to reminderTimeInMinutes
    )
)

I remove the event when required like this:
contentResolver.delete(
    Uri.parse("content://com.android.calendar/events"),
    String.format(
        "%s = ? and %s = ? and %s = ?",
        CalendarContract.Events.TITLE,
        CalendarContract.Events.DTSTART,
        CalendarContract.Events.DTEND
    ),
    arrayOf(event.title, event.startTimeInMillis.toString(), event.endTimeInMillis.toString())
)

However, I am unable to delete its reminder because I am not keeping event id's.
Does the reminder get automatically deleted when I delete its event? If not, how can I delete the reminder, preferably without storing any id?

A: It seems an event's reminders are automatically deleted when the event is deleted.

redpajama_set_name: RedPajamaStackExchange


text:
Q: To PerformanceCounter or To Write Custom Monitoring? I have a Windows service that runs implementations of a framework across multiple threads.  Each running instance has several things in common that I need to keep track of, for example, number of items processed, last time an item was processed, etc.  On top of this base monitoring data, I'd like to offer functionality in the framework to allow implementations to dynamically add their own monitoring data.
I've worked with PerformanceCounters before, and though they offer decent functionality, I find the code to create and maintain them to be quite cumbersome, as well as being loaded with the possibility of instance-related pitfalls (i.e., hard-coding a counter instance name, category name, and counter type).  Also, I'm not certain that I could offer simple base functionality dynamic counter creation without writing a massive amount of code.
Has anyone implemented something like this using PerformanceCounters?  If so, would you recommend it?  If not, does anyone have a suggestion for a medium that I can easily write performance/health-monitoring data to that wouldn't introduce 1) a lot of slowdown and 2) another point of failure?
Thanks, and I'm happy to add clarification if necessary, as I know this is somewhat nebulous.
Conclusion:
I ended up implementing performance counters.  It was a bit of a PITA (heh), but my boss was really into the idea and now that I've figured it out, it's not so bad.  I was hoping for something a little more easily configurable with a simpler way to present hierarchical data.  But this works fine, and it's hard to argue with the built-in interface.

A: Agreed, it can take a bit of time to put together code that leverages performance counters. However, last time I did this I wrapped it all up in a nice reusable class. It made it much simpler for me to use perf counters throughout my code base with minimal friction.
The end result was well worth it to me, given the tooling that exists on top of perf counters (perfmon is a big boon).

A: Have you considered using the Instrumentation classes from Enterprise Library? Can't say anything pro/con the EntLib, but it seems to gain popularity, and Microsoft seem to continue to invest in it...
http://msdn.microsoft.com/en-us/library/dd203352.aspx


text:
Q: How to use Querystring with $location.path() in AngularJS I want to redirect user to another page after successful login using query string. If I copy & paste to browser's address bar http://example.com/#/login?ref=/path/to/redirect it works fine. But if I use
$location.path("/login?ref=/path/to/redirect");

url looks like
http://example.com/#/login%3Fref=/path/to/redirect

How can I decode %3F to '?' ?
Thanks

A: It should be
$location.path('/login').search('ref', '/path/to/redirect')

A: I had the same problem.
I want to change path and search the same time.
It is possible by doing this:
$location.$$search ={foo:'bar', buz:'buz'}
$location.$$path = '/some/path'
$location.$$compose()

It is not documented and it could broke at any new angular version.


text:
Q: ListView with ImageButton and Text I try to make a listview with imagebutton and text. Somehow my app crashed when I run it. I need someone can go through my log to see the mistakes I have made. Please help as I have zero background of coding.
Here is my main_java = IngredientChoices.java
public class IngredientChoices extends AppCompatActivity {

ListView lv;

String[] category_titles={"Baking Goods", "Beverages/Alcohol", "Dairy", "Fruit", "Herbs & Spices", "Meat", "Nuts & Seeds", "Pasta, Breads & Grains", "Poultry", "Sauces, Soup & Condiments", "Seafood", "Vegetables"};
int [] category_icons={R.drawable.bakingood,R.drawable.beverages, R.drawable.dairy, R.drawable.apple, R.drawable.herbs, R.drawable.meat, R.drawable.nuts, R.drawable.bread, R.drawable.poultry, R.drawable.soup, R.drawable.seafood, R.drawable.vegetable};

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

    lv = (ListView) findViewById(R.id.listView);

    //Adapter

    IngredientCategoryAdapter adapter = new IngredientCategoryAdapter(this, category_titles, category_icons);
    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(getApplicationContext(), category_titles[position], Toast.LENGTH_SHORT).show();

        }
    });

}
}

Here is my adapter.java
public class IngredientCategoryAdapter extends ArrayAdapter<String> {

// Declarations
int[] category_icons={};
String[] category_titles={};
Context c;
LayoutInflater inflater;

public IngredientCategoryAdapter(Context context, String[]      category_title, int[] category_icon) {
    super(context, R.layout.ingcategory_list_view, category_title);

    this.c=context;
    this.category_icons=category_icons;
    this.category_titles=category_titles;

}

public class ViewHolder {

    TextView category_title;
    ImageButton category_icon;
}

@SuppressLint("InflateParams")
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if(convertView==null){
        inflater= (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView=inflater.inflate(R.layout.ingcategory_list_view, null);
    }

    //our viewholder object

    final ViewHolder holder = new ViewHolder();

    // Initialize our views
    holder.category_title= (TextView) convertView.findViewById(R.id.category_title);
    holder.category_icon=(ImageButton) convertView.findViewById(R.id.category_icon);

    //Assign data

    holder.category_icon.setImageResource(category_icons[position]);
    holder.category_title.setText(category_titles[position]);

    return convertView;
}
}

Thank you!
crash log

03-08 15:23:17.545 8166-8224/? E/BooksSync: Soft error
                                              com.google.android.apps.books.net.HttpHelper$AuthIoException: 403: Forbidden
                                              Request: GET https://encrypted.google.com/books?cp_activate=2%3AC4q8DQZi0PFAsa4LWbLehD8AAAA6gAd6-baW_r-qDKNVNPTjsycPW8Iqe-VhNJcXNKhi02FNTv6sb_oW-B67bwycWnmqttWYrKqXuC56--BtZlv5 HTTP/1.1
  03-08 15:23:17.555 8166-8224/? E/BooksSync: Sync error
                                              com.google.android.apps.books.net.HttpHelper$AuthIoException: 403: Forbidden
                                              Request: GET https://encrypted.google.com/books?cp_activate=2%3AC4q8DQZi0PFAsa4LWbLehD8AAAA6gAd6-baW_r-qDKNVNPTjsycPW8Iqe-VhNJcXNKhi02FNTv6sb_oW-B67bwycWnmqttWYrKqXuC56--BtZlv5 HTTP/1.1
  03-08 15:23:20.418 1281-1281/? E/LSO: LSO Service is not yet ready!!!
  03-08 15:23:20.518 1281-1281/? E/SoundPool: error loading /system/media/audio/ui/lens_flare_tap.ogg
  03-08 15:23:20.518 1281-1281/? E/SoundPool: error loading /system/media/audio/ui/lens_flare_unlock.ogg
  03-08 15:23:20.758 300-18933/? E/AwesomePlayer: LPAPlayer::Clip duration setting of less than 30sec not supported, defaulting to 60sec
  03-08 15:23:20.758 300-18933/? E/AwesomePlayer: LPAPlayer::Clip duration setting of less than 30sec not supported, defaulting to 60sec
  03-08 15:23:20.958 300-19477/? E/AwesomePlayer: LPAPlayer::Clip duration setting of less than 30sec not supported, defaulting to 60sec
  03-08 15:23:20.958 300-19477/? E/AwesomePlayer: LPAPlayer::Clip duration setting of less than 30sec not supported, defaulting to 60sec
  03-08 15:23:22.050 8338-8338/? E/Diag_Lib:  Diag_LSM_Init: Failed to open handle to diag driver, error = 2
  03-08 15:23:23.571 8267-8267/? E/SMD: smd_init start
  03-08 15:23:23.571 8267-8267/? E/SMD: smd Interface open failed errno is 2 -1
  03-08 15:23:24.332 884-1422/? E/Watchdog: !@Sync 10416
  03-08 15:23:24.572 8267-8267/? E/SMD: smd Interface open failed errno is 2 -1
  03-08 15:23:25.573 8267-8267/? E/SMD: smd Interface open failed errno is 2 -1
  03-08 15:23:26.574 8267-8267/? E/SMD: smd Interface open failed errno is 2 -1
  03-08 15:23:27.505 8339-8339/? E/Diag_Lib:  Diag_LSM_Init: Failed to open handle to diag driver, error = 2
  03-08 15:23:27.565 8267-8267/? E/
  03-08 15:24:00.677 884-2563/? E/PersonaManagerService: inState():  stateMachine is null !!
  03-08 15:24:01.058 8434-8434/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.cassieleong.delishcart, PID: 8434
                                                   java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
                                                       at com.example.cassieleong.delishcart.IngredientCategoryAdapter.getView(IngredientCategoryAdapter.java:59)
                                                       at android.widget.AbsListView.obtainView(AbsListView.java:2823)
                                                       at android.widget.ListView.measureHeightOfChildren(ListView.java:1290)
                                                       at android.widget.ListView.onMeasure(ListView.java:1202)
                                                       at android.view.View.measure(View.java:18596)
                                                       at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
                                                       at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:464)
                                                       at android.view.View.measure(View.java:18596)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                       at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:610)
                                                       at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:677)
                                                       at android.view.View.measure(View.java:18596)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                       at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                       at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                       at android.view.View.measure(View.java:18596)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1435)
                                                       at android.widget.LinearLayout.measureVertical(LinearLayout.java:721)
                                                       at android.widget.LinearLayout.onMeasure(LinearLayout.java:612)
                                                       at android.view.View.measure(View.java:18596)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                       at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                       at android.view.View.measure(View.java:18596)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1435)
                                                       at android.widget.LinearLayout.measureVertical(LinearLayout.java:721)
                                                       at android.widget.LinearLayout.onMeasure(LinearLayout.java:612)
                                                       at android.view.View.measure(View.java:18596)
                                                       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5827)
                                                       at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
                                                       at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2897)
                                                       at android.view.View.measure(View.java:18596)
                                                       at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2248)
                                                       at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1306)
                                                       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1548)
                                                       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1191)
                                                       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6642)
                                                       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:777)
                                                       at android.view.Choreographer.doCallbacks(Choreographer.java:590)
                                                       at android.view.Choreographer.doFrame(Choreographer.java:560)
                                                       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:763)
                                                       at android.os.Handler.handleCallback(Handler.java:739)
                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                       at android.os.Looper.loop(Looper.java:145)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5942)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
  03-08 15:24:01.448 884-8480/? E/android.os.Debug: !@Dumpstate > sdumpstate -k -t -z -d -o /data/log/dumpstate_app_error
  03-08 15:24:01.578 8267-8267/? E/SMD: smd Interface open failed errno is 2 -1
  03-08 15:24:02.579 8267-8267/? E/SMD: smd Interface open failed errno is 2 -1
  03-08 15:24:02.639 8503-8503/? E/Diag_Lib:  Diag_LSM_Init: Failed to open handle to diag driver, error = 2
  03-08 15:24:03.580 8267-8267/? E/SMD: smd Interface open failed errno is 2 -1
  03-08 15:24:04.581 8267-8267/? E/SMD: smd Interface open failed errno is 2 -1
  03-08 15:24:05.592 8267-8267/? E/SMD: smd Interface open failed errno is 2 -1
  03-08 15:24:06.593 8267-8267/? E/SMD: smd Interface open failed errno is 2 -1
  03-08 15:24:07.594 8267-8267/? E/SMD: smd Interface open failed errno is 2 -1

A: It's a problem sometimes to get resources without context in android. Try to change:
holder.category_icon.setImageResource(category_icons[position]);

to
holder.category_icon.setImageDrawable(c.getResources().getDrawable(category_icons[position]));

EDIT: ok, it seems one (or both) of your arrays is empty. Try to pu the data right before you initialize your adapter in onCreate(Bundle savedInstanceState)
like
ListView lv;

String[] category_titles;
int [] category_icons;

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

    lv = (ListView) findViewById(R.id.listView);

    category_titles = {"Baking Goods", "Beverages/Alcohol", "Dairy", "Fruit", "Herbs & Spices", "Meat", "Nuts & Seeds", "Pasta, Breads & Grains", "Poultry", "Sauces, Soup & Condiments", "Seafood", "Vegetables"};
    category_icons={R.drawable.bakingood,R.drawable.beverages, R.drawable.dairy, R.drawable.apple, R.drawable.herbs, R.drawable.meat, R.drawable.nuts, R.drawable.bread, R.drawable.poultry, R.drawable.soup, R.drawable.seafood, R.drawable.vegetable}
    //Adapter

    IngredientCategoryAdapter adapter = new IngredientCategoryAdapter(this, category_titles, category_icons);
    lv.setAdapter(adapter);

A: There is a problem with your adapter constructor.
Change your adapter exactly to:
public IngredientCategoryAdapter(Context context, String[] category_title, int[] category_icon) {
    super(context, R.layout.ingcategory_list_view, category_title);

    this.c=context;
    this.category_icons=category_icon;
    this.category_titles=category_title;
}


text:
Q: How do I assign a HTML file to a certain link So I have all my HTML, CSS, and JS files ready to be uploaded to a server (Using cPanel as I have experience with them). But i was wondering how to assign a HTML file to a certain link like "devwebdevelopment.com/about" or something like that
What I want is to have a link with a "/". For ex. "google.com/developers"

A: Webservers are very similar to windows folders in a windows PC.
For example, think of www.google.com as a folder called "home". In this "home" folder, this is your root directory, where you serve the index.html for the home page.
Now in your case, the "www.google.com/developer" is created doing... you guessed it, creating another folder in your "home" directory.
Example: in your root directory of "home" (in web servers this is called the public I believe), just create another folder called "developer". Now your website is structured as:
www.mywebsite.com and www.mywebsite.com/developer
In your developer, create an "index.html" file, which will be the first file served to the client upon initial http request.

A: You need to create a directory with the desired name.
Let's say you want to add a / contact
For this, just follow this directory structure
index.html
contact (this is a folder)
gallery (this is another folder)
And play the files for each folder. If my answer does not help you, comment here so I can help you.


text:
Q: Netlify deploy has error: WebpackError: ReferenceError: window is not defined When deploying my gatsby site to Netlify I get this error:
WebpackError: ReferenceError: window is not defined
Here is my code:
import React, { useState } from "react";
import { Link } from "gatsby";

// components
import Layout from "../components/Layout/Layout";
import SEO from "../components/seo";

// css

export default function IndexPage() {
// i took out my strip id so I could post online
  const stripe = window.Stripe("stripeID_Here");
  const [sku, setSku] = useState("sku_GKCxZJybZKaHr7");

  const placeOrder = () => {
    stripe.redirectToCheckout({
      items: [
        {
          sku,
          quantity: 1,
        },
      ],
      successUrl: "http://localhost:8000/success",
      cancelUrl: "http://localhost:8000/cancel",
    });
  };

  return (
    <Layout>
      <SEO title="Home" />

      {/* Popular   */}

Check out our most popular items

SET HAPPENS T-Shirt

            <select value={sku} onChange={e => setSku(e.target.value)}>
              <option value="sku_GKCxZJybZKaHr7">Small</option>
              <option value="sku_GK8OJSyke6mMrm">Medium</option>
              <option value="sku_GKCy45LwrpfmV8">Large</option>
            </select>
            <button onClick={placeOrder}>Buy Me</button>

      {/* Popular End */}

    </Layout>
  );
}

it says error "window" is not available during server side rendering.
so what can I use in place of window?
Everything else works fine.

A: During development react component are only run in the browser where window is defined so it works properly. But when building react components are rendered on the server where window is not defined. That is the reason you are seeing this error.
You can fix this error by calling the window in componentDidMount or useEffect hook.
You can also try doing this
const stripe = typeof window !== 'undefined' && window.Stripe("stripeID_Here");


text:
Q: Starting point of Android drawLine changes with angle I'm drawing a line from a fixed point and moving it in a circle. Depending on the angle of the line (specifically which quarter of the circle the angle is within) the starting x and y co-ordinate of the line change. See this video to see what I mean.
I've put a white 2x2 pixel square behind the line to better show the change in the starting x and y co-ordinates. The line should be drawn from the bottom right pixel of the square.
Here is the code which I am running in my DrawFrame method:
radians = Math.toRadians(angle);
x2 = 15.0 * Math.cos(radians);
y2 = 15.0 * Math.sin(radians);
c.drawLine(80, 140, 80 + (float)x2, 140 + (float)y2, mPaint);
angle += 1;

c is the Canvas and mPaint is a new Paint() object.
I'm new to Android, so maybe I'm missing something.

A: Technically, with floating point precision, your starting point is the exact center of the white box, which is the left and top of point 80, 140.

You might be happier with the results if you have your line start in the middle of the pixel-- like using 80.49 and 140.49 for you center.

Either way, you are just suffering from rounding problems in trying to draw a fine line with clunky pixels.


text:
Q: alternative to multidimensional array in c tI have the following code:
 #define FIRST_COUNT 100
 #define X_COUNT 250
 #define Y_COUNT 310
 #define z_COUNT 40

struct s_tsp {

     short abc[FIRST_COUNT][X_COUNT][Y_COUNT][Z_COUNT];
};

struct s_tsp xyz;

I need to run through the data like this:
for (int i = 0; i < FIRST_COUNT; ++i)
    for (int j = 0; j < X_COUNT; ++j)
          for (int k = 0; k < Y_COUNT; ++k)
                for (int n = 0; n < Z_COUNT; ++n)
                      doSomething(xyz, i, j, k, n);

I've tried to think of a more elegant, less brain-dead approach. ( I know that this sort of multidimensional array is inefficient in terms of cpu usage, but that is irrelevant in this case.)  Is there a better approach to the way I've structured things here?

A: If you need a 4D array, then that's what you need. It's possible to 'flatten' it into a single dimensional malloc()ed 'array', however that is not quite as clean:
abc = malloc(sizeof(short)*FIRST_COUNT*X_COUNT*Y_COUNT*Z_COUNT);

Accesses are also more difficult:
*(abc + FIRST_COUNT*X_COUNT*Y_COUNT*i + FIRST_COUNT*X_COUNT*j + FIRST_COUNT*k + n)

So that's obviously a bit of a pain.
But you do have the advantage that if you need to simply iterate over every single element, you can do:
for (int i = 0; i < FIRST_COUNT*X_COUNT*Y_COUNT*Z_COUNT; i++) {
    doWhateverWith *(abc+i);
}

Clearly this method is terribly ugly for most uses, and is a bit neater for one type of access. It's also a bit more memory-conservative and only requires one pointer-dereference rather than 4.

A: NOTE: The intention of the examples used in this post are just to explain the concepts. So the examples may be incomplete, may lack error handling, etc.
When it comes to usage of multi-dimension array in C, the following are the two possible ways.
Flattening of Arrays
In C, arrays are implemented as a contiguous memory block. This information can be used to manipulate the values stored in the array and allows rapid access to a particular array location.
For example,
int arr[10][10];
int *ptr = (int *)arr ;

ptr[11] = 10;
// this is equivalent to arr[1][0] = 10; assign a 2D array
// and manipulate now as a single dimensional array.

The technique of exploiting the contiguous nature of arrays is known as flattening of arrays.
Ragged Arrays
Now, consider the following example.
char **list;
list[0] = "United States of America";
list[1] = "India";
list[2] = "United Kingdom";
for(int i=0; i< 3 ;i++)
    printf(" %d ",strlen(list[i]));
// prints 24 5 14

This type of implementation is known as ragged array, and is useful in places where the strings of variable size are used. Popular method is to have dynamic-memory-allocation to be done on the every dimension.

NOTE: The command line argument (char *argv[]) is passed only as ragged array.

Comparing flattened and ragged arrays
Now, lets consider the following code snippet which compares the flattened and ragged arrays.
/* Note: lacks error handling */
int flattened[30][20][10];
int ***ragged;
int i,j,numElements=0,numPointers=1;
ragged = (int ***) malloc(sizeof(int **) * 30);
numPointers += 30;
for( i=0; i<30; i++) {
    ragged[i] = (int **)malloc(sizeof(int*) * 20);
    numPointers += 20;
    for(j=0; j<20; j++) {
        ragged[i][j]=(int*)malloc(sizeof(int) * 10);
        numElements += 10;
    }
}

printf("Number of elements = %d",numElements);
printf("Number of pointers = %d",numPointers);

// it prints
// Number of elements = 6000
// Number of pointers = 631

From the above example, the ragged arrays require 631-pointers, in other words, 631 * sizeof(int *) extra memory locations for pointing 6000 integers. Whereas, the flattened array requires only one base pointer: i.e. the name of the array enough to point to the contiguous 6000 memory locations.
But OTOH, the ragged arrays are flexible. In cases where the exact number of memory locations required is not known you cannot have the luxury of allocating the memory for worst possible case. Again, in some cases the exact number of memory space required is known only at run-time. In such situations ragged arrays become handy.
Row-major and column-major of Arrays
C follows row-major ordering for multi-dimensional arrays. Flattening of arrays can be viewed as an effect due this aspect in C. The significance of row-major order of C is it fits to the natural way in which most of the accessing is made in the programming. For example, lets look at an example for traversing a N * M 2D matrix,
for(i=0; i<N; i++) {
    for(j=0; j<M; j++)
        printf("%d ", matrix[i][j]);
    printf("\n");
}

Each row in the matrix is accessed one by one, by varying the column rapidly. The C array is arranged in memory in this natural way. On contrary, consider the following example,
for(i=0; i<M; i++) {
    for(j=0; j<N; j++)
        printf("%d ", matrix[j][i]);
    printf("\n");
}

This changes the column index most frequently than the row index. And because of this there is a lot of difference in efficiency between these two code snippet. Yes, the first one is more efficient than the second one!
Because the first one accesses the array in the natural order (row-major order) of C, hence it is faster, whereas the second one takes more time to jump. The difference in performance would get widen as the number of dimensions and the size of element increases.
So when working with multi-dimension arrays in C, its good to consider the above details!


text:
Q: Homogeneous metrics on compact Lie groups Given a differentiable manifold $M$, a Riemannian metric $g$ on $M$ is called homogeneous if its isometry group acts transitively on $M$. In that case, given any group $G$ acting transtitively on $(M,g)$ by isometries, we have the diffeomorphism $M\simeq G/H$ where $H$ is the stabilizer of any point $o\in M$.
We now fix $M=G$, a compact connected Lie group (I am mostly interested in the semisimple case).
It turns out that $G$ acts on itself by multiplication on the left, and this action is obviously transtive. Thus, one has a natural space of homogeneous metrics on $G$: the space of left-invariant metrics, which are the Riemannian metrics on $G$ such that this action is an isometry.

Is any homogeneous Riemannian metric on $G$ necessarily isometric to a left-invariant metric on $G$?

Although a right-invariant metric on $G$ is in general not left-invariant, it is true that $(G,g_r)$ with $g$ a right-invariant metric on $G$ is isometric to $(G,g_l)$ for some left-invariant metric $g_l$ on $G$.
Edit on April 18, 2022:
The general problem of classifying all homogeneous metrics on a fixed differentiable manifold $M$ seems to be extremely difficult. As far as I understand, one has to know all transitive Lie group actions on $M$ and (i.e., roughly, all possible realization $M=G/H$), for each of them, obtain the invariant metrics.
This problem is solved for tori, the (underlying manifolds) compact rank one symmetric spaces, and for certain Grassmannian spaces.
A more general question than previous one is

Are the homogeneous metrics on a compact connected Lie group $M=G$ classified?


text:
Q: Ubuntu internet connection problem I installed Ubuntu on my laptop. Here are my internet settings:
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
        address 10.1.17.10  /*this is my IP @ddress*/
        netmask 255.255.255.0
        dns-nameservers 8.8.8.8

I cannot connect to internet. I can ping 8.8.8.8 successfully but not any website.
Any help, please? I cannot access the internet this way.

A: You have no viable route because you haven't specified one. I suggest you change your file to:
auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
    address 10.1.17.10
    netmask 255.255.255.0
    gateway 10.1.17.1
    dns-nameservers 8.8.8.8 10.1.17.1

Of course, substitute the address of your router or access point if not 10.1.17.1.
Generally, setting such details is preferred in Network Manager rather than in /etc/network/interfaces.
If you have an interface eth1, it is either a second ethernet card or a wireless interface. Check:
iwconfig

Does your computer have two ethernet ports? Are you attempting to connect with wired ethernet?
Have you confirmed the gateway and other details by checking the network settings on other connected devices on your network?

A: I believe your problem is the lack of a gateway. How are you connected to the internet? What is the output of route?


text:
Q: React todo app Login page appears for a moment even though logged in I have a CRUD todo application where the user logs in if they are not logged in and this is stored locally. Also todo app making CRUD operations via API. But even if the user is logged in, when the page is refreshed, the login screen appears and disappears for a moment. How can I solve this?
  const [todoList, setTodoList] = useState([]);
  const [newTask, setNewTask] = useState("");
  const [todoEditing, setTodoEditing] = useState(null);
  const [editingText, setEditingText] = useState("");
  const [username, setUsername] = useState("");
  const [savedUsername, setSavedUsername] = useState("");
  const [theme, setTheme] = useState("light");
  const [addLoading, setAddLoading] = useState(false); // when adding a todo loading spinner appears in button
  const [todoLoading, setTodoLoading] = useState(null); //when crud operations happen a loading spinner appears in todo cards
  const [loading, setLoading] = useState(false); // loading state for crud functions
  const [loginLoading, setLoginLoading] = useState(false); // loading screen for app rendering

useEffect(() => {
    setLoginLoading(true);
    const storageUsername = localStorage.getItem("username");
    if (storageUsername) {
      setSavedUsername(storageUsername);
    }

    setLoginLoading(false);
  }, []);

<ThemeContext.Provider value={{ theme }} style={{ position: "relative" }}>
      {savedUsername ? (

.... Components

  ) : (

          {loginLoading ? (
            <Loading />
          ) : (
            <Login
              handleChange={setUsername}
              handleLogin={handleLogin}
              value={username}
            />
          )}

      )}
    </ThemeContext.Provider>

A: Your effect from useEffect is only executed after your first render. So your first state for the loginLoading is false then true and then false again. This should fix it:
  const [todoList, setTodoList] = useState([]);
  const [newTask, setNewTask] = useState("");
  const [todoEditing, setTodoEditing] = useState(null);
  const [editingText, setEditingText] = useState("");
  const [username, setUsername] = useState("");
  const [savedUsername, setSavedUsername] = useState("");
  const [theme, setTheme] = useState("light");
  const [addLoading, setAddLoading] = useState(false); // when adding a todo loading spinner appears in button
  const [todoLoading, setTodoLoading] = useState(null); //when crud operations happen a loading spinner appears in todo cards
  const [loading, setLoading] = useState(false); // loading state for crud functions
  const [loginLoading, setLoginLoading] = useState(true); // loading screen for app rendering

useEffect(() => {
    const storageUsername = localStorage.getItem("username");
    if (storageUsername) {
      setSavedUsername(storageUsername);
    }

    setLoginLoading(false);
  }, []);

<ThemeContext.Provider value={{ theme }} style={{ position: "relative" }}>
      {savedUsername ? (

.... Components

  ) : (

          {loginLoading ? (
            <Loading />
          ) : (
            <Login
              handleChange={setUsername}
              handleLogin={handleLogin}
              value={username}
            />
          )}

      )}
    </ThemeContext.Provider>

But, to improve even more, I wouldn't use a loading state for the login because localStorage.getItem("username") is a synchronous operation that can be performed more elegantly like that:
  const [todoList, setTodoList] = useState([]);
  const [newTask, setNewTask] = useState("");
  const [todoEditing, setTodoEditing] = useState(null);
  const [editingText, setEditingText] = useState("");
  const [username, setUsername] = useState("");
  const [savedUsername, setSavedUsername] = useState(() => localStorage.getItem("username") || "");
  const [theme, setTheme] = useState("light");
  const [addLoading, setAddLoading] = useState(false); // when adding a todo loading spinner appears in button
  const [todoLoading, setTodoLoading] = useState(null); //when crud operations happen a loading spinner appears in todo cards
  const [loading, setLoading] = useState(false); // loading state for crud functions

<ThemeContext.Provider value={{ theme }} style={{ position: "relative" }}>
      {savedUsername ? (

.... Components

  ) : (

          <Login
            handleChange={setUsername}
            handleLogin={handleLogin}
            value={username}
          />

      )}
    </ThemeContext.Provider>


text:
Q: Objective-C Extract index of a range returned by rangeOfString: How to extract an NSUInteger index from
NSRange range = [string rangeOfString: substring]

so I can write this index in [array objectAtIndex:index]?

A: NSRange range = [string rangeOfString:substring];
NSUInteger index = range.location;
//...

A: // make sure that the substring was actually found:
NSRange result = [string rangeOfString:substring];

if (result.location != NSNotFound)
{
    // make sure that the index exists in the array
    if (result.location < [array count])
    {
        id someObj = [array objectAtIndex:result.location];
        // do something cool with someObj here
    }
}


text:
Q: Even after importing Numpy not recognised My code:
import numpy as np

import tensorflow

Output:
NameError                                 Traceback (most recent call last)
< ipython-input-1-87dbf2ff9b36 > in < module >
----> 1 x = np.random.randint(0,100)

NameError: name 'np' is not defined

What I don't understand is that even though I have already imported the library it is not getting detected and gives me a NameError, Same is the case with a lot of libraries.
I am currently using Jupyter Lab through Anaconda.
=================================>
Got the solution for all the Issues while installing TensorFlow on M1 Macbook
Follow the below link:
https://naturale0.github.io/machine%20learning/setting-up-m1-mac-for-both-tensorflow-and-pytorch#:~:text=Macs%20with%20ARM64%2Dbased%20M1,both%20from%20consumers%20and%20developers.

A: Thank you @Akella Niranjan for the reference. For the benefit of community providing solution here as written by @Sihyung Park.
Install TensorFlow-macOS for Apple Silicon M1
It is easy to install it with the system python since the installation script is given by Apple. However, my goal was to install it with other python so that I can install additional packages for data science without difficulty.
I mainly followed instructions from here to install tensorflow-macos, and then created ipykernel of it so that I can run this environment any time by switching the kernel inside jupyter notebook.

*

*First install miniforge, which natively supports M1. The installation defaults to directory ~/miniforge3/.

*Create virtual environment named tf_macos with conda and install Python 3.8.
conda create -n tf_macos
conda activate tf_macos
conda install -y python=3.8

I specified the version 3.8 so that it matches requirement of tensorflow-macos.

*Download and install tensorflow-macos from Apple Github.

git clone https://github.com/apple/tensorflow_macos.git
cd tensorflow_macos/arm64

pip install --force pip==20.2.4 wheel setuptools cached-property six
pip install --upgrade --no-dependencies --force numpy-1.18.5-cp38-cp38-macosx_11_0_arm64.whl grpcio-1.33.2-cp38-cp38-macosx_11_0_arm64.whl h5py-2.10.0-cp38-cp38-macosx_11_0_arm64.whl tensorflow_addons-0.11.2+mlcompute-cp38-cp38-macosx_11_0_arm64.whl
pip install absl-py astunparse flatbuffers gast google_pasta keras_preprocessing opt_einsum protobuf tensorflow_estimator termcolor typing_extensions wrapt wheel tensorboard typeguard
pip install --upgrade --force --no-dependencies tensorflow_macos-0.1a1-cp38-cp38-macosx_11_0_arm64.whl

*Add the environment as jupyter kernel.

pip install jupyter

python -m ipykernel install --name=tf_macos

Then merely switching the ipython kernel to tf_macos allows us to use mlcompute-backend TensorFlow without a hassle

*Install additional packages (optional)

conda install scipy pandas matplotlib

For more information you can refer here


text:
Q: How to transition VSCode devcontainers to a production environment? I'm a bit of a newb so bear with me.  I'm familiar with writing local applications and scripts to automate admin tasks that I need to do, but now I'm trying to get familiar with the Gitlab CI/CD process.  I have been using (and loving) VSCode devcontainers because I fell into a hole of learning Python virtual environments and trying to manage different python versions, etc., and devcontainers makes all that headache go away for me.  Now I'm trying to figure out how I can write a simple application (like a flask endpoint) and deploy it via Gitlab CI/CD.
I'm currently stuck on how to transition my VSCode Dockerfile for the devcontainer to a production ready Dockerfile.  For instance, the VSCode Dockerfile uses a VSCode base image that I wouldn't imagine would be acceptable in a production environment.  Is there a best practice for creating a production Docker configuration for deployments?  If it is simply a matter of creating a separate Dockerfile, doesn't that defeat one of the purposes of using Docker containers for development?  You would still have a situation of "well it works in my container..."


text:
Q: Why is a Quadratic programming problem a Second-order cone programming? I have seen that QP can be rewritten as a SOCP from several resources online. Why is this the case? More precisely, using relaxation, QP can be written as
$$
\min_{x,t} c^Tx + t ~\text{ subject to } Ax = b, Dx \le d, \frac{1}{2}x^TQx \le t.
$$
Resources I have encountered said
$$
\frac{1}{2}x^TQx \le t \Longleftrightarrow \left|\left|\left(\frac{1}{\sqrt{2}}Q^{\frac{1}{2}}x, \frac{1}{2}(1-t)\right)\right|\right|_2 \le \frac{1}{2}(1+t)
$$
I understand how these two constraints are the same, but why is the right-hand side of the form of the second-order norm cone? Clearly, $t$ is in both the left-hand side and the right-hand side, so I am not sure why this can be treated as the second-order norm-cone.
If there is an alternative way to see why QP is an SOCP, I would appreciate it if one could elaborate it.


text:
Q: Android phone's microSD not useable by Windows 8, after using under Ubuntu I connected my Android phone (as 'mass storage') to Ubuntu 14.04 LTS. It has a microSD card with fat32 filesystem. Thereafter I logged it to Windows and connected, but my Windows 8 didn't recognise it. It shows the card as a new drive, but when I double click it says corrupted file system, do you wish to repair files; I cannot use or open files in it.
Then I logged into Ubuntu again, card works properly under Ubuntu.
To solve this I formatted the card by logging into windows, so it worked. But again when I connected it to Ubuntu (where it worked) and then to Windows on a different PC it shows same error.
Why does card not open in Windows, if opened with Ubuntu, but works properly on Ubuntu itself no matters what. Seems like Ubuntu is altering file system of card.
Please help solving this so that I can use my microSD card without any trouble on any OS.
I have Android 4.4.2


text:
Q: Recursive parameter estimation for partially observed Ito SDEs I'm trying to get my head around online (recursive) maximum-likelihood parameter estimation in the language of stochastic processes and in the context of stochastic filtering, i.e. where we have a partially observed Ito diffusion process
\begin{align}
dX_t&=f(t,\theta_0,X_t)dt+g(t,\theta_0,X_t)dW_t, \\
dY_t&=h(t,\theta_0,X_t)dt+dV_t.
\end{align}
Here, everything is scalar, $X_t$ is the (unobserved) signal, $Y_t$ is the observation, $W_t$ and $V_t$ are independent standard Wiener processes, and $\theta_0$ is a parameter. Suppose we don't know $\theta_0$ and we want to estimate it recursively as observations $Y_t$ come in.
Moura & Mitter (1986) give a formula for the log likelihood function for parameter estimation based on only observations of $Y_t$, namely
\begin{equation}
L_t(\theta)=\frac{1}{r}\int_0^t\left ( \hat h_s dY_s-\frac{1}{2} \hat h^2_s ds \right), \quad \hat h_t=E \left[ h(t,\theta,X_t)|\mathcal{F}^Y_t \right].
\end{equation}
First of all, it is not entirely clear why the above function would be the correct thing to look at, and the paper mentioned above does not really help me with a lot of detail. What I can guess so far is that they use a sequence of changes of measures, ending up with one (let's call it $\mathcal{Q}_{\theta}$) under which the innovations process $n_t$, defined as
\begin{equation}
dn_t=dY_t-\hat h_t dt,
\end{equation}
is a Wiener process. By Girsanov's theorem, the above log likelihood function is the log of the Radon-Nikodym (RN) derivative $d\mathcal{Q}_{\theta}/d\tilde{\mathcal{P}}_{\theta}|_{\mathcal{F}_t}$ of that measure with respect to another measure $\tilde{\mathcal{P}}_{\theta}$ under which $Y_t$ is a Wiener process (is this correct?). However, what I would want to maximize looks something like
\begin{equation}
L'_t(\theta)=\log \frac{d\mathcal{P}^Y_{\theta}}{d\mathcal{P}^Y_0},
\end{equation}
i.e. the RN derivative of the measure of the process $Y_t$, with $X_t$ 'integrated' or 'marginalized' out, with respect to a parameter-independent reference measure $\mathcal{P}^Y_0$. So my first question is: why should $L_t$ be the log likelihood function instead of $L'_t$, or alternatively, why is it equivalent to maximize $L'_t$?

For my second question, let's pretend that we understand why $L_t$ is the log likelihood function, and let's maximize it. For simplicity, I assume that everything is linear,
\begin{align}
dX_t&=-X_tdt+dW_t, \\
dY_t&=\theta X_tdt+dV_t,
\end{align}
such that
\begin{equation}
L_t(\theta)=\frac{1}{r}\int_0^t\left ( \theta\mu_s dY_s-\frac{1}{2} \theta^2(\mu_s)^2 ds \right),
\end{equation}
where $\mu_t$ is the mean of the Kalman-Bucy filter
\begin{align}
d\mu_t&=-\mu_tdt+\theta \sigma^2_t(dY_t-\theta\mu_tdt), \\
\frac{d\sigma^2_t}{dt}&=1-2\sigma^2_t-\theta^2\sigma^4_t,
\end{align}
which is integrated using the parameter $\theta$, acquiring an implicit parameter dependence. To maximize $L_t$ for fixed $t$, we could use a steepest ascent algorithm, i.e.
\begin{equation}
\begin{split}
\frac{d}{d\tau}\hat \theta_{\text{ML,offline}}(\tau)&=\eta \partial_{\theta}L_t(\theta)\Big|_{\theta=\hat \theta_{\text{ML,offline}}(\tau)}\\
&=\frac{\eta}{r}\int_0^t\left(dY_s-\theta\mu_sds\right)\left(\mu_s+\theta\nu_s\right)\Big|_{\theta=\hat \theta_{\text{ML,offline}}(\tau)}.
\end{split}
\end{equation}
Here, $\tau$ is the parameter of the offline gradient ascent, i.e. while the process $(X,Y)$ is stopped (observations from 0 to $t$ have been collected and stored), the gradient ascent is initialized at $\tau=0$ with an initial guess $\theta_{\text{ML,offline}}(0)$, and then updated according to the differential equation above until it converges. We also introduced a learning rate $\eta>0$ and the derivative of the mean of the Kalman-Bucy filter, $\nu_t=\partial_{\theta}\mu_t$, for which we find
\begin{align}
d\nu_t&=-\nu_tdt+(\sigma^2_t+\theta\rho^2_t)(dY_t-\theta\mu_tdt)-\theta\sigma^2_t(\mu_t+\theta\nu_t)dt, \quad &\nu_0=0,\\
\frac{d\rho^2_t}{dt}&=-2\rho^2_t-2\theta^2\sigma^2_t\rho^2_t-2\theta\sigma^4_t\quad &\rho^2_0=0.
\end{align}
Finally, we could turn the above gradient-based update equation into a recursive update rule by getting rid of the integral:
\begin{equation}
d\hat\theta_t=\frac{\eta}{r}\left(dY_t-\hat\theta_t\mu_tdt\right)\left(\mu_t+\hat\theta_t\nu_t\right),
\end{equation}
a rule which works well enough in practice (simulations). The problem is reconciling this with another derivation one could come up with. Let's discretize the Ito SDEs above:
\begin{align}
X_i&=X_{i-1}-\delta t X_{i-1}+\sqrt{\delta t}\xi_i, \\
Y_i&=Y_{i-1}+\theta\delta t X_{i-1}+\sqrt{\delta t}\eta_i,
\end{align}
where $\xi_i,\eta_i$ are sampled i.i.d from $\mathcal{N}(0,1)$. This is the Euler-Maruyama discretization. We can write down a log likelihood function in discrete time:
\begin{align}
L^D_n(\theta)&=\log P(\mathbf{Y}|\theta), \\
P(\mathbf{Y}|\theta)&=\int d\mathbf{X}\, P(\mathbf{X},\mathbf{Y}|\theta), \\
P(\mathbf{X},\mathbf{Y}|\theta)&=P(X_1)P(Y_1)\prod_{i=2}^n P(X_i|X_{i-1}) P(Y_i|X_{i-1},Y_{i-1},\theta).
\end{align}
Taking the derivative, we obtain
\begin{equation}
\begin{split}
\partial_{\theta}L^D_n(\theta)&=\frac{1}{P(\mathbf{Y}|\theta)}\int d\mathbf{X}\,\partial_{\theta} P(\mathbf{X},\mathbf{Y}|\theta) \\
&=\int d\mathbf{X}\, P(\mathbf{X}|\mathbf{Y},\theta)\partial_{\theta}\log P(\mathbf{X},\mathbf{Y}|\theta).
\end{split}
\end{equation}
Now, using the structure of the joint distribution in the integrand, and the explicit form of the Gaussian distribution, one ends up with
\begin{equation}
\partial_{\theta}\log P(\mathbf{X},\mathbf{Y}|\theta) = \sum_{i=2}^n \left[X_{i-1}(Y_i-Y_{i-1})-\theta\delta t X^2_{i-1} \right],
\end{equation}
which, after taking the continuum limit, expectations over $P(\mathbf{X}|\mathbf{Y},\theta)$ and getting rid of the integral, seems to lead to an update rule
\begin{equation}
d\hat\theta_t\propto \left[\mu_t dY_t-\theta(\mu^2_t+\sigma^2_t)dt \right].
\end{equation}
So the second question (sorry for being so long-winded) is: Why are the two rules different? Note that they are fairly similar, with the only differences being that the first rule has expectations under the square, and the second one expectation of the square, and the second one does not contain filter derivatives. Is there a flaw in one of these derivations? Or is it to be expected that we get different rules because the problem is not well-posed?

A: The formulation of a likelihood function for a continuous-time stochastic process requires the choice of a reference measure. In the context of parameter estimation, the reference measure has to be parameter-independent. In the case of partially observed diffusion processes with additive observation noise, the innovation process is a Brownian motion adapted to the observation filtration, and consequently there is a reference measure under which $Y_t$ is a Brownian motion.
The big miracle is that the Radon-Nikodym derivative gives us an expression of the likelihood function in terms of the filter, which makes it perfect for online parameter estimation.
The full story, including numerical examples, is written up in the following article:
Online Maximum Likelihood Estimation of the Parameters of Partially Observed Diffusion Processes


text:
Q: $locationProvider in angular url Recently I have developed a website http://www.skduhariya.com, this is completely based on angularJS.  I'm using the concept of ui-router for routing between the static pages. Symbol(#) is being displayed in the URL like skduhariya.com/#/blogs
I tried using $locationProvider to remove Symbol(#) from the URL so URL becomes like skduhariya.com/blogs,
its working fine, But, when we refresh the browser is not working as expected. Its display 404-Page Not found.
code:
function routeConfig($stateProvider, $locationProvider) {
    $stateProvider.state('public', {
        abstract: true,
        templateUrl: 'src/public/public.html'
    });
    $locationProvider.html5Mode(true);
}

can anyone help me out to fix this.

A: You may could watch here
As he is already describing:

Server side
  Using this mode requires URL rewriting on server side,
  basically you have to rewrite all your links to entry point of your
  application (e.g. index.html)

:)


text:
Q: Error al transferir dominio de GoDaddy a Siteground Cometí un error al transferir mi dominio de GoDaddy a SiteGround para crear un nuevo WordPresss desde 0 allí. El asunto fue que transferí el dominio sin cambiar previamente los DNS en GoDaddy por los de SiteGround y al Instalar el nuevo WordPress no puedo ver la página ahora! Como se borró la instalación de WordPress en GoDaddy, y se transfirió el dominio no puedo ver los DNS que tenía allí!
Mi pregunta sería: Si tengo los DNS que tenía en GoDaddy copiados en un archivo de texto y los remplazo en mi SiteGround podré tener acceso de nuevo a mi WordPress con el mismo dominio?

A: En en panel donde tienes el nuevo dominio busca algo como: "Servidores de nombres" o DNS y cambialos por los de tu hosting y eso será todo.


text:
Q: Setuid shell script Need some help on passing argv, so the shell script can be run as /usr/local/bin/script.sh user domain
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main( int argc, char *argv[] )
{

   if( argc == 3 )
   {
      char *user = argv[1];
      char *domain = argv[2];
      setuid(0);
      system("/usr/local/bin/somescript.sh user domain");
      return 0;
   }
   else if( argc > 3 )
   {
      printf("Too many arguments supplied.\n");
   }
   else
   {
      printf("One argument expected.\n");
   }
}

After compiling, i executed the code:
[user@server:/usr/local/bin]#c_setuid hello hello.com
Invalid username/domain
[user@server:/usr/local/bin]#

I suspect the string hello & hello.com wasn't pass to /usr/local/bin/somescript.sh. Anyone can help?

A: You cannot become root by calling setuid(0).
You are passing the literal "user" and "domain" strings to the script. C is not Perl, variables are not magically interpolated into strings.
You need to create the string passed to system in runtime:
char cmd[100];
sprintf(cmd, "/usr/local/bin/somescript.sh %s %s", user, domain);
system(cmd);


text:
Q: Textarea is not showing in php. What is error? I have following script to print a textarea and some text into that. When page is loaded, textarea does not appear even when while condition is true. What could be the problem?
$seq_query = "SELECT * FROM `mcsm`.`conseq_human` WHERE `MCSM_Id`='$mcsm_id';";
$seq_result = mysql_query($seq_query);

print '

Conserved sequence
';

if(!$conseq = mysql_fetch_array($seq_result))
{
    print "

Not sufficient information yet.

";
}
else
{
    while($conseq = mysql_fetch_array($seq_result))
    {
        print "
<textarea name='seq_textarea' cols='100' rows=''>".$conseq['ConSequence']."</textarea>

Based on MSA of ".$conseq['MSA_No_of_Seq']." sequences from ".$conseq['FamilyName']." family.

";
    }
}

A: try this
$seq_query = "SELECT * FROM `mcsm`.`conseq_human` WHERE `MCSM_Id`='$mcsm_id';";
$seq_result = mysql_query($seq_query);
print '

Conserved sequence
';
if(mysql_num_rows($seq_result)>0)
{
    while($conseq = mysql_fetch_array($seq_result))
   {
    print "
<textarea name='seq_textarea' cols='100'        rows=''>".$conseq['ConSequence']."</textarea>

Based on MSA of ".$conseq['MSA_No_of_Seq']." sequences from ".$conseq['FamilyName']." family.

";
   }
}
else{
print "

Not sufficient information yet.

";
}

A: You are printing
 for each while iteration.try this:
$seq_query = "SELECT * FROM `mcsm`.`conseq_human` WHERE `MCSM_Id`='$mcsm_id';";
$seq_result = mysql_query($seq_query);
if (!$seq_result) {
    die('Invalid query: ' . mysql_error());
}
else{
    print '

Conserved sequence
';
    if(mysql_num_rows($seq_result)==0)
    {
        print "

Not sufficient information yet.

";
    }
    else
    {
        while($conseq = mysql_fetch_array($seq_result))
        {
            print "
<textarea name='seq_textarea' cols='100' rows=''>".$conseq['ConSequence']."</textarea>

Based on MSA of ".$conseq['MSA_No_of_Seq']." sequences from ".$conseq['FamilyName']." family.
";
        }
        echo '
';
    }
}


text:
Q: Genymotion error when rotating android screen When I run my application, it runs perfectly. But when I press the "Rotate Screen" button, i get this error message:
It says: "Unable to start the virtual device" and "Unable to initialize the subwindow system"
Thank you.

A: You mean,you want a horizontal Screen? If not ,try this to lock the screen.
<activity
            android:name="com.hf.yuguo.home.TabActivityHome"
            android:screenOrientation="portrait" />


text:
Q: Angular 4 saving data and setting new page while loading data from a JSON API I'm having trouble with the use of a JSON API and Angular with this code

          {{i}}.  {{Questionnaire.attributes.content.question}}

         <input type="radio"  name="answ" [value]="j" >{{ans}}

so I'm loading a survey from my JSON API to my website with the help of angular. Now my problem is there are 122 questions at the moment. While loading the answers with ngFor the radio buttons get all the same name an so it's just possible to give one answer for 122 questions:

*

*Question:

Is it possible to give the radio buttons a name which automatically counts up when the next question begins?

*Question:

Is it possible to start a new page after loading 5 questions from the API or do I have to post all the 122 Questions to the same page?
Hope somebody knows what to do. Thank you!

A: I would suggest you create a component for displaying Question/Answer, let's say "PollComponent", and handling the server communication via a service i.e. posting the user selected option etc. The input to this component would be a question id. Another component would be responsible for fetching your 122 question id's and rendering the "PollComponent" based on the id selected.
It would be similar to TODO app in angular 2 as shown here. https://github.com/tastejs/todomvc/tree/master/examples/angular2


text:
Q: eclipse can not start up my tomcat server, how to turn the server on when i try to run the jsp-file using eclipse, eclipse shows me that my tomcat server is turned off although i turned it on from 'startup.bat' file which is located in the bin directory inside the tomcat installation folder.
I encounter the error shown in the image posted below.how to solve it?

A: When you configure Tomcat using Runtime configuration in eclipse, then you need NOT to run the tomcat manually. When you execute a server side program such as jsp/servlet, eclipse will first start the associated runtime(Tomcat) and then deploy your jsp/servlet on it.
In your case, as you have manually started the Tomcat, so when eclipse tries to launch the same tomcat, it throws and error saying port already in use.

A: It seems your sever is already in running state and you are trying to start again.
Any chance you started your server though comand prompt, before trying in eclipse.
If exsist try kiiling the java process of the server in task manager and try again

A: Let Eclipse handle the Tomcat instance. Run shutdown.bat, then start Tomcat from Eclipse by clicking Windows->Show view->Servers, right click and Start.


text:
Q: Handling plugins with configuration with Ninject I'm writing an application where various bits of business logic can sit in separate assemblies, then those bits are used to build an object expecting two interfaces, something like this:
public interface ISubjectSource {}
public interface IStudySource {}

public class Worker
{
   public Worker(ISubjectSource subjectSource, IStudySource studySource)
   {
     ....
   }
}

The seperate assemblies can contain various implementations of ISubjectSource and IStudySource. Then along with a config file:
"Study1":{
    "assemblies":["Compare.Sql.dll"],
    "mappingSource":"Compare.Sql.SqlSubjectSource,Compare.Sql",
    "studySource":"Compare.Sql.SqlStudySource,Compare.Sql",
}

Which describes what is needed to build to worker for "Study1". My problem arrives when the various sources have their own dependencies (e.g. the Sql Sources take an interface that handles creating a connection whose connection string might come from different files).
So, my question boils down to: How do I tell Ninject that when I create a worker for study1, be sure it gets these objects, but when I create a worker for Study2, it gets this other set of objects?

A: Here's what we do:
We've got an interface IPlugin, with an identifier and an enumerable of modules.
public interface IPlugin
{
  string Identification { get; }

  IEnumerable<Type> Modules { get; }
}

The Types in Modules must all be inheriting from NinjectModule. Identification is what you refer to in your configuration, like "i want to use plugin SQLStudySource" or "i want to use plugin FileStudySource".
Then we are using https://github.com/ninject/ninject.extensions.conventions to bind all IPlugin implementations from a specific set of assemblies (like all assemblies in the plugin folder):
this.Bind(x => x.FromAssembliesInPath("foo")
            .SelectAllClasses()
            .InheritedFrom<IPlugin>()
            .BindTo<IPlugin>());

Next you activate plugins (or rather their modules, respectively), according to configuration:
IEnumerable<Type> activatedPluginModules = kernel
  .GetAll<IPlugin>()
  .Where(plugin => configuration.ActivatedPluginIdentifications.Contains(plugin.Identification)
  .SelectMany(x => x.Modules)
  .Distinct();

foreach(Type module in activatedPluginModules)
{
  kernel.Load(module);
}

That's about it.


text:
Q: nodejs c++ addon -- unable to node-gyp build using nan module I am learning how to build C/C++ addons for nodejs.
I could successfully node-gyp configure, node-gyp build and run node index.js on a simple hellow world program.  So, my basic setup is working. The below code (copy-paste from official nodejs documentation) is the working version of my C++ code.
//hello.cc
//#include <node.h>
//#include <nan.h>
#include "./node_modules/nan/nan.h"
#include <iostream>
using namespace v8;

namespace demo {
  using v8::FunctionCallbackInfo;
  using v8::Isolate;
  using v8::Local;
  using v8::Object;
  using v8::String;
  using v8::Value;

  void Method (const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();
    std::cout << "Executing some stupid func..." << std::endl;
    args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
  }

  void init(Local<Object> exports) {
    NODE_SET_METHOD(exports, "hello", Method);
  }

  NODE_MODULE(addon, init)
} // namespace demo

However, when I use Nan module, and the version of code documented in the nan site, I get compilation errors indicating NanScope is not declared in this scope.
//hello.cc
#include "./node_modules/nan/nan.h"
#include <iostream>
using namespace v8;

  NAN_METHOD(Method) {
          Nan::NanScope();
    NanReturnValue(String::New("world"));
  }

  void init(Handle<Object> exports) {
    exports->Set(NanSymbol("hello"),
        FunctionTemplate::New(Method)->GetFunction());
  }

  NODE_MODULE(hello, init)

Part of the error output...
make: Entering directory '/home/rvnath/projects/comviva/node-addons/hello-world/build'
  CXX(target) Release/obj.target/addon/hello1.o
../hello1.cc: In function 'Nan::NAN_METHOD_RETURN_TYPE Method(Nan::NAN_METHOD_ARGS_TYPE)':
../hello1.cc:7:14: error: 'NanScope' was not declared in this scope
     NanScope();
              ^

After a bit of googling around, a few sites pointed out that we should be using Nan::Scope, and that the Nan documentation was out-of-date.  I tried the change but it still didn't work.  It gives an error saying "Scope is not a member of Nan".
I am unable to find, how to use the Nan version correctly.  Any help here will be highly appreciated.


text:
Q: Can not add reference to COM lib - no such tab in reference manager I need to add a reference to MS Excel into my solution, but I simply can not find where to do it. In the Reference manager (on Right Click on solution / Add / Add Reference I simply get this
Where I've gone wrong?


text:
Q: EntityFramework GroupBy with DBFunctions or alternative I have 100 rows of data with different dates. I would like to group by the result by same dates each 30 minutes apart.
Instead:
Result 1, 2016-02-02 13:00:24
Result 1, 2016-02-02 13:01:24
Result 1, 2016-02-02 13:02:24
Result 1, 2016-02-02 13:33:24
Needed:
Result 1, 2016-02-02 13:00:24
Result 1, 2016-02-02 13:33:24
Original query:
    return await loc.Where(p => p.ReadTime >= df && p.ReadTime <= dt)
        .OrderBy(p => p.ReadTime)
        .ProjectTo<LocationModel>().ToListAsync();

What I tried:
    return await loc.Where(p => p.ReadTime >= df && p.ReadTime <= dt)
        .GroupBy(p => DbFunctions.TruncateTime(p.ReadTime))
        .Select(p => new LocationModel
        {
            Lng = p.FirstOrDefault().Lng,
            Lat = p.FirstOrDefault().Lat
        })
        .ToListAsync();

Stack trace error:

.ThrowForNonSuccess(Task task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification
  (Task task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter1.GetResult()\r\n   at
  System.Web.Http
  .Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()","innerException":{"message":"An
  error  has occurred.","exceptionMessage":"Timeout expired.  The
  timeout period elapsed prior to completion  of the operation or the
  server is not
  responding.","exceptionType":"System.Data.SqlClient.SqlException"
  ,"stackTrace":"   at
  System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__167_0(Task1
  result )\r\n   at
  System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()\r\n
  at System .Threading.Tasks.Task.Execute()\r\n--- End of stack trace
  from previous location where exception was  thrown ---\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r \n   at
  System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.

d__c.MoveNext()","innerException":{"message":"An error has occurred.","exceptionMessage":"The wait operation  timed
    out","exceptionType":"System.ComponentModel.Win32Exception","stackTrace":null}}}

A: Other than loading all of the data in to memory and manually formatting it as required, the only feasible way I can think of to do this with a single query is to put the rows in to pre-defined date "buckets" and choose a row from each bucket.
The most logical choice for the buckets would be on the hour and half past the hour since you're looking for 30 minute intervals, for example:
Result 1, 2016-02-02 13:00:24, 2016-02-02 13:00:00 (bucket 1)
Result 1, 2016-02-02 13:01:24, 2016-02-02 13:00:00 (bucket 1)
Result 1, 2016-02-02 13:02:24, 2016-02-02 13:00:00 (bucket 1)
Result 1, 2016-02-02 13:33:24, 2016-02-02 13:30:00 (bucket 2)

The next problem to tackle is selecting which row to use for each of the buckets. One approach you could use is to determine the date closest to the bucket (minimum) and use it:
from l in loc
join bucket in (
    from l in loc
    group l by new DateTime(l.ReadTime.Year, l.ReadTime.Month, l.ReadTime.Day, l.ReadTime.Hour, l.ReadTime.Minute < 30 ? 0 : 30, 0) into g
    select g.Min(m => m.ReadTime)
) on l.ReadTime equals bucket
select new LocationModel
{
    Lng = l.FirstOrDefault().Lng,
    Lat = l.FirstOrDefault().Lat
}

Care needs to be taken with this approach though as you could end up with duplicates if there are rows with identical date/time values. If the entity/table uses an identity column as its primary key and rows are inserted in to the table in a date/time sequential manner, you can use the key to determine the row per bucket as the key is effectively in ascending date order:
from l in loc
join bucket in (
    from l in loc
    group l by new DateTime(l.ReadTime.Year, l.ReadTime.Month, l.ReadTime.Day, l.ReadTime.Hour, l.ReadTime.Minute < 30 ? 0 : 30, 0) into g
    select g.Min(m => m.Id)
) on l.Id equals bucket
select new LocationModel
{
    Lng = l.FirstOrDefault().Lng,
    Lat = l.FirstOrDefault().Lat
}

This will ensure there are no duplicates. Otherwise you'll either need to filter the duplicates in code or extend the query further. I don't know enough about your particular domain though so I'll leave this part for you to solve.
I should also point out the above queries are supported by Linq to SQL, however you may need to use the DbFunctions class for the DateTime bits with EF if something isn't supported (e.g. DbFunctions.CreateDateTime).


text:
Q: Able to download files from main method trigger But Not from behind Rest Service in Java via wget I have this code enclosed within a method, which when I call through the main method, runs absolutely fine, and downloads for me the required file via wget. I can see the file in my project directory.
At the same time when I expose this method behind a rest svc, which passes the required url to the method, it does not appear to download files, although it passes through the code. (Checked in debugger mode). Does it mean, its trying to download it elsewhere or the ProcessBuilder exposed behind rest svc is a problem here?
    Runtime rt = Runtime.getRuntime();
    ProcessBuilder pb;
    int exitVal = 0;
    try {
        pb = new ProcessBuilder("wget", "-O", "myFile.csv",myFileUrl);
        pb.redirectErrorStream(true);
        Process downloadFirst = pb.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(downloadFirst.getInputStream()));
        while (reader.readLine() != null) {}
        exitVal = downloadFirst.waitFor();
        LOG.info("Downloaded my file with exitValue:" + exitVal);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

A: As stated by @MrSmith42, it worked if I specify full path when calling from the rest service.


text:
Q: bootstrap make accordion responsive? I'm using the Bootstrap 3 Accordion Collapse,right now everything loads in one column, how can I make it so the panels use multiple columns in desktop resolution and one column in mobile mode?

                <?php
                foreach ($states as &$state) {
                    ?>

                                <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo $state; ?>">
                                    <?php echo $state; ?>

                        <div id="<?php echo $state; ?>" class="panel-collapse collapse in">

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
                                sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                                minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
                                commodo consequat.

                <?php }
                ?>

EDIT
This is my edided html

                        <?php
                        foreach ($states as &$state) {
                            ?>

                                        <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo preg_replace('/\s+/', '', $state); ?>">
                                            <?php echo $state; ?>

                                <div id="<?php echo preg_replace('/\s+/', '', $state); ?>" class="panel-collapse collapse in">

test

                        <?php }
                        ?>

and it looks like this now. Only one slim column in desktop resolution

A: I am not sure this is what you mean, but wouldn't it be enough to wrap your accordion in a col- class?
Like:

            <?php
            foreach ($states as &$state) {
                ?>

                            <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo $state; ?>">
                                <?php echo $state; ?>

                    <div id="<?php echo $state; ?>" class="panel-collapse collapse in">

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
                            sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                            minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
                            commodo consequat.

            <?php }
            ?>

A: Your amended code wont work simply because you are defining the col before the foreach so you are wrapping all of them into one col. You should have the col inside your foreach so they all wrap independently.
Try this:

    <?php foreach ($states as &$state) { ?>

                        <a data-toggle="collapse" data-parent="#accordion" href="#<?php echo $state; ?>">
                            <?php echo $state; ?>

                <div id="<?php echo $state; ?>" class="panel-collapse collapse in">

Lorem ipsum dolor sit amet, consectetur adipisicing elit,
                        sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                        minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
                        commodo consequat.

    <?php } ?>

Also it is bad practise within Bootstrap to have a div inbetween your row and cols
Hopefully this works for you!

A: if this is your answer:
all you have to do is add bootstrap column classes before the panel group.

col-xs-12  smaller screen sizes, col-md-4 medium screen sizes / PC,
  col-lg-12 for large screen sizes, col-sm-6 for tablet screen sizes.


text:
Q: Access VBA to Pass Parameter To Report Based On Query I am close on having syntax accurate, just one big problem!
The User ID that I am capturing from the input box, is not being passed into the report, so I have to input the user id twice
What needs to be altered in order to achieve this?
Public Function userProd() As Integer
Dim userID As String, saveloc As String, filename As String, reportname As String

'Report Name
reportname = "rpt_UserProduction"

'Setting Save location
saveloc = "C:\Test\"

'Setting filename
filename = "userProd "

'Getting User ID To Process
userID = InputBox("Enter User ID:", "VBA InputBox Function")

'Putting together full save location
saveloc = saveloc + filename + userID + ".pdf"

If userID = "" Then
    'Do Nothing and Stop Processing
    Exit Function
Else
    If IsNumeric(userID) Then
        'Preview Report
        DoCmd.OpenReport reportname, acViewPreview, , "User_ID=" & userID

        'Save As PDF
        DoCmd.OutputTo acOutputReport, reportname, acFormatPDF, saveloc, True

        'Close Report
        DoCmd.Close acReport, reportname
    End If
End If

End Function

A: Is the User_ID field a text field that holds a number?  If so, you need to add single quotes to the filter.  ... "User_ID='" & userId & "'".  If it's not text, are you getting too many records or not enough? Is there another filter being applied when the report loads, or in the underlying report record source that is causing the filter to not work as expected?

A: If "twice" means once for the inputbox and once for the report, then "User_ID=" in your where condition is either misspelled or excluded from the query you use as source for the report.


text:
Q: Black border with tikz shapes I have a tikz triangle to which I am trying to add the border. For some reason, I see the black border on two sides but not on the third. Can you please help me figure out why?
Below is the MWE:
\documentclass{article}

\usepackage{etoolbox}
\usepackage{tikz}
\definecolor{mycolor}{RGB}{255,255,0}       % use mycolor to give a specific color to tikz

%\newrobustcmd*{\mytriangle}[1]{\tikz{\filldraw[draw=red,fill=#1] (0,0) --
%(0.2cm,0) -- (0.1cm,0.2cm);}}

\newrobustcmd*{\mytriangle}[1]{\tikz{\draw[thick, fill=mycolor] (0,0) -- (0.2cm,0) -- (0.1cm,0.2cm);}}

\begin{document}
\listoffigures

\section{Sample}
This is a triangle \mytriangle{mycolor}.

\begin{figure}[htp]
  \centering
  A figure
  \caption{A triangle \mytriangle{mycolor}.}
\end{figure}

\end{document}

A: Close the path:
(0,0) -- (0.2cm,0) -- (0.1cm,0.2cm) -- cycle;


text:
Q: DNN Platform: Is it possible to not log a specific IP address in the log files? DNN Platform: Is it possible to not log a specific IP address in the log files?  We have a load balance that pings the home site and it is creating a log every time it visits.  Also, we turned off the user online module because the purge visitor function was not working; an internal site which only a dozen people has access to was logging 500+ visitors.

A: Have you tried pinging the KeepAlive.aspx page?


text:
Q: I need to get an exact match on this PHP code I have this code in a plugin in Wordpress, it creates tables in MySQL and store data in then I get it with search page, this page has a search form and its supposed to search with id but the problem is that when I click submit 0 in the search form it's got all results to start with 0
but I need it to work with an exact match
function ghazale_sds_front_end_search_field( $atts ) {
    $output = '<form id="sds-search-entries" method="post">';
    $output .= '
' . __( 'Search', 'custom-searchable-data-entry-system' ) . ':
';
    $output .= '
<input required type="number"  name="sds-search-data" size="9" placeholder="' . __( 'Patient ID', 'custom-searchable-data-entry-system' ) . ' "  autocomplete="off" >
';

    $output .= '
<input type="submit" name="submit-sds-search-query" value="' . __( 'Search', 'custom-searchable-data-entry-system' ) . '">

';
    $output .= '</form>';

    if ( isset( $_POST['submit-sds-search-query'] ) ) {
        global $wpdb;
        $tables       = $wpdb->prefix . "ghazale_sds_";
        $input_tables = $wpdb->get_results( "SHOW TABLES LIKE " . "'" . $tables . "%_inputs'", ARRAY_A );
        $field_tables = $wpdb->get_results( "SHOW TABLES LIKE " . "'" . $tables . "%_fields'", ARRAY_A );
        $has_result   = array();
        if ( ! empty( $input_tables ) ) {
            $hidden_field  = array();
            $shown_field   = array();
            $results_array = array();
            foreach ( $input_tables as $input_table ) {
                foreach ( $input_table as $table ) {
                    if ( get_option( 'ghazale_sds_separate_search' ) ) {
                        shortcode_atts( array(
                            'table' => str_replace( array(
                                $tables,
                                '_inputs'
                            ), '', $table )
                        ), $atts );
                    }
                    if ( get_option( 'ghazale_sds_separate_search' ) && str_replace( array(
                            $tables,
                            '_inputs'
                        ), '', $table ) == $atts['table'] ) {

                        $inputs_sql = "SELECT * FROM " . $table . " ORDER BY id ASC";
                        $inputs     = $wpdb->get_results( $inputs_sql, ARRAY_A );
                        if ( trim( $_POST['sds-search-data'] != '' ) ) {
                            $results_sql = "SELECT id,field_id,field_input FROM " . $table . " WHERE field_input COLLATE UTF8_GENERAL_CI LIKE '" . $_POST['sds-search-data'] . "%' ORDER BY id ASC";
                            $results     = $wpdb->get_results( $results_sql, ARRAY_A );
                            foreach ( $field_tables as $field_table ) {
                                foreach ( $field_table as $field_table_single ) {
                                    if ( $field_table_single == str_replace( "_inputs", "_fields", "$table" ) ) {
                                        $fields_sql = "SELECT id,field_name,field_type,field_hide FROM " . $field_table_single;
                                        $fields     = $wpdb->get_results( $fields_sql, ARRAY_A );

                                        if ( ! empty( $inputs ) ) {

                                            foreach ( $fields as $field ) {
                                                $first_id = $field['id'];
                                                break;
                                            }

                                            foreach ( $fields as $field ) {
                                                $last_id = $field['id'];
                                            }
                                            if ( $results ) {

                                                foreach ( $results as $result ) {
                                                    if ( strstr( $result['field_input'], '@' ) != true ) {
                                                        $output            .= "
";
                                                        $output            .= "
";
                                                        $range_initial_sql = 'SELECT id FROM ' . $table . ' WHERE field_id<= ' . $result['field_id'] . ' AND field_id =' . $first_id . ' AND id<= ' . $result['id'] . ' ORDER BY id DESC LIMIT 1';
                                                        $range_initial     = $wpdb->get_results( $range_initial_sql, ARRAY_A );
                                                        $range_final_sql   = 'SELECT id FROM ' . $table . ' WHERE field_id>= ' . $result['field_id'] . ' AND field_id =' . $last_id . ' AND id>= ' . $result['id'] . ' ORDER BY id ASC LIMIT 1';
                                                        $range_final       = $wpdb->get_results( $range_final_sql, ARRAY_A );

                                                        $result_range_sql = 'SELECT id,field_id,field_input FROM ' . $table . ' WHERE id BETWEEN ' . $range_initial[0]['id'] . ' and ' . $range_final[0]['id'];
                                                        $result_range     = $wpdb->get_results( $result_range_sql, ARRAY_A );
                                                        foreach ( $fields as $field ) {
                                                            if ( $field['field_hide'] == "Hide" ) {
                                                                //if the field is hidden don't show anything
                                                                array_push( $hidden_field, $field['id'] );
                                                            } else {
                                                                //otherwise show it on search query
                                                                array_push( $shown_field, $field['field_name'] );
                                                            }
                                                        }
                                                        foreach ( $result_range as $single_result ) {
                                                            if ( ! in_array( $single_result['field_id'], $hidden_field ) ) {
                                                                array_push( $results_array, $single_result['field_input'] );
                                                            }
                                                        }

                                                        foreach ( $shown_field as $index => $single_field ) {
                                                            $output .= "
";
                                                            if ( $results_array[ $index ] != "" ) {
                                                                $link_or_img = strlen( $results_array[ $index ] ) - 3;
                                                                $jpeg_img    = strlen( $results_array[ $index ] ) - 4;
                                                                if ( substr( $results_array[ $index ], 0, 4 ) === "http" && ( substr( $results_array[ $index ], $link_or_img, 3 ) == "png" || substr( $results_array[ $index ], $link_or_img, 3 ) == "jpg" || substr( $results_array[ $index ], $link_or_img, 3 ) == "pdf" || substr( $results_array[ $index ], $link_or_img, 3 ) == "bmp" || substr( $results_array[ $index ], $jpeg_img, 4 ) == "jpeg" ) ) {
                                                                    $output .= "" . $single_field . "		";
                                                                } elseif ( substr( $results_array[ $index ], 0, 4 ) === "http" && ( substr( $results_array[ $index ], $link_or_img, 3 ) != "png" || substr( $results_array[ $index ], $link_or_img, 3 ) != "jpg" || substr( $results_array[ $index ], $link_or_img, 3 ) != "pdf" || substr( $results_array[ $index ], $link_or_img, 3 ) != "bmp" || substr( $results_array[ $index ], $jpeg_img, 4 ) != "jpeg" ) ) {
                                                                    $output .= "" . $single_field . "	" . $results_array[ $index ] . "	";
                                                                } else {
                                                                    $output .= "" . $single_field . "	" . stripslashes( $results_array[ $index ] ) . "	";
                                                                }
                                                            }

                                                            $output .= "
";

                                                        }
                                                        $output .= "
";
                                                        $output .= "
";
                                                        unset( $hidden_field );
                                                        $hidden_field = array();
                                                        unset( $shown_field );
                                                        $shown_field = array();
                                                        unset( $results_array );
                                                        $results_array = array();
                                                    }
                                                }

                                                array_push( $has_result, 'Has Result' );
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } elseif ( ! get_option( 'ghazale_sds_separate_search' ) ) {
                        $inputs_sql = "SELECT * FROM " . $table . " ORDER BY id ASC";
                        $inputs     = $wpdb->get_results( $inputs_sql, ARRAY_A );
                        if ( trim( $_POST['sds-search-data'] != '' ) ) {
                            $results_sql = "SELECT id,field_id,field_input FROM " . $table . " WHERE field_input COLLATE UTF8_GENERAL_CI LIKE '" . $_POST['sds-search-data'] . "%' ORDER BY id ASC";
                            $results     = $wpdb->get_results( $results_sql, ARRAY_A );
                            foreach ( $field_tables as $field_table ) {
                                foreach ( $field_table as $field_table_single ) {
                                    if ( $field_table_single == str_replace( "_inputs", "_fields", "$table" ) ) {
                                        $fields_sql = "SELECT id,field_name,field_type,field_hide FROM " . $field_table_single;
                                        $fields     = $wpdb->get_results( $fields_sql, ARRAY_A );

                                        if ( ! empty( $inputs ) ) {

                                            foreach ( $fields as $field ) {
                                                $first_id = $field['id'];
                                                break;
                                            }

                                            foreach ( $fields as $field ) {
                                                $last_id = $field['id'];
                                            }
                                            if ( $results ) {

                                                foreach ( $results as $result ) {
                                                    if ( strstr( $result['field_input'], '@' ) != true ) {
                                                        $output            .= "
";
                                                        $output            .= "
";
                                                        $range_initial_sql = 'SELECT id FROM ' . $table . ' WHERE field_id<= ' . $result['field_id'] . ' AND field_id =' . $first_id . ' AND id<= ' . $result['id'] . ' ORDER BY id DESC LIMIT 1';
                                                        $range_initial     = $wpdb->get_results( $range_initial_sql, ARRAY_A );
                                                        $range_final_sql   = 'SELECT id FROM ' . $table . ' WHERE field_id>= ' . $result['field_id'] . ' AND field_id =' . $last_id . ' AND id>= ' . $result['id'] . ' ORDER BY id ASC LIMIT 1';
                                                        $range_final       = $wpdb->get_results( $range_final_sql, ARRAY_A );

                                                        $result_range_sql = 'SELECT id,field_id,field_input FROM ' . $table . ' WHERE id BETWEEN ' . $range_initial[0]['id'] . ' and ' . $range_final[0]['id'];
                                                        $result_range     = $wpdb->get_results( $result_range_sql, ARRAY_A );
                                                        foreach ( $fields as $field ) {
                                                            if ( $field['field_hide'] == "Hide" ) {
                                                                //if the field is hidden don't show anything
                                                                array_push( $hidden_field, $field['id'] );
                                                            } else {
                                                                //otherwise show it on search query
                                                                array_push( $shown_field, $field['field_name'] );
                                                            }
                                                        }
                                                        foreach ( $result_range as $single_result ) {
                                                            if ( ! in_array( $single_result['field_id'], $hidden_field ) ) {
                                                                array_push( $results_array, $single_result['field_input'] );
                                                            }
                                                        }

                                                        foreach ( $shown_field as $index => $single_field ) {
                                                            $output .= "
";
                                                            if ( $results_array[ $index ] != "" ) {
                                                                $link_or_img = strlen( $results_array[ $index ] ) - 3;
                                                                $jpeg_img    = strlen( $results_array[ $index ] ) - 4;
                                                                if ( substr( $results_array[ $index ], 0, 4 ) === "http" && ( substr( $results_array[ $index ], $link_or_img, 3 ) == "png" || substr( $results_array[ $index ], $link_or_img, 3 ) == "jpg" || substr( $results_array[ $index ], $link_or_img, 3 ) == "gif" || substr( $results_array[ $index ], $link_or_img, 3 ) == "bmp" || substr( $results_array[ $index ], $jpeg_img, 4 ) == "jpeg" ) ) {
                                                                    $output .= "" . $single_field . "		";
                                                                } elseif ( substr( $results_array[ $index ], 0, 4 ) === "http" && ( substr( $results_array[ $index ], $link_or_img, 3 ) != "png" || substr( $results_array[ $index ], $link_or_img, 3 ) != "jpg" || substr( $results_array[ $index ], $link_or_img, 3 ) != "gif" || substr( $results_array[ $index ], $link_or_img, 3 ) != "bmp" || substr( $results_array[ $index ], $jpeg_img, 4 ) != "jpeg" ) ) {
                                                                    $output .= "" . $single_field . "	" . $results_array[ $index ] . "	";
                                                                } else {
                                                                    $output .= "" . $single_field . "	" . stripslashes( $results_array[ $index ] ) . "	";
                                                                }
                                                            }

                                                            $output .= "
";

                                                        }
                                                        $output .= "
";
                                                        $output .= "
";
                                                        unset( $hidden_field );
                                                        $hidden_field = array();
                                                        unset( $shown_field );
                                                        $shown_field = array();
                                                        unset( $results_array );
                                                        $results_array = array();
                                                    }
                                                }

                                                array_push( $has_result, 'Has Result' );
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

            }

        }
        if ( count( $has_result ) == 0 ) {
            $output .= "
" . __( 'No Result', 'custom-searchable-data-entry-system' ) . "
";
        }

    }

    return $output;
}

add_shortcode( 'sds-search', 'ghazale_sds_front_end_search_field' );

/**
 * loading language file
 */
function ghazale_sds_load_plugin_textdomain() {
    load_plugin_textdomain( 'custom-searchable-data-entry-system', false, basename( dirname( __FILE__ ) ) . '/languages/' );
}

add_action( 'plugins_loaded', 'ghazale_sds_load_plugin_textdomain' );


text:
Q: Pre-validate messages sent to Kafka topic Is it possible to validate / filter messages that are being sent to Kafka topic?
Like, I want to ensure that only valid clients / producers send messages to my topic. I can certainly perform validation on the consumer side by discarding invalid messages based on certain parameters / criteria. But, what if I want to do it before the messages are written into the topic.
Say, Kafka receives a message, performs some validation and accordingly decides if it needs to discard or write that message into a topic. Is this possible?

A: A short answer - current versions of Kafka has no support for  such functionality out of the box. And since Kafka producers are designed to communicate with multiple brokers during single session, there is no easy way to implement such ad-hoc filtering.
There are couple of reasonable options still exists:

*

*Use 2 topics: one "public" topic opened to everyone which will allow all messages, and another non-public "filtered" topic which will be populated by your own application with data from "public" after applying your filtering rules.

*If you absolutely need to validate incoming messages before writing them down, then you could hide actual Kafka brokers behind some form of proxy application, which will do validation before writing messages into Kafka