text:
Q: [SQL]How to delete all rows containing NULL value on the joined table column using LEFT JOIN and DELETE I am trying to get rid of every row that has no relation to the other table.
This is what I tried:
DELETE obj FROM objednavky obj
    LEFT JOIN polozky_objednavek poObj
            ON poObj.objednavka_id = obj.id
            WHERE poObj.objednavka_id = null

A: DELETE is only working on one table, so it should not be joined.  you can use the other table in your WHERE clause though, like this:
DELETE FROM objednavky obj
  WHERE( SELECT objednavka_id FROM polozky_objednavek WHERE objednavka_id=objednavky.id) IS NULL

If you're doing this manually I recommend running the SELECT clause first (or at least a COUNT variant) to check you're not going to accidentally wipe out the entire table.

A: You can use NOT EXISTS.
Try this:
DELETE FROM objednavky obj
WHERE NOT EXISTS (
      SELECT
          *
      FROM
          polozky_objednavek poObj
      WHERE
           `poObj`.`objednavka_id` = `obj`.`id`);

Demo

A:
DELETE obj FROM objednavky obj
    LEFT JOIN polozky_objednavek poObj
            ON poObj.objednavka_id = obj.id
            WHERE poObj.objednavka_id IS null

thanks to @forpas for comenting, I just needed to change: item = NULL to item IS NULL and worked itexactly as I needed. Keep in mind that SQL doesn't support this type of comparison.


text:
Q: To use fgets and puts in C for string input and ouput I tried a C code to input 3 strings of max length '6' and print the string within the loop using fgets() and puts(). However, when I run the code, it only takes 2 string inputs instead of 3 string inputs. Could anyone please explain this?

*

*Code

*Output

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add a table reference to an entry in another table in asp.net mvc? I have to create a website where users can log in and create and share music playlists. I'm using Asp.net MVC with C# in Visual Studio.
Each playlist is an entry in the playlists table and has the fields PlaylistName, UserId (id of the user the playlist belongs to), and list of tracks in the playlist in either the form of a vector (the vector contains IDs to tracks contained the tracks table) or in the form of a reference to a table that contains the tracks associated with this playlist (so each playlist entry in the playlists table has its own table). Being new to ASP.NET and databases in general I'm not really sure if either of these approaches are ideal and even how to implement them. If I went with the vector method could I do this:
namespace MvcApplication1.Models
{
    public class Playlist
    {
        public string PlaylistName { get; set; }
        public int UserId { get; set; }
        public List<int> Tracks { get; set; }
    }

    public class PlaylistDBContext : DbContext
    {
        public DbSet<Playlist> Playlists { get; set; }
    }
}

And then scaffold the model?
For the other method I'm not sure how to use visual studio to set that up.

A: So if im reading this right you have a playlist that has a bunch of tracks?
Add an ID to playlist, something like an int will do
public class Playlist
{
    public int ID {get;set;}
    public string PlaylistName { get; set; }
    public int UserId { get; set; }
    public List<int> Tracks { get; set; }
}

I have no clue what your track object looks like, so lets pretend it has a name and an ID.
I am assuming each track only belongs to one playlist only.
If so, add a "playlistID" to each track.
public class Track
{
   public int ID {get;set;}
   public int PlayListID {get;set;}
   public string Name {get;set;}
}

Now this links the track to a playlist.
If you're using entity framework as your data access and it kinda looks like you are, you can add virtual properties and entity framework understands the relations to get you what you want.
So you can go add "tracks" to the playlist class like this :
 public class Playlist
{
    public int ID {get;set;}
    public string PlaylistName { get; set; }
    public int UserId { get; set; }
    public virtual ICollection<Track> Tracks{ get; set; }
}

and whenever you use the tracks property it will go and find the child records.
similarly on the track child record you can add the following "Playlist" property and it will find the parent whenever needed.
public class Track
{
  public int ID {get;set;}
  public int PlayListID {get;set;}
  public string Name {get;set;}
  public virtual Playlist Playlist {get;set;}
}

if you're using entity framework 6 with codefirst migrations this should just work.
EDIT ::
if you need a many to many relationship then you simply update the tracks as follows :
public class Track
{
  public int ID {get;set;}
  public string Name {get;set;}
  public virtual ICollection<Playlist> Playlists {get;set;}
}

i removed the playlist ID on the track and also the virtual property is now a collection of playlists. entity framework should automatically create the reference table "Track_Playlists" or whatever in between.


text:
Q: Social Sharing for a third party JQuery widget I am writing a third party JQuery widget. I wanted to have a Social Sharing option for these widgets. These widgets would be installed for different websites, so the sharing urls, content etc would be specific to that website.
I was starting to write my own code for social sharing, but I wanted to know if there are good API's that already take care of this, which could prevent me from writing my own?
Thanks.

A: I use social-share-button. It's implemented in Rails, should be a good start if you're looking to call it in jQUery
https://github.com/huacnlee/social-share-button

A: For strictly "Social Sharing" of Twitter and Facebook, you don't need a back-end.  It can all be done client side in a pure jQuery widget.


text:
Q: Nodes and Stacks adding error I'm trying to create a code for a card game in Java, and I have encountered a problem.
My deck is a Stack<Character> and a static for my class named Players and my 'hand' is a private Node<Character>.
I've created a method that pops a card from my deck and adds it to my hand.
It's code:
public void takeCard() {
    char a = Players.deck.pop();
    Node<Character> hand = new Node<Character>(this.hand);
    while(hand.getNext()!=null) {
        hand = hand.getNext();
    }
    Node<Character> next = new Node<Character>(a, null);
    hand.setNext(next);

    this.hand = hand;
}

And it doesn't work and tells me
Exception in thread "main" java.lang.NullPointerException
at Players.takeCard(Players.java:56)
at Game.main(Game.java:31)

(Game is where my main function is)
Any idea how I should write the function?

A: The only possible place where this code can throw a NullPointerException with that stack trace is in
char a = Players.deck.pop();

if Players.deck is null. It looks like you're not initialising your deck.
Add
assert(Players.deck!=null);

at the beginning of the method, and see if it burps.


text:
Q: Drop-down list doesn't send POST data My situation is, I have 2 drop-down list and only one data from one of the drop-down list will be sent into the second page. That's mean, the data from another drop-down list will not be sent. So, I choose to display the drop-down list by using the radio button. If I choose the 1st button, it will only display the 1st drop-down list and vice versa.
The problem is, when I choose the 1st drop-down list, it doesn't send any POST data from the drop-down list to the second page, only blank. But, if I choose the 2nd drop-down list, it send the data properly! I thought that there are errors in 1st drop-down list codes (even both codes are practically identical). So, I add another list, and this time, only the 3rd drop-down list's data is sent. 1st and 2nd list doesn't send anything.
I realize that my problem is my codes only sent data from the last drop-down list, not both. I only need 1 data from either drop-down list, but I need both to function. If I can only choose one list, I dont even need to make 2 drop-down list.
This is my codes, but not a full code. The other data works fine, only the drop-down list is having problem.
<form name="list" action="index.php?site=11" method="post">

Choose:
<input type="radio" onclick="javascript:check();" name="duration" id="1H">1 Hour
<input type="radio" onclick="javascript:check();" name="duration" id="2H">2 Hour

Choose time slot:

    <select name="time1" >
     <option value="">---Choose---</option>
     <option value="8-9">8:00am-9:00am</option>
    </select>

    <select name="time2" >
     <option value="">---Choose---</option>
     <option value="8-10">8:00am-10:00am</option>
    </select>

<input type="submit" name="submit" value="Next">

This is php codes to show how I receive the POST data, just until the query.
include('../include/dbconnect.php');
$user = $_SESSION['username'];

if(isset($_POST['submit'])){

if(isset($_POST['time'])){
$lab=$_POST['lab'];
$day=$_POST['day'];
$month=$_POST['month'];
$year=$_POST['year'];
$time=$_POST['time'];

echo "1:".$time;

$results = mysql_query("SELECT COUNT(*) FROM `booking` WHERE `lab` = '".$lab."' AND `day` = '".$day."' AND `month` = '".$month."' AND `year` = '".$year."' AND `time` = '".$time."'");
}

if(isset($_POST['time2'])){
$lab=$_POST['lab'];
$day=$_POST['day'];
$month=$_POST['month'];
$year=$_POST['year'];
$time=$_POST['time2'];

echo "2:".$time;

$results = mysql_query("SELECT COUNT(*) FROM `booking` WHERE `lab` = '".$lab."' AND `day` = '".$day."' AND `month` = '".$month."' AND `year` = '".$year."' AND `time` = '".$time."'");
}
}

echo "3:".$time;

How do I solve this problem? I need to make sure that both drop-down list can sent POST data to another pages, not only one functioning at all. I hope you can understand my problem.
EDIT: I have change both select box's names.
2nd EDIT: I add Fred's code

A: The select boxes both have the same name. You need to set different name attributes for the two select options.
Edit
The issue is that the select box will post data even if it's not explicitly set. So each isset() will always return true.
As long as your default option has an empty value attribute you can check against that like this:
if(!empty($_POST['time']))

Or maybe set a default value to test against like so:
<option value="0">---Choose---</option>

<?php if($_POST['time'] != '0') ?>

The original issue was that the form would always post the last select even if you only made a choice with the first one. The issue now is that both if(isset clauses will be true.

A: What has already been said in regards to both selects holding the same name, still stands.
Sidenote: (I renamed the 2nd select to time2)
However, in order to use the time from either radio button/dropdown selects, you need to use an isset conditional statement, then use that variable for your DB insert.
Tested as follows while naming the submit button as my own self test and inside the same file. You can modify it to suit.
Scenario: The $time variable that's being (set) then passed to your DB, will be set as such, depending on which time select was chosen.
<?php
if(isset($_POST['submit'])){

    if(isset($_POST['time'])){
    $time=$_POST['time'];
    echo $time;
    }

    if(isset($_POST['time2'])){
    $time=$_POST['time2'];
    echo $time;
    }
}

?>

<form name="list" action="" method="post">

Choose:
<input type="radio" onclick="javascript:check();" name="duration" id="1H">1 Hour
<input type="radio" onclick="javascript:check();" name="duration" id="2H">2 Hour

Choose time slot:

    <select name="time" >
     <option value="">---Choose---</option>
     <option value="8-9">8:00am-9:00am</option>
    </select>

    <select name="time2" >
     <option value="">---Choose---</option>
     <option value="8-10">8:00am-10:00am</option>
    </select>

<input type="submit" name="submit" value="Next">

EDIT (DB-related)
And in your case, it would be: (and do name your submit button to name="submit" for this):
<?php
if(isset($_POST['submit'])){

    if(isset($_POST['time'])){
    $lab=$_POST['lab'];
    $day=$_POST['day'];
    $month=$_POST['month'];
    $year=$_POST['year'];
    $time=$_POST['time'];

    $results = mysql_query("SELECT COUNT(*) FROM `booking` WHERE `lab` = '".$lab."' AND `day` = '".$day."' AND `month` = '".$month."' AND `year` = '".$year."' AND `time` = '".$time."'");

    }

    if(isset($_POST['time2'])){
    $lab=$_POST['lab'];
    $day=$_POST['day'];
    $month=$_POST['month'];
    $year=$_POST['year'];
    $time=$_POST['time2'];
    $results = mysql_query("SELECT COUNT(*) FROM `booking` WHERE `lab` = '".$lab."' AND `day` = '".$day."' AND `month` = '".$month."' AND `year` = '".$year."' AND `time` = '".$time."'");

    }
}

?>


text:
Q: sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL: Ident authentication failed for user "airflow" I have a CentOS 7 instance,and I've installed airflow and postgresql on top of that.
Initially installed the postgres-server and the contrib via yum by following the steps here:
https://www.hostinger.com/tutorials/how-to-install-postgresql-on-centos-7/
upon installation, then I started the postgres service and checked the status whether it's up and running.
After this I installed apache-airflow by using the following command:
pip3 install "apache-airflow[postgresql]==2.3.1" --constraint "https://raw.githubusercontent.com/apache/airflow/constraints-2.3.1/constraints-3.7.txt"

Then followed the steps here to create the airflow user, db via the psql cli.
Finally I updated the airflow.cfg with the correct sqlalchemy conn details:
sql_alchemy_conn = postgresql+psycopg2://airflow:airflow@localhost/airflow

Once I start to run airflow db init it throws me this error:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL:
Ident authentication failed for user "airflow"

The pg_hba.conf looks like below:

I could also see the airflow user and the airflow db via psql

Not sure where am I going wrong? Any help could be appreciated.
NOTE: Postgresql version - 9.2.24 || Airflow version - 2.3.1

A: It seems very similar to this thread, have you checked it out?
airflow postgresql backend: (psycopg2.OperationalError) FATAL: Ident authentication failed for user "airflow"
In your case, you also have the uncommented line:
host    all             all             ::1/128                 ident

So I would start by reading that thread, and trying to remove this line :)


text:
Q: Error 109 when stopping Mongo DB running as a service (1.6.1) I'm running Mongo DB as windows service and every second time I stop the service it reports "Error 109: The pipe has been ended". Here is the command line being used to run the service
"C:\Temp\mongodb\bin\mongod" --service --serviceUser  --servicePassword  --dbpath C:\temp\db --rest --logpath C:\temp\db\log\mongo.log --logappend --directoryperdb

A: This bug was fixed for version 2.1.0 ( https://jira.mongodb.org/browse/SERVER-2833 ) and then resurfaced ( https://jira.mongodb.org/browse/SERVER-6771 ).  Hopefully it will be fixed again for version 2.2.0.


text:
Q: Java volume doesn't change in Eclipse under Linux I have a little problem:
I'm using javazoom.* to make a simple music player. To change volume level i use
private BasicPlayer player = new BasicPlayer();
player.setGain(<double value between 0..1>);

Method .setGain() works directly with FloatControl from java.sound.
When I star Java application in eclipse(under Linux) music don't change it level. But when I export Java application to app.jar everything works fine(under all OS). Also all everything works in eclipse that working under Windows. Can some one explain why it happens?
Tested software:

*

*OS: WinXP, Win7; Ubuntu 12.04, 13.10(Some 32-bit, Some 64)

*JVM: OpenJDK 6,7; SunJDK 6

*Eclipse Kepler(4,*) and Indigo(3,7).

*Javazoom latest

Solved
This happens only when you start project under eclipse.
If you makes *.jar and starts in OS volume change works without any problems.

A: Solved
This happens only when you start project under eclipse. If you makes *.jar and starts in OS volume change works without any problems.


text:
Q: Custom ViewGroup, GridView, and SimpleCursorAdapter I need to display data in 3 textviews, inside each grid item, but also I want each grid item to be square. Also the cursoradapter is all based on a search.
Based on my necessities I found by research that I should be creating my own viewgroup for each grid item and setting the height to be the same as the width (in onMeasurement), which produces proper squares. But now my data from the cursoradapter will not show up in the views.
I can tell that the cursoradapter is being referenced because the number of white boxes in the gridview changes depending on what I search.
Where am I going wrong?
<ubiquia.sqbxsync.main.GridViewGroup
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffffff">

<RelativeLayout
    android:id="@+id/gridLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ellipsize="end"
        android:singleLine="true"
        android:text="TextView"
        android:textSize="15dp"
        android:textColor="#ff000000" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="10dp"
        android:ellipsize="end"
        android:singleLine="true"
        android:text="TextView"
        android:textSize="11dp"
        android:textColor="#ff000000" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView2"
        android:layout_marginLeft="10dp"
        android:ellipsize="end"
        android:singleLine="true"
        android:text="TextView"
        android:textSize="11dp"
        android:textColor="#ff000000" />

</RelativeLayout>

package ubiquia.sqbxsync.main;

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;

public class GridViewGroup extends ViewGroup {

    public GridViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
     // Do nothing
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }
}

My CursorAdapter
public class GridCursorAdapter extends CursorAdapter {

    public GridCursorAdapter(Context context, Cursor c) {
        super(context, c);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View gridView = inflater.inflate(R.layout.grid_item, null, true);
        return gridView;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TextView tv1 = (TextView) view.findViewById(R.id.textView1);
        TextView tv2 = (TextView) view.findViewById(R.id.textView2);
        TextView tv3 = (TextView) view.findViewById(R.id.textView3);
        tv1.setText(cursor.getString(cursor.getColumnIndexOrThrow("trackingnumber")));
        tv2.setText(cursor.getString(cursor.getColumnIndexOrThrow("recipient_name")));
        tv3.setText(cursor.getString(cursor.getColumnIndexOrThrow("carrier_name")));
    }
}

A: I found out that after changing my extends to LinearLayout and writing in the super.onLayout(changed,l,t,r,b); it now shows my layout in the square that I wanted.


text:
Q: Explain seemingly non-random figures which arise from random Poisson points with normalization Context Working with some biological datasets it was puzzling to see the patterns like Figure 2 (right) below. The first feeling was, that it corresponds to some biological effects like correlations between genes, however discussions with colleagues suggested that it more likely to be some purely mathematical phenomenon.
Small simulation confirms that very simple mathematical model will reproduce the same effect which we see in biological data (single cell RNA sequencing data to be precise).
Setup Let us generate say $1000\times n$ random numbers from Poisson distribution and put them in a matrix of the size $(1000,n).$ Normalization: divide each ROW of the matrix by its sum. (So now rows will be summed to $1$). That is all – just plot the coordinates of the first two columns on a plane.
We get figures like below (right sides – after normalization, left – before). Three plots for different $n=100,10,3$ with Poisson and one is for uniform distribution – which does NOT show similar phenomena.
Question Can one explain why for Poisson (and NOT the other tried distributions – uniform, normal, Pareto) seemingly non-random pattern arises? I mean it looks like points are aggregated into rays? What are the other distributions except Poisson will produce the same phenomenon?
Simulation code: https://www.kaggle.com/alexandervc/toy-model-for-single-cell-rna-seq-data
More figures are there.
Essentially the code is:

X = np.random.poisson(5, size = (n_samples,n) )

    v = X.sum(axis = 1)
    X2 = X / v[:,None]
    plt.scatter(X2[:,0],X2[:,1])

A: The key thing to notice is that there are many fewer distinct points in the plot on the left than on the right. Let me reproduce the three-column plots:

There are about 100 distinct points on the left and 1000 on the right. So how do you go from 100 to 1000? Take a coordinate $(n_x,n_y)$ on the left plot, which will contain some $N\approx 10$ coinciding data points. Then construct $N$ new coordinates
$$(x_i,y_i)=\frac{(n_x,n_y)}{n_x+n_y+p_i},\;\;i=1,2,\ldots N,$$
where $p_i$ is a random Poisson variable.
Now you immediately understand the origin of the points that fall on the line $x=y$ in the right plot: these arise from the data points in the left plot with $n_x=n_y$. There is also a distinct line in the right plot at $y=1/2$, which arises from points in the left plot with $p_i=n_y-n_x$. Similarly, the line on the right at $x=1/2$ arises from points at the left with $p_i=n_x-n_y$. And further linear relations can explain the other lines, for example the two lines $x+2y=1$ and $2x+y=1$ arise, respectively, from $p_i=n_y$ and $p_i=n_x$.
So you need to start with a distribution on integers and the distribution should be sharply peaked, to ensure this expansion of few points without normalization to many points with linear relations after normalization.

A: In each of your pictures, $1000$ iid realizations of the random point $P:=(X_1,X_2)/S_n$ are shown, where $X_1\dots,X_n$ are iid Poisson with mean $5$ and $S_n:=X_1+\dots+X_n$. So, the values of the $X_i$'s are fairly well concentrated near the mean $5$ and hence mostly take rather small natural values.
So, the realizations of the random point $P$ lie mostly on a rather small number of straight lines through the origin, with the slopes $X_2/X_1$, which are rational numbers with rather small numerators and denominators.
Also, for $n=3$ the equation $(X_1+X_2)/S_n=c$ for real $c\ne1$ can be rewritten as $X_1+X_2=\frac c{1-c}\,X_3$, so that the realizations of the random point $P$ lie mostly on a rather small number of straight lines with equations of the form $x+y=a$ for some real $a$.

A: "seemingly non-random pattern arises" because for the Poisson examples above the expected value of the random variables is 5, while for the uniform distribution it is 25.
Larger expected value makes numbers appear denser after the row normalization step, hence visually the graphs look different.
If one takes uniform distribution with the expected value 5, the picture would look similar to Poisson examples. E.g., for cases with 3 columns,
graphs look like this.

For 20 columns, we start seeing rays for both distributions as
can be seen here.


text:
Q: Why do people use Messaging when you can use Files and a Batch tool? We have 2 in-memory java components (a data grid and an olap cube).
We currently use a batch processing tool to load the data grid, and we dynamically create batch jobs when users want to make updates to the data. What I am thinking is we should extend our batch tool so that it also takes responsibility to load data into the olap cube. In terms of the data transfer, the data grid should write out a file, copy it to the server the olap cube runs on, and the olap cube should then read in this file.
The other option we have is when the data grid finishes loading or applying an update, it sends a message to a queue. The olap cube will then read this message, and call a service on the data grid to pull the data in. I am strongly against this option since it is not file based, which means the support team will have trouble understanding it.
So question is, why should we use messaging?

A: Because if you write your own transaction files, you have to worry about:

*

*whether the transaction got written to the file

*whether the file got transmitted correctly, completely, or indeed at all.

*whether the file got read completely, and if not where you were up to when you stopped reading

as well as all kinds of reliablity issues concerning the actual media.
Messaging systems do all that for you.


text:
Q: java: I cannot run the program after compilation? Help me i just downloaded a java program TableDrivenVaccumAgent.java while i was searching some robot class examples, i have included the requisite jars in the path C:\Program Files\Java\jdk1.7.0_25\jre\lib\ext but i am getting error after it compiles successfully.
what should i need to do more to resolve the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: TableDrivenVacuumAgent (wrong name: aima/core/environment/vacuum/TableDrivenVacuumAgent)
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(Unknown Source)
        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$100(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)

now error is:
Exception in thread "main" java.lang.NoClassDefFoundError: TableDrivenVaccumAgent (wrong name: aima/core/environment/vacuum/TableDrivenVaccumAgent)
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(Unknown Source)
        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$100(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)

A:
NoClassDefFoundError in Java comes when Java Virtual Machine is not
  able to find a particular class at runtime which was available during
  compile time. For example if we have a method call from a class or
  accessing any static member of a Class and that class is not available
  during run-time then JVM will throw NoClassDefFoundError.

Obvious reason of NoClassDefFoundError is that a particular class is not available in Classpath, so we need to add that into Classpath or we need to check why it's not available in Classpath if we are expecting it to be. There could be multiple reasons like:

*

*Class is not available in Java Classpath.

*You might be running your program using jar command and class was
not defined in manifest file's ClassPath attribute.

*Any start-up script is overriding Classpath environment variable.

A: NoClassDefFoundError in Java comes when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time. For example if we have a method call from a class or accessing any static member of a Class and that class is not available during run-time then JVM will throw NoClassDefFoundError.


text:
Q: Porting a UNIX daemon to a Windows Service I wrote a UNIX daemon, in C, which I want to port to Windows.
My target is Windows 10.
When I search on how to create a Windows service, I am met by an approach using .NET and C# which I both want to avoid at all cost.
How can I make a simple straightforward service in C, without kitchen sinks that Microsoft tries to unload on me? If I really have to, I would consider C++, but C# and .Net are simply taking it too far.
I'm fine with switching to a different compiler too, if this is easier outside of VisualStudio. (Currently I am using Visual Studio 2019, latest update.)
NOTE: My Linux daemon just has one dependency: libhidapi which is available for Windows.
UPDATE
No C++ templates available.

A: This comes down to creating two different applications (.exe)
One to run the service using StartServiceCtrlDispatcher() where the dispatching function calls RegisterServiceCtrlHandlerEx() to register a controller.
One to install the service using CreateService()
It is possible to skip on the installer, and use the sc command line utility for that, which is part of the OS.
See full example.


text:
Q: Render admin form either from controller or from xml I am implementing some code in custom module controller after saving all
things in database i want to render admin form.
i tried this is my controller action
$this->loadLayout();
$this->getLayout()->createBlock('hello_world/adminhtml_world_edit_form')->toHtml();

but it's giving me fatal error Call to a member function toHtml() on a non-object.
i have tried this code as well in xml, savecccard is controller action where i am made some functionality and saving data
<hello_world_admin_world_savecccard>
            <reference name="content">
                <block type="hello_world/adminhtml_world_edit_form" name="autoship.form"></block>
            </reference>
</hello_world_admin_world_savecccard>

but this gives me blank content page with header and footer only.
Please help.

A: First you need to ensure, your module is active or not.
SecondtoHtml() is calling in a non-object means that, createBlock('hello_world/adminhtml_world_edit_form') is not working correctly.
createBlock() is used to create a new block and add it to the layout.
This function has 3 parameters:
1- type
2- name
3- attributes / arguments
you have specified type as hello_world/adminhtml_world_edit_form.
SO magento will look for app/code/local/namespace/Hello_world/Block/Adminhtml/World/Edit/Form.php and the file should be properly declared.
Next parameter is attribute. It is optionnal.


text:
Q: openVino: __cinit__() got an unexpected keyword argument 'weights' I'm trying to run this repo but found an error.
PPE-detector-Tiny-YOLOv3-Rasp.erry-PI-and-NCS2
I never used python before. when I run the PPE_Detector_Pc.py I got an error like this :
PS D:\repository\PPE-detector-Tiny-YOLOv3-Rasp.erry-PI-and-NCS2> py PPE_Detector_Pc.py
loading the model...
loading plugin on Intel NCS2...
Traceback (most recent call last):
  File "PPE_Detector_Pc.py", line 406, in <module>
    sys.exit(main_IE_infer() or 0)
  File "PPE_Detector_Pc.py", line 201, in main_IE_infer
    net = IENetwork(model=path_to_xml_file, weights=path_to_bin_file)
  File "ie_api.pyx", line 1598, in openvino.inference_engine.ie_api.IENetwork.__cinit__
TypeError: __cinit__() got an unexpected keyword argument 'weights'

this is the part where it gave me error:
path_to_xml_file = "tiny_yolo_IR_500000_FP32.xml" #<--- MYRIAD
path_to_bin_file = os.path.splitext(path_to_xml_file)[0] + ".bin"

time.sleep(1)
print("loading plugin on Intel NCS2...")

plugin = IECore()
net = IENetwork(model=path_to_xml_file, weights=path_to_bin_file)
input_blob = next(iter(net.inputs))
exec_net = plugin.load(network=net)

my path_to_xml_file and path_to_bin_file was using tiny_yolo_IR_500000_FP32.xml and tiny_yolo_IR_500000_FP32.bin i put in same folder i downloaded from the repo.
I just changed IEPlugin to IECore because it is no longer supported on the newer version openVino.
is there anything I miss on that?

A: The repository you've provided is not maintained by OpenVINO™ and is using deprecated APIs.
You're partially correct on steps to replace IEPlugin with IECore. Here are the full steps required to read and load networks using IECore API:
ie = IECore()
net = ie.read_network(model=model_xml, weights=model_bin)
exec_net = ie.load_network(network=net, device_name="CPU", num_requests=2)

The provided IR models (.xml and .bin files) from the repository are also in deprecated version as they are IR version 5 as shown here when running the edited code in OpenVINO™ Development Tools 2022.1:

To avoid this error, you will need to convert the original model into the latest IR format (IR v11) using OpenVINO™ 2022.1 Model Optimizer.


text:
Q: use tags in echo chunk option I have an rmarkdown document that uses code chunks in various languages, including R, bash, and python.  For the R code chunks, context is preserved between chunks.  For the bash and python chunks it is not.  Hence, I have to replicate the set-up code in each python (for instance) chunk.  I prefer not to have the replicated stuff appear in the output, but I do want the stuff that's new in the code chunk to appear.  I'm using:
```{python someName, echo=19:32}

and similar to do this, and that works just fine.  The drawback is that if I add/subtract/rearrange, the absolute numbers (19 and 32 in the example) change.  This is a minor nuisance, but it would be nice if I could just tag the sections of code that I want to include/omit.  Is there some way to do that?  Thanks.


text:
Q: React Router Rerouting Hi I have a kinda dumb question. Im working on a react micro service that runs on the url /checkout which everything after checkout redirecting to the correct page components. The problem I have is that there is a route in our monolith that has a page with the route /checkout/settings. My questions is: is there a way to react-router ignore said route and proceed to navigate away to that page? Thanks
EDIT:
Example.
/checkout/cart will redirect to cart page
/checkout/review will redirect to review page
/checkout/pageThatDoesNotExist will display our 404 page
I want to be able to navigate away from my microservice and go to the monolith when we hit checkout/settings

A: You can use exact in react router
<Route exact path="/checkout" component={}/>

if you want to render /checkout/settings instead of /checkout


text:
Q: EmberJS: Emit event from Service to Route? I'd like to be able to emit an event from a service, and setup my application Route to listen and act on that event.
app/services/service-action.js:
export default Ember.Service.extend({
  actionA() {
    this.trigger('actionA');
  }
});

app/routes/application.js:
export default Route.extend({
  serviceAction: service(),

  on('serviceAction.actionA', ()=>{
    console.log('actionA fired from serviceAction');
  })
});

Is this possible? Or is there an alternate design pattern I should use to solve this?


text:
Q: Insufficient Security with RabbitMQ 3.7.15 and Erlang 22.0.1 / 22.0.2 on centOS 7.6 Observing an Insufficient Security error after upgrading RabbitMQ server to 3.7.15 with Erlang 22.0.1 / 22.0.2 on centOS 7.6.
Initial State of system where SSL was found to be working:
CentOS Linux release - 7.5
RMQ - 3.7.7-1.el7
Erlang - 20.3.8.2-1.el7.x86_64
SSL was found to be working even when CentOS was upgraded to 7.6 and RMQ to 3.7.15. Checked after RMQ restart.
However when Erlang was upgraded to erlang-22.0.2-1.el7.x86_64.rpm, SSL stopped working. (After RMQ restart)
RabbitMQ config:
[
  {rabbitmq_management,
  [{listener, [{port,     15671},
               {ssl,      true},
              {ssl_opts, [{cacertfile, "<path>/cacert.pem"},
                          {certfile,   "<path>/cert.pem"},
                          {keyfile,    "<path>/key.pem"}]}
              ]}
  ]},

  {rabbit, [
     {log_levels, [{connection,info}]},
     {tcp_listeners, []},
     {ssl_listeners, [5671]},
     {ssl_options, [{cacertfile,"<path>/all_cacerts.pem"},
                    {certfile,"<path>/cert.pem"},
                    {keyfile,"<path>/key.pem"},
                    {depth, 5},
                    {verify,verify_peer},
                    {fail_if_no_peer_cert,false}]},
    {auth_mechanisms, ['PLAIN','AMQPLAIN','EXTERNAL']},
    {loopback_users, []},
    {ssl_cert_login_from, common_name}
  ]}
].

RabbitMQ enabled pluggins:
[rabbitmq_auth_mechanism_ssl,rabbitmq_management,rabbitmq_shovel,rabbitmq_shovel_management].
Please help.
Edit 1:
Updated the rabbitmq.config in this manner. Cert based auth is working now.
[
      {rabbitmq_management,
      [{listener, [{port,     15671},
                   {ssl,      true},
                  {ssl_opts, [{cacertfile, "<path>/cacert.pem"},
                              {certfile,   "<path>/cert.pem"},
                              {keyfile,    "<path>/key.pem"}]},
                              {ssl, [{versions, ['tlsv1.3', 'tlsv1.2', 'tlsv1.1', 'tlsv1', 'sslv3']},
                              {ciphers,
                                [{ecdhe_ecdsa,aes_256_gcm,aead,sha384}, {...}]}
                  ]}
      ]},

      {ssl, [{versions, ['tlsv1.3', 'tlsv1.2', 'tlsv1.1', 'tlsv1', 'sslv3']},
      {rabbit, [
         {log_levels, [{connection,info}]},
         {tcp_listeners, [5672]},
         {ssl_listeners, [5671]},
         {ssl_options, [{cacertfile,"<path>/all_cacerts.pem"},
                        {certfile,"<path>/cert.pem"},
                        {keyfile,"<path>/key.pem"},
                        {ssl, [{versions, ['tlsv1.3', 'tlsv1.2', 'tlsv1.1', 'tlsv1', 'sslv3']},
                              {ciphers,
                                [{ecdhe_ecdsa,aes_256_gcm,aead,sha384}, {...}]},
                        {depth, 5},
                        {verify,verify_peer},
                        {fail_if_no_peer_cert,false}]},
        {auth_mechanisms, ['PLAIN','AMQPLAIN','EXTERNAL']},
        {loopback_users, []},
        {ssl_cert_login_from, common_name}
      ]}
    ].

However, shovels with amqps with port 5671 still error out.
[error] <0.7391.6> Shovel 'ShovelTest' failed to connect (URI: amqps://<ip>:5671/<blah>): {tls_alert,{insufficient_security,"received SERVER ALERT: Fatal - Insufficient Security"}}

Shovels work fine with ampq with port 5672 though.
Please help.


text:
Q: Is this a bug? "Method is never used." warning although it is used in setOnClickListener I have been following https://developer.android.com/courses/android-basics-kotlin/unit-2 tutorial on how to build Android apps in Android Studio. Code inspection is also introduced there as part of fixing warnings and making code perfect.
Adding my MainActivity.kt code:
package com.example.tiptime

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.example.tiptime.databinding.ActivityMainBinding
import java.text.NumberFormat

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        //setContentView(R.layout.activity_main)
        setContentView(binding.root)

        binding.tipResult.text = ""
        binding.calculateButton.setOnClickListener {
            calculateTip()
        }

        // Hide keyboard on enter press
        binding.costOfServiceEditText.setOnKeyListener { view, keyCode, _ ->
            handleKeyEvent(
                view,
                keyCode
            )
        }
    }

    private fun calculateTip() {
        val cost = binding.costOfServiceEditText.text.toString().toDoubleOrNull()
        if (cost == null) {
            binding.tipResult.text = ""
            return
        }

        val tipPercentage = when (binding.tipOptions.checkedRadioButtonId) {
            R.id.option_twenty_percent -> 0.20
            R.id.option_eighteen_percent -> 0.18
            else -> 0.15
        }

        var tip = tipPercentage * cost
        if (binding.roundUpSwitch.isChecked) {
            tip = kotlin.math.ceil(tip)
        }
        val formattedTip = NumberFormat.getCurrencyInstance().format(tip)
        binding.tipResult.text = getString(R.string.tip_amount, formattedTip)
    }

    private fun handleKeyEvent(view: View, keyCode: Int): Boolean {
        if (keyCode == KeyEvent.KEYCODE_ENTER) {
            // Hide the keyboard
            val inputMethodManager =
                getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
            return true
        }
        return false
    }
}

I have completed part 2 of getting user input and I wanted to make sure there are no code warnings. But after using code inspection on project I noticed couple of warnings.
One warning is about calculateTip() and says: "Method is never used." although it is used in setOnClickListener.
After pressing button "Safe delete" it says: "function MainActivity.calculateTip() has 1 usage that is not safe to delete." that's completely opposite. Is this code inspection bug or I don't see some smart fix that is ment for this?
Attached screenshots also.
Method is never used:
warning that shows up
Usages detected upon pressing safe delete:
usages detected

A: I run the Google code and it seems ok on this, it uses the calculateTip() function.


text:
Q: IPC between a C DLL and Python application to process data I would like to send over a message structure from a DLL-callback function to a python application so I can log the messages.
For this I would like to use ZeroMQ. Sadly I am unable to get the messages to python using the example provided by ZeroMQ.

DLL:
// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <zmq.h>
HHOOK tHook;
HMODULE hinstDLL;
void* requester;
void* context;
LRESULT CALLBACK meconnect(int code, WPARAM wParam, LPARAM lParam) {
    if (code == HC_ACTION) {
        LPMSG data = (LPMSG)lParam;
        UINT message = data->message;
        switch (message)
        {
        case WM_POINTERUPDATE:
            if (!IS_POINTER_INCONTACT_WPARAM(wParam))
                break;
        case WM_POINTERDOWN:
        case WM_POINTERUP:
            POINTER_INFO pointerInfo = {};
            GetPointerInfo(GET_POINTERID_WPARAM(wParam), &pointerInfo);
            int request_nbr;
            for (request_nbr = 0; request_nbr != 10; request_nbr++) {
                char buffer[10];
                printf("Sending Hello %d…\n", request_nbr);
                zmq_send(requester, data, 5, 0);
                zmq_recv(requester, buffer, 10, 0);
                printf("Received World %d\n", request_nbr);
            }
        }
    }
    return(CallNextHookEx(tHook, code, wParam, lParam));
}
extern "C" __declspec(dllexport) BOOL ConnectServer() {
    printf("Connecting to hello world server…\n");
    static void* context = zmq_ctx_new();
    static void* requester = zmq_socket(context, ZMQ_REQ);
    zmq_connect(requester, "tcp://127.0.0.1:5555");
    printf("connected");
    return TRUE;
}
extern "C" __declspec(dllexport) BOOL DisconnectServer() {
    zmq_close(requester);
    zmq_ctx_destroy(context);
    return TRUE;
}
extern "C" __declspec(dllexport) BOOL SetHook()
{
    tHook = SetWindowsHookEx(WH_GETMESSAGE, meconnect, hinstDLL, 0);

    if (tHook == NULL)
        return FALSE;
    else
        return TRUE;
}
extern "C" __declspec(dllexport) BOOL UnHook()
{
    return UnhookWindowsHookEx(tHook);
}

BOOL APIENTRY DllMain(HMODULE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved
)
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        hinstDLL = hModule;
        break;
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

Python:
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://127.0.0.1:5555")

def message_msg_loop():
    while True:
        #  Wait for next request from client
        message = socket.recv()
        print("Received request: %s" % message)

        #  Do some 'work'
        time.sleep(1)

        #  Send reply back to client
        socket.send(b"World")

def pointer_msg_loop():
    global lib
    lib = cdll.LoadLibrary(r'C:\Users\Braun\Documents\BA_Thesis\ba-oliver-braun-logging-tool-code\MessagesDll\x64\Release\HOOKDLL.dll')
    print(lib)
    res = lib.ConnectServer()
    res = lib.SetHook()
    pythoncom.PumpMessages()
    res = lib.UnHook()

Basically my plan was to detect a certain event through windows messages and pass the message structure from the DLL-callback over to the server in Python, so I can handle the data there and put them into a log file. It does not seem to work though.

A: In case one has never worked with ZeroMQ,one may here enjoy to first look at "ZeroMQ Principles in less than Five Seconds"before diving into further details

Simplicity helps us start,rather than remain headbanging into Complexity First
Best avoid all the complexities :
- set .setsockopt( zmq.LINGER, 0 ) # ALWAYS, never know what version will try to join the Club
- prototype with PUSH/PULL(it a) meets the spec.+b) does not block in a mutual deadlock as all REQ/REP do )
- never share a socket ( yes, the requester ought be a private, non-shared instance )
- always read-in and assert-eval the return-codes from the ZeroMQ API calls ( detect many issues on-spot )

Can you POSACK / prove the both of the module-level declarations
...
void* requester;
void* context;
LRESULT CALLBACK meconnect(...) {...}
...

actually work as expected, or does the ConnectServer(){...}'s internal, in-scope declarations mask both of these globals ?

extern "C" __declspec(dllexport) BOOL ConnectServer() {
    printf("Connecting to hello world server…\n");
    static void* context = zmq_ctx_new();                   // shadows out void* context
    static void* requester = zmq_socket(context, ZMQ_REQ); //  shadows out void* requester
    zmq_connect(requester, "tcp://127.0.0.1:5555");
    printf("connected");
    return TRUE;
}


text:
Q: How to filter groups where the user is an admin? Making a request on the graph API in a user/groups node, I would like to bring only the data of groups in which the user is an administrator.
Can I pass some filter parameter to the administrator bringing only 'true' results? Or is there any other way to do this?
I've tried a few uses of .filtering, but none have worked. Other Meta APIs have filter defaults of admin_only, but I couldn't make use of them here.
Request:
https://graph.facebook.com/me?fields=name,id,first_name,last_name,email,picture{url},groups.limit(250){id,name,administrator}&access_token=xx

A: https://developers.facebook.com/docs/graph-api/reference/user/groups/#parameters:

admin_only
boolean
Default value: false
Filter to get only groups admined by this viewer

Will need the user_managed_groups permission, without it I get an empty list.


text:
Q: Let $I$ be a prime ideal. Show that $f^{-1}(I)$ is a prime ideal of $R$. Is this also true for maximal ideals? I'm solving some exercises to prepare for my ring theory exam.

Let $f:R→R'$ be a ring homomorphism, with $f(1)=1$, and $R,R'$
  commutative rings with $1$. Let $I$ be a prime ideal. Show that
  $f^{-1}(I)$ is a prime ideal of $R$. Is this also true for maximal
  ideals? Prove or disprove.

I was able to prove this for prime ideals. But I don't know how to prove anything for maximal ideals. I think it is not true. But I find it hard to think of a counterexample.

A: Here is a possibly different way to prove the result for prime ideals, and it will help us determine a sufficient condition for the inverse image of a maximal ideal to be maximal.
Let $f:A\to B$ be any commutative ring homomorphism, and let $\mathfrak b$ be any ideal of $B$. Then $\mathfrak a=f^{-1}\mathfrak b$ is an ideal of $A$ such that $f$ determines an injection $$\varphi:A/\mathfrak a\to B/\mathfrak b$$ This is basically the lattice theorem from group theory. Now, an ideal $\mathfrak q\subset B$ is prime if and only if $B/\mathfrak q$ is an integral domain. Let $\mathfrak p=f^{-1}\mathfrak q$ and note that $A/\mathfrak p$ embeds $B/\mathfrak q$. Since a subring of an integral domain is in turn an integral domain, $\mathfrak p$ is necessarily prime.
Now, an ideal $\mathfrak n\subset B$ is maximal if and only if $B/\mathfrak n$ is a field. Moreover, if we set $\mathfrak m$ to be the preimage of $\mathfrak n$, $A/\mathfrak m$ embeds the field $B/\mathfrak n$. So far so good. But the problem is that subrings of fields are not necessarily fields; this is the only reason why we cannot draw the same conclusion with maximal ideals as we did with prime ideals. However, it can be seen that if $f$ is surjective, then the embedding $\varphi$ is surjective--hence, $\varphi$ is an isomorphism--and $A/\mathfrak m$ is a field.

A: $I$ a prime ideal $⇒$ $f^{-1}(I)$ a prime ideal
Suppose $I$ is a prime ideal. Then we know that $I≠R'$. We need to prove that $f^{-1}(I)≠R$. Suppose $f^{-1}(I)=R$. Then $f(1)=1 \in f^{-1}(I)$. So then $1 \in I$. And then $I=R'$.
Let $x,y \in R$ with $xy \in f^{-1}(I)$. Then $f(xy) \in I$. Then $f(x),f(y) \in I$. Then $x,y\in f^{-1}(I)$.
$I$ a maximal ideal $\not ⇒$ $f^{-1}(I)$ a maximal ideaal
Take the ring homomorphism $f : ℤ →\mathbb{Q} : x ↦ x$. As $\mathbb{Q}$ is a field, therefore $(0)$ is a maximal ideal. But $f^{-1}((0))=(0)$ is not a maximal ideal because $ℤ$ is not a field.


text:
Q: Can't get eclipse to recognize my plugin I exported my eclipse plugin through the "Export Wizard" in the manifest and seems like everything went well (no errors). It created a .jar file within a plugin directory in a zip file.
I thought putting the jar into my Eclipse plugin directory would install it (after re-launching eclipse) but that didn't work. Eclipse can't see the plugin (the perspective isn't showing up)
I tried with Help->Install new software->local archive but it keeps saying "no software found"
Can you help me getting my plugin ready to be installed on a fresh Eclipse copy?
Ps. my plugin uses other dependencies like EMF/GMF

A: In eclipse, go to your console window. From the drop down meny, select OSGI console. Run the command ss or ss <name of your plugin>
You will then see the state of your plugin and a number. The state will probably be "installed" which means if has been found, but some dependencies were not satisfied.
Run the command diag <number of your plugin> and you will see why it wasn't started.
For more details, see Wheres my bundle
Edit: A first step to verify that the plugin is working would be to start up a new eclipse instance with your plugin. In the run configuration dialog, there is a tab with all the plugins that should be started. Make sure yours is checked and it will start with the new eclipse instance.

A: If you are using Eclipse 3.4 or above, put your plugin in the 'dropins' directory.
To install via Help->Install new software you need to create an 'Update site' or a 'p2 repository'.

A: By far the most ellaborate descriptions of installing your plugin is provided by Vogella deployment of your plug-in
It covers all 3 possible ways in which you may install your plugin detailing the pros & cons of each of the following approaches :
1 . Installing your plug-in from your Eclipse IDE
2 . Export plug-in and put into dropins folder
3 . Create update site for your plug-in

A: Sometimes you just have to restart Eclipse. File -> Restart and try again. Worked for me because Eclipse was caching the results of my local update site.

A: *

*Open plugin.xml

*In "Overview" Tab in "Exporting section" go to "Export Wizard"

*In "Export" window in "Destination" section choose "Install into host. Repository" and choose dir which will looks like "xxx/.metadata/.plugins/org.eclipse.pde.core/install/"

*Press "Finish" button

*Wait for Export to finish without any problems

*Restart Eclipse


text:
Q: how to check a condition before exectuing any apis - python My project has many APIs. but now I have to put a check in all of these APIs before start executing the codes in it. I have to make sure that API only returns data if that particular form's deactivation date is grater than datetime.date.today(). Queryset would be -
available_for_entry = Forms.objects.filter(form_id=form_id, deactivate_date__gte=today_date).exists()
One way to do this to write that query set in each of APIs and then use if available_for_entry: condition. But, I was wondering if there is any other way to achieve this without writing similar conditions so many times.
I tried to achieve this with writing decorator but I could not able to pass the form_id value from function based API to that decorator. snapshot of the code is...
def is_form_available(func):
    def checking():
        today_date = datetime.date.today()
        available_for_entry = Forms.objects.filter(form_id=form_id, deactivate_date__gte=today_date).exists()
        if available_for_entry:
            func()
        else:
            print('form is not available now')
    return checking

@api_view(['POST'])
@is_form_available
def question_list(request):
  form_id = request.POST.get('form_id')
  parameter_list = (FormParameters.objects.filter(mappings__form__formparametermappings=   form_id).all())
  serializer = FormParametersQuizSerializer(parameter_list, many=True)

  return serializer.data

A: Decorator is a good idea, you can get some inspiration from native Django decorators like require_http_methods
from functools import wraps

def is_form_available(func):
    @wraps(func)
    def checking(request, *args, **kwargs):
        form_id = <extract from request>
        today_date = datetime.date.today()
        available_for_entry = Forms.objects.filter(form_id=form_id, deactivate_date__gte=today_date).exists()
        if available_for_entry:
            return func(args, kwargs)
        else:
            print('form is not available now')
    return checking


text:
Q: Grouping data with JavaScript (linq.js) with multiple grouping criteria? I've been reading stack overflow for some time now, and found that this time I have a question of my own to post as I can't quite find the answer. I'm quite new to Javascript and I'm having some difficulties getting started coming from a lot of work with SQL, Qlikview and VBA.
The question I have is about grouping a bunch of data in the way I would in SQL; from the research I've done it seems to me that linq.js is the way to go, or are there other good alternatives?
The data I have is following:
    var data = [

        { ID: I1, Group: G1, Name: A, ArrivalDate: 42097, ReturnDate: 42098, Travellers: 22, City: Boston },
        { ID: I1, Group: G1, Name: A, ArrivalDate: 42098, ReturnDate: 42099, Travellers: 22, City: New York },
        { ID: I1, Group: G1, Name: A, ArrivalDate: 42099, ReturnDate: 42100, Travellers: 22, City: Chicage },
        { ID: I2, Group: G1, Name: A, ArrivalDate: 42097, ReturnDate: 42098, Travellers: 14, City: Boston },
        { ID: I2, Group: G1, Name: A, ArrivalDate: 42098, ReturnDate: 42099, Travellers: 14, City: New York },
        { ID: I2, Group: G1, Name: A, ArrivalDate: 42099, ReturnDate: 42100, Travellers: 14, City: Chicage },
        { ID: I3, Group: G2, Name: B, ArrivalDate: 42091, ReturnDate: 42092, Travellers: 21, City: Boston },
        { ID: I3, Group: G2, Name: B, ArrivalDate: 42092, ReturnDate: 42093, Travellers: 21, City: New York },
        { ID: I3, Group: G2, Name: B, ArrivalDate: 42093, ReturnDate: 42094, Travellers: 21, City: Chicage },
        { ID: I4, Group: G2, Name: B, ArrivalDate: 42091, ReturnDate: 42092, Travellers: 22, City: Boston },
        { ID: I4, Group: G2, Name: B, ArrivalDate: 42092, ReturnDate: 42093, Travellers: 22, City: New York },
        { ID: I4, Group: G2, Name: B, ArrivalDate: 42093, ReturnDate: 42094, Travellers: 22, City: Chicage },
        { ID: I5, Group: G3, Name: C, ArrivalDate: 42082, ReturnDate: 42083, Travellers: 30, City: Boston },
        { ID: I5, Group: G3, Name: C, ArrivalDate: 42083, ReturnDate: 42084, Travellers: 30, City: New York },
        { ID: I5, Group: G3, Name: C, ArrivalDate: 42084, ReturnDate: 42085, Travellers: 30, City: Chicage },
        { ID: I6, Group: G3, Name: C, ArrivalDate: 42082, ReturnDate: 42083, Travellers: 10, City: Boston },
        { ID: I6, Group: G3, Name: C, ArrivalDate: 42083, ReturnDate: 42084, Travellers: 10, City: New York },
        { ID: I6, Group: G3, Name: C, ArrivalDate: 42084, ReturnDate: 42085, Travellers: 10, City: Chicage }
    ]

In SQL I would do following:
Select  ID,
        Group,
        Name,
        min(ArrivalDate) as ArrivalDate,
        max(ReturnDate) as ReturnDate,
        Travellers
    from data
    group by ID, Group, Name, Travellers

The output would be:
    [
        { ID: I1, Group: G1, Name: A, ArrivalDate: 42097, ReturnDate: 42100, Travellers: 22 }
        { ID: I2, Group: G1, Name: A, ArrivalDate: 42097, ReturnDate: 42100, Travellers: 14 }
        { ID: I3, Group: G2, Name: B, ArrivalDate: 42091, ReturnDate: 42094, Travellers: 21 }
        { ID: I4, Group: G2, Name: B, ArrivalDate: 42091, ReturnDate: 42094, Travellers: 22 }
        { ID: I5, Group: G3, Name: C, ArrivalDate: 42082, ReturnDate: 42085, Travellers: 30 }
        { ID: I6, Group: G3, Name: C, ArrivalDate: 42082, ReturnDate: 42085, Travellers: 10 }
    ]

Intuitively this is what I would want to write with linq.js:
    var datagroup = Enumerable.From(data)
            .GroupBy("$.id", null,
                     function (key, g) {
                         return {
                           id: key,
                           group: g("$.group"),
                           name: g("$.name"),
                           arrivaldate: g.min("$.arrivaldate"),
                           returndate: g.max("$.returndate"),
                           travellers: g("$.travellers")
                         }
            })
            .ToArray();

Any help is a appreciated, thanks for being a great source of information!

A: You have a composite key so you need to use the overloads that provide a compare function for the keys.
var query = Enumerable.From(data)
    .GroupBy(
        // key composed of ID, Group, Name, and Travellers
        "{ ID: $.ID, Group: $.Group, Name: $.Name, Travellers: $.Travellers }",
        null,
        "{ ID: $.ID, Group: $.Group, Name: $.Name, ArrivalDate: $$.Min('$.ArrivalDate'), ReturnDate: $$.Max('$.ReturnDate'), Travellers: $.Travellers }",
        // compare keys using this string representation
        "[ $.ID, $.Group, $.Name, $.Travellers ].join('|')")
    .ToArray();


text:
Q: How to back up my.cnf file from /etc/mysql I encountered same problem here https://askubuntu.com/questions/760724/16-04-upgrade-broke-mysql-server
I am trying to follow the answers but I am not sure how to back up my.cnf file in /etc/mysql. Can anyone help me?

A: You can do sudo cp /etc/mysql/my.cnf /etc/mysql/my.cnf.bak This basically copies the file and renames it.


text:
Q: OkHttpClient offline cache I'm trying to implement response caching using OkHttpClient, but i'm a bit confused. To do this, i'm using Interceptor like this:
final Interceptor interceptor = chain -> {
    Response response = chain.proceed(chain.request());
    if (isOnline()) {
        int maxAge = 60; // read from cache for 1 minute
        response = response.newBuilder()
                .addHeader("Cache-Control", "public, max-age=" + maxAge)
                .build();
    } else {
        int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
        response = response.newBuilder()
                .addHeader("Cache-Control","public, only-if-cached, max-stale=" + maxStale)
                .build();
    }
    if (!response.isSuccessful()) {
        response = response.cacheResponse();
    }
    return response;
}
mClient.networkInterceptors().add(interceptor);
mClient.interceptors().add(interceptor);

But i'm getting UnknownHostException if there's no internet connection. But i want to get cached response. How to deal with it?


text:
Q: Code not working due to line 6, it runs but doesn't work as designed import random
randomNum=random.randint(1,9999)
print(randomNum)
userGuess=input("Please guess a 4 digit number, if you get it correct, we'll tell you, otherwise we will tell if you got any of the positions of the numbers correct\n")
if userGuess==randomNum:
    print("Congratulations, you guessed the number correctly")

Why doesn't last line work after i enter the correct number? I don't think its indentation and I'm confused.

A: You need to cast userGuess as an integer.
i.e.
import random
randomNum=random.randint(1,9999)
print(randomNum)
userGuess=int(input("Please guess a 4 digit number, if you get it correct, we'll tell you, otherwise we will tell if you got any of the positions of the numbers correct\n"))
if userGuess==randomNum:
    print("Congratulations, you guessed the number correctly")

A: By default input is considered as str and not the data type of entered value, that's why you need to take the input and covert it to int or convert the randomNum to str.
import random
randomNum= str(random.randint(1,9999))
print(randomNum)
userGuess=input("Please guess a 4 digit number, if you get it correct, we'll tell you, otherwise we will tell if you got any of the positions of the numbers correct\n")
if userGuess==randomNum:
    print("Congratulations, you guessed the number correctly")

OR
import random
randomNum=random.randint(1,9999)
print(randomNum)
userGuess=int(input("Please guess a 4 digit number, if you get it correct, we'll tell you, otherwise we will tell if you got any of the positions of the numbers correct\n"))
if userGuess==randomNum:
    print("Congratulations, you guessed the number correctly")


text:
Q: Why am I having problems syncing non-itunes music to my iphone? I have an iPhone 4S with loads of music from CDs and such on my iTunes. I had an old iPod with the same account that it would all sync onto fine, however, when I try to sync it to my iPhone, nothing happens. The songs are definitely in my iTunes library. I have the settings for my iPhone to sync all songs when plugged in to the computer. Also, I have tried dragging the songs over to my iPhone where devices is shown in iTunes, and my iPhone doesn't highlight to accept songs.
Does anyone have a solution?

A: You need to make sure your iPhone is configured to sync music from iTunes:

*

*Connect your iPhone to your computer

*Start iTunes

*Select you iPhone in Devices list

*Select Music tab

*Check the box Sync Music and select what you want to sync to your iPhone (all music / specific playlists)

Also make sure to "Sync only checked songs and videos" option is not checked on your iPhone Summary tab.
On your next sync (automatic or manual, depending on your settings) music should begin to sync to your iPhone.


text:
Q: Spring Cloud Config- Decryption of properties is not working on Client Side I have a basic setup for a config client and config server( exactly as in the tutorial here- https://spring.io/guides/gs/centralized-configuration/
My issue is I can decrypt properties on the server side and send them over as plain text but cannot decrypt properties on the client side rather than the server side. I am using symmetric encryption, and have gone through the documentation several times but am unable to get decryption on client side working.
I have added the following property on the server side, so it does not decrypt properties on the server side-
       spring.cloud.config.server.encrypt.enabled=false

I have an application.yml file which has a encrypted value-
       name: '{cipher}hdshdghsgdhjsgdhsgdyassudyadssd2313wdw2e'

I have tried adding ENCRYPT_KEY/encrypt.key as an environment variable, system property on the client side. Also, have tried adding the same in application.properties and bootstrap.properties but the client is not able to decrypt.
Thank you in advance.
Config Client POM-
.......................
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

  <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
<version>1.4.2.RELEASE</version>
</dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
</dependency>

    <dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.3.0</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka-server</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Edgware.SR2</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

..............
In the config Server i have added the property-
           spring.cloud.config.server.encrypt.enabled=false

On the config Client side, I have added encrypt.key in both application.properties and bootstrap.properties.
           encrypt.key=abcd

A: So, this is what solved it. I had added the following property-
          spring.cloud.config.server.encrypt.enabled=false

in application.properties/yaml on the config server side. This was wrong. It needs
to be inside bootstrap.properties/yaml instead of application.properties/yaml.
Can this be added to the documentation explicitly?
I do see the mention of the property above in the documentation but not of the location it should be added in.
https://cloud.spring.io/spring-cloud-config/single/spring-cloud-config.html


text:
Q: Makeing a Proxy connection (both client / server behint NAT) I want to get a PROXY Server getting to run behind NAT. (Ok I can configure the Port forwarding in the router, but I want it instantly!).
So lets say A wants use Bs running proxy server. A / B are behind a router with NAT. So what now? A calls up the Server S to let him know that he wants a Proxy connection to B while B did already tell S that he is ready to connect.
So S exchages somehow the IPs / Ports so that A / B can send UDP Packages to get a connection (hole punshing).
Am I right till now?
Ive read abou STUN (http://www.codeproject.com/KB/cs/STUN_client.aspx) but how the hell does me the backgiven IP / Port help me!? Does A / B need to exchange exactly those from the STUN Server and make a UPD hole Punsh through this Port!? I dont think so.
I would really apricieate a lot for helping me! Because my research, for this takes now friking to long. Id spend more than 30h to get Information and didnt come up with at least a idea!
Also other / better solutions are truly wanted :) Please help me guys.
Prefered language C#.

A: I have written a chapter about NAT traversal in the Practical JXTA II book available online for reading at Scribd. It describes the different techniques available. It could be a good starting point for your project.


text:
Q: Populating of list after a redirect action in struts2 I have a index.jsp which redirects to otl_homepage.jsp on successful login.
When the user logs in, I need to display a list in the otl_homepage.jsp.
In my struts.xml, if i give type="chain" or no type at all, the list is getting fetched. But if I use type="redirectAction", the list is returning null.
How do I obtain this list?
The list is maintained in my java action class.
please find the struts.xml here and the java class
struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
  <constant name="struts.enable.DynamicMethodInvocation"
    value="false" />
  <constant name="struts.devMode" value="false" />
  <constant name="struts.custom.i18n.resources" value="MessageResource" />
   <constant name="struts.convention.result.path" value="/"></constant>

 <package name="default" namespace="/" extends="struts-default">
        <interceptors>
            <interceptor name="authentication"
                class="com.opentext.planning.interceptor.LoginInterceptor"></interceptor>
            <interceptor-stack name="authStack">
                <interceptor-ref name="authentication"></interceptor-ref>
                <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        </interceptors>

        <default-interceptor-ref name="authStack"></default-interceptor-ref>

       <!--  <global-results>
            <result name="login" type="redirect">/home.action</result>
        </global-results>

        <action name="home">
            <interceptor-ref name="defaultStack"></interceptor-ref>
            <result>/index.jsp</result>
        </action>-->

        <action name="login" class="com.opentext.planning.view.OTLAuthentication" >
            <result name="success" type="redirectAction">Otl_Homepage</result>
            <param name="otlUserList">${otlUserList}</param>
            <result name="login">/index.jsp</result>
            <result name="failure">/index.jsp</result>
            <result name="failure2">/index.jsp</result>
            </action>
            <action name="Otl_Homepage" class="com.opentext.planning.view.OTLAuthentication" method="home">
            <interceptor-ref name="defaultStack"></interceptor-ref>
            <result name="success">/Otl_Homepage.jsp</result>
             <result name="failure">/index.jsp</result>
            <result name="failure2">/index.jsp</result>
            </action>

Java class:
public String execute(){
    System.out.println("inside execute");

    //System.out.println("user is" +user.getUser());
   // System.out.println("username is " +user.getUserName());
    //if("pankaj".equals(user.getUserName()) && "admin".equals(user.getPassword())){
        //System.out.println("inside if");

        if (j_username != null) {
        System.out.println("inside function");
    System.out.println("user name is "+j_username);
   // add userName to the session
    System.out.println("user name is 2"+j_username);
    sessionMap.put("loginId", j_username);
   System.out.println("dunno if the will print");
       // user.setUserName(user.getUserName());
      //  sessionMap.put("USER", j_username);
        status = otlAuthenticationController.loginAuthentication(j_username,j_password);
        if(status == "success")
        {
            this.otlUserList= otlAuthenticationController.obtainList();
            System.out.println("size is"+otlUserList.size());
            return "success";
        }

    }
        return status;
}

A: After redirection to another action you need to populate the list again in the home action. The redirectAction result type redirects to another action. Another action instantiate a new instance of the action class. This instance should be initialized and populated before you return a JSP result. In JSP the list values retrieved from the ValueStack which has an action instance that returned a list if the public getter method exists in the action class.
public String home(){
    this.otlUserList= otlAuthenticationController.obtainList();
    System.out.println("size is"+otlUserList.size());
    return "success";
}


text:
Q: git clone won't update even though differences exist between the directory and repository I have a repository, which I cloned. This worked, and the contents of the repository transferred to my directory. I updated a file in the repository, and deleted the same file from my directory. However, when I write:
git pull origin main
# or
git pull origin master

I am told:
* branch            main       -> FETCH_HEAD
Already up-to-date.

I tried to reset the stash, but I'm not really sure what that does.
git reset HEAD --hard

A: I'm not entirely sure what your question is, but I think you want to have your file back which you deleted locally but not on the repository.
git reset --hard origin/main

This command resets your local branch and make it exactly as origin/main, but keep in mind that it will delete all your staged and unstaged files!
It already says up to-to-date, because your local repository is running the same commit as your online repository (it's up-to-date for git), so git expects that you are going to stage and commit the deleted file.


text:
Q: "404" error while uploading large file (>150mb) in laravel 5.7 on godaddy server I'm facing one problem during upload of large file (>150mb) through post request in laravel 5.7 on godaddy server.
Small files (<150mb) I can upload but large files i can't while i can upload large files in localhost. On server when I'm trying to upload large file during form submission the page is redirecting to the route path and displaying "404" error.
I have also updated the values of upload_max_filesize, post_max_size, memory_limit upto 2G on server but its not working for me. I have attached the screenshot of error:


text:
Q: How to check that value of input is equal to specific string when keydown using javascript? I've got a form with differents fields which have different name value.
I'm searching a way to when u write something in a field, it compares what u wrote (current value) with the default value and then, remove a disabled button.
<form id="myForm">
    <input type="text" class="form-control name-saisie" onkeyup="onKeyUp(this);" name="something" value="something" maxlength="40">
    <input type="text" class="form-control name-saisie" onkeyup="onKeyUp(this);" name="somethingelse" value="somethingelse" maxlength="40">
    <input type="text" class="form-control name-saisie" onkeyup="onKeyUp(this);" name="somethingElseElse" value="somethingElseElse" maxlength="40">
</form>

I tried something like :
function onKeyUp(el) {
    var inputValue = 'I dunno what i'm supposed to put here!!!' // cant got this
    if(el.value!=inputValue) { // el.value is current value, inputValue is the default value
        $('[name="actionSave"]').removeClass('disabled');
    } else {
         $('[name="actionSave"]').addClass('disabled');
    }
}

A: please check this code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
 <form id="myForm">
<input type="text" class="form-control name-saisie" onkeyup="onKeyUp(this)" name="something" value="something"
       maxlength="40">
<input type="text" class="form-control name-saisie" onkeyup="onKeyUp(this)" name="somethingelse"
       value="somethingelse" maxlength="40">
<input type="text" class="form-control name-saisie" onkeyup="onKeyUp(this)" name="somethingElseElse"
       value="somethingElseElse" maxlength="40">
</form>

<script>
 function onKeyUp(el) {
    var update_value = el.value;
  var  inputValue = el.getAttribute('value');
    alert(update_value+"=="+inputValue)
    if (update_value != inputValue) { // el.value is current value, inputValue is the default value
        $('[name="actionSave"]').removeClass('disabled');
    } else {
        $('[name="actionSave"]').addClass('disabled');
    }
}
</script>

A: You want to get value attribute of target input. In javascript Element.getAttribute() return value of attribute.
function onKeyUp(el) {
  if (el.value!= el.getAttribute("value"))
    $('[name="actionSave"]').removeClass('disabled');
  else
    $('[name="actionSave"]').addClass('disabled');
}

function onKeyUp(el) {
  if (el.value!= el.getAttribute("value"))
    $('[name="actionSave"]').removeClass('disabled');
  else
    $('[name="actionSave"]').addClass('disabled');
}
.disabled { color: red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
  <input type="text" class="form-control name-saisie" onkeyup="onKeyUp(this);" name="something" value="something" maxlength="40">
  <input type="text" class="form-control name-saisie" onkeyup="onKeyUp(this);" name="somethingelse" value="somethingelse" maxlength="40">
  <input type="text" class="form-control name-saisie" onkeyup="onKeyUp(this);" name="somethingElseElse" value="somethingElseElse" maxlength="40">
  <button name="actionSave" class="disabled">Save</button>
</form>

Also when you use jQuery, you can use jQuery event handler instead of html event handler.
$("#myForm > input").keyup(function(){
  if (this.value != $(this).attr("value"))
    $('[name="actionSave"]').removeClass('disabled');
  else
    $('[name="actionSave"]').addClass('disabled');
});

$("#myForm > input").keyup(function(){
  if(this.value != $(this).attr("value"))
    $('[name="actionSave"]').removeClass('disabled');
  else
    $('[name="actionSave"]').addClass('disabled');
});
.disabled { color: red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
    <input type="text" class="form-control name-saisie" name="something" value="something" maxlength="40">
    <input type="text" class="form-control name-saisie" name="somethingelse" value="somethingelse" maxlength="40">
    <input type="text" class="form-control name-saisie" name="somethingElseElse" value="somethingElseElse" maxlength="40">
    <button name="actionSave" class="disabled">Save</button>
</form>


text:
Q: Insert Multiple Image Paths Into Multiple Columns On an Intranet site, I am moving quite a few images from the file system into MySQL and have written a little function to assist. There are no errors but neither are the images being inserted so I need to help to figure out how to do it without LOAD_FILE() as it requires folder and file permissions changes that I cannot do.
Note that it is necessary to query the albums table in order that the Primary Key from the albums table can be inserted with the image so that the programming that displays the album will know which image to load.
function uploadFolder($path,$thumbpath) {
    // Use form to submit path (keeps process from running automatically when loaded)
    if (isset($_POST['create']) && isset($path)) :
        global $siteDB;

        // Fetch image names from existing albums
        $sqlAlbum = "SELECT ID, ImageName FROM albums ORDER BY ImageName";
        $sqlRow = DBConnect($sqlAlbum, "Multiple", $siteDB, "assoc");

        // Build queries to insert all images to table
        foreach ($sqlRow as $row) :
            $filename = basename($row['ImageName']);
            $albumID = $row['ID'];
            $pathname = $path.$filename;
            $sqlUpload = "INSERT INTO images (`ImageName`,`AlbumID`,`ImageFull`) VALUES ('$filename', $albumID, LOAD_FILE('$pathname'))";
            // Run the query for each file
            DBConnect($sqlUpload,"Run", $siteDB);
        endforeach;

        // FOR TEST PURPOSES ONLY
        $_SESSION['testSQL'] = $sqlUpload;
    endif;
}

it is being called with:
if (isset($_POST)) :
    $path = (isset($_POST['path'])) ? $_POST['path'] : "";
    uploadFolder($path,"thumbnails");
endif;

Not much to the images table but here it is for reference:
CREATE TABLE IF NOT EXISTS `images` (
  `ID` int unsigned NOT NULL AUTO_INCREMENT,
  `ImageName` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
  `AlbumID` int unsigned DEFAULT NULL,
  `ImageFull` blob,
  `ImageThumb` blob,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=228 DEFAULT CHARSET=utf8;

LOAD_FILE() problems aside, there are two ways I could have done this. One is to read all the files and insert them IF they exist in the albums table by querying it. The other as I showed above is to get a list of files from the albums table by querying it, then find and insert those images from the file system. Doing the latter (in theory) prevents it from inserting stray photos that are not supposed to be in the album.
Although I didn't show it here because I realized it after posting the question, doing the latter also lets me grab the Description column from the albums table so that I could tell which image was which.

A: It's hard to tell for sure, because you are using some sort of database wrapper with some odd parameter conventions.  Typically you would not be using LOAD_FILE but rather, reading the file with php into a variable and using the mysql client api to save each row.
LOAD_FILE can work, but it must be the exact path to the file AND the effective webserver user (the user the webserver is running as) must have permissions to the directories you are trying to read from.
Assuming that is true, something like this should work:
    foreach ($sqlRow as $row) :
        $filename = basename($row['ImageName']);
        $albumID = $row['ID'];
        $pathname = $path.$filename;
        $thumbPathname = $path . $thumbpath . DIRECTORY_SEPARATOR . $filename
        $sqlUpload = "INSERT INTO images (`ImageName`,`AlbumID`,`ImageFull`,`ImageThumb`) VALUES ('$filename', $albumID, LOAD_FILE('$pathname'), LOAD_FILE('$thumbPathname'));\n";
        // Run the query for each file
        DBConnect($sqlUpload,"Run", $siteDB);
    endforeach;

This code assumes that thumbNail directory is a child of the path directory.  The path directory needs to be entered with a trailing slash.
Potential issues:

*

*The SQL statement has a semi colon and a newline.  I have never seen a database client call that would include those.  The MySQL client library doesn't use those, so I am not sure why they would be part of the DB wrapper.

*There is no error checking code here.  If something goes wrong in the DBConnect() function, how will you know?

*The path variable must be complete and must have an end separator.

ok
/somepath/to/directory/

won't work
/somepath/to/directory


text:
Q: Is it possible to "install" a virtualbox snapshot onto a computer? I needed to put together a local server, but before spending money on extra hardware, I decided it would be best to create a virtual machine in virtualbox to do a couple tests first and make sure everything is working properly.
Now that everything is working as intended, instead of reinstalling ubuntu, and all the required server packages, etc., is it possible to take the snapshot I created and "install" it on a fresh computer not running vbox?
Basically, I want to create a bootable disc image of the virtual box snapshot.

A: Step 1: Download Clonezilla iso.
Step 2: Add the iso as a CD in virtual box.

Step 3: Start the VM and press F12 to open boot options.
Step 4: Choose to boot from CD.
Step 5: Follow Clonezilla instructions.
Step 6: Prepare USB drive when prompted.
Step 7: After Clonezilla is complete, remove the USB drive.
Step 8: Burn the Clonezilla iso to a different USB drive.
Step 9: Boot Clonezilla on the new machine and restore the backup.
Step 10: Profit.


text:
Q: Graph theory - The clients can still communicate with all the remaining servers I have the following graph problem that I have no idea how to solve. Could you help me please? I need a proof.
In a computer network there are two types of nodes: client and server. Each client is directly
connected (using network cables) to at least one server and there are no direct connections between
clients. Suppose that each server can route messages to other servers with which it is directly connected
and the entire network is connected. In order to make the network more reliable, a scenario is considered:
Every client is directly connected to at least 2 servers and every pair of servers having the
distance between them 2 are connected using a direct cable.
Prove that, in this new network, if
a server becomes unavailable the clients can still communicate with all the remaining servers.

A: Let $S$ be the server the became unavaible.
If a client was not connected to $S$, it's still connected to at least $2$ other servers, and each of those is connected to all other servers.
If a client was connected to $S$, it's still connected to at least one other server, and each of those is connected to all other servers.
Regardless of the situation, the client can communicate to all other servers.


text:
Q: Symfony 4.3 PHP: How to read the cookie from a 302 redirection response? What I want to do (in the controller)

*

*Receive a request, based on which

*Send an external HTTP request

*Parse the response, based on which

*Return a response

I plan to have multiple functions that all follow this pattern. They're called one by one, in succession.
Symfony 4.3 introduces the HttpClient component and the BrowserKit component which at first sight seem to fit the bill. But as it turns out, things get more complicated. The external HTTP requests are sent to a server that tracks sessions with cookies, which shouldn't be anything too unusual. If the request is sent without cookies, the server always responds with the same landing page content. So we need the cookie. No worries, the response to the initial request comes with a "Set-Cookie" header that contains the cookie that is sent in the "Cookie" header in the subsequent requests. The HTTP status of the response with the cookie is "302 Found" which in a normal web environment, using a web browser, redirects to the next page with the same cookie in the request. Replicating this action in my Symfony controller seems to be very tricky. Expanding on step 2. of what I want to do now:
2.a. Send an external HTTP request
2.b. Read the cookie from the 302 response (without automatic redirection)
2.c. Set the "Cookie" header of the subsequent request, the value coming from 2.b.
2.d. Send the request to the new target (set in the "Location" header of the 302 response)
Here's some of the code from the controller:
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpClient\Exception\RedirectionException;
use Symfony\Component\HttpFoundation\JsonResponse;

public function init(Request $request): JsonResponse
{
    $url = "external url";
    $client = HttpClient::create();
    try {
        $response = $client->request('GET', $url, [
            'max_redirects' => -1
        ]);
    } catch (RedirectionException $redirectionException) {

    }
    return new JsonResponse([], 200);
}

Not setting max_redirects means that the client follows the redirects and ends up returning the 200 response without any cookies. Setting the value to -1 will throw a redirection
exception and again, the 302 response with the cookie seems to be lost.
I've also tried the HttpBrowser component:
$cookieJar = new CookieJar();
$client = new HttpBrowser(HttpClient::create(), null, $cookieJar);
$client->request('GET', $url);

But I get a 200 response without the cookie as it automatically follows the redirects.
I understand that the components mentioned here are new to Symfony 4.3 and "experimental" but I also don't think my task is overly complicated or unusual. But maybe there are other http clients for Symfony that would be better suited for the task?

A: As it turns out, this task was easier to complete by trying out other HTTP client components for Symfony than the native ones. So I've put Symfony HttpClient and HttpBrowser aside for now. I managed to implement a solution for this problem with guzzlehttp/guzzle version 6.3.3. Here's what it looks like in my controller function:
use GuzzleHttp\Client;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

public function init(Request $request): JsonResponse {
    $client = new Client([
        'base_uri' => 'an external domain',
        'cookies' => true
    ]);
    // get the 302 response, without following
    $response = $client->get('path',[
        'allow_redirects' => false
    ]);
    // get the cookie from the 302 response
    $jar = new \GuzzleHttp\Cookie\CookieJar(true,[$response->getHeader('Set-Cookie')]);
    // follow the redirect manually, with the cookie from the 302 response
    $redirectResponse = $client->request('GET', $response->getHeader('Location')[0], [
        'cookies' => $jar
    ]);

    $jsonResponse = new JsonResponse(['message' => 'my message'],200);
    $originalCookie = Cookie::fromString($response->getHeader('Set-Cookie')[0]);
    $newCookie = Cookie::create(
        $originalCookie->getName(),
        $originalCookie->getValue(),
        $originalCookie->getExpiresTime(),
        '/',
        'my domain',
        false,
        true,
        $originalCookie->isRaw(),
        $originalCookie->getSameSite()
    );

    $jsonResponse->headers->setCookie($newCookie);
    return $jsonResponse;
}

The cookie cannot be taken from the response as such or it will never be sent back because the domain or the path doesn't match. So I create a new cookie which is very similar to the original one, then send it back to the browser. This way the cookie comes back in the subsequent requests and the data content can be sent forward.
Other issues that arise here are the same-origin requirements which have to be taken care of on the external server.
I'm still interested in how to do all this with the native Symfony 4.3 components, or also, if anyone can confirm that it's not possible.


text:
Q: HtmlAgility - dealing with in-between html Lets say I have a website "example.com". I call the following line
// Pass html content of the site.com to a string
string htmlCode = client.DownloadString("http://example.com");

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(WebUtility.HtmlDecode(htmlCode));

For some websites I have the exact html I want. But some sites return a html consist of forms, or with an empty body and some kind of scripts.
Example for script one:
<!DOCTYPE html>

<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="-1">
<meta http-equiv="CacheControl" content="no-cache">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="shortcut icon" href="data:;base64,iVBORw0KGgo=">

Please enable JavaScript to view the page content.

How can I deal with this "ecnryption" system and get the final html I want that is on "example.com", that you see when you check the source on the browser?

A: Do you have a F5 Server in front of your webserver? Because I have a similar situation, where that Javascript gets injected in my code (which leads to problems).

A: This was due to page loading with an AJAX call. It could be solved by using PhantomJS web driver.


text:
Q: How to I unlock Death Wish? I downloaded the Hat in Time DLC recently, but I do not have access to the Death Wish mode. I have beaten all of the boss battles

 except for the Conductor, but I did battle DJ Grooves.

What must I do to unlock Death Wish?

 The wiki said that I must beat all of the bosses to unlock Death Wish, but unless DJ Grooves and the Conductor count as different bosses, then I have beaten them all.

A: According to the Steam store page for the DLC, Death Wish also requires 27 Time Pieces.
If you are eligible, you should get an "Intruder Alert" cutscene either when you start the game (if you already have 27) or after you collect the Time Piece, showing you Snatcher sitting by the edge of the ball pit.
You should also be able to access the Death Wish map menu from the pause menu.


text:
Q: How to configure whisper in VSCode for typescript types imports I would like to ask you about whisper in VS code for typescript.
I am importing interface IQueryPreparePaymentsArgs from some another file (see image). The whisper show me that its IQueryPreparePaymentsArgs is interface (it is good, thank you whisper), but is should allow me to see a content of this interface.
Is there any way (extension?) how to enable fully whisper like what is inside:
export interface IQueryPreparePaymentArgs {
  requestId: string;
}

Current state is not helpful for me.
Thank you in advice.

A: *

*You can navigate to the interface via Ctrl+left click

*Peek the interface via hover + Ctrl

*Peek the definition via right click context menu

*Peek the definition from Command Palette


text: Q: Any plan for adding API to select different temperature sensors in a nest thermostat? I noticed that there is no mention in the API for selecting sensors attached to a thermostat.  Is this limitation going to be addressed?