Q: Is this a variation of the decorator pattern or a pattern at all? Below is a simplified version of code I've written to override a class method (using composition), in this case method name i'm overriding is addbuttons(); The class "Screen" adds buttons to a screen whereas class "SubScreen" adds custom buttons to an instance of Screen. Maybe this is not an example of decorator pattern since I'm overriding functionality instead of extending it ? Is there a better way (using a design pattern ?) to achieve same functionality ?
public class Driver {

    public static void main(String args[]){
        AddComponents add1 = new Screen();
        add1.addButtons();

        Screen newScreen = new Screen();
        AddComponents add2 = new SubScreen(newScreen);
        add2.addButtons();
    }

}
    public interface AddComponents {

         public void addButtons();
        }

public class Screen implements AddComponents{

    public void addButtons() {
        //Add Buttons to screen class
    }

}
public class SubScreen implements AddComponents{

    private Screen screen;

    public SubScreen(Screen screen){
        this.screen = screen;
    }

    public void addButtons() {
        //add different custom buttons to Screen class
    }

}

A: Another possibility would be to call it Proxy. Decorator and Proxy are technically very similar - the difference is - in most cases - not a technical one but based on the intention.
Your example is a little bit minimal and therefore it is hard to guess the intention correctly.
Edit
At the detailed level: Screen and SubScreen do not share any code. If you start adding methods to both implementations and the common interface AddComponents you might find

*

*that you must duplicate code both in Screen and SubScreen (or delegate to Screen) and

*that you must add methods to AddComponents which make this interface badly named.

If both screen classes are similar both on the abstract logical level and at the implementation level, then a an class AbstractScreen with two derived classed would be better. To bring back pattern speak: Use a Factory Method in AbstractScreen to specialize the behaviour regarding the different buttons.
On your current code there is one strange thing: Why is there a method addButton defined anyway? Simply add the buttons in the appropriate constructor, since the user has to call addButtons in any case and the method does not have arguments.
Another point not explained is this: SubScreen has a reference to Screen which is not used. Why? Will there be more method in all involved classes Screen, SubScreen and AddComponents? Will each method be a in SubScreen delegate to Screen or only half of them?
You see - there are many possibilities we do not know and are not shown in the example code but are very important. I'm sure that your head contains a lot of details saying "This proposed stuff will not work because I want to do this and that one way or the other in the near future." Sadly we cannot get the content of your head into this site without more writing. :-)


Q: Как передать параметры в скрипт по именам? То есть если есть некий скрипт с параметрами apple и orangescript --apple yes --orange noили сокращенно a и oscript -a yes -o noИли еще что-то такое, не использующее %1, %2 и т.п.
A: getopt Вам поможет.Я все таки умудрился указать неправильную ссылку. Это ссылка на getopt для Си. А поскольку вопрос был про скрипт, да и в метках указан bash, то полезней будет все же посмотреть здесь.В принципе аналог getopt можно найти в любом языке для Unix.


Q: Firebase re-authenticate using PhoneNumberProvider To delete user the user has to be recently authenticated ... I am using Phone number authentication and looking at the example in the docs:  https://firebase.google.com/docs/auth/android/manage-users#re-authenticate_a_user
I need to get the credential of the user which requires 2 parameters: verification Id and SMS code which are fetched from authenticating the user in the first place ... so is there another way to fetch them or I have to send a verification code once more as I did when the user was first authenticated ?


Q: AttributeError: 'dict' object has no attribute 'plot' from iexfinance import Stock
import matplotlib.pyplot as plt
tsla = Stock('TSLA')
tsla.get_close()
tsla.get_price()

from iexfinance import get_historical_data
from datetime import datetime
import pandas as pd
pd.set_option('display.max_rows', 1000)

start = datetime(2017, 2, 9)
end = datetime(2017, 5, 24)

df = get_historical_data("TSLA", start=start, end=end, output_format='json')
df.plot()
plt.show()

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call
last)
<ipython-input-16-77b5455be846> in <module>()
      8
      9 df = get_historical_data("TSLA", start=start, end=end,
output_format='json')
---> 10 df.plot()
     11 plt.show()
     12 df

AttributeError: 'dict' object has no attribute 'plot'

I am trying to get the plot for the dataframe created with the different prices from the start and end date. I tried reading different blogs but none seem to solve it. I am sure I am making a very basic error. Although, I am not able to figure out what am I doing wrong here, any suggestions to fix it?

A: You cannot directly plot a dictionary in matplotlib. It needs x values and y values.
You can see that type(df) will be a <class 'dict'> which contains the value something like this:
{'TSLA': {'2017-02-09': {'open': 266.25, 'high': 271.18, 'low': 266.15, 'close': 269.2, 'volume': 7820222}}}
so, if you want to get it graphed, you need to convert it into pandas dataFrame
your code has to change like this:
from iexfinance import Stock
import matplotlib.pyplot as plt

tsla = Stock('TSLA')
tsla.get_close()
tsla.get_price()

from iexfinance import get_historical_data
from datetime import datetime
import pandas as pd

pd.set_option('display.max_rows', 1000)

start = datetime(2017, 2, 9)
end = datetime(2017, 5, 24)

df = get_historical_data("TSLA", start=start, end=end, output_format='json')
df = pd.DataFrame(df["TSLA"]).transpose() #transpose to get dates as x
df = df.drop(columns = "volume")  #deleted volume column, else it make other graphs smaller
df.index = pd.to_datetime(df.index) #change string to date format
df.plot()
plt.show();

You will get a graph like this:
Graph


Q: How to configure mvc to support binding dd/MM/yyyy date formates for all cultures? I have MVC web application and I am supporting 2 languages(Arabic, English).
I have post-action which takes the following model:
public class MyModel
{
    public DateTimeOffset StartDate { get; set; }
    public DateTimeOffset EndDate { get; set; }
}

When UI language is English it serializes the following date formate "dd/MM/yyyy" perfectly after adding globalization config inside web.config:

<globalization uiCulture="en" culture="en-GB" />

but when UI language is Arabic they are serialized into 0001-01-01T00:00:00 +00:00 (even the value posted by Jquery is startDate: 26/08/2020)
So how can I configure my web application to support binding the "dd/MM/yyyy" format for all cultures?

A: Try using this
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTimeOffset StartDate { get; set; }


Q: Using JavaScript inside a Eclipse plugin It is possible to use JavaScript inside a view of a Eclipse Plugin?

A: By default eclipse runs on java in a JVM.  But JVMs have more and more support for dynamic scripting languages.  You can always use org.mozilla.javascript so your view can implement parts in javascript.  The linke I've included to eclipse Orbit builds are versions that have been OSGi-ified so they can be used easily in eclipse.


Q: Will OS X ever install anything suspicious without my express permission? I clicked a link (turned out to be Breitbart) that said "your Flash is not updated", despite the fact that I just installed it yesterday. The two choices were "Update" and "Ok". Strangely, there was no ability to simply dismiss the popup without clicking one of those buttons. I should have force quit Safari, but instead I clicked "Ok". Then it tried to download something! I immediately dragged it to the trash, but when I tried to empty the trash it said that file was in use! I don't recall clicking on it or giving it any instructions to open so I immediately pulled the plug on the computer. I was able to delete it once I restarted.
Three questions:
1) Why did the computer download software from a random site without being given permission?
2) Why did it say the file was in use when I very clearly did not open it up?
3) Can the Mac actually install this kind of garbage without my permission?

A: It will download anything if you told it to do so.
It will obey your commands, down to self destruct (kill it self) if you ask it to do it.
There are some preventative measures in place (but at your control) to make it safer (from you).
For example the Downloads:

In order to change this setting you would have to enter a Password. In your case it is probably set (by you) to Anywhere, and that is fine if you know what are the risks.
Hopefully you learned a lesson, and in the future close the web site asking you to Update or OK (they mean the same). Anytime you get a pop up asking you to download something that you did not ask for, shall be killed instantly.
Now without further beating the bushes, tell us what site did that and what file did you trash so we can do some surgery.


Q: RegEx to match if the string contains 1 or more sets of 1-10 alphanumerics RegEx to match if the string contains 1 or more sets of 1-10 alphanumerics (separated by 1 space)
Right now i have this and that will match the alphanumeric part.
var regex = /^[0-9a-zA-Zs]+$/;

After it matches i plan to just use
var matches = thetext.Split(' ');

to get the various matches.
Thanks in advance

A: You wrote s in your regular expression instead of \s (meaning whitespace).
If you want to enforce that there is exactly one space character (not multiple spaces and not tabs or other whitespace characters) then you can use this:
/^[0-9A-Za-z]{1,10}(?: [0-9A-Za-z]{1,10})*$/

If you also want to allow underscores, you can use \w to make the expression more concise:
/^\w{1,10}(?: \w{1,10})*$/

A: Try regexp like this if you don't expact space at begin and spaces should be longer than 1 character
var regex = /^([0-9a-zA-Zs]+\s*)*$/;

With possible space at begin you can use
var regex = /^\s*([0-9a-zA-Zs]+\s*)*$/;

If you expact exactly one space and no spaces at begin or end then use
var regex = /^([0-9a-zA-Zs]+\s)*[0-9a-zA-Zs]+$/;


Q: android bootcamp medical calculator fails to open Whenever I try to run the below calculator app on the emulator, it instantly crashes.  Not knowing Java, reading the logcat is a bit overwhelming.
The program's purpose is to create a weight conversion app that uses a radio group and converts kilograms to pounds or vice versa.
Here is my manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.androidbootcamp.medicalcalculator"

 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Here is my logcat:
>02-26 11:14:42.147 1535-1535/? E/AndroidRuntime: FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{net.androidbootcamp.medicalcalculator/net.androidbootcamp.medicalcalculator.MainActivity}: java.lang.NullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
    at android.app.ActivityThread.access$600(ActivityThread.java:130)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4745)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
    at net.androidbootcamp.medicalcalculator.MainActivity.onCreate(MainActivity.java:24)
    at android.app.Activity.performCreate(Activity.java:5008)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
    at android.app.ActivityThread.access$600(ActivityThread.java:130)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4745)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    at dalvik.system.NativeStart.main(Native Method)

Here is my MainActivity:
package net.androidbootcamp.medicalcalculator;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import java.text.DecimalFormat;

public class MainActivity extends AppCompatActivity {
    double conversionRate = 2.2;
    double weightEntered;
    double convertedWeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        assert getSupportActionBar() != null;
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setLogo(R.mipmap.ic_launcher);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
        final EditText weight = (EditText)findViewById(R.id.txtWeight);
        final RadioButton lbToKilo = (RadioButton)findViewById(R.id.radLbToKilo);
        final RadioButton kiloToLb = (RadioButton)findViewById(R.id.radKiloToLb);
        final TextView result = (TextView)findViewById(R.id.txtResult);
        Button convert = (Button)findViewById(R.id.btnConvert);

        convert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                weightEntered=Double.parseDouble(weight.getText().toString());
                DecimalFormat tenth = new DecimalFormat("#.#");
                if(lbToKilo.isChecked()){
                    if (weightEntered <= 500){
                        convertedWeight = weightEntered / conversionRate;
                        result.setText(tenth.format(convertedWeight) + "kilograms");
                    } else {
                        Toast.makeText(MainActivity.this,"Pounds must be less than 500",Toast.LENGTH_LONG).show();
                    }
                }
                if(kiloToLb.isChecked()){
                    if(weightEntered <= 225) {
                        convertedWeight = weightEntered * conversionRate;
                        result.setText(tenth.format(convertedWeight) + "pounds");
                    } else {
                        Toast.makeText(MainActivity.this,"Kilos must be less than 225",Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
    }
}

A: In your manifest you are using android:theme="@style/AppTheme.NoActionBar" so the main activity will not contain the action bar and you will get a NullPointerException.
The assert getSupportActionBar() != null throw the Exception because it is always null in this case. In this case the Assert works like:
if(!getSupportActionBar() != null) {
    throw new Exception(); //NullPointerException in this case
}


Q: MyBatis do a fetch and based on return value do an update/insert inside the Xxxmapper.xml? Is there a way to embed a select from table inside a Mybatis Insert SQL config, Which checks if the record is existing -> Runs the Update on the same table
else just inserts the data.
I know it can be done programtically but need a way to do it in the mapper.xml
Database: Oracle 11g, mybatis 3.1.x
Any suggestions are helpful
thanks

A: Use UPSERT statement, most of the database support UPSERT statements. the return value would be number of records updated or inserted. Though You have not provided the database against which you have performing the update or insert operation.
UPDATE
Oracle 11g does support upsert
MERGE INTO KP_TBL USING DUAL ON (MY_KEY= #{myKey})
        WHEN MATCHED THEN
                UPDATE SET OTHER_PARAM = #{myOtherParam},
                           SEC_PARAM = #{sec_param}
        WHEN NOT MATCHED THEN
                INSERT (MY_KEY, OTHER_PARAM,SEC_PARAM)  VALUES(#{myKey},#{myOtherParam},#{sec_param)

A: This could be done using means of SQL. Unfortunately you didn't mention which particular database management systen you use as there is no such feature in ANSI SQL.
For example if you use MySQL INSERT ... ON DUPLICATE KEY UPDATE is the way to go.
E.g.:
<insert id="instSample" parameterType="SampleModel">
   INSERT INTO table (a,b,c) VALUES (#{a}, #{b}, #{c})
   ON DUPLICATE KEY UPDATE c = #{c};
</insert>


Q: Regex input only number and backspace I have a code
private void DataGridTypePayments_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            e.Handled = new Regex("[^0-9]+").IsMatch(e.Text);
        }

I need input number or backspace.How i can disable input symbol space?

A: The C-style escape for the backspace character is \b which is also the Regex escape for a word boundary.  Fortunately you can put it in a character class to change the meaning:
e.Handled = Regex.IsMatch(e.Text, "[0-9\b]+");


Q: Load local files(CSS or JS) into website of choice I want to load my own coded CSS into a website that I do not own or have server access too. This is for perdonal use only. My problem is I dont know if there is a plugin available to do this; in chrome or firefox. Is there any easy way to do this? How do I do it?
Any help is appreciated. Thanks in advance!

A: Stylebot is a chrome extension that does the very thing. Use this link or if it doesn't work, just go to chrome://extensions then get more extensions and search for Stylebot
But still it won't let you add your own CSS file. It would just allow you to change the CSS of the website and it will store them for you so that whenever you'll visit that site, it would show you the same styles.

A: There are several ways of doing this: 1. First, plugin as you ask for, there is one called User Stylesheet for Chrome and Stylish for Firefox
2. You can edit C:\Users*\AppData\Local\Google\Chrome\User Data\Default\User StyleSheets\Custom.css directly for Chrome
3. You can use dev tool in both Chrome and Firefox to temporary change the element styles.
Just saw you asked for custom javascript as well, you can use Greasemonkey for Firefox and Tampermonkey for Chrome.


Q: Would updating Facebook Android SDK crash my apps on api level below 15? The new Facebook Android SDK requires android min API level 15 but almost all of my apps are at min API level 9. If I integrate new FB Android SDK would that crash my apps on devices with API level below 15?
Also would Share images on FB functionality on API level 9 devices stop working if I get the new SDK?

A: The minSdkVersion attribute means that the library was designed without considering the API levels lower than that value. The developers didn't pay attention if a method or a field is unavailable on API level lower than 15, and this is the method to inform you.
For example the field THREAD_POOL_EXECUTOR used in the method getExecutor is available only from API level 11:
public static Executor getExecutor() {
    synchronized (LOCK) {
        if (FacebookSdk.executor == null) {
            FacebookSdk.executor = AsyncTask.THREAD_POOL_EXECUTOR;
        }
    }
    return FacebookSdk.executor;
}

In version 4.5.1 the getExecutor method is different and supports also API level 9:
public static Executor getExecutor() {
    synchronized (LOCK) {
        if (FacebookSdk.executor == null) {
            Executor executor = getAsyncTaskExecutor();
            if (executor == null) {
                executor = new ThreadPoolExecutor(
                        DEFAULT_CORE_POOL_SIZE, DEFAULT_MAXIMUM_POOL_SIZE, DEFAULT_KEEP_ALIVE,
                        TimeUnit.SECONDS, DEFAULT_WORK_QUEUE, DEFAULT_THREAD_FACTORY);
            }
            FacebookSdk.executor = executor;
        }
    }
    return FacebookSdk.executor;
}

In conclusion you shouldn't use the last version of the Facebook SDK but you should stick with the last compatible version (4.5.0).
The change in minApk version is shown in the upgrade log below: -
https://developers.facebook.com/docs/android/upgrading-4.x.
and the  release of interest is below
https://github.com/facebook/facebook-android-sdk/releases?after=sdk-version-4.8.1


Q: why does this make calls javascript Im creating a angular5 application and I have some problems with the services i use to make requests to a simple node backend server. I won't include the backend code because it doesn't matter if it works or not.
My idea was to have the Service remember if it already has the data and if so, don't make another call. I created a boolean called useCache to keep track of whether to make another call. Code shown below.
getPeople() {
    console.log('before ', this.useCache);
    if (this.useCache === false) {
      console.log('after', this.useCache);
      this.setPeople(this.api.get(this.url));
      this.useCache = true;
    }
    return this.people;
}

useCache is initialized as false so the first time it should make a call.
The second+ times it prints useCache to be true.
This code will not log the ('after', this.useCache) when pressing a button that triggers the GET call multiple times. However my backend server is still registering calls.
people is a undefined variable at first with type any
I tried logging in the api.get function also, and that log isn't printed either.
public get(url: string) {
    console.log('get');
    return this.http.get(API_BASE_URL + url).map(response => {
        return response;
    }).catch(this.handleError);
}

Inside the component that im calling from i have this function to call the getPeople() function.
getPeople() {
    this.personService.getPeople().subscribe(result => {
        console.log(result);
        this.people = result.result;
        this.dataType = 'people';
    });
}

Does anyone have any idea how/why my backend is still logging GET calls?
It shouldn't know I pressed that button inside the separate front-end application right?


Q: I need to optimize my first T-SQL update trigger How do I rewrite this update trigger without using a lot of variables?
I wrote my first SQL Server trigger and it works fine, but I think, that there must be an easier solution.
If minimum one of 5 columns is changed I write two new rows in another table.
row 1 = old Fahrer (=Driver) and old dispodate and update-time
row 2 = new Fahrer and new dispodate and updatedatetime
My solution is just a copy of the foxpro-trigger, but there must be a easier solutions in T-SQL to check whether one colum is changed.
ALTER TRIGGER [dbo].[MyTrigger]
ON [dbo].[tbldisposaetze]
AFTER UPDATE
AS
SET NOCOUNT ON;
/*SET XACT_ABORT ON
SET ARITHABORT ON
*/
DECLARE @oldfahrer varchar(10)
DECLARE @oldbus varchar(10)
DECLARE @olddispodat date
DECLARE @oldvzeit decimal(4,0)
DECLARE @oldbzeit  decimal(4,0)
DECLARE @oldbeschreibk varchar(255)

DECLARE @newfahrer varchar(10)
DECLARE @newbus varchar(10)
DECLARE @newdispodat date
DECLARE @newvzeit decimal(4,0)
DECLARE @newbzeit  decimal(4,0)
DECLARE @newbeschreibk varchar(255)

    SELECT  @oldfahrer = fahrer,@oldbeschreibk=beschreibk,@oldbus=bus,@oldbzeit=bzeit,@olddispodat=dispodat,@oldvzeit=vzeit
        FROM DELETED D
    SELECT  @newfahrer = fahrer,@newbeschreibk=beschreibk,@newbus=bus,@newbzeit=bzeit,@newdispodat=dispodat,@newvzeit=vzeit
        FROM inserted I

if @oldbeschreibk <> @newbeschreibk or @oldbus <> @newbus or @oldbzeit <> @newbzeit or @oldfahrer <> @newfahrer or @oldvzeit <> @newvzeit
begin
  IF (SELECT COUNT(*) FROM tbldispofahrer where fahrer=@oldfahrer and dispodat=@olddispodat) > 0
    update tbldispofahrer  set laenderung = GETDATE()  where fahrer=@oldfahrer and dispodat=@olddispodat
  else
    INSERT into tbldispofahrer (fahrer,dispodat,laenderung) VALUES (@oldfahrer,@olddispodat,getdate())

  IF (SELECT COUNT(*) FROM tbldispofahrer where fahrer=@newfahrer and dispodat=@newdispodat) > 0
    update tbldispofahrer  set laenderung = GETDATE()  where fahrer=@newfahrer and dispodat=@newdispodat
  else
    INSERT into tbldispofahrer (fahrer,dispodat,laenderung) VALUES (@newfahrer,@newdispodat,getdate())
 end

A: I'll assume you have SQL Server 2008 or greater. You can do this all in one statement without any variables.
Instead of doing all the work to first get the variables and see if they don't match, you can easily do that in as part of where clause. As folks have said in the comments, you can have multiple rows as part of inserted and deleted. In order to make sure you're working with the same updated row, you need to match by the primary key.
In order to insert or update the row, I'm using a MERGE statement. The source of the merge is a union with the where clause above, the top table in the union has the older fahrer, and the bottom has the new farher.  Just like your inner IFs, existing rows are matched on farher and dispodat, and inserted or updated appropriately.
One thing I noticed, is that in your example newfahrer and oldfahrer could be exactly the same, so that only one insert or update should occur (i.e. if only bzeit was different). The union should prevent duplicate data from trying to get inserted. I do believe merge will error if there was.
MERGE tbldispofahrer AS tgt
USING (
    SELECT d.farher, d.dispodat, GETDATE() [laenderung]
    INNER JOIN inserted i ON i.PrimaryKey = d.PrimaryKey
        AND (i.fahrer <> d.fahrer OR i.beschreibk <> d.beschreik ... )
    UNION
    SELECT i.farher, i.dispodat, GETDATE() [laenderung]
    INNER JOIN inserted i ON i.PrimaryKey = d.PrimaryKey
        AND (i.fahrer <> d.fahrer OR i.beschreibk <> d.beschreik ... )
) AS src (farher, dispodat, laenderung)
ON tgt.farher = src.farher AND tgt.dispodat = src.dispodat
WHEN MATCHED THEN UPDATE SET
    laenderung = GETDATE()
WHEN NOT MATCHED THEN
    INSERT (fahrer,dispodat,laenderung)
    VALUES (src.fahrer, src.dispodat, src.laenderung)

A: There were a few little syntax errors in the answer from Daniel.
The following code is running fine:

MERGE tbldispofahrer AS tgt
USING (
    SELECT d.fahrer, d.dispodat, GETDATE() [laenderung] from deleted d
    INNER JOIN inserted i ON i.satznr = d.satznr
        AND (i.fahrer <> d.fahrer OR i.beschreibk <> d.beschreibk or i.bus <> d.bus or i.bzeit <> d.bzeit or i.vzeit <> d.vzeit)
    UNION
    SELECT i.fahrer, i.dispodat, GETDATE() [laenderung] from inserted i
    INNER JOIN deleted d ON i.satznr = d.satznr
        AND  (i.fahrer <> d.fahrer OR i.beschreibk <> d.beschreibk or i.bus <> d.bus or i.bzeit <> d.bzeit or i.vzeit <> d.vzeit)
) AS src (fahrer, dispodat, laenderung)
ON tgt.fahrer = src.fahrer AND tgt.dispodat = src.dispodat
WHEN MATCHED THEN UPDATE SET
    laenderung = GETDATE()
WHEN NOT MATCHED THEN
    INSERT (fahrer,dispodat,laenderung)
    VALUES (src.fahrer, src.dispodat, src.laenderung);


Q: How can I insert hash values in columns with Perl's DBI? I have a hash and I am trying to insert its values into database. Hash is defined as follows:
my %hash = (
            1   =>  'First Word',
            2   =>  'Second Word is correct',
            0   =>  'Third word does not exist',
            );

I do not know how to insert values in a database using hashes. I notice my question is similar to this question. But, none of the answers seem to be correct. On using any of the listed answers, the values in hash are not inserted, instead reference to hash is inserted i.e. ARRAY(0x9e63b30). But when I print Dumper @values, values get printed and not reference values.
Any suggestions on how to insert values and not their reference? And, what is going wrong in the solutions listed in answers to question.
@values is defined same as this question i.e.
my @values = values %hash;

Edit:
Db structure:
T1:
sid  sentence
1    First Word
2    Second Word is correct
0    Third word does not exist

in above sid is keys of hash and sentence is values of hash.
this is what I tried out (it is one of the answers to question):
my @keys = keys %hash;

my @values = values %hash;

my $sth = $dbh->prepare("INSERT INTO T1(sid, sentence) VALUES (?,?);");

$sth->execute_array({},\@keys, \@values);

again, while inserting @values reference values are getting inserted.
EDIT:
_ OUTPUT _
$VAR1 = 'First Word';
$VAR2 = 'Third word does not exist';
$VAR3 = 'Second Word is correct';

_ CODE _
this is how I am inserting values into %hash
my $x=0;
foreach my $file(@files){
        if ($file =~ /regex/){
                push(@{$hash{$x}}, "$1 $2 $3 $4 $5 $6 $7");
        }
        elsif ($file =~ /regex/){
                push(@{$hash{$x}}, "$1 $2 $3 $4 $5 $6");
        }
        elseif ($file =~ /Hs_(.+)_(.+)_(.+)_(.+)_(.+)_W.+txt/){
                push (@{$hash{$x}}, "$1 $2 $3 $4 $5");
        }
$x++;
}

A: That's not what you originally posted!!!  You have a hash of reference to arrays.  Read the perl reference tutorial (perlreftut) to learn about them.
(Use the command
perldoc perlreftut

to access this tutorial)

A: This should work.
my $key;
my $value;
while (($key, $value) = each %hash) {
    $sth->bind_param(1, $key);
    $sth->bind_param(2, $value);
    $sth->execute();
}

A: UPDATE:
I suggest that you grab one of the functional examples from the previous thread and get it working on your machine with your database. Once you can get one of these examples working then you should be able to fix your own code.

Previous answer:
My reply on the other thread that uses execute_array() also works, I tested it before posting it.


Q: How to allow or deny IP with regex or Wildcard in NGINX? I want to allow/deny set of IPs in my Nginx
allow   192.168.1.75;
allow   192.168.1.76;
allow   192.168.2.25;
allow   192.168.2.30;

Can I do this something like this?
allow   192.168.*.*;

A: Use CIDR notation.
For example:
allow 192.168.0.0/16;


Q: For a matrix $A$ find the smallest positive $n$ for which $A^n=I$
Let $A$ be a $8 \times 8$ square matrix with $a_{12} = a_{24} = a_{33} = a_{41} = a_{58} = a_{65} = a_{77} = a_{86} = 1$ and all other entries $0$. Then $A^n=I$ for some $n$; find $n$.

I successfully found that $n=3$ by multiplying the matrix $A$ one by one. I want to ask if there is any alternative method that is easier and less tedious.

A: This is a permutation matrix.
We can represent it by
$$(4, 1, 2)(5, 8, 6).$$
which consists of $3$-cycles. Hence $A^n=I$, for $n$ being multiple of $3$.

A: Hint This is a permutation matrix $P_{\sigma}$ for the permutation $\sigma = (124)(586)$. Permutation matrices have the convenient properties that $P_{\sigma \tau} = P_{\sigma} P_{\tau}$ and $P_{\textrm{id}} = I$. Thus, $n$ is the minimal positive $n$ such that $\sigma^n = \textrm{id}$, that is, the order of $\sigma$.


Q: Feeding Azure Event Hub data to ReactJS
I'm trying to read data from the Azure Event Hub and display it on a simple web app using ReactJS. I've used the code sample from Microsoft to read Azure data, and this works fine standalone. I have an IoT temperature sensor and every time the sensor sends I receive the value from the function in the console:
const consumerClient = new EventHubConsumerClient("$Default",
connectionString, clientOptions);

async function getTemperature() {

consumerClient.subscribe({
  processEvents: async(events, context) => {
      for(const event of events){
         var temperature = event.body.temperature;
         var humidity = event.body.humidity;
         console.log(temperature);
         console.log(humidity);
      }
  },
  processError: async (err, context) => {
      console.log(`Error : ${err}`);
  }
});
}

getTemperature().catch((error) => {
   console.error("Error running sample:", error);
});

I now wish to use this in ReactJS component, something like this:
const returnTemperature = () => {
    return (

The temperature is { temperature }° Celcius.

     );
}

export default returnTemperature;

I am new to ReactJS and I cannot get my head around how to update the value on the web page every time the temperature received by the Azure function is updated. I have looked into useState/useEffect but not got anything working.
Any suggestions?
Thanks in advance,
Jeff

A: I made assumptions that you can work with functional components.
const Temperature = () => {
  const [temperature, setTemperature] = useState();
  const consumerClient = new EventHubConsumerClient(
    "$Default",
    connectionString,
    clientOptions
  );

  const getTemperature = async () => {
    consumerClient.subscribe({
      processEvents: async (events, context) => {
        for (const event of events) {
          var temperature = event.body.temperature;
          var humidity = event.body.humidity;
          setTemperature(temperature);
          console.log(temperature);
          console.log(humidity);
        }
      },
      processError: async (err, context) => {
        console.log(`Error : ${err}`);
      },
    });
  };

  useEffect(() => {
    getTemperature().catch((error) => {
      console.error("Error running sample:", error);
    });
    return () => {
      // cleanUpFunction if applicable
      // consumerClient.unsubscribe()
    };
  }, []);

  return (

The temperature is {temperature}° Celcius.

  );
};

The useEffect() with empty dependencies [] array acts like componentDidMount as in, it only runs once. i.e calls your getTemperature on first load.
After that, the setState() will keep the temperature value updated, and re-render the component whenever the temperature updates.


Q: HOW to avoid completely showing data which is in another MySQL table? I am trying to avoid some data which is already in two tables... which means... I used the select statement to get an advertisement which is stored in MySql database using Member Id and I use JOIN tables... there is no problem... all advertisements are showing perfectly which are belong to the member package...
Now the problem is... after the member clicks on an advertisement... it's stored in a table which is called "view" with the date of click, ad_id, and member id. And again the same member should not be able to click that advertisement till the next day... I need to avoid showing that advertisement data using select statements with the condition...
can anyone help me, please? I paste my query below
SELECT `advertisements`.`Ads_ID`,`advertisements`.`AdsName`,`advertisements`.`code`,`advertisements`.`Ad_Value`,`advertisements`.`images`,`advertisements`.`date` FROM `advertisements` JOIN `package_ads` ON `package_ads`.`Ads_ID`=`advertisements`.`Ads_ID` JOIN `packages` ON `packages`.`Package_ID`=`package_ads`.`Package_ID` JOIN `member_package` ON `member_package`.`Package_ID`=`packages`.`Package_ID` JOIN `members2`ON `members2`.`Mem_ID`=`member_package`.`Mem_ID` JOIN `views`ON `views`.`Mem_ID`=`members2`.`Mem_ID` WHERE `member_package`.`Mem_ID`="M100" AND `views`.`clickeddate`!="2021-12-04" AND `views`.`Ads_ID`!=`advertisements`.`Ads_ID`

A: Whenever you want avoid showing a row based on it's existence in another table you can do that using one of two ways

*

*Use not exists or not in condition

*or use a left join and add IS NULL for the joining condition.

The below query will provide you the desired result. It removes from the select query the ads that have already been visited by a particular member on a particular date.
SELECT
advertisements.Ads_ID,
advertisements.AdsName,
advertisements.code,
advertisements.Ad_Value,
advertisements.images,
advertisements.date
FROM advertisements
JOIN package_ads ON package_ads.Ads_ID=advertisements.Ads_ID
JOIN packages ON packages.Package_ID=package_ads.Package_ID
JOIN member_package ON member_package.Package_ID=packages.Package_ID
JOIN members2 ON members2.Mem_ID=member_package.Mem_ID
LEFT JOIN views ON (views.Mem_ID=members2.Mem_ID and date(views.clickeddate) = current_date and views.Ads_ID=advertisements.Ads_ID)
WHERE
member_package.Mem_ID="M100"
AND views.Ads_ID IS NULL


Q: How do i write a jQuery input string so that it works with Django query string Am working on a name search app but having a challenge getting it to work with Django query string, the challenge which i observed comes from my JavaScript input type with ${input} string when added to Django query string eg. "address/get-name/?search=${input}" doesn't return the query object or the payload data, instead it return an empty list, but when i make search through the browser it return all search query data eg  "address/get-name/?search=smith", Now how do i get input through my scripts without having to use the java scripts query input type ${input} with django so let i get a query string like this "address/get-name/?search=james" ? Here is my script, Am a novice in JavaScript

my view.py

def get_names(request):
    search = request.GET.get('search')
    payload = []
    if search:
        objs = Names.objects.filter(name__startswith=search)
        for obj in objs:
            payload.append({
            'name' : obj.name
            })

    return JsonResponse({
        '200': True,
        'playload': payload
    })

A: The problem is your javascript syntax, it's
const url = `/address/get-names/?search=${input}`

instead of
const url = "/address/get-names/?search=${input}"


Q: Symfony sfWidgetFormInputFile deleted my file Sorry for the many questions but I'm new to Symfony.   I made a form and all it working well.  I a few fields for pictures (Picture1, Picture2, Picture3, etc).   I used te sfWidgetFormInputFile and all is working well with that as well.   It uploads the file where it needs to and it gives it a unique name.
The problem I'm having is that those fields are set in mySQL to have a default value of "no-pic.png" so that if the user doesn't upload a picture, it will still have something to show in the post.   But every time someone uploads a picture, it deletes my no-pic.png file and the posts without a picture show with a blank square.  I'm thinking it's because it's set to "delete previous image" before uploading the new one to reduce excess unused pictures on the server.
I'm wondering if there's a way to have it check to see if the value is "no-pic.png" before deleting it from the folder.  In case it helps, this is the code I'm using in the form.class file.
      $this->widgetSchema['picture1'] = new sfWidgetFormInputFile(array('label' => 'Pictures', ));
  $this->validatorSchema['picture1'] = new sfValidatorFile(array('required' => false, 'path' => sfConfig::get('sf_upload_dir').'/car', 'mime_types' => 'web_images', ));
  $this->widgetSchema['picture1'] = new sfWidgetFormInputFileEditable(array(
    'label' => 'Pictures',
    'file_src' => '/uploads/car/'.$this->getObject()->getPicture1(),
    'is_image' => true,
    'edit_mode' => !$this->isNew(),
    'template' => '
%file%
%input%
%delete%%delete_label%
',
    ));
  $this->validatorSchema['picture_delete'] = new sfValidatorPass();

A: Just for reference here is the code I used.
$this->setWidget('logo_image', new sfWidgetFormInputFileEditable(array(
  'file_src'  => 'uploads/logos/'.$this->getObject()->getFilename(),
  'edit_mode' => !$this->isNew()
)));

$validatorOptions = array(
  'max_size'           => 1024*1024*10,
  'path'               => sfConfig::get('sf_upload_dir').'/logos',
  'mime_type_guessers' => array(),
  'required'           => false
);

if ($this->isNew())
{
  $validatorOptions['required'] = true;
}

$this->setValidator('logo_image', new sfValidatorFile($validatorOptions));
$this->setValidator('logo_image_delete', new sfValidatorString(array('required' => false)));

A: I found a workaround.  I had the page check to see if it was set to no-pic.png and then it displays a no-pic.png in another location.   That way when it goes to upload a picture, it won't delete it.   :)   Thanks for your help though.


Q: Can I write a function to revalue levels of a factor? I have a column 'lg_with_children' in my data frame that has 5 levels, 'Half and half', 'Mandarin', 'Shanghainese', 'Other', 'N/A', and 'Not important'. I want to condense the 5 levels down to just 2 levels, 'Shanghainese' and 'Other'.
In order to do this I used the revalue() function from the plyr package to successfully rename the levels. I used the code below and it worked fine.
data$lg_with_children <- revalue(data$lg_with_children,
                             c("Mandarin" = "Other"))
data$lg_with_children <- revalue(data$lg_with_children,
                             c("Half and half" = "Other"))
data$lg_with_children <- revalue(data$lg_with_children,
                             c("N/A" = "Other"))
data$lg_with_children <- revalue(data$lg_with_children,
                             c("Not important" = "Other"))

To condense the code a little I went back data before I revalued the levels and attempted to write a function. I tried the following after doing research on how to write your own functions (I'm rather new at this).
revalue_factor_levels <- function(df, col, source, target) {df$col <- revalue(df$col, c("source" = "target"))}

I intentionally left the df, col, source, and target generic because I need to revalue some other columns in the same way.
Next, I tried to run the code filling in the args and get this message:
warning message
I am not quite sure what the problem is. I tried the following adjustment to code and still nothing.
revalue_factor_levels <- function(df, col, source, target) {df$col <- revalue(df$col, c(source = target))}

Any guidance is appreciated. Thanks.

A: You can write your function to recode the levels - the easiest way to do that is probably to change the levels directly with levels(fac) <- list(new_lvl1 = c(old_lvl1, old_lvl2), new_lvl2 = c(old_lvl3, old_lvl4))
But there are already several functions that do it out of the box. I typically use the forcats package to manipulate factors.
Check out fct_recode from the forcats package. Link to doc.
There are also other functions that could help you - check out the comments below.
Now, as to why your code isn't working:

*

*df$col looks for a column literally named col. The workaround is to do df[[col]] instead.

*Don't forget to return df at the end of your function

*c(source = target) will create a vector with one element named "source", regardless of what happens to be in the variable source.
The solution is to create the vector c(source = target) in 2 steps.

revalue_factor_levels <- function(df, col, source, target) {
  to_rename <- target
  names(to_rename) <- source
  df[[col]] <- revalue(df[[col]], to_rename)
  df
}

Returning the df means the syntax is:
data <- revalue_factor_levels(data, "lg_with_children", "Mandarin", "Other")

I like functions that take the data as the first argument and return the modified data because they are pipeable.
library(dplyr)

data <- data %>%
  revalue_factor_levels("lg_with_children", "Mandarin", "Other") %>%
  revalue_factor_levels("lg_with_children", "Half and half", "Other") %>%
  revalue_factor_levels("lg_with_children", "N/A", "Other")

Still, using forcats is easier and less prone to breaking on edge cases.
Edit:
There is nothing preventing you from both using forcats and creating your custom function. For example, this is closer to what you want to achieve:
revalue_factor_levels <- function(df, col, ref_level) {
  df[[col]] <- forcats::fct_others(df[[col]], keep = ref_level)
  df
}

# Will keep Shanghaisese and revalue other levels to "Other".
data <- revalue_factor_levels(data, "lg_with_children", "Shanghainese")

A: Here is what I ended up with thanks to help from the community.
revalue_factor_levels <- function(df, col, ref_level) {
  df[[col]] <- fct_other(df[[col]], keep = ref_level)
  df
}

data <- revalue_factor_levels(data, "lg_with_children", "Shanghainese")


Q: How to convert Mysqli results into an array in OO Php I want to retrieve data from a table in database and display the result in an array in the form below.
array("1"=>"Value 1", "2"=>"value2")
Here is the function I tried using but I get error when I try to display the array. Please I need help on this. I'm new to OO Php.
<?php
class query {

public function listfields (){
    $result = $this->mysqli->query("SELECT id, name FROM fields", MYSQLI_USE_RESULT);
    while($row=$result->fetch_assoc()){
    $this->fields[$row["id"]] = $row["name"];
    }
    $result->free();

}

public function fields(){
return $this->fields;
}
        }

$list = new query;
$list->listfields();
$field1 = $list->fields();

echo $field1;
?>

A: Try This.
<?php

class query {

public function listfields (){

 $fields = array();
 $rowcnt =1;
 $result = $this->mysqli->query("SELECT id, name FROM fields", MYSQLI_USE_RESULT);
    while($row=$result->fetch_assoc()){
      $this->fields[$row["id"]] = $row["name"];
     //$this->fields[$rowcnt] = $row["name"];   // if you want different indexing.
      $rowcnt++;
 }
 $result->free();
}

public function fields(){
    return $this->fields;
}
}
$list = new query();
$list->listfields();
$field1 = $list->fields();
var_dump($field1);
?>

A: Instead of your function fields, you will need a property fields, which you can access.
Furthermore i suggest using getters and setters instead of a public property, im sure you will find out how.
This will return the Data in form array("1"=>"Value 1", "2"=>"value2").

class query {

public $fields;

public function fillfields ()
{
    $result = $this->mysqli->query("SELECT id, name FROM fields", MYSQLI_USE_RESULT);
    while($row=$result->fetch_assoc()){
         $this->fields[] = $row["name"];
    }
    $result->free();
}

$list = new query;
$list->fillfields();
$field1 = $list->fields[1];

echo $field1;


Q: After uninstalling JPfofiler ( from Ubuntu ) when i run my application in Netbeans,it shows Error I installed JProfiler, after 2 days i uninstall Jprofiler (in Ubuntu) but when i run my application Netbeans IDE shows following Error:
Error occurred during initialization of VM
Could not find agent library /home/bsoft/jprofiler7/bin/linux-x86/libjprofilerti.so in absolute path, with error: /home/bsoft/jprofiler7/bin/linux-x86/libjprofilerti.so: cannot open shared object file: No such file or directory
Please help me to solve this problem.
Finally i solved the problem.
 i just removed two files(startup_jprofiler.sh, setenv.sh) from my  tomcat installation directory(/var/lib/tomcat6/bin).**

A: Please first make sure that, your JVM is working or not. Try to start JVM from command prompt. It you are able to launch java.exe file then there are some problems with your project.
You are using netbeans. So before starting netBeans remove cache of netBeans. There are changes that your netBeans is pointing to old class path of jProfiler.
Regards,
Gunjan.


Q: How to run Gant targets from within a Grails controller? Suppose I have a block of Gant code:
 target(echo:"test"){
    ant.echo(message:"hi")
 }
 setDefaultTarget("echo")

This is usually run from a command line.
How could I place the block in a Grails controller and run it from there?

A: You can use AntBuilder for this:
class FooController {

   def index = {
      def ant = new AntBuilder()
      ant.echo(message:"hi")
   }
}

A: You can create a groovy script say DynaScript_.groovy that contains your Gant code and place this script file in the {grailsHome}/scripts folder.
And then you can invoke the script file from your controller like this:
class FooController {

     def index = {
           def process  =  "cmd /c grails dyna-script".execute()
           def out = new StringBuilder()
       process.waitForProcessOutput(out, new StringBuilder())
           println "$out"
     }
}

It's important that your script name ends with an underscore.


Q: Error connect between PostgreSQL and XAMPP Can someone help me to fixing the problem about connecting PostgreSQL with XAMPP?
The error is :

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; Misc has a deprecated constructor in C:\xampp\phpPgAdmin\classes\Misc.php on line 8

I use PostgreSQL version 9.6.2-3 and XAMPP 7.1.1.0

A: That (notice) message is based on changes to PHP 7.
So an old way of using a constructor is still in use, is what that message means. It will be ok at the moment, until the support is completely removed in the future. However, I don't believe that should/would cause any connection trouble ?
What is expected is instead of having a class with a constructor like this:
<?php
    class foo {
        function foo() {
            echo 'I am the constructor';
        }
    }
?>

... would now be expected to look like this:
<?php
    class foo {
        function __construct() {
            echo 'I am the constructor';
        }
    }
?>

See the first section section of this PHP 7 deprecation info.
You could apply that change yourself, just comment-out the old way, and use the other constructor form.


Q: How do I get the current date in Javascript, using an argument There are loads of questions about the current date in JavaScript in general, but in my scenario, I have to pass in something to the date object, because usually there is a valid date I'm looking for. However, my question is - assuming the argument is undefined, what should I pass to mimic new Date()?
As an example, my code will do something like this.
const date = '2019-11-26T19:10:12.000Z'
const diff = new Date(date).getTime() - new Date().getTime()

While my components are rendering, I need to give date an initial value (while it loads from the server). During this initial loading time, I expect the diff to equal 0.
I have tried the following
new Date(undefined) >> Invalid Date

new Date('') >> Invalid Date

new Date(null) >> Thu Jan 01 1970

new Date(0) >> Thu Jan 01 1970

I'm trying to solve it in a simple way, by passing in whatever value would match no argument for Date. It seems weird, but if it's the case, I'll just assume it's JavaScript date objects being weird.

A: You can define your date with another date object as parameter.

var params = new Date;
var date = new Date(params);

console.log(date)


Q: React form: loop through event.target to create an object I have a rather long form to submit and would like to create an object containing the name of the input as a key and the value of the input as the value. I tried looping through the event.target and event.target.elements as shown below:
handleModify(event) {
    let tempPlayer = {}
    Object.entries(event.target.elements).forEach(([name, input]) => {
        tempPlayer[name] = input;
    });
}

But I got the TypeError about looping cyclic object value. It is probably not the right way to loop those values, as I saw by logging on the console event.target and event.target.elements actually contain html form elements. I don't know how else to get the form data. My form looks like that:
<form onSubmit={e=> props.onSubmit(e)}>
  <label htmlFor="name">
    Name:
    <input type="text" name="name" placeholder="Estelle Nze Minko" />
  </label>
  <label htmlFor="poste">
    Poste:
    <input type="text" name="poste" placeholder="Back" />
  </label>
  <label htmlFor="number">
    Number:
    <input type="number" min="0" max="100" step="1" name="number" placeholder="27" />
  </label>
  <label htmlFor="height">
    Height (m):
    <input type="number" min="1.00" max="2.34" step="0.01" name="height" placeholder="1.78" />
  </label>
  <label htmlFor="selects">
    Number of selects:
    <input type="number" min="0" max="300" step="1" name="selects" placeholder="88" />
  </label>
  <button type="submit">Add</button>
</form>

I was using this method because it is the way I did it on the server side by fetching the form data and looping the req.body entries. However now that I have changed the ejs templates to React I can't send the form data. That is why I am trying to loop through the values directly in the React handle method. I was unable to send the form data with fetch to my node + express server. The req.body always ended up being empty. I think it is because I am using body-parser and I was sending a new FormData() (which isn't supported?) as such:
handleModify(event) {
    event.preventDefault();
    fetch(`/players/modify/${this.props.match.params.id}/confirm`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        mode: "cors",
        body: JSON.stringify(new FormData(event.target))
    });
}

However, if I create the object first and then send it with fetch, it works. So, does anyone know how to loop through the form elements or how to solve the fetch problem? Thank you :))

A: That's not how you should do it in ReactJS. Here's a good tutorial for handling forms: https://reactjs.org/docs/forms.html
Basically you need to set a value to each input and handling their respective onChange callback:
e.g.
    <input type="text" name="name" value={this.state.name} onChange={onNameChange} placeholder="Estelle Nze Minko" />

Then in your component you have a method onNameChange which saves the new value to a state for example:
onNameChange(event) {
  const name = event.target.value;
  this.setState(s => {...s, name});
}

Finally when submitting the form you need to use the values inside this.state
handleSubmit(e) {
  e.preventDefault(); // prevent page reload
  const {name} = this.state;
  const data = JSON.stringify({name});
  fetch(`/players/modify/${this.props.match.params.id}/confirm`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    mode: "cors",
    body: data
  });
}

This is all just an example, I recommend you read the link I gave you first.
LE: Using an uncontrolled component:
https://codesandbox.io/s/dark-framework-k2zkj here you have an example I created for an uncontrolled component.
basically you can do this in your onSubmit function:
  onSubmit(event) {
    event.preventDefault();
    const tempPlayer = new FormData(event.target);
    for (let [key, value] of tempPlayer.entries()) {
      console.log(key, value);
    }
  };

A: Is there a reason you don't use controlled components? You could keep the input values in the state, and when submitting the form, you just use the values from the state.
React Docs on Forms

A: The error seems to come from storing the input itself as value, you might have ended up performing an operation on it somewhere. Instead you can store the name and value of input with:
tempPlayer[input.name] = input.value;

Demo:

const root = document.getElementById("root");

const { render } = ReactDOM;

function App() {
  const handleSubmit = (event) => {
    event.preventDefault();
    let tempPlayer = {}
    Object.entries(event.target.elements).forEach(([name, input]) => {
        if(input.type != 'submit') {
          tempPlayer[input.name] = input.value;
        }
    });
    console.log(tempPlayer)
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="name">
        Name:
        <input type="text" name="name" placeholder="Estelle Nze Minko" />
      </label>
      <label htmlFor="poste">
        Poste:
        <input type="text" name="poste" placeholder="Back" />
      </label>
      <label htmlFor="number">
        Number:
        <input
          type="number"
          min="0"
          max="100"
          step="1"
          name="number"
          placeholder="27"
        />
      </label>
      <label htmlFor="height">
        Height (m):
        <input
          type="number"
          min="1.00"
          max="2.34"
          step="0.01"
          name="height"
          placeholder="1.78"
        />
      </label>
      <label htmlFor="selects">
        Number of selects:
        <input
          type="number"
          min="0"
          max="300"
          step="1"
          name="selects"
          placeholder="88"
        />
      </label>
      <button type="submit">Add</button>
    </form>
  );
}

render(<App />, root);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root" />

PS: Uncontrolled forms are known to have performance improvements and reduced rerenders as shown in React hook form. You don't have to use a controlled component.
You may not need Controlled Components - swyx Blog


Q: Identify tool that created FPGA files I have a set of old FPGA files. I'm trying to identify the tool that created them so I can try to import them into a current tool.
The file extensions of the set of files are *.abl, *.pin, *.ipf, *.dri and others.
The files are 10-15 years old. They were originally built on a Sun Workstation.
The target package is an Actel A1280A.
Any suggestions?

A: The .abl extension is suggestive of the ABEL language, but I don't know whether that was ever used to program FPGAs. The Wikipedia page says that Xilinx now owns ABEL, so you could ask them whether it still supports Actel (kind of doubtful).
I worked extensively with Actel FPGAs in the 1990s, but we used Orcad schematic capture (not HDL) to design logic using Actel-supplied libraries, and then transferred the netlists into Actel's own toolchain for synthesis and programming.
I have some backup disks with the Actel software (as installed) on them, but I don't seem to have any original installation media. It's possible that their toolchain could parse ABEL source code directly, but I wouldn't know.

A: As mentioned by others and in my comment.  Try reading these files in a text editor and you should see human readable information especially in the .abl file which should include the logical description of the device operation in tha ABEL language.
If you need to modify and rebuild this device then you should contact Actel/Microsemi to find out what software support is there.  A quick search on their website indicates that ABEL might still be supported and their libero 9.1 toolset still supports the ACT2 devices which appears to be the device you have.
http://www.actel.com/documents/PCN1108_LiberoIDE_support.pdf
You can get a free license and test the tool to see if it can import your files.
http://www.actel.com/products/software/libero/licensing.aspx

A: .abl indicates that they were written in ABEL (Advanced Boolean Expression Language).


Q: Message: Uninitialized string offset: 0 in coideigniter I want to insert multiple rows by one click. I have an add button called add. When I click add button it loads another row. In my case when, I submit a single row it saves to data base and gives an error:
A PHP Error was encountered

Severity: Notice

Message: Uninitialized string offset: 0

Filename: controllers/boq_controller.php

Line Number: 46

and this will occurs when I click add button also. Please help me to fix those problems.
controller
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Boq_controller extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('form_validation');
        $this->load->model('boq_model');

    }

public function index(){

    $this->load->view('admin_include/header');
    $this->load->view('project/boq');

}
public function create(){

                if ($_POST)
    {
        $work_product_id=$this->input->post('work_product_id');
        $work_item_description=$this->input->post('work_item_description');
        $quentity=$this->input->post('quentity');
        $rate=$this->input->post('rate');
        $laboure_hrs=$this->input->post('laboure_hrs');
        $laboure_cost=$this->input->post('laboure_cost');
        $others=$this->input->post('others');
        $txtmultTotal=$this->input->post('txtmultTotal');
        $txtgrandTotal=$this->input->post('txtgrandTotal');
        $data = array();
        for ($i = 0; $i < count($this->input->post('work_product_id')); $i++)
        {
            $data[$i] = array(
                'work_product_id' => $work_product_id[$i],
                'work_item_description' => $work_item_description[$i],
                'quentity' => $quentity[$i],
                'rate' => $rate[$i],
                'laboure_hrs' => $laboure_hrs[$i],
                'laboure_cost' => $laboure_cost[$i],
                'others' => $others[$i],
                'txtmultTotal' => $txtmultTotal[$i],
                'txtgrandTotal' => $txtgrandTotal[$i],
            );
        }
        $this->boq_model->create($data);
    }
   }
 }

model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Boq_model extends CI_Controller{

function create($data) {
    $this->db->insert_batch('boq', $data);
}

}
?>

view
<?php include 'header.php'; ?>

<form class="form-inline" role="form" id="frmadd" action="<?php echo base_url() ?>index.php/boq_controller/create" method="POST">

          Work Product Id
          Work Item Description
          Quentity
          Unit
          Rate
          Laboure-Hrs
          Labour Cost
          Others
          Total

        <input type="text" name="work_product_id" class="form-control" id="work_product_id" placeholder="">
        <input type="text" name="work_item_description" class="form-control" id="work_item_description" placeholder="">
        <input type="text" name="quentity" id="" class="form-control val1" />
        <select style=" height: 33px; width: 102px; border-radius: 2px;" >
            <option value=""selected> </option>
            <option value="cube">cube</option>
            <option value="sq.ft">sq.ft</option>
            <option value="Cwts">Cwts</option>
            <option value="Gal" >Gal</option>
        </select>
        <input type="text" name="rate" class="form-control val2"/>
        <input type="text" name="laboure_hrs" id="" class="form-control val3" />
        <input type="text"name="laboure_cost" id="" class="form-control val4"/>
        <input type="text" name="others" class="form-control" id="others" placeholder="">

                0.00<input type="text" id="txtmultTotal" name="txtmultTotal">

    Grand Total# 0.00 <input type="text" id="txtgrandTotal" name="txtgrandTotal">
    <button id="insert-more" class="btn btn-primary">ADD</button>

                    <input type="submit" class="btn btn-success" id="btn btn-success" value="submit">

</form>


Q: syntax error near unexpected token `newline' for my simple if statement? #include <stdio.h>
int main(void)
{
  char input;
  printf("Enter a character: ");
  scanf("%c", &input);

  if (input == 'a') {
    printf("A\n");

  } else {
    printf("B\n");
  }
  return (0);
}

What am I doing wrong? this should be easy. I don't understand.

A: Your program is perfectly correct.
The error message -bash: syntax error near unexpected token 'newline' is produced by bash, the command line interpreter, not the compiler.
There are a few potential reasons for this, but here is the most likely:

*

*You are running the program with bash instead of having the system execute the binary, which is what happens if you typed . ./prog or . prog instead of ./prog.


Q: prevent yeoman.io from minifying images So I've been using yeoman.io for my projects and I have a set folder structure for my images. But when I build it changes the file name of my files.
I even use:
$ yeoman build:text

because I want to only minify my css,js and html templates, yet it still minifies the images.
Not sure if im doing something wrong.
EDIT:
I commented out all instances of img in the gruntfile and that seemed to work, but I dont think thats the right way.

A: You mean image optimization or revisioning? There is no problem to configure GruntFile.js to your own needs. It makes Yeoman/Grunt very powerful, because it is highly adaptable.
If you don't want image optimization, remove the configuration in the img task.
// Optimizes JPGs and PNGs (with jpegtran & optipng)
   img: {
   },

If you dont want the renaming of image files, remove the img line from the rev task:
// renames JS/CSS to prepend a hash of their contents for easier
// versioning
rev: {
  js: 'scripts/**/*.js',
  css: 'styles/**/*.css'
},

A: If you remove the image revving it will bust your cache, you should try to keep the revving and update your JS files instead.
Try updating your usemin block to something like this:
usemin: {
    html: ['<%= yeoman.dist %>/{,*/}*.html'],
    css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
    js: '<%= yeoman.dist %>/scripts/{,*/}*.js',
    options: {
        assetsDirs: [
            '<%= yeoman.dist %>',
            '<%= yeoman.dist %>/images',
            '<%= yeoman.dist %>/styles'
        ],
        patterns: {
            js: [
                [/(images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm, 'Update the JS to reference our revved images']
            ]
        }
    }
}

You should already have the usemin method, just add the js attribute with you js path regex and add the pattern attribute.
This will replace all occurrences of the image in your JS files with the new revved version, so that the clients' browsers don't use a cached image instead of a new one.


Q: Svg icon not working on desktop but work fine on mobile Hello my svg icons are not working on desktop i get only a white space but the icon work fine on mobile devices this is my code :

<svg xmlns="http://www.w3.org/2000/svg" width="56" height="56" fill="none"><g clip-path="url(#a)" fill="#000"><path d="M13.079 49.653H5.137v1.682h7.942v-1.682ZM25.476 49.653h-7.942v1.682h7.942v-1.682ZM37.873 49.653H29.93v1.682h7.942v-1.682ZM50.27 49.653h-7.942v1.682h7.942v-1.682Z"></path><path d="M0 0v56h56V0H0Zm54.255 1.744v9.968H1.745V1.744h52.51Zm0 11.712v31.89H10.997l-3.346-3.4H1.745v-28.49h52.51Zm-52.51 40.8V43.69H6.92l3.347 3.4h43.989v7.164H1.744Z"></path><path d="M8.095 5.557H5.944v1.745h2.15V5.557ZM49.807 5.557h-7.35v1.745h7.35V5.557ZM17.354 39.71l1.095-1.358-9.569-7.718 8.864-7.396-1.118-1.34-10.496 8.76 11.224 9.052ZM34.54 38.371l1.142 1.319 10.483-9.08-11.236-8.73-1.07 1.377 9.557 7.425-8.877 7.69ZM30.347 16.43l-9.5 26.172 1.64.595 9.5-26.171-1.64-.596ZM5.66 45.448a.765.765 0 1 0-1.53 0 .765.765 0 0 0 1.53 0Z"></path></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h56v56H0z"></path></clipPath></defs></svg>

and this is my website :


Q: What beamer environment is text within a frame? I'm going crazy just trying to change the color of the text within a frame environment.
\begin{frame}[plain]
  I want this text to be red!!!
\end{frame}

I have tried almost every single environment listed on the Latex Wiki.
{
  %\usebackgroundtemplate{\includegraphics[width=\paperwidth]{dark_galaxy.jpg}}
  \begin{frame}[plain]
    \setbeamercolor{alerted text}{fg=red}
    \setbeamercolor{background canvas}{fg=red}
    \setbeamercolor{block body alerted}{fg=red}
    \setbeamercolor{block body}{fg=red}
    \setbeamercolor{block body example}{fg=red}
    \setbeamercolor{block title}{fg=red,bg=blue}
    \setbeamercolor{fine separation line}{}
    \setbeamercolor{frametitle}{fg=red}
    \setbeamercolor{item projected}{fg=red}
    \setbeamercolor{normal text}{fg=red}
    \setbeamercolor{section in sidebar}{fg=red}
    \setbeamercolor{section in sidebar shaded}{fg=red}
    \setbeamercolor{separation line}{fg=red}
    \setbeamercolor{sidebar}{fg=red}
    \setbeamercolor{structure}{fg=red}
    \setbeamercolor{subsection in sidebar}{fg=red}
    \setbeamercolor{subsection in sidebar shaded}{fg=red}
    \setbeamercolor{title}{fg=red}
    \setbeamercolor{titlelike}{fg=red}

    Electromagnetic radiation from hydrogen gas in VIRGOHI 21 suggests it is
    part of a system with a mass of \approximately $10^{11}$ solar masses.
  \end{frame}
}

A: The question asks what Beamer styling commands to use to change the default color of text within a frame. Locally setting the text color as suggested works, but isn't quite what is being asked (as currently worded)—It doesn't use Beamer styling commands, as pointed out in the comments to that answer.
A more complete answer is provided with this other question, which was closed as a duplicate to this one. User oneself points out that
one should use \setbeamercolor{normal text}{fg=red} to set the text color globally, but this must be followed by \usebeamercolor[fg]{normal text} to take effect.
\setbeamercolor{normal text}{fg=red}
\usebeamercolor[fg]{normal text}
\begin{frame}
  Some text in red
\end{frame}

A: To highlight some text in beamer, use \alert{some text}.
From the beamer tutorial (specifically Section 3.8)

beamer offers the command \alert, which
      is used like \emph and, by default, typesets its argument in bright red.

The command is again described in Section 12.3 of the manual, along with the alertenv environment.
Why doesn't changing the color of normal text work? The beamer manual says:

The color [normal text] is used for normal text. At the beginning of the document the foreground color is installed as \normalcolor.

What this means is that it has to be changed before \begin{document} and then affects all frames. There doesn't seem to be an easy way around that particular limitation of the beamer's themes. I guess the reason for this (except for being easier to implement) is to force users to use semantic markup instead of constantly changing the normal text color.

A: For a single frame in a different colour, a regular \color{<col>} works:

\documentclass{beamer}% http://ctan.org/pkg/beamer
\begin{document}
\begin{frame}
  \color{red}%
  I want this text to be red!!!
\end{frame}
\end{document}


Q: can't return observable of customError in network call I want to use catchError for getting back my error as custom type.
At first, I want my network layer return Observable and then in ViewModel I subscribed it for .OnNext, .OnError, .OnCompleted events, But I don't know how should I handle Errors such as 4xx, 5xx network status code and then, them return my Custom Error Object!
My Login ViewModel :
func getAccessToken() {
        let network = NetworkRequest()

        network.logInRequest(tokenType: .guest, token: "cce577f6021608", secondKey: "09128147040", client: "cce577f6021608bc31424d209cbf5120c3683191").subscribe(onNext: { loginData in
            self.token.onNext(loginData.access_token)
        }, onError: { error in
            print("The Error is: \(error.localizedDescription)")
        }, onCompleted: {
            print("Its Completed")
        }).disposed(by: bag)
    }

My network layer function:
class NetworkRequest: NSObject {
    var rxProvider: MoyaProvider<WebServiceAPIs>

    override init() {
        rxProvider = MoyaProvider<WebServiceAPIs>( plugins: [ NetworkLoggerPlugin(verbose:true) ])
    }

    func logInRequest(tokenType: accessTokenTypeEnum, token: String, secondKey: String, client: String) -> Observable<LoginModel> {
        return rxProvider.rx
              .request(WebServiceAPIs.getAccessToken(tokenType: tokenType.rawValue, token: token, secondKey: secondKey, client: client))
              .filterSuccessfulStatusCodes()
              .catchError({ error -> Observable<NetworkError> in
                return //Observable.just() => I want to return a custom network error as obserable
              })
              .map(LoginModel.self, atKeyPath: nil, using: JSONDecoder(), failsOnEmptyData: true).asObservable()
    }

}

thanks for any help

A: Moya returns MoyaError enum in error block which you can handle by extracting the error type using switch on MoyaError and then using statusCode to convert to NetworkError enum
func logInRequest(tokenType: accessTokenTypeEnum, token: String, secondKey: String, client: String) -> Observable<LoginModel> {
        return sharedProvider.rx
                .request(WebServiceAPIs.getAccessToken(tokenType: tokenType.rawValue, token: token, secondKey: secondKey, client: client))
                .filterSuccessfulStatusCodes()
                .catchError({ [weak self] error -> Observable<NetworkError> in
                    guard let strongSelf = self else { return Observable.empty() }
                    if let moyaError = error as? MoyaError {
                        let networkError = self?.createNetworkError(from: moyaError)
                        return Observable.error(networkError)
                    } else {
                        return Observable.error(NetworkError.somethingWentWrong(error.localizedDescription))
                    }
                })
                .map(LoginModel.self, atKeyPath: nil, using: JSONDecoder(), failsOnEmptyData: true).asObservable()
    }

    func createNetworkError(from moyaError: MoyaError) -> NetowrkError {
        switch moyaError {
        case .statusCode(let response):
            return NetworkError.mapError(statusCode: response.statusCode)
        case .underlying(let error, let response):
            if let response = response {
                return NetworkError.mapError(statusCode: response.statusCode)
            } else {
                if let nsError = error as? NSError {
                  return NetworkError.mapError(statusCode: nsError.code)
                } else {
                  return NetworkError.notConnectedToInternet
                }
            }
         default:
              return NetworkError.somethingWentWrong("Something went wrong. Please try again.")
        }
    }

You can create your custom NetworkError enum like below which will map statusCode to custom NetworkError enum value. It will have errorDescription var which will return custom description to show in error view
enum NetworkError: Swift.Error {
    case unauthorized
    case serviceNotAvailable
    case notConnectedToInternet
    case somethingWentWrong(String)

    static func mapError(statusCode: Int) -> NetworkError {
        switch statusCode {
        case 401:
            return .unauthorized
        case 501:
            return .serviceNotAvailable
        case -1009:
            return .notConnectedToInternet
        default:
            return .somethingWentWrong("Something went wrong. Please try again.")
        }
    }

    var errorDescription: String {
        switch self {
        case .unauthorized:
            return "Unauthorised response from the server"
        case .notConnectedToInternet:
            return "Not connected to Internet"
        case .serviceNotAvailable:
            return "Service is not available. Try later"
        case .somethingWentWrong(let errorMessage):
            return errorMessage
        }
    }
}

A: In my experience, '.materialize()' operator is the perfect solution for handling HTTP errors.
Instead of separate events for success and error you get one single wrapper event with either success or error nested in it.


Q: How to create a Server using ServerSocket to connect two or more client device via wifi Am trying to connect (using ServerSocket for server) to android device via wifi. But the problems seems to be the ip of the server. what ip can i use, or is there some other way round.
-Code Sample
//ServerSide
WifiManager wmanager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
String addr = String.valueOf(wmanager.getConnectionInfo().getIpAddress());
ServerSocket server = ServerSocket(3000, 3, InetAddress.getByName(addr));
Socket s = server.accept();

//ClientSide
//Howerver testing with terminal<telnet: open wifiIp 3000> returns connection error.


Q: Почему надо 2 раза писать va_arg Здравствуйте! Написал лабу по функции с переменным числом параметров. Первый параметр - размерность массива, второй - указатель на массив.
Но не могу понять, почему для того чтобы перейти к след. элементу необходимо два раза писать переход к следующему элементу?
a=va_arg(arg1,int);
a=va_arg(arg1,int);

и
n=va_arg(arg2,double*);
n=va_arg(arg2,double*);

В гугле везде примеры с 1 параметром -_-
А как сделать чтобы 2 раза не писать?(
#include <stdio.h>
#include <conio.h>
#include <stdarg.h>

float getsum(int a,double *n,...) { //
    int i;
    double s=0;
    va_list arg1;
    va_list arg2;
    va_start(arg1,a);
    va_start(arg2,n);

    printf("\nas = %d",a);
    printf("\nns = %lf\n",n[0]);

    while (1) {
        for(i=0;i<a;i++) s+=n[i];

        a=va_arg(arg1,int);
        a=va_arg(arg1,int);
        if(a==0) break;
        printf("\na1 = %d",a);
        n=va_arg(arg2,double*);
        n=va_arg(arg2,double*);
        printf("\nn1 = %lf\n",n[0]);
    }

    va_end(arg1);
    va_end(arg2);
    return s;
}

void main() {
    double d[2]={5.5,2.2};
    double f[4]={1.1,2.1,1.3,4.1};
    double g[1]={3.7};

    double s;
    s = getsum(2,d,4,f,1,g,0);
    printf("\nSumma vseh chisel massivov = %lf",s);
    getch();
}

Всё, разобрался! Внизу - "правильная" функция без повторов
float getsum(int a,double n,...) {
    int i;
    double s=0;
    va_list args;
    va_start(args,a);
    va_start(args,n);
    while (1) {
        for(i=0;i<a;i++)
            s+=n[i];
        a=va_arg(args,int);
        if(a==0)
            break;
        n=va_arg(args,double);
    }
    va_end(args);
    return s;
}

A: Потому что va_list arg1 в действительности представляет не один аргумент, а все. Поэтому корректнее переменную следует назвать args. Аргументы выбираются последовательно, как вы уже догадались.
A: Два раза va_start писать не надо, и va_arg надо писать один раз для каждого аргумента, которого нет в списке.
Например
void
targs (int n, char *s, ...)
{
  int  i = n;
  char *p = s;
  va_list args;
  va_start (args, s);

  while (1) {
    printf ("i = %d s = %s\n",i,p);
    if (!(i = va_arg(args,int)))
      break;
    p = va_arg(args, char *);
  }
  va_end(args);

}

main ()
{
  targs(1,"one",2,"two",3,"three",0);
}

Т.е. Вашу функцию можно написать так
double
getsum (int n, ...)
{
  va_list args;
  va_start (args, n);

  double s = 0.0, *arr;
  int    sz = n, i;

  while (sz)  {
    arr = va_arg(args, double *);
    for (i = 0; i < sz; i++) s += arr[i];
    sz = va_arg(args, int);
  }
  va_end(args);
  return s;
}

Один раз va_start и по одному разу va_arg для размера и адреса массива.


Q: gcc cross compilation for powerpc7448 I want to cross compile the gcc for powerpc7448, and after this I want to run one simple program and get the elf from the  cross compiled gcc for powerpc7448,I am using the linux OS,could anyone please suggest me the steps, cross compilation gcc for powerpc7448(any link) and what are all the components are required for cross compilation,Thanks in advance.

A: Try ELDK cross compiler toolchain (linux distributions) for PowerPC:
ftp://ftp.denx.de/pub/eldk/4.2/ppc-linux-x86/distribution/README.html
Check Eldk version 4.2.
Help: https://www.denx.de/wiki/ELDK-5/WebHome

ppc_74xx-gcc from eldk can be used to compile for your platform.
`
  $ ppc_74xx-gcc -c myfile.c

`


Q: Trouble understanding a specific C implementation of Merge Sort I'm trying to follow this code step by step but still I can't understand certain steps it's taking.
void merge (int *a, int n, int m) {
    int i, j, k;
    int *x = malloc(n * sizeof (int));
    for (i = 0, j = m, k = 0; k < n; k++) {
        x[k] = j == n      ? a[i++]
             : i == m      ? a[j++]
             : a[j] < a[i] ? a[j++]
             :               a[i++];
    }
    for (i = 0; i < n; i++) {
        a[i] = x[i];
    }
    free(x);
}

void merge_sort (int *a, int n) {
    if (n < 2)
        return;
    int m = n / 2;
    merge_sort(a, m);
    merge_sort(a + m, n - m);
    merge(a, n, m);
}

Here's a simple example so that you can see what the issues are. It's sorting the integer array {4,3,2,1} .
#include <stdio.h>
#include <stdlib.h>

void merge (int *a, int n, int m) {
    int i, j, k;
    int *x = malloc(n * sizeof (int));
    for (i = 0, j = m, k = 0; k < n; k++) {
        x[k] = j == n      ? a[i++]
             : i == m      ? a[j++]
             : a[j] < a[i] ? a[j++]
             :               a[i++];
    }
    for (i = 0; i < n; i++) {
        a[i] = x[i];
    }
    free(x);
}

void merge_sort (int *a, int n) {
    if (n < 2)
        return;
    int m = n / 2;
    int g;
    printf("a before merge_sort(a,m) %i\n",a);
    printf("m %i\n",m);
    printf("n %i\n",n);
    printf("\n");
    for(g=0;g<m;++g) printf("%i\n", a[g]);
    merge_sort(a, m);
    printf("a after merge_sort(a,m) %i\n",a);
    printf("m %i\n",m);
    printf("n %i\n",n);
    printf("\n");
    for(g=0;g<m;++g) printf("%i\n", a[g]);
    merge_sort(a + m, n - m);
    printf("a after merge_sort(a+m, n-m) %i\n",a);
    printf("m %i\n",m);
    printf("n %i\n",n);
    printf("\n");
    for(g=0;g<m;++g) printf("%i\n",a[g]);
    merge(a, n, m);
    printf("a after merge(a,n,m) %i\n ",a);
    printf("m %i\n",m);
    printf("n %i\n",n);
    for(g=0;g<m;++g) printf("%i\n",a[g]);
}

int main(){
    int test[4] = {4,3,2,1};
    int i;
    merge_sort(&test[0],4);
    printf("\nFinal result:\n");
    for(i=0;i<4;++i){
        printf("%i ",test[i]);
    }
    printf("\n");
}

And here's the output.
Begin of if
End of if(no return)

a before merge_sort(a,m) 0xbfadcebc
m 2
n 4

4
3

Begin of if
End of if(no return)

a before merge_sort(a,m) 0xbfadcebc
m 1
n 2

4

Begin of if

a after merge_sort(a,m) 0xbfadcebc
m 1
n 2

4

Begin of if

a after merge_sort(a+m, n-m) 0xbfadcebc
m 1
n 2

4

a after merge(a,n,m) 0xbfadcebc
 m 1
n 2

3

a after merge_sort(a,m) 0xbfadcebc
m 2
n 4

3
4

Begin of if
End of if(no return)

a before merge_sort(a,m) 0xbfadcec4
m 1
n 2

2

Begin of if

a after merge_sort(a,m) 0xbfadcec4
m 1
n 2

2

Begin of if

a after merge_sort(a+m, n-m) 0xbfadcec4
m 1
n 2

2

a after merge(a,n,m) 0xbfadcec4
 m 1
n 2

1

a after merge_sort(a+m, n-m) 0xbfadcebc
m 2
n 4

3
4

a after merge(a,n,m) 0xbfadcebc
 m 2
n 4

1
2

Final result:
1 2 3 4

This is what's puzzling me:
Begin of if

a after merge_sort(a+m, n-m) 0xbfadcebc
m 1
n 2

4

a after merge(a,n,m) 0xbfadcebc
 m 1
n 2

3

I'd expect a+m to change the address of a from 0xbfadcebc to something else, but it simply produces the number 4 as an output again. It's as if merge(a+m,n-m) didn't have any effect and produced the same as if I had written merge(a,n-m).
Furthermore, merge(a,n,m) is not a recursive function, so I'd just expect the function to end after running it.
I don't get how this:
a after merge_sort(a,m) 0xbfadcebc
m 2
n 4

3
4

...can be the next step after merge(a,n,m).

A: Commented code:
/* a = ptr to sub-array */
/* 0 = starting index */
/* m = mid point index */
/* n = ending index */
/* left  half indices = 0 to m-1 */
/* right half indices = m to n   */
void merge (int *a, int n, int m) {
    int i, j, k;
    int *x = malloc(n * sizeof (int)); /* allocate temp array */
    for (i = 0, j = m, k = 0; k < n; k++) {
        x[k] = j == n      ? a[i++]    /* if end of right, copy left */
             : i == m      ? a[j++]    /* if end of left, copy right */
             : a[j] < a[i] ? a[j++]    /* if right < left, copy right */
             :               a[i++];   /* else (left <= right), copy left */
    }
    for (i = 0; i < n; i++) {          /* copy x[] back into a[] */
        a[i] = x[i];
    }
    free(x);                           /* free temp array */
}

/* a = ptr to sub-array */
/* n = size == ending index of sub-array */
void merge_sort (int *a, int n) {
    if (n < 2)                         /* if < 2 elements nothing to do */
        return;
    int m = n / 2;                     /* m = mid point index */
    merge_sort(a, m);                  /* sort a[0] to a[m-1] */
    merge_sort(a + m, n - m);          /* sort a[m] to a[n-1] */
    merge(a, n, m);                    /* merge the two halves */
}


Q: Calling mulltiple methods of the same class In my class Helper() I have 2 methods which look like this:
public function is_active_page($page) {
    $url = explode("/",$_SERVER["REQUEST_URI"]);
    if (end($url) === $page) {
        return true;
    }
}

public function go_to_dashboard() {
    if (isset($_SESSION['login'])) {
        header('Location: http://example.com');
    }
}

I would now like to call them like this: $helper->is_active_page('page')->go_to_dashboard(); instead of using 2 lines for each method.
For some reason this is not working for me. Why?

A: In order to be able to chain methods, those methods need to return the original Helper instance. Try returning $this from inside the methods. Like RomanPerekhrest commented however, I dont think the methods you listed here are suitable for chaining. You would be better off with adding another method to your class that combines the two you stated here.
I'm not exactly sure what you are trying to do, but something along the lines of below might be what you are looking for:
public function redirect($page){
    if($this->is_active_page($page)){
        $this->go_to_dashboard();
    }
}

Lastly, you could think about reducing the scope of your is_active_page and go_to_dashboard functions, if they no longer need to be called from outside the Helper class.


Q: Import GeoJSON into PostGIS I want to import GeoJSON avaliable in the following dump into PostGIS but I am not able to import it. I already imported geousa data available in this public dump into MongoDB smoothly. Let me know is there a way to import this data directly or through MongoDB?
As this data is huge please check following data:
{"geometry": {"type": "Point", "coordinates": [19.056792, 47.490894]}, "type": "Feature",
"id": "SG_1iYphlxn9BSHyGrpv1aXKc_47.490894_19.056792@1308163237",
"properties": {"website": "http://mito.hu", "city": "Budapest",
"name": "Mito Europe", "tags": ["online", "communication", "design",
"branding", "development", "mito"], "country": "HU", "classifiers":
[{"category": "Professional", "type": "Services", "subcategory": "Advertising"}], "href":
"http://api.simplegeo.com/1.0/features/SG_1iYphlxn9BSHyGrpv1aXKc_47.490894_19.056792@1308163237.json",
"address": "N\u00e1dor u. 23.", "owner": "simplegeo", "postcode": "1051"}}

http://s3.amazonaws.com/simplegeo-public/places_dump_20110628.zip

A: ./ogr2ogr -f "PostgreSQL" PG:"dbname=theDatabaseName user=postgres" "/Users/dev/Downloads/theGeometry.json" -where "name not like 'Whatever%'" -nln theFeatureName -overwrite

ogr2ogr displays a list of drivers when the file is not found. in that case just pass in the full path to the json file

A: You can use PostGIS's ST_GeomFromGeoJSON to bring in just the geometry part of the GeoJSON.
Better yet, you can use ogr2ogr to import the entire JSON document:
ogr2ogr -f "PostgreSQL" PG:"dbname=my_database user=postgres" "source_data.json" -nln destination_table -append
(I haven't tested this with your data, add a comment if you have issues.)


Q: How can I get Symbolic-Name of an Osgi bundle which is using one of my exported packages? Inside one of my implementation libraries I want to know from which user library request is coming from?
Bundle A
 ClientCode -- > ServiceInterface
Bundle B
 ClientCode -- > ServiceInterface
Bundle C
 ServiceInterface
 ServiceImpl.
And those interfaces are resolved by one of impl. bundles (Bundle C). Inside that bundle I want to know from which bundle request is coming from (A or B)?
Thanks.

A: You could add a parameter for the BundleContext to your interface methods.  Then, when the client code calls into your service, passing in its bundle context, you can call context.getBundle().getSymbolicName() or other methods to get information about the bundle from which the call came.

A: The correct way to do this is to use a ServiceFactory, as explained in the OSGi specification. If you register your service as a service factory, you can supply an implementation for each "client" (where "client" is defined as bundle, invoking your service). This allows you to know who is invoking you, without the client having to specify anything as it's clearly not good design to add a parameter called BundleContext (unless there is no other way).
Some "pseudo" code:
class Bundle_C_Activator implements BundleActivator {
  public void start(BundleContext c) {
    c.registerService(ServiceInterface.class.getName(),
      new ServiceFactory() {
        Object getService(Bundle b, ServiceRegistration r) {
          return new ServiceImpl(b); // <- here you hold on to the invoking bundle
        }
        public void ungetService(Bundle b, ServiceRegistration r, Object s) {}
      }, null);
  }
}

class ServiceImpl implements ServiceInterface {
  ServiceImpl(Bundle b) {
    this.b = b; // <- so we know who is invoking us later
  }
  // proceed here with the implementation...
}


Q: How to restrict input values and save it separately jQuery? I am a jquery beginner working on a input as shown in the picture where the user has to follow proper syntax like "name=value". I want to make validations if the entered data is in the correct format or if there any white spaces on the right or left side of "=". For that, I can use trim(). The part I am struggling with is how to break the user input into 3 parts "name", "=" and "value" because later on, I want to sort the list by name and by value. Please, someone, point me in the right direction.
Image Link
My code
$("#add-pair").on("submit", function(e) {
e.preventDefault();
const addItem = $('#add-pair > input[type="text"]').val();
if (!addItem || addItem === null) {
  $("#add-pair").append(
    '
Cannot post empty string. Please add Name=Value!
'
  );
  setTimeout(function() {
    $(".error").fadeOut();
  }, 4000);
} else {
  $li = $("
");
  $textSpan = $("")
    .addClass("name")
    .text(addItem);
  $deleteSpan = $("")
    .addClass("btn delete")
    .text("Delete");
  $listItem = $li.append($textSpan).append($deleteSpan);
  $("#list")
    .hide()
    .prepend($listItem)
    .fadeIn(500);
}

});
<form id="add-pair">
                <input type="text" name="addPair" id="input" placeholder="Name=Value..." />
                <button class="btn">Add</button>
            </form>

A: Try using split to split along the string before the = and after the =:
const inputStr1 = ' name   = value  ';
const inputStr2 = ' name   value  ';
function validate(str) {
  if (!str.includes('=')) {
    console.log('no = found, returning');
    return;
  }
  const [cleanedName, cleanedValue] = str.split('=').map(uncleanStr => uncleanStr.trim());
  console.log('returning values "' + cleanedName + '" "' + cleanedValue + '"');
  return [cleanedName, cleanedValue];
}

const results1 = validate(inputStr1);
const results2 = validate(inputStr2);


Q: How do I get the values of the params from a form I need to work with the inputs from a form before storing the records. I'm stuck at simply reading the params.
In my create controller, I have
def create
   @document_history = DocumentHistory.new(document_history_params)
   $temp1 = params[:by]
   $temp2 = params[:sent_to]

In my show, I have

<%= $temp1 %>

<%= $temp2 %>

On the show, $temp1 and $temp2 are blank. How can I read the params and store the value to a variable?

A: I am assuming that your fields are named in the standard rails way.That is,If your input fields are named like this document_history[name] then the correct way to access them would be params[:document_history][:name].
To verify if they have been copied to your variable you can print to log.


Q: Implement Linked list where data is separate In C, can a Linked list be implemented and modified so that rather having the data stored within each node of the list, it is separated from the node. And a pointer within the node points to the data?

A: The answer is yes. Just instead of keeping keys in the nodes, you store pointers to keys:
#include <stdio.h>
#include <stdlib.h>

typedef struct s_ListNode {
  struct s_ListNode *next;
  int *pointer;
} ListNode;

main() {
  int a = 3, b = 5;
  ListNode *root = malloc(sizeof(ListNode));
  ListNode *tail = malloc(sizeof(ListNode));
  ListNode *iter;
  root->next = tail;
  root->pointer = &a;
  tail->next = NULL;
  tail->pointer = &b;
  for(iter=root; iter!=NULL; iter=iter->next) {
    printf("%d\n", *iter->pointer);
  }
  return 0;
}

A: A. Yes, it is possible.
B. Why doing it ? the node is already a pointer by itself.


Q: jQuery post to the same PHP page I am creating a jQuery search bar, that will asynchronously send the inputted value from a form from the client side to the same page on the server side (in PHP). Then I can search my database with the value. Unfortunately when I send this value, using $.ajax, and attempt to echo out the value, I don't get the value at all. How can I receive my value? I've tried print_r, var_dump, echo but to no avail.
Here is my form:

<form method = 'POST'>
  <input id="myInput" type ="text"  name ="value"
  placeholder="press enter when finished" >
</form>

And here is my script to make the call. I get the value in my console when I press enter (key===13), but it seems to be the furthest my variable (value) seems to go.

$(document).ready(function(){
    $('#myInput').bind('keypress', function(e){
        if(e.keyCode ===13){
        let value = $(this).val().toLowerCase();
        console.log(value);

        e.preventDefault();  //stops the damn page refreshing

         $.ajax({
            type: "POST",
            data: value

        });

        };
    });
});

I haven't put the URL in the AJAX call for a reason: I'm sending to the same page.
Here is the code (further up the page) that I'm using to echo out the posted value, on the same page.
if(isset($_POST['value'])) { echo $_POST['value']; exit;  }

No matter what I seem to do, my value isn't sent to the page! I've tried to add in the URL, I've added "success" to the call.... nothing seems to work.
How can I successfully send my data?


Q: ¿Cómo definir Collation que ignore acentos en SQLite usando Entity Framework en .NET 5 (C#)? Estoy trabajando con una base de datos SQLite en una aplicación Windows Forms programada en c# y usando .NET 5. Para realizar consultas, modificar, etc. sobre la base de datos hago uso de Entity Framework Core. Me gustaría que, al realizar comparaciones con los datos de la base de datos utilizando Linq, me ignore los acentos. He estado mirando en internet y, por lo que he visto, tengo que definir un Collation que me ignore los acentos, pero exactamente en SQLite no se como hacerlo. Al construir el contexto de mi base de datos en el método OnModelCreating he añadido la sentencia modelBuilder.UseCollation("NOACCENTS");, pero me sigue sin funcionar. Me ha quedado algo así.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
        modelBuilder.UseCollation("NOACCENTS");
        // A partir de aquí  está la definición de las tablas y campos de mi BBDD
}

Sin embargo, no me funciona, ¿qué puedo hacer para ello?

A: Te propongo hacerlo de esta manera personalizada:
Primero creas una clase estática que tendrá el o los métodos encargados de estandarizar las palabras:
public static class Fonetica
{
   public static string EliminarTildes(string texto)
    {
        return texto.Replace('á', 'a').Replace('é', 'e').Replace('í', 'i').
                     Replace('ó', 'o').Replace('ú', 'u');
    }
}

Esta clase tiene un método encargado de sustituir las tildes por vocales sin tilde utilizando la función Replace.
Y a la hora de buscar con Linq harías una consulta de esta forma:
texto = Fonetica.EliminarTildes(texto.ToLower());

var lista = from a in db.Entidad.ToList()
            where Fonetica.EliminarTildes(a.Campo.ToLower()).Contains(texto)
            select a).ToList();

En esta consulta Linq estandarizamos tanto la palabra a buscar como los registros que tiene la tabla, es decir eliminamos las tildes en ambos lados, para asegurarnos de que haya una mayor coincidencia en la búsqueda.
Esto tiene como ventaja que puedes hacer métodos de búsqueda aún más complejos, por ejemplo, en la clase Fonetica podrías tener un método como este:
public static string SustitucionSimple(string palabra)
    {
        return (palabra.Replace('ñ', 'n').Replace('á', 'a').Replace('é', 'e').Replace('í', 'i').
                        Replace('ó', 'o').Replace('ú', 'u').Replace('ü', 'u').
                        Replace("aa", "a").Replace("ee", "e").
                        Replace("ii", "i").Replace("oo", "o").Replace("uu", "u").Replace("ge, je").Replace("ce", "se").
                        Replace(" ", "")).Trim();
    }

Este método sustituye vocablos teniendo en cuenta como suenan, por ejemplo ahora podrías buscar "Gerardo" o "Jerardo", "Cepillo" o "Sepillo", esto estandariza aún más la búsqueda y ofrece mejores coincidencias en la búsqueda, y es bueno ya que la persona puede tener faltas de ortografía y escribir mal las palabras, esto es algo así como un buscador fonético el cual puedes complejizar tanto como desees.
Para usar Linq debes poner en los usings:
using System.Linq;