Q: Why does a Rust macro re-exported from another crate work unless there's a dependency conflict I'm writing a Rust crate for internal company use that wraps the excellent Tokio tracing crate, with a bit of additional functionality.  Not only do I re-export the macros in tracing, but I also add a few of my own that internally invoke the tracing macros.  My goal is to enable all of our other internal crates to depend only on my wrapper crate, without having to pull in tracing dependencies explicitly in each crate.
This works really well, until I ran into an issue today that took me a few hours to isolate.  I've made a minimal example to show the behavior here.
In this example, I have a workspace with two crates: my-logger-crate which wraps tracing and exposes a macro print_trace!, and a binary crate my-binary-crate which has a dependency on my-logger-crate, and invokes the macro inside the main function.
The Cargo.toml for my-logger-crate is very simple; the only thing I added to the auto-generated skeleton is a tracing dependency:
[package]
name = "my-logger-crate"
version = "0.1.0"
authors = ["Adam Nelson <anelson@users.noreply.github.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
tracing = "0.1.12"

This is the my-logger-crate macro:
/// Re-export everything in the `tracing` crate
pub use ::tracing::*;

/// A version of the `trace!` macro that sets a special target
#[macro_export]
macro_rules! print_trace {
    ($($arg:tt)*) => (
        // Invoke the `trace!` macro which is defined in the `tracing` crate but which has been
        // re-exported from this crate, so that downstream callers don't have to take an explicit
        // dependency on `tracing`
        $crate::trace!(target: "console", $($arg)*)
    )
}

This is used by my-binary-crate, whose Cargo.toml is also simple:
[package]
name = "my-binary-crate"
version = "0.1.0"
authors = ["Adam Nelson <anelson@users.noreply.github.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
my-logger-crate = { path = "../my-logger-crate" }

# If the following line is uncommented, then the call to `print_trace!` in `main()` fails to compile.
# tower = "0.3"

And here's the main() function in my-binary-crate:
fn main() {
    println!("Hello, world!");

    // Log a trace event with the logging system
    my_logger_crate::print_trace!("this is a trace message from print_trace!");
}

If my-binary-crate doesn't have any conflicting dependencies, this compiles and runs fine.
But take a look at what happens if we have a dependency on tower in the my-binary-crate/Cargo.toml file:
[package]
name = "my-binary-crate"
version = "0.1.0"
authors = ["Adam Nelson <anelson@users.noreply.github.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
my-logger-crate = { path = "../my-logger-crate" }

# If the following line is uncommented, then the call to `print_trace!` in `main()` fails to compile.
tower = "0.3"

Here's what happens:
Compiling my-binary-crate v0.1.0 (/home/cornelius/scrap/e2780c4bd3dfa24758fcfd93e225b100/my-binary-crate)
error[E0433]: failed to resolve: use of undeclared type or module `tracing`
 --> my-binary-crate/src/main.rs:5:5
  |
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ use of undeclared type or module `tracing`
  |
  = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

The print_trace! macro is expanding out to the tracing::trace! macro, which then expands to tracing::event!, and then expands to the code to log an event, which includes calls to tracing::....  All of this works fine before I add that tower dependency, so clearly the compiler is able to resolve tracing::... properly, even though my-binary-crate doesn't have a direct dependency on tracing itself.
I suspect this is related to a dependency conflict.  tower pulls in a long dependency tree, including tower-buffer, which itself has a dependency on tracing = "0.1.2".
My understanding of how Cargo resolves this seeming conflict is that it would use tracing version 0.1.12, since my logging crate explicitly depends on version =0.1.12, and tower-buffer specifies 0.1.2, which is equivalent to ^0.1.2.  But I don't understand why adding this additional dependency tree breaks the use of my macro.
For the moment I've worked around it by adding explicit dependencies on tracing in all of the downstream crates that use my logging crate, but that's far from ideal.
I ran with macro tracing enabled:
$ RUSTFLAGS="-Z macro-backtrace" cargo +nightly test
   Compiling my-binary-crate v0.1.0 (/home/cornelius/scrap/e2780c4bd3dfa24758fcfd93e225b100/my-binary-crate)
error[E0433]: failed to resolve: use of undeclared type or module `tracing`
   --> <::tracing::macros::__mk_format_args macros>:78:17
    |
1   |    /  (@ { $ (,) * $ ($ out : expr), * $ (,) * }, $ fmt : expr, fields : $ (,) *) =>
2   |    |  { format_args ! ($ fmt, $ ($ out), *) } ;
3   |    |  (@ { $ (,) * $ ($ out : expr), * }, $ fmt : expr, fields : $ ($ k : ident) . +
4   |    |   = ? $ val : expr $ (,) *) =>
...      |
78  |    |          (@ { }, tracing :: __mk_format_string ! ($ ($ kv) *), fields : $
    |    |                  ^^^^^^^ use of undeclared type or module `tracing`
79  |    |           ($ kv) *)
80  |    |      }
81  |    |  } ;
... [a lot of macro expansions snipped]

Not surprisingly, the error is an attempt to call tracing::__mk_format_string!, which fails because there is no such crate tracing referenced by my-binary-crate.  The strange thing is that in order to get to this error, several other macros in tracing had to be evaluated.  Perhaps this is a bug in tracing, and it should be $crate::__mk_format_string!.  However I still don't understand why this works until I add a tower dependency on my-binary-crate.


Q: Why does C++ has an additional class name declaration? why do we have to declarer a class name in C++ like:
class MDT_DECL Transfer{
    // declaration goes here
};

? What's the reason for the <DIRNAME>_DECL? I see it's especially used when the code needs to be compiled in Windows

A: You don't have to. But in windows you have to explicitly state you want the class to export symbols with _declspec(dllexport) (which is probably what that macro expands to).


Q: Python Reading JSON as Binary I need to parse a file with JSONs in it. File format is txt and content is like below:
{"key_1":"value_1", ....., "key_n":"value_n"}
{"key_1":"value_1", ....., "key_n":"value_n"}
......

There is no association between JSONs they are just in the file consecutively. They also includes non-utf characters, so it is impossible to parse them with using json library. I tried to read them line by line in byte format. Then a line that read as like below:
b'{"key_1":"value_1", ....., "key_n":"value_n"}'

I'm stuck to that step. I read a line corresponds to a JSON but it includes non-utf characters and its format is byte. How can I convert it to a dictionary?


Q: Why ZipEntry fails to work in Jelly Bean I have a ZIP file of 140 MB containing about 40 thousand MP3 files. I use the following code to play a certain file inside the ZIP file without decompressing it:
String fullPath = Environment.getExternalStorageDirectory().getPath() + "_audio_.mp3";
String path = Environment.getExternalStorageDirectory().getPath() + "mySoundFolder";

try {
ZipFile zip = new ZipFile(path + "myFile.zip");
Enumeration zipEntries = zip.entries();
ZipEntry entry = zip.getEntry("myFile" + "/" + currentWord + ".mp3");

if (entry != null) {
    Log.i(MAIN_TAG, "entry found: " + entry.getName());
    InputStream in = zip.getInputStream(entry);

        File f = new File(fullPath);
        FileOutputStream out = new FileOutputStream(f);
        IOUtils.copy(in, out);
        byte buffer[] = new byte[4096];
        int read;
        while ((read = in.read(buffer)) != -1)
        {
        out.write(buffer, 0, read);
        }
            if (f.exists())
                {
                    Log.i(MAIN_TAG,"Audio file found!");
                    final MediaPlayer mp = new MediaPlayer();
                    mp.setDataSource(fullPath);
                    mp.prepare();
                    mp.setOnBufferingUpdateListener(null);
                    mp.setLooping(false);
                    mp.setOnPreparedListener(new OnPreparedListener()
                    { public void onPrepared(MediaPlayer arg0)
                        {
                            mp.start();
                        Log.i(MAIN_TAG,"Pronunciation finished!");
                        }});

                        }
                    else
                    {
                        Log.i(MAIN_TAG,"File doesn't exist!!");
                    }
                }
                else {
                    // no such entry in the zip
                    Log.i(MAIN_TAG, "no such entry in the zip");
                 }
            }
            catch (IOException e) {

                e.printStackTrace();
             Log.i(MAIN_TAG,"IOException reading zip file");
            }
        }

There are two strange things with this code:

*

*It works flawlessly in Android 2.2 but fails in Android 4.0.3. In 2.2, it finds and plays the MP3 file as I expect, but in 4.0.3, it keeps saying it cannot find the entry in the ZIP file ("no such entry in the zip").

*If I reduce the number of MP3 files down to about 100 files, then in Android 4.0.3, it finds and plays the selected MP3 files as it should do.

Can you guys please help me to figure out what the problem is?
Thanks a lot in advance.

A: In the end, I have a workaround for this problem. I split my zip file into two files, with each containing about 20k entries. Voila, it works like a charm again.
I've heard of Java's problem with reading entries in zip files of more than 64k entries. What I have no idea why is my file has only about 40k entries but it faces the problem as well.


Q: How to make jQuery UI Draggable/Droppable work properly in this case I have a floating toolbar with tools buttons in it. The toolbar itself is draggable using its header with title "Basic tools". Below the toolbar there is a workspace filling the whole page. Buttons on the toolbar are draggable too and droppable to the workspace. When I drag/drop a button to the workspace, it turns into a rectangle widget with some content in it.
My issue is that I want an icon to be dropped only when it's over the gridded workspace, not over the toolbar. I have added console.log to track Draggable/Droppable events and it seems that the workspace emits drop event event if I drop the element on the toolbar. I suppose it's because the workspace is below the toolbar. So, when it's being dropped on the toolbar, it should revert back to its initial position in the toolbar.

A: You have to determine where the tool is dropped: How do I get the coordinate position after using jQuery drag and drop?
You also have to determine where your toolbox is placed: http://api.jquery.com/position/
Then you have to determine the width and height of your toolbox: http://api.jquery.com/width/
After that calculate the rectangle of your toolbox and check if the tool is placed there. If it is placed there then deny dropping, if not allow dropping.


Q: Why my csv file doesn't pass the internal CSVHelper test? i'm trying to use CSVHelper inside my project. I created that files:

*

*JobApplicationMap.cs

*JobApplicationModel.cs

*ICsvParserService.cs

*CsvParserService.cs

*JobApplicationCSV.cs

*Constants.cs
But after executing the JobApplicationCSV.WriteCSV method i'm getting a CSVHelper Exception:

System.Exception
HResult=0x80131500
Nachricht = Header with name 'Company' was not found. If you are expecting some headers to be missing and want to ignore this validation, set the configuration HeaderValidated to null. You can also change the functionality to do something else, like logging the issue.
Quelle = latex_curriculum_vitae
Stapelüberwachung:
at latex_curriculum_vitae.Services.CsvParserService.ReadCsvFileToJobApplicationModel(String path) in C:\Users\Sasch\source\repos\Visual Studio\latex_curriculum_vitae-dotnet\latex_curriculum_vitae\Services\CsvParserService.cs:line 51
at latex_curriculum_vitae.JobApplicationCSV.WriteCSV(String company, String jobtitle, String city, String joburl) in C:\Users\Sasch\source\repos\Visual Studio\latex_curriculum_vitae-dotnet\latex_curriculum_vitae\JobApplicationCSV.cs:line 17
at latex_curriculum_vitae.MainWindow.BtnGenerate_Click(Object sender, EventArgs e) in C:\Users\Sasch\source\repos\Visual Studio\latex_curriculum_vitae-dotnet\latex_curriculum_vitae\MainWindow.xaml.cs:line 106

I pre created a CSV file in path, with the header:

Company,Jobtitle,City,Status,EmailSent,JobOfferUrl

So i actually don't know why it don't passes the test. Maybe i have missed anything?

A: The version of CsvHelper you are using uses CurrentCulture to get the delimiter.  It appears your are in Germany, so your delimiter would be ";" instead of ",".  The current version of CsvHelper forces you to pass in a CultureInfo object to CsvReader and CsvWriter with the suggestion of CultureInfo.InvariantCulture to try and mediate this issue.
In your CsvParserService try adding the following to both the ReadCsvFileToJobApplicationModel() and WriteNewCsvFile() methods.
csv.Configuration.Delimiter = ",";


Q: How to ignore mv error? I'm making a Makefile that moves an output file (foo.o) to a different directory (baz).
The output file moves as desired to the directory. However since make won't recompile the output file if I type make again, mv gets an error when it tries to move the non-existent empty file to the directory baz.
So this is what I have defined in my rule make all after all compilation:
-test -e "foo.o" || mv -f foo.o ../baz

Unfortunately, I'm still getting errors.

A: I notice nobody has actually answered the original question itself yet, specifically how to ignore errors (all the answers are currently concerned with only calling the command if it won't cause an error).
To actually ignore errors, you can simply do:
mv -f foo.o ../baz 2>/dev/null; true

This will redirect stderr output to null, and follow the command with true (which always returns 0, causing make to believe the command succeeded regardless of what actually happened), allowing program flow to continue.

A:    -test -e "foo.o" || if [ -f foo.o ]; then mv -f foo.o ../baz; fi;

That should work

A: Errors in Recipes (from TFM)

To ignore errors in a recipe line, write a - at the beginning of the
  line's text (after the initial tab).

So the target would be something like:
moveit:
    -mv foo.o ../baz

A: +@[ -d $(dir $@) ] || mkdir -p $(dir $@)

is what I use to silently create a folder if it does not exist.  For your problem something like this should work
-@[ -e "foo.o" ] && mv -f foo.o ../baz

A: Something like
test -e "foo.o" && mv -f foo.o ../baz

should work: the operator should be && instead of ||.
You can experiment with this by trying these commands:
test -e testfile && echo "going to move the file"
test -e testfile || echo "going to move the file"

A: I faced the same problem and as I am generating files, they always have different time. Workaround is set the same time to the files: touch -d '1 June 2018 11:02' file. In that case, gzip generates the same output and same md5sum. In my scenario, I don't need the time for the files.


Q: Add data two tables Sequelize Here its my problem.
I create a Api rest in nodejs where i manage my database. I have 3 tables: bets, users and users-bets (this one link bets with users).
Well my problem is when im using Sequelize to do this. In my webpage, its an Angular2 app, i want to create a new bet so when i fill the formulary i send all the data to the server by post method. The problem start here because i want to add in the bets table (thats not the problem) and add the reference in bets-users.
Example:
User A create a new bet, so when he click on create, he send a post method with the bet data that contains Title, cost and earnings. In the server side, the query runs fine but what i want it is that when i insert the bet in the bet table, i want to add the id_bet and the id_user in bet-users because i want to link the user that adds the bet with the bet that he create.
I dont know if im explaining good.
Here its my code:
This is the bets model.
module.exports = (sequelize, Sequelize) => {
  const Bet = sequelize.define('apuestas', {
    id: {
      type: Sequelize.INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    titulo: {
      type: Sequelize.STRING
    },
     coste: Sequelize.INTEGER,
     beneficio: Sequelize.INTEGER
  }, {
    updatedAt: false,
    classMethods: {
      associate: (models) => {
      Bet.belongsTo(models['usuarios_apuestas'], {
          foreignKey: 'id',
           targetKey: 'id_apuesta'
       });
      }
    },
    freezeTableName: true
  });

  return Bet;
};

I have a controller:
createBet(req, res) {
        return this.service.create(this.mapper.inputUpdate(req.body))
        .then(this.mapper.outputGet.bind(this.mapper, req.body))
        .then(res.json.bind(res)).catch(res.send.bind(res));
      }

This is the mapper:
inputUpdate(inputBet) {
    return  {
      titulo: inputBet.titulo,
      coste: inputBet.coste,
      beneficio: inputBet.beneficio
    };
  }

And the service:
create(model) {
    return this.db.create(model);
  }

All this methods are separate in different files.
In summary, what i want its that when i add a new bet i want to add in the bet-users the relation between users and bets saving his id.
The bets-user table have 3 columns: id, id_bet, id_user.
Now i can find all bets in that an user participate using his id_user.
I dont know if i need to explain more my problem or if you dont understand it.
titulo = title
coste = cost
beneficio = earnings


Q: How can I see if any values in one data frame exist in any other data frame? I have eight data frames, all of which contain an id field and I want to know if any of the id values are common among all eight data frames.
I'm not looking for an intersection (where the values are common across all data frames); I simply want to know those instances where they appear in any of the other data frames.
Let's say that one of the data frames looks like this:
   id TestDay
1  66       m
2  90       t
3  71       w
4  59      th
5  38       f
6  84      sa
7  15      su
8  89       m
9  18       t
10 93       w
11 88      th
12 42       f
13 10      sa
14 33      su
15 49       m
16 51       t
17 80       w
18 32      th
19  1       f
20 91      sa
21 58      su

If you wish to create eight sample data frames, you can do so by using this code eight times (with different data frame names, naturally):
x <- data.frame(id = sample(1:100, 21, FALSE), TestDay = rep(c("m","t","w","th","f","sa","su"), 3))

I want to know if any of the id values listed here appear in any of the other seven data frames, and conversely, whether any of the id values listed in any of the other seven data frames exist in this one.
How can this be done?

A: Combine all the dataframes in one dataframe with a unique id value which will distinguish each dataframe.
I created two dataframes here with data column representing the dataframe number.
library(dplyr)

x1 <- data.frame(id = round(runif(21, 1, 21)), TestDay = rep(c("m","t","w","th","f","sa","su"), 3))
x2 <- data.frame(id = round(runif(21, 1, 21)), TestDay = rep(c("m","t","w","th","f","sa","su"), 3))
combine_data <- bind_rows(x1, x2, .id = 'data')

group by the id column and count how many dataframes that id is present in.
combine_data %>%
  group_by(id) %>%
  summarise(count_unique = n_distinct(data))

You can add filter(count_unique > 1) to the above chain to get id's which are present in more than 1 dataframe.

A: To add to @Ronak 's answer, you can also concatenate c() the dataframe number using summarise(). This tells you which dataframe the ID comes from.
df1 <- data.frame(id = letters[1:3])
df2 <- data.frame(id = letters[4:6])
df3 <- data.frame(id = letters[5:10])

library(tidyverse)
df <- list(df1, df2, df3)

df4 <- df %>%
  bind_rows(.id = "df_num") %>%
  mutate(df_num = as.integer(df_num)) %>%
  group_by(id) %>%
  summarise(
    df_found = list(c(df_num)),
    df_n = map_int(df_found, length)
  )

df4

A: We can use data.table methods

*

*Get the datasets in a list and rbind them with rbindlist

*Grouped by 'id' get the count of unique 'data' with uniqueN
library(data.table)
rbindlist(list(x1, x2, idcol = 'data')[, .(count_unique = uniqueN(data)), by = id]


Q: storing user data in firebase with unique identifiers I have a publicly accessible app. No sign in is required but I need a way to store user data in the database as an object associated with a unique key.
From what I understand, tokens would be a way to get a unique identifier from firebase(??)
I tried creating an anonymous user and getting a token like this:
let user = firebase.auth().signInAnonymously();
user.getIdToken(true);

I expected getIdToken to return a string but I get an object.
So...
1) Are tokens what I want to do this?
2) If so how can I get a new token as a string?

A: Use the following code as a global listener on ur page to check if the sign-in is successful:
firebase.auth().onAuthStateChanged(function(user) {
   if (user) {
       // User is signed in.
       var isAnonymous = user.isAnonymous;
       var unique_id = user.uid;

   } else {
       // User is signed out.
       // ...
   }
});

This snippet has been taken from the Firebase Anonymous Auth link: Click Here to open link.

A: For some reason I was trying to set up a binding to sync my app with Firebase, which I just realized I don't need at all! (I just need to push the data at the end of the poll).
Of course as soon as removed that requirement it was as simple as:
firebase.database().ref().push().set(myData);

When using the push() method, Firebase automatically generates a unique key which is all I need...


Q: Programmatically selecting radios in jQuery buttonset makes it break down I'm building an editor function on a website using a jQuery buttonset based on radio buttons. When I load the item into the editor I need to set the selected radio button and then, of course, the user can change the option and it get's saved into the database. When the item closes I want to reset the buttonset to default.
Problem is that when I set the buttonset it works the first time I select each item then it breaks down and stops working all together.
Demo of problem: http://jsfiddle.net/kallsbo/vSmjb/
HTML:

    <input type="radio" name="security" id="r_public" value="public" class="rSec">
     Public
    <input type="radio" name="security" id="r_private" value="private" class="rSec">
     Private
    <input type="radio" name="security" id="r_link" value="link" class="rSec">
     Anyone with the link

    If you use the buttons below you can programmatically select each of the radios in the buttonset once before it all breaks down...

     <button id="nbr1">Select Private</button>

     <button id="nbr2">Select Link</button>

     <button id="nbr3">Select Public</button>

JavaScript:
// Basic function
$("#dumpSec").buttonset();
$("#r_public").attr("checked", true);
$("#dumpSec").buttonset('refresh');

// Put in functions on the demo buttons
$( "#nbr1" )
  .button()
  .click(function( event ) {
    $("#r_private").attr("checked", true);
    $("#dumpSec").buttonset('refresh');
  });

$( "#nbr2" )
  .button()
  .click(function( event ) {
    $("#r_link").attr("checked", true);
    $("#dumpSec").buttonset('refresh');
  });

$( "#nbr3" )
  .button()
  .click(function( event ) {
    $("#r_public").attr("checked", true);
    $("#dumpSec").buttonset('refresh');
  });

I have tried a number of things like trying to trigger the click function of the label for each radio button and so on but I can't find anything that works. Any input is appreciated!

A: http://jsfiddle.net/vSmjb/2/
you can trigger click(), to make it work
  $("#r_private").click()

A: You need to use .prop() instead of .attr() to set the checked status
$("#r_link").prop("checked", true);

Demo: Fiddle
Read: Attributes vs Properties


Q: Crash with iOS 8 SceneKit Assets when building over command line I am building a 3D game over command line with. My script works for all other applications without a problem. Unfortunately the built IPA of the game crashes when I start it on my iPhone. If I build it with the Xcode GUI, it works fine. This error only appears for Xcode projects with SceneKit Assets.
Any idea how I can prevent this error?

A: Seems like Xcode forgets to generate the scnassets when building on command line (xcodebuild). we fixed it with the following build rule:

Script:
${DEVELOPER_TOOLS_DIR}/../usr/bin/copySceneKitAssets "${INPUT_FILE_PATH}" -o "${DERIVED_FILE_DIR}/${INPUT_FILE_NAME}”
Output Files:
$(DERIVED_FILE_DIR)/${INPUT_FILE_NAME}


Q: Is it possible to get the optional parameter values from a constructor using reflection? Given a class like this:
public abstract class SomeClass
  {
      private string _name;
      private int _someInt;
      private int _anotherInt;

      public SomeClass(string name, int someInt = 10, int anotherInt = 20)
      {
          _name = name;
          _someInt = someInt;
          _anotherInt = anotherInt;
      }
  }

Is it possible using reflection to get the optional parameter's default values?

A: Lets take a basic program:
class Program
{
    static void Main(string[] args)
    {
        Foo();
    }
    public static void Foo(int i = 5)
    {
        Console.WriteLine("hi"   +i);
    }
}

And look at some IL Code.
For Foo:
.method public hidebysig static void  Foo([opt] int32 i) cil managed
{
  .param [1] = int32(0x00000005)
  // Code size       24 (0x18)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  ldstr      "hi"
  IL_0006:  ldarg.0
  IL_0007:  box        [mscorlib]System.Int32
  IL_000c:  call       string [mscorlib]System.String::Concat(object,
                                                              object)
  IL_0011:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0016:  nop
  IL_0017:  ret
} // end of method Program::Foo

For Main:
.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       9 (0x9)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  ldc.i4.5
  IL_0002:  call       void ConsoleApplication3.Program::Foo(int32)
  IL_0007:  nop
  IL_0008:  ret
} // end of method Program::Main

Notice that main has 5 hardcoded as part of the call, and in Foo. The calling method is actually hardcoding the value that is optional! The value is at both the call-site and callee site.
You will be able to get at the optional value by using the form:
typeof(SomeClass).GetConstructor(new []{typeof(string),typeof(int),typeof(int)})
                .GetParameters()[1].RawDefaultValue
On MSDN for DefaultValue (mentioned in the other answer):
This property is used only in the execution context. In the reflection-only context, use the RawDefaultValue property instead. MSDN
And finally a POC:
static void Main(string[] args)
{
   var optionalParameterInformation = typeof(SomeClass).GetConstructor(new[] { typeof(string), typeof(int), typeof(int) })
   .GetParameters().Select(p => new {p.Name,  OptionalValue = p.RawDefaultValue});

   foreach (var p in optionalParameterInformation)
      Console.WriteLine(p.Name+":"+p.OptionalValue);

   Console.ReadKey();
}

http://bartdesmet.net/blogs/bart/archive/2008/10/31/c-4-0-feature-focus-part-1-optional-parameters.aspx

A: DefaultValue of the ParameterInfo class is what you are looking for:
var defaultValues = typeof(SomeClass).GetConstructors()[0].GetParameters().Select(t => t.DefaultValue).ToList();


Q: How do I find a .NET remoting memory leak on select machines? The memory leak is not happening on every machine, but reliably on a couple at my work, and it's looking like close to 10% in the field.
I have a product that uses a Windows service to monitor user input to launch alerts, paired with a visual application that serves only to sit in the system tray, and allow the user to make configuration changes.
I chose to use a remoted object to share the configuration information between the two processes.  In the service it is called serviceConfig, and in the visual application it is called configData.  The object is created on the server first, and then remoted as follows:
try
{
    InitializeComponent();
    setAppInitDLL(thisDirectory);
    serviceConfig = new serviceConfigData();
    Regex getVersion = new Regex("Version=(?<ver>[^,]*)");
    if (getVersion.IsMatch(Assembly.GetExecutingAssembly().FullName))
    {
        serviceConfig.Version = new Version(getVersion.Match(Assembly.GetExecutingAssembly().FullName).Result("${ver}").ToString());
    }
    // Create the server channel for remoting serviceConfig.
    serverChannel = new TcpServerChannel(9090);
    ChannelServices.RegisterChannel(serverChannel, false);
    RemotingServices.Marshal(this.serviceConfig, "ServiceConfigData");
    baseLease = (ILease)RemotingServices.GetLifetimeService(serviceConfig);
    lock (Logger) { Logger.Write(String.Format("The name of the channel is {0}", serverChannel.ChannelName)); }

    lock (Logger) { Logger.Write("Exiting Constructor"); }
}
catch (Exception ex)
{
    lock (Logger) { Logger.Write(String.Format("Error in Constructor:{0}", ex.Message)); }
}

Then in the visual application I have a private object that I connect using:
configData = (serviceConfigData)Activator.GetObject(typeof(serviceConfigData), "tcp://localhost:9090/ServiceConfigData");

When reading or writing to this object, I have catch statements for Socket Exceptions and Remoting Exceptions which then call this same statement.
On most machines this works without leaking memory, but on some it leaks very quickly.  All machines at work have .NET 3.5, some are XP, a couple are Vista.  The problem has only been seen on XP machines, and the machines in the field are all XP.
Any ideas where I should be looking, and as a secondary question, should I be using something completely different from this?

A: My first thought would be to profile the application on the machines you're seeing the leak with something like Red Gate's Memory Profiler.
It'll be a lot more reliable than attempting to guess what the leak might be.
As for chosing the right technology, if all your machines will have .NET 3.5 installed you might want to consider migrating to WCF (primarily Named Pipes) for your inter-process communication. Check this SO post for more detail...


Q: JQuery - Clear Textboxes I have a drop down list and two textboxes on an ASP.Net MVC 3 view. The drop down lists numbers from 1 to 10. The two textboxes are both wired up to use the JQuery Datepicker.
When the user selects an option from the drop down, I would like JQuery code to clear the values in the two textboxes.
I have written the JQuery code below which does just this, however, when I go to submit the form details to the post method within my controller, the dates I have selected for the two textboxes are cleared.
This is my code to date:
$(document).ready(function () {

$('#equipment_warrantyLength').change(ResetDates); //fires when drop down changed

function ResetDates() {
    alert("hello");

    $("#equipment_purchaseDate").val(''); // clear textbox
    $('#equipment_warrentyExpires').val(''); //clear textbox

}

});

The textboxes should only be cleared when the drop down is selected, but currently, they also clear when the user attempts to submit the form.
Any feedback would be much appreciated.

A: When the form is submitted to the server the page is reloaded. Unless you set the submitted values in the textboxes upon loading the page again they are cleared. ASP.NET MVC doesn't use Viewstate like ASP.NET WebForms so unless you manually init the fields they will be empty when pages are reloaded after a form submission.
Update:
You can also submit the form data via jQuery. In order to do that you would do something like this:

*

*Add a click handler to the submit button. (If it is declared as  you should also change it to a normal button so that the browser wont submit the form automatically.

*In the click handler add code to do the ajax submission. See this question for tips on that Submit form using AJAX and jQuery
But en the end it might be easier to just put the submitted data in the viewmodel and reinitialize the fields in the view after submission.


Q: Error while buliding pysha3 with pip? ERROR: Failed building wheel for pysha3 when I try to install with pip install pysha3, I get the error "ERROR: Failed building wheel for pysha3". I did already install the Windows build tools. I can't find much help on Google unfortunately. I am on Windows 11.
Here is the log
`
PS C:\Users\Alexis> pip3 install pysha3
Collecting pysha3
  Using cached pysha3-1.0.2.tar.gz (829 kB)
  Preparing metadata (setup.py) ... done
Building wheels for collected packages: pysha3
  Building wheel for pysha3 (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [16 lines of output]
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-cpython-311
      copying sha3.py -> build\lib.win-amd64-cpython-311
      running build_ext
      building '_pysha3' extension
      creating build\temp.win-amd64-cpython-311
      creating build\temp.win-amd64-cpython-311\Release
      creating build\temp.win-amd64-cpython-311\Release\Modules
      creating build\temp.win-amd64-cpython-311\Release\Modules\_sha3
      "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -DPY_WITH_KECCAK=1 -IC:\Python311\include -IC:\Python311\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\cppwinrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" /TcModules/_sha3/sha3module.c /Fobuild\temp.win-amd64-cpython-311\Release\Modules/_sha3/sha3module.obj
      sha3module.c
      C:\Users\Alexis\AppData\Local\Temp\pip-install-78ji94vk\pysha3_9e9c90f2f01445aeb1ab3ed6a6c14e42\Modules\_sha3\backport.inc(78): fatal error C1083: Cannot open include file: 'pystrhex.h': No such file or directory
      error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.34.31933\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for pysha3
  Running setup.py clean for pysha3
Failed to build pysha3
Installing collected packages: pysha3
  Running setup.py install for pysha3 ... error
  error: subprocess-exited-with-error

  × Running setup.py install for pysha3 did not run successfully.
  │ exit code: 1
  ╰─> [18 lines of output]
      running install
      C:\Python311\Lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-cpython-311
      copying sha3.py -> build\lib.win-amd64-cpython-311
      running build_ext
      building '_pysha3' extension
      creating build\temp.win-amd64-cpython-311
      creating build\temp.win-amd64-cpython-311\Release
      creating build\temp.win-amd64-cpython-311\Release\Modules
      creating build\temp.win-amd64-cpython-311\Release\Modules\_sha3
      "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -DPY_WITH_KECCAK=1 -IC:\Python311\include -IC:\Python311\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\cppwinrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" /TcModules/_sha3/sha3module.c /Fobuild\temp.win-amd64-cpython-311\Release\Modules/_sha3/sha3module.obj
      sha3module.c
      C:\Users\Alexis\AppData\Local\Temp\pip-install-78ji94vk\pysha3_9e9c90f2f01445aeb1ab3ed6a6c14e42\Modules\_sha3\backport.inc(78): fatal error C1083: Cannot open include file: 'pystrhex.h': No such file or directory
      error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.34.31933\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> pysha3

note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.

`
I did install the Windows Build tools for c++

A: Having this same issue, last time I resolved it by back-switching to Python 3.8.7 perhaps. But now I installed 3.11 and now again pysha3 is not installing. (Window 10)


Q: Gekko: MINLP - Error options.json file not found I am trying to solve a MINLP problem using first the IPOPT solver to get an initial solution then the APOPT to get the mixed integer solution. However, I get the following error when calling the APOPT solver:

Error: Exception: Access Violation                                                                                At line 359 of file ./f90/cqp.f90                                                                                Traceback: not available, compile with -ftrace=frame or -ftrace=full                                                                                Error: 'results.json' not found. Check above for additional error details                                               Traceback (most recent call last):                                                                                File "optimisation_stack.py", line 244, in                                                                        Optimise_G(t,ob, jofbuses, q, qc, s, oa, k, l, T, G_previous, C, Y, G_previous, G_max, G_min)                         File "optimisation_stack.py", line 134, in Optimise_G                                                                     sol = MINLP(xinit, A, B, A_eq, B_eq, LB ,UB, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_previous, C, Y, G_previous)    File "optimisation_stack.py", line 215, in MINLP                                                                          m_APOPT.solve(disp = False)                                                                                File "C:\Users\Zineb\AppData\Local\Programs\Python\Python37\lib\site-packages\gekko\gekko.py", line 2227, in solve        self.load_JSON()                                                                                File "C:\Users\Zineb\AppData\Local\Programs\Python\Python37\lib\site-packages\gekko\gk_post_solve.py", line 13, in load_JSON                                                                                f = open(os.path.join(self._path,'options.json'))                                                                   FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\Zineb\AppData\Local\Temp\tmptdgafg1zgk_model1\options.json'

My code is the following, I tried to simplify it as much as possible :
import numpy as np
from gekko import GEKKO

# Define matrices A,A_eq, and vectors b, b_eq for the optimization

def Optimise_G(t,ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous, G_max, G_min):
    Mbig_1 = T*C
    Mbig_2 = C
    nb_phases = len(G_next)
    b_max = len(t)
    no_lanegroups = len(q)

    A_eq = np.zeros(((nb_phases+1)*b_max + 1, (3*nb_phases+3)*b_max+nb_phases))
    for i in range(nb_phases):
        A_eq[0][i] = 1

    #B_eq = np.zeros(((nb_phases+1)*b_max + 1, 1))
    B_eq = np.zeros((nb_phases+1)*b_max + 1)
    B_eq[0] = C - sum(Y[0:nb_phases])

    counter_eq = 0

    # G(i)=Ga(i,b)+Gb(i,b)+Gc(i,b)
    for b in range(b_max):
        for i in range(nb_phases):
            counter_eq = counter_eq + 1
            A_eq[counter_eq][i] = 1
            A_eq[counter_eq][nb_phases*(b+1)+ i] = -1
            A_eq[counter_eq][nb_phases*b_max + nb_phases*(b+1) + i] = -1
            A_eq[counter_eq][2*nb_phases*b_max + nb_phases*(b+1) + i] = -1

    # ya(b)+y(b)+y(c)=1
    for b in range(b_max):
        counter_eq = counter_eq + 1
        A_eq[counter_eq][3*nb_phases*b_max + nb_phases + b] = 1
        A_eq[counter_eq][(3*nb_phases+1)*b_max + nb_phases + b] = 1
        A_eq[counter_eq][(3*nb_phases+2)*b_max + nb_phases + b] = 1
        B_eq[counter_eq] = 1

    A = np.zeros((no_lanegroups + (2*3*nb_phases+4)*b_max, (3*nb_phases+3)*b_max+nb_phases))
    B = np.zeros(no_lanegroups + (2*3*nb_phases+4)*b_max)

    counter = -1

    # Sum Gi (i in Ij)>=Gj,min
    for j in range(no_lanegroups):
        counter = counter + 1
        for i in range(k[j], l[j]+1):
            A[counter][i-1] = -1
        B[counter] = -C*qc[j]/s[j]

    # ya(b)G_lb(i)<=Ga(i,b), yb(b)G_lb(i)<=Gb(i,b), yc(b)G_lb(i)<=Gc(i,b)
    for b in range(b_max):
        for i in range(nb_phases):
            counter = counter + 1
            A[counter][nb_phases*(b+1)+i] = -1
            A[counter][3*nb_phases*b_max + nb_phases + b] = G_min[i]
            B[counter] = 0

            counter = counter + 1
            A[counter][nb_phases*b_max + nb_phases*(b+1) + i] = -1
            A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = G_min[i]
            B[counter] = 0

            counter = counter + 1
            A[counter][2*nb_phases*b_max + nb_phases*(b+1) +i] = -1
            A[counter][(3*nb_phases+2)*b_max + nb_phases + b] = G_min[i]
            B[counter] = 0

    # ya(b)Gmax(i)>=Ga(i,b), yb(b)Gmax(i)>=Gb(i,b), yc(b)Gmax(i)>=Gc(i,b)
    for b in range(b_max):
        for i in range(nb_phases):
            counter = counter + 1
            A[counter][nb_phases*(b+1) +i] = 1
            A[counter][3*nb_phases*b_max + nb_phases + b] = -G_max[i]
            B[counter] = 0

            counter = counter + 1
            A[counter][nb_phases*b_max + nb_phases*(b+1) + i] = 1
            A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = -G_max[i]
            B[counter] = 0

            counter = counter + 1
            A[counter][2*nb_phases*b_max + nb_phases*(b+1) +i] = 1
            A[counter][(3*nb_phases+2)*b_max + nb_phases + b] = -G_max[i]
            B[counter] = 0

    # (1-yc(b))t(b)<=(T-1)C+sum(Gi(1:l(jofbuses(b))))+sum(Y(1:l(jofbuses(b))-1))
    for b in range(b_max):
        counter = counter + 1
        A[counter][0:l[jofbuses[b]-1]] = -np.ones((1,l[jofbuses[b]-1]))
        A[counter][(3*nb_phases+2)*b_max+nb_phases+b] = -t[b]
        B[counter] = -t[b] + (T-1)*C + sum(Y[0:l[jofbuses[b]-1]-1])

    # (T-1)C+sum(Gi(1:l(jofbuses(b))))+sum(Y(1:l(jofbuses(b))-1))<=yc(b)t(b)+(1-yc(b))Mbig_1
    for b in range(b_max):
        counter = counter + 1
        A[counter][0:l[jofbuses[b]-1]] = np.ones((1,l[jofbuses[b]-1]))
        A[counter][(3*nb_phases+2)*b_max+nb_phases+b] = -t[b] + Mbig_1
        B[counter] = Mbig_1 - (T-1)*C - sum(Y[0:l[jofbuses[b]-1]-1])

    # -Mbig_2(1-yb(b))<=db(b)=right-hand side of Equation (6)
    for b in range(b_max):
        counter = counter + 1
        constant = q[jofbuses[b]-1]/s[jofbuses[b]-1]*(t[b] - (T-1)*C + sum(G_previous[l[jofbuses[b]-1]:nb_phases]) + sum(Y[l[jofbuses[b]-1] -1:nb_phases]))+ (T-1)*C + sum(Y[0:k[jofbuses[b]-1]-1]) - t[b]
        A[counter][0:k[jofbuses[b]-1]-1] = -np.ones((1,k[jofbuses[b]-1]-1))
        A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = Mbig_2
        B[counter] = constant + Mbig_2

    # db(b)<=Mbig_2 yb(b)
    for b in range(b_max):
        counter = counter + 1
        constant = q[jofbuses[b]-1]/s[jofbuses[b]-1]*(t[b] - (T-1)*C +sum(G_previous[l[jofbuses[b]-1]:nb_phases]) + sum(Y[l[jofbuses[b]-1] -1:nb_phases]))+ (T-1)*C + sum(Y[0:k[jofbuses[b]-1]-1]) - t[b]
        A[counter][0:k[jofbuses[b]-1]-1] = np.ones((1,k[jofbuses[b]-1]-1))
        A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = -Mbig_2
        B[counter] = -constant

    #Lower Bound LB
    LB_zeros = np.zeros(3*b_max*(nb_phases+1))
    G_min = np.array(G_min)
    LB = np.append(G_min, LB_zeros)

    #Upper Bound UB
    UB = np.ones(3*b_max)
    G_max = np.array(G_max)
    for i in range(3*b_max+1):
        UB = np.concatenate((G_max,UB))

    xinit = np.array([(a+b)/2 for a, b in zip(UB, LB)])
    sol = MINLP(xinit, A, B, A_eq, B_eq, LB ,UB, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_previous, C, Y, G_previous)

The objective function:
def objective_fun(x, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous):
    nb_phases = len(G_next)
    b_max = len(t)
    no_lanegroups = len(q)
    obj = 0
    obj_a = 0
    obj_b = 0

    G = x[0:nb_phases]

    for j in range(no_lanegroups):
        delay_a = 0.5*q[j]/(1-q[j]/s[j]) * (pow((sum(G_previous[l[j]:nb_phases]) + sum(G[0:k[j]-1]) + sum(Y[l[j]-1:nb_phases]) + sum(Y[0:k[j]-1])),2) + pow(sum(G[l[j]:nb_phases]) + sum(G_next[0:k[j]-1]) + sum(Y[l[j]-1:nb_phases]) + sum(Y[0:k[j]-1]),2))

        obj = obj + oa*delay_a
        obj_a = obj_a + oa*delay_a

    for b in range(b_max):

        delay_b1 = x[(3*nb_phases+1)*b_max + nb_phases + b]*(q[jofbuses[b]-1]/s[jofbuses[b]-1] * (t[b] - (T-1)*C + sum(G_previous[l[jofbuses[b]-1]:nb_phases]) + sum(Y[l[jofbuses[b]-1] -1:nb_phases])) + (T-1)*C - t[b] + sum(Y[0:k[jofbuses[b]-1]-1]))
        delay_b2 = x[(3*nb_phases+2)*b_max + nb_phases + b-1]*(q[jofbuses[b]-1]/s[jofbuses[b]-1] * (t[b] - (T-1)*C - sum(Y[0:l[jofbuses[b]-1]-1])) + T*C + sum(G_next[0:k[jofbuses[b]-1]-1]) + sum(Y[0:k[jofbuses[b]-1]-1]) - t[b])
        delay_b3 = sum(x[nb_phases*b_max + nb_phases*b:nb_phases*b_max + nb_phases*b+k[jofbuses[b]-1]-1]) - q[jofbuses[b]-1]/s[jofbuses[b]-1]*sum(x[2*nb_phases*b_max + nb_phases*b:2*nb_phases*b_max + nb_phases*b +l[jofbuses[b]-1]])
        delay_b = delay_b1+delay_b2 +delay_b3

        obj = obj + delay_b*ob[b]
        obj_b = obj_b + delay_b*ob[b]
    return obj

MINLP solver:
def MINLP(xinit, A, B, A_eq, B_eq, LB ,UB, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous):
    nb_phases = len(G_next)
    b_max = len(t)
    ## First Solver: IPOPT to get an initial guess
    m_IPOPT = GEKKO(remote = False)
    m_IPOPT.options.SOLVER = 3 #(IPOPT)

    # Array Variable
    rows  = nb_phases + 3*b_max*(nb_phases+1)#48
    x_initial = np.empty(rows,dtype=object)

    for i in range(3*nb_phases*b_max+nb_phases+1):
        x_initial[i] = m_IPOPT.Var(value = xinit[i], lb = LB[i], ub = UB[i])#, integer = False)

    for i in range(3*nb_phases*b_max+nb_phases+1, (3*nb_phases+3)*b_max+nb_phases):
        x_initial[i] = m_IPOPT.Var(value = xinit[i], lb = LB[i], ub = UB[i])#, integer = True)

    # Constraints
    m_IPOPT.axb(A,B,x_initial,etype = '<=',sparse=False)

    m_IPOPT.axb(A_eq,B_eq,x_initial,etype = '=',sparse=False)

    # Objective Function
    f = objective_fun(x_initial, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous)
    m_IPOPT.Obj(f)

    #Solver
    m_IPOPT.solve(disp = True)

####################################################################################################
    ## Second Solver: APOPT to solve MINLP
    m_APOPT = GEKKO(remote = False)
    m_APOPT.options.SOLVER = 1 #(APOPT)

    x = np.empty(rows,dtype=object)

    for i in range(3*nb_phases*b_max+nb_phases+1):
        x[i] = m_APOPT.Var(value = x_initial[i], lb = LB[i], ub = UB[i], integer = False)

    for i in range(3*nb_phases*b_max+nb_phases+1, (3*nb_phases+3)*b_max+nb_phases):
        x[i] = m_APOPT.Var(value = x_initial[i], lb = LB[i], ub = UB[i], integer = True)

    # Constraints
    m_APOPT.axb(A,B,x,etype = '<=',sparse=False)

    m_APOPT.axb(A_eq,B_eq,x,etype = '=',sparse=False)

    # Objective Function
    f = objective_fun(x, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous)
    m_APOPT.Obj(f)

    #Solver
    m_APOPT.solve(disp = False)

    return x

Define parameters and call Optimise_G:
#Define Parameters

C = 120
T = 31
b_max = 2
G_base = [12,31,12,11,1,41]
G_max = [106, 106, 106, 106, 106, 106]
G_min = [7,3,7,10,0,7]
G_previous = [7.3333333, 34.16763, 7.1333333, 10.0, 2.2008602e-16, 47.365703]
Y = [2, 2, 3, 2, 2, 3]
jofbuses = [9,3]
k = [3,1,6,4,1,2,5,4,2,3]
l = [3,2,6,5,1,3,6,4,3,4]
nb_phases = 6
oa = 1.25
ob = [39,42]
t = [3600.2, 3603.5]
q = [0.038053758888888886, 0.215206065, 0.11325116416666667, 0.06299876472222223,0.02800455611111111,0.18878488361111112,0.2970903402777778, 0.01876728472222222, 0.2192723663888889, 0.06132227222222222]
qc = [0.04083333333333333, 0.2388888888888889, 0.10555555555555556, 0.0525, 0.030555555555555555, 0.20444444444444446,0.31083333333333335, 0.018333333333333333, 0.12777777777777777, 0.07138888888888889]
s = [1.0, 1.0, 1.0, 1.0, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5]

nb_phases = len(G_base)
G_max = []
for i in range(nb_phases):
    G_max.append(C - sum(Y[0:nb_phases]))

Optimise_G(t,ob, jofbuses, q, qc, s, oa, k, l, T, G_previous, C, Y, G_previous, G_max, G_min)

Is there a way to solve this issue?
Thanks a lot !

A: The Windows version of the APOPT solver crashed and wasn't able to find a solution. However, the online Linux version of APOPT is able to find a solution. Get the latest version of Gekko (v1.0.0 pre-release) available on GitHub. This will be available with pip install gekko --upgrade when the new version is published but for now you need to copy the source to Lib\site-packages\gekko\gekko.py. After updating gekko, switch to remote=True as shown below.
import numpy as np
from gekko import GEKKO

# Define matrices A,A_eq, and vectors b, b_eq for the optimization

def Optimise_G(t,ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous, G_max, G_min):
    Mbig_1 = T*C
    Mbig_2 = C
    nb_phases = len(G_next)
    b_max = len(t)
    no_lanegroups = len(q)

    A_eq = np.zeros(((nb_phases+1)*b_max + 1, (3*nb_phases+3)*b_max+nb_phases))
    for i in range(nb_phases):
        A_eq[0][i] = 1

    #B_eq = np.zeros(((nb_phases+1)*b_max + 1, 1))
    B_eq = np.zeros((nb_phases+1)*b_max + 1)
    B_eq[0] = C - sum(Y[0:nb_phases])

    counter_eq = 0

    # G(i)=Ga(i,b)+Gb(i,b)+Gc(i,b)
    for b in range(b_max):
        for i in range(nb_phases):
            counter_eq = counter_eq + 1
            A_eq[counter_eq][i] = 1
            A_eq[counter_eq][nb_phases*(b+1)+ i] = -1
            A_eq[counter_eq][nb_phases*b_max + nb_phases*(b+1) + i] = -1
            A_eq[counter_eq][2*nb_phases*b_max + nb_phases*(b+1) + i] = -1

    # ya(b)+y(b)+y(c)=1
    for b in range(b_max):
        counter_eq = counter_eq + 1
        A_eq[counter_eq][3*nb_phases*b_max + nb_phases + b] = 1
        A_eq[counter_eq][(3*nb_phases+1)*b_max + nb_phases + b] = 1
        A_eq[counter_eq][(3*nb_phases+2)*b_max + nb_phases + b] = 1
        B_eq[counter_eq] = 1

    A = np.zeros((no_lanegroups + (2*3*nb_phases+4)*b_max, (3*nb_phases+3)*b_max+nb_phases))
    B = np.zeros(no_lanegroups + (2*3*nb_phases+4)*b_max)

    counter = -1

    # Sum Gi (i in Ij)>=Gj,min
    for j in range(no_lanegroups):
        counter = counter + 1
        for i in range(k[j], l[j]+1):
            A[counter][i-1] = -1
        B[counter] = -C*qc[j]/s[j]

    # ya(b)G_lb(i)<=Ga(i,b), yb(b)G_lb(i)<=Gb(i,b), yc(b)G_lb(i)<=Gc(i,b)
    for b in range(b_max):
        for i in range(nb_phases):
            counter = counter + 1
            A[counter][nb_phases*(b+1)+i] = -1
            A[counter][3*nb_phases*b_max + nb_phases + b] = G_min[i]
            B[counter] = 0

            counter = counter + 1
            A[counter][nb_phases*b_max + nb_phases*(b+1) + i] = -1
            A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = G_min[i]
            B[counter] = 0

            counter = counter + 1
            A[counter][2*nb_phases*b_max + nb_phases*(b+1) +i] = -1
            A[counter][(3*nb_phases+2)*b_max + nb_phases + b] = G_min[i]
            B[counter] = 0

    # ya(b)Gmax(i)>=Ga(i,b), yb(b)Gmax(i)>=Gb(i,b), yc(b)Gmax(i)>=Gc(i,b)
    for b in range(b_max):
        for i in range(nb_phases):
            counter = counter + 1
            A[counter][nb_phases*(b+1) +i] = 1
            A[counter][3*nb_phases*b_max + nb_phases + b] = -G_max[i]
            B[counter] = 0

            counter = counter + 1
            A[counter][nb_phases*b_max + nb_phases*(b+1) + i] = 1
            A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = -G_max[i]
            B[counter] = 0

            counter = counter + 1
            A[counter][2*nb_phases*b_max + nb_phases*(b+1) +i] = 1
            A[counter][(3*nb_phases+2)*b_max + nb_phases + b] = -G_max[i]
            B[counter] = 0

    # (1-yc(b))t(b)<=(T-1)C+sum(Gi(1:l(jofbuses(b))))+sum(Y(1:l(jofbuses(b))-1))
    for b in range(b_max):
        counter = counter + 1
        A[counter][0:l[jofbuses[b]-1]] = -np.ones((1,l[jofbuses[b]-1]))
        A[counter][(3*nb_phases+2)*b_max+nb_phases+b] = -t[b]
        B[counter] = -t[b] + (T-1)*C + sum(Y[0:l[jofbuses[b]-1]-1])

    # (T-1)C+sum(Gi(1:l(jofbuses(b))))+sum(Y(1:l(jofbuses(b))-1))<=yc(b)t(b)+(1-yc(b))Mbig_1
    for b in range(b_max):
        counter = counter + 1
        A[counter][0:l[jofbuses[b]-1]] = np.ones((1,l[jofbuses[b]-1]))
        A[counter][(3*nb_phases+2)*b_max+nb_phases+b] = -t[b] + Mbig_1
        B[counter] = Mbig_1 - (T-1)*C - sum(Y[0:l[jofbuses[b]-1]-1])

    # -Mbig_2(1-yb(b))<=db(b)=right-hand side of Equation (6)
    for b in range(b_max):
        counter = counter + 1
        constant = q[jofbuses[b]-1]/s[jofbuses[b]-1]*(t[b] - (T-1)*C + sum(G_previous[l[jofbuses[b]-1]:nb_phases]) + sum(Y[l[jofbuses[b]-1] -1:nb_phases]))+ (T-1)*C + sum(Y[0:k[jofbuses[b]-1]-1]) - t[b]
        A[counter][0:k[jofbuses[b]-1]-1] = -np.ones((1,k[jofbuses[b]-1]-1))
        A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = Mbig_2
        B[counter] = constant + Mbig_2

    # db(b)<=Mbig_2 yb(b)
    for b in range(b_max):
        counter = counter + 1
        constant = q[jofbuses[b]-1]/s[jofbuses[b]-1]*(t[b] - (T-1)*C +sum(G_previous[l[jofbuses[b]-1]:nb_phases]) + sum(Y[l[jofbuses[b]-1] -1:nb_phases]))+ (T-1)*C + sum(Y[0:k[jofbuses[b]-1]-1]) - t[b]
        A[counter][0:k[jofbuses[b]-1]-1] = np.ones((1,k[jofbuses[b]-1]-1))
        A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = -Mbig_2
        B[counter] = -constant

    #Lower Bound LB
    LB_zeros = np.zeros(3*b_max*(nb_phases+1))
    G_min = np.array(G_min)
    LB = np.append(G_min, LB_zeros)

    #Upper Bound UB
    UB = np.ones(3*b_max)
    G_max = np.array(G_max)
    for i in range(3*b_max+1):
        UB = np.concatenate((G_max,UB))

    xinit = np.array([(a+b)/2 for a, b in zip(UB, LB)])
    sol = MINLP(xinit, A, B, A_eq, B_eq, LB ,UB, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_previous, C, Y, G_previous)

def objective_fun(x, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous):
    nb_phases = len(G_next)
    b_max = len(t)
    no_lanegroups = len(q)
    obj = 0
    obj_a = 0
    obj_b = 0

    G = x[0:nb_phases]

    for j in range(no_lanegroups):
        delay_a = 0.5*q[j]/(1-q[j]/s[j]) * (pow((sum(G_previous[l[j]:nb_phases]) + sum(G[0:k[j]-1]) + sum(Y[l[j]-1:nb_phases]) + sum(Y[0:k[j]-1])),2) + pow(sum(G[l[j]:nb_phases]) + sum(G_next[0:k[j]-1]) + sum(Y[l[j]-1:nb_phases]) + sum(Y[0:k[j]-1]),2))

        obj = obj + oa*delay_a
        obj_a = obj_a + oa*delay_a

    for b in range(b_max):

        delay_b1 = x[(3*nb_phases+1)*b_max + nb_phases + b]*(q[jofbuses[b]-1]/s[jofbuses[b]-1] * (t[b] - (T-1)*C + sum(G_previous[l[jofbuses[b]-1]:nb_phases]) + sum(Y[l[jofbuses[b]-1] -1:nb_phases])) + (T-1)*C - t[b] + sum(Y[0:k[jofbuses[b]-1]-1]))
        delay_b2 = x[(3*nb_phases+2)*b_max + nb_phases + b-1]*(q[jofbuses[b]-1]/s[jofbuses[b]-1] * (t[b] - (T-1)*C - sum(Y[0:l[jofbuses[b]-1]-1])) + T*C + sum(G_next[0:k[jofbuses[b]-1]-1]) + sum(Y[0:k[jofbuses[b]-1]-1]) - t[b])
        delay_b3 = sum(x[nb_phases*b_max + nb_phases*b:nb_phases*b_max + nb_phases*b+k[jofbuses[b]-1]-1]) - q[jofbuses[b]-1]/s[jofbuses[b]-1]*sum(x[2*nb_phases*b_max + nb_phases*b:2*nb_phases*b_max + nb_phases*b +l[jofbuses[b]-1]])
        delay_b = delay_b1+delay_b2 +delay_b3

        obj = obj + delay_b*ob[b]
        obj_b = obj_b + delay_b*ob[b]
    return obj

def MINLP(xinit, A, B, A_eq, B_eq, LB ,UB, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous):
    nb_phases = len(G_next)
    b_max = len(t)
    ## First Solver: IPOPT to get an initial guess
    m_IPOPT = GEKKO(remote = True)
    m_IPOPT.options.SOLVER = 3 #(IPOPT)

    # Array Variable
    rows  = nb_phases + 3*b_max*(nb_phases+1)#48
    x_initial = np.empty(rows,dtype=object)

    for i in range(3*nb_phases*b_max+nb_phases+1):
        x_initial[i] = m_IPOPT.Var(value = xinit[i], lb = LB[i], ub = UB[i])#, integer = False)

    for i in range(3*nb_phases*b_max+nb_phases+1, (3*nb_phases+3)*b_max+nb_phases):
        x_initial[i] = m_IPOPT.Var(value = xinit[i], lb = LB[i], ub = UB[i])#, integer = True)

    # Constraints
    m_IPOPT.axb(A,B,x_initial,etype = '<=',sparse=False)

    m_IPOPT.axb(A_eq,B_eq,x_initial,etype = '=',sparse=False)

    # Objective Function
    f = objective_fun(x_initial, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous)
    m_IPOPT.Obj(f)

    #Solver
    m_IPOPT.solve(disp = True)

####################################################################################################
    ## Second Solver: APOPT to solve MINLP
    m_APOPT = GEKKO(remote = True)
    m_APOPT.options.SOLVER = 1 #(APOPT)

    x = np.empty(rows,dtype=object)

    for i in range(3*nb_phases*b_max+nb_phases+1):
        x[i] = m_APOPT.Var(value = x_initial[i], lb = LB[i], ub = UB[i], integer = False)

    for i in range(3*nb_phases*b_max+nb_phases+1, (3*nb_phases+3)*b_max+nb_phases):
        x[i] = m_APOPT.Var(value = x_initial[i], lb = LB[i], ub = UB[i], integer = True)

    # Constraints
    m_APOPT.axb(A,B,x,etype = '<=',sparse=False)

    m_APOPT.axb(A_eq,B_eq,x,etype = '=',sparse=False)

    # Objective Function
    f = objective_fun(x, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous)
    m_APOPT.Obj(f)

    #Solver
    m_APOPT.solve(disp = True)

    return x

#Define Parameters

C = 120
T = 31
b_max = 2
G_base = [12,31,12,11,1,41]
G_max = [106, 106, 106, 106, 106, 106]
G_min = [7,3,7,10,0,7]
G_previous = [7.3333333, 34.16763, 7.1333333, 10.0, 2.2008602e-16, 47.365703]
Y = [2, 2, 3, 2, 2, 3]
jofbuses = [9,3]
k = [3,1,6,4,1,2,5,4,2,3]
l = [3,2,6,5,1,3,6,4,3,4]
nb_phases = 6
oa = 1.25
ob = [39,42]
t = [3600.2, 3603.5]
q = [0.038053758888888886, 0.215206065, 0.11325116416666667, 0.06299876472222223,0.02800455611111111,0.18878488361111112,0.2970903402777778, 0.01876728472222222, 0.2192723663888889, 0.06132227222222222]
qc = [0.04083333333333333, 0.2388888888888889, 0.10555555555555556, 0.0525, 0.030555555555555555, 0.20444444444444446,0.31083333333333335, 0.018333333333333333, 0.12777777777777777, 0.07138888888888889]
s = [1.0, 1.0, 1.0, 1.0, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5]

nb_phases = len(G_base)
G_max = []
for i in range(nb_phases):
    G_max.append(C - sum(Y[0:nb_phases]))

Optimise_G(t,ob, jofbuses, q, qc, s, oa, k, l, T, G_previous, C, Y, G_previous, G_max, G_min)

The APOPT solver is successful and returns an integer solution.
 APMonitor, Version 1.0.0
 APMonitor Optimization Suite
 ----------------------------------------------------------------

 --------- APM Model Size ------------
 Each time step contains
   Objects      :            2
   Constants    :            0
   Variables    :           48
   Intermediates:            0
   Connections  :           96
   Equations    :            1
   Residuals    :            1

 Number of state variables:             48
 Number of total equations: -          105
 Number of slack variables: -            0
 ---------------------------------------
 Degrees of freedom       :            -57

 * Warning: DOF <= 0
 ----------------------------------------------
 Steady State Optimization with APOPT Solver
 ----------------------------------------------
Iter:     1 I:  0 Tm:      0.00 NLPi:    1 Dpth:    0 Lvs:    3 Obj:  1.64E+04 Gap:       NaN
Iter:     2 I: -1 Tm:      0.00 NLPi:    2 Dpth:    1 Lvs:    2 Obj:  1.64E+04 Gap:       NaN
Iter:     3 I:  0 Tm:      0.00 NLPi:    3 Dpth:    1 Lvs:    3 Obj:  1.81E+04 Gap:       NaN
Iter:     4 I: -1 Tm:      0.01 NLPi:    6 Dpth:    1 Lvs:    2 Obj:  1.64E+04 Gap:       NaN
--Integer Solution:   2.15E+04 Lowest Leaf:   1.81E+04 Gap:   1.68E-01
Iter:     5 I:  0 Tm:      0.00 NLPi:    4 Dpth:    2 Lvs:    1 Obj:  2.15E+04 Gap:  1.68E-01
Iter:     6 I: -1 Tm:      0.01 NLPi:    4 Dpth:    2 Lvs:    0 Obj:  1.81E+04 Gap:  1.68E-01
 No additional trial points, returning the best integer solution
 Successful solution

 ---------------------------------------------------
 Solver         :  APOPT (v1.0)
 Solution time  :   4.670000000623986E-002 sec
 Objective      :    21455.9882666580
 Successful solution
 ---------------------------------------------------

If you need to use remote=False (local solution) on Linux then the new executable will be available with the new release of Gekko. There are some compiler differences and it appears that the Windows FORTRAN compiler that creates the local apm.exe is not as good as the Linux FORTRAN compiler that creates the local apm executable. Those executables are in the bin folder: Lib\site-packages\gekko\bin of the Python folder.


Q: How to convert sample in AWS Lambda from javascript to Java? I currently am trying to convert this javascript sample:
javascript
'use strict';

exports.handler = (event, context, callback) => {
        callback(null, {"speech": "hello lambda js"});
};

output from hitting test button in aws lambda
{
  "speech": "hello lambda js"
}

Now I want to convert this in the simplest way into a Java program.
This is what I tried:
public class Sample implements RequestHandler<String, String> {

  @Override public String handleRequest(String s, Context context) {
    return "{\"speech\": \"hello lambda java\"}";
  }
}

but hitting the test button in AWS lamda complains:
{
  "errorMessage": "An error occurred during JSON parsing",
  "errorType": "java.lang.RuntimeException",
  "stackTrace": [],
  "cause": {
    "errorMessage": "com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token\n at [Source: lambdainternal.util.NativeMemoryAsInputStream@5f375618; line: 1, column: 1]",
    "errorType": "java.io.UncheckedIOException",
    "stackTrace": [],
    "cause": {
      "errorMessage": "Can not deserialize instance of java.lang.String out of START_OBJECT token\n at [Source: lambdainternal.util.NativeMemoryAsInputStream@5f375618; line: 1, column: 1]",
      "errorType": "com.fasterxml.jackson.databind.JsonMappingException",
      "stackTrace": [
        "com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)",
        "com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:857)",
        "com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:62)",
        "com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11)",
        "com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1511)",
        "com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:1102)"
      ]
    }
  }
}

A: Your javascript function is returning an object literal, not a JSON string.  Probably you need to do the parallel in Java, which would be to return an instance of a class that contains a property named speech, which a getter and setter for speech, and with the value of speech set to "hello lambda java".  AWS will probably take care of serializing that object to the JSON response you want.
More typing in Java than Javascript.  Ha!  I punned.

A: It doesn't really make sense but send the method something like "hello", not JSON.  Lambda tries to be smarter than you and, if it sees something that looks like JSON it tries to parse it.  But then you ask for a string so it gets confused.  Personally I think this is a bug but since you can't pass a "Content-Type" it has to guess.
For reference, if I use this code:
public class HelloWorldLambdaHandler implements RequestHandler<String, String> {

    public String handleRequest(String inputObject, Context context) {
        context.getLogger().log("context logger - got \"" + inputObject + "\" from call");
        return "{\"speech\": \"hello lambda java\"}";
    }
}

and test with the string "hello" (yes, including the quotes) I get back what I expect in the Lambda test console.  If I send:
{
  "key3": "value3",
  "key2": "value2",
  "key1": "value1"
}

I get the same error as you.


Q: Kendo UI - custom grid filter: checkbox doesn't work on each click [UPDATE]
After I did as in:
http://dojo.telerik.com/aqIXa
 when I click for example ProductName filter, and then select and deselect all items, go to other fields example Unit Price,click select and deselect all I turnback to Product Name field, and in filter is now:

You can see that Select All combobox is created once more and it will continue to create after I repeat the steps. Does anyone has the Idea why is it happend?
I'm currently working in Kendo and try to make custom grid filter for each column.
I used this example:
http://dojo.telerik.com/iwAWU
inside initCheckboxFilter function I added, which created checkbox for select all.
var selectAllCheckbox= $("
<input type='checkbox' id='checkAll' checked/> Select All
").insertBefore(".k-filter-help-text");

and outside that function I implemeted:
function clickMe(){
   $("#checkAll").click(function () {
    if ($("#checkAll").is(':checked')) {
        $(".book").prop("checked", true);
    } else {
        $(".book").prop("checked", false);
    }
});
}

(.book is class for template inside:
 var element = $("

").insertAfter(helpTextElement).kendoListView({
          dataSource: checkboxesDataSource,
          template: "
<input type='checkbox' class='colDefFilter'  value='#:" + field + "#' checked />#:" + field + "#
",
        });

)
I also added UnitPrice and UnitInStock fields:
function onFilterMenuInit(e) {
        debugger;
        if (e.field == "ProductName" || "UnitPrice" || "UnitInStock") {
          initCheckboxFilter.call(this, e);

        }
      }

This looks like:

The first time I click Select All  checkbox on some column filter, it check and uncheck all items and it works fine. When I try to do it on other column, the event is not trigger. Does anyone has idea what is wrong?
Thanks!

A: Your problem is that you are using id for check all checkbox that's why jquery always select check-box from first drop-down (Product)
you need to use checkAll as class not id then change your clickMe() function like this and it will work :
function clickMe(){
       $(".checkAll").click(function () {
        if ($(this).is(':checked')) {
           $(this).closest('.k-filter-menu').find(".book").prop("checked", true);
        } else {
            $(this).closest('.k-filter-menu').find(".book").prop("checked", false);
        }
    });
    }

Here is working example http://dojo.telerik.com/aqIXa
Edit :
the way you are using to add Select all checkbox should be like this
var selectAllCheckbox= $("
<input type='checkbox' class='checkAll' checked/> Select All
").insertBefore(e.container.find(".k-filter-help-text"));

insted of this
var selectAllCheckbox= $("
<input type='checkbox' id='checkAll' checked/> Select All
").insertBefore(".k-filter-help-text");

otherwise it will add multiple Select All check box for previously initialized filter-dropdowns.
Here is updated demo :http://dojo.telerik.com/aqIXa/4


Q: Does superclass constructor exist (but not inherited) in subclass? We are able to invoke super() from subclass constructor. Since subclass IS-A superclass , and there is only 1 object created ( new Subclass()) does this imply superclass constructor exists, although it cannot be inherited, in subclass?

A: Constructors are not inherited. Superclass constructor 'exists' in a way that you could call it from a subclass unless it's marked as private.
And as I.K. has mentioned class could have a default constructor:

If a class contains no constructor declarations, then a default
  constructor with no formal parameters and no throws clause is
  implicitly declared.


Q: How to call a PHP function in an URL of ajax? I have written a PHP code having single function with an echo statement and I wish to call that function as a url in ajax code.
I tired doing this.

        <title>Writing PHP Function</title>

        <?php

            function myFirst()
            {
             echo 'The First ran successfully.';
            }

        ?>

A: There are a lot of things wrong with what you have. Here is just a simple example that should work for you.
practice.php
<?php
    if(isset($_GET['f']))
        echo strip_tags($_GET['f']);
?>

index.php
<?php function myFirst() {
    echo 'The First ran successfully.';
} ?>

<title>Writing PHP Function</title>

Load

A: I would try to call the functions based on the params from the URL.
Ajax part,
$.ajax({url:'localhost/practice.php?f=myFirst',type:'GET'}).done(function(response){
  alert(response); // or you can write to your document
});

and PHP file
<?php
      if(isset($_GET) && $_GET['f'] == 'myFirst'){
        myFirst();
      }else{
        die('No GET params received');
      }

      function myFirst(){
           echo 'The First ran successfully.';
      }

?>


Q: How to redirect a page from '/' route to main '/dashboard' route automatically after first sign in angular js? I have auth.js page which decides which route to direct to after login.I am using ui-router for routing.Now the thing is after login user details are captured and the route accordingly changes.Here if I change the route from '/dashboard' to '/' and hit enter, then it first shows sign in page then redirects to dashboard which I don't want.If I go from '/dashboard' to '/' then it should automatically go to dashboard page without going to sign in page.How do I achieve this?
Thanks in advance

A: In your auth.js when user signIn (callback after user signIn success)
//In SignIn success callback.

$state.go('dashboard');//for state
$location.path("/dashboard");//for url dashboard

Hope it helps

A: You can use resolve to address this issue. When you are redirecting to "/" page. Just check in resolve section, whether the user is logged in or not. If the user is logged in, redirect to dashboard page.

A:
then it first shows sign in page then redirects to dashboard which I don't want.If I go from '/dashboard' to '/' then it should automatically go to dashboard page without going to sign in page.How do I achieve this

Really depends on your code. I recommend having the login route / logic maintained by the backend (check credentials there, and send a redirect to /login if not logged in.)

A: <!--HTML code-->
<div ng-init="CheckIfLoggedIn()">
  <form id="login-form">
  ..............
  </form>
</div>

//in angular JS
$scope.CheckIfLoggedIn = function(){
    if (loggedinuser){
        $location.path("/dashboard");
    }
};


Q: How to get the data from log file using udp appender How to send log details by using udp appender in wowza Media Server . i have uncomment the   udp appender in log4j.properties and added serverAccessUDP to root. but i Cant view the result.Where i Can Get the Result?
Anybody Help Me
Thanks in Advance?

A:
By using .Net framework,Udp Appender is easy to Access the Log File,Here the link

Udp Appender


Q: How to save server state of CGI application? I have a cgi web program (in C) that prints out different error messages to a log file. If the program is run again and runs into he same error, I do not want the same error message to log again. I'm looking at different options and any advice is appreciated. Thanks.
-Cookie: unable to set cookie after the html <head> section has been printed out.
(After the head section is where any errors would occur.)
-Database: Do not have one. Too much overhead for this issue to install one.
-Parse log file: Many other processes are writing to this log file.
-Hidden form inputs on html file: Seems messy. Have 3 different forms on the same html page. How do am I sure the hidden fields are always submitted regardless of which form is submitted? But one of the errors is when the html can not be produced, so can not depend on this.
Thanks.

A: Storing the built page in a variable and outputting it at the end will allow you to emit a header any time before then.

A: The other option is to create some form of temporary file wherever you are able (not sure about permissions) and read that pre doing any work. Simply list the error types and optionally times in there, perhaps? This is assuming you want to persist this behaviour across runs of your program. This is the database solution without the database, really, so I'm not sure how helpful that is.
Whenever I mention database solutions without databases I always have to mention SQLite which is a file based serverless SQL "server".

A: I think you should refactor your program to create all its output previously to sending any HTML to the client, that way you'll be able to know beforehand all existing errors and set a cookie.
Now, if this is not viable for any reason you should have a temporary file identifying IP address and user agent and errors already shown. A simple text file should be quick enough to parse.

A: Using memcached might be a way to keep states throughout different sessions.


Q: ViewPager fragmentstatepageadapter getItem isn't passing correct position I have created a viewpager layout, a class that extends FragmentActivity and a fragment. What I want is that each fragment get's passed in what position it is within the viewpager. So first viewpager is created getting the argument 0, second getting 1 etc. Then if I scroll one way or another these numbers remain a true count.
The problem is the first time a fragment is created, it seems to be created twice so the position passed is 0 then 1. However I can't scroll back but I know for sure the class is being called twice. Now as I scroll forward the position increases incrementally by one. However if I scroll back it drops immediately to three on just one page back, then continues to drop past the 1 to 0 so now I can finally see my layout for 0.
I have this:
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {

    public ScreenSlidePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        PracticeFragment fragment = new PracticeFragment();
        getAll.putInt("position", position);
        fragment.setArguments(getAll);
        return fragment;
    }

    @Override
    public int getCount() {
        return numberofQ;
    }
}

It first of all runs getItem twice before even going to my fragment class so that the position is 0 then 1. Then when it gets to my fragment class it makes a layout fine, I scroll through a few (3 or 4) new pages and it adds one to the position each time then when I scroll back it says it is zero or two then the numbers continue to be just as sporadic. Finally suddenly when I scroll back to the beginning the position is again 0 so my fragment for position 0 is suddenly displayed.
I don't understand what's happening, so I'm wondering what the mistake is?
public class PracticeFragment extends Fragment {
TextView question, explain;
private ScrollView sv;
private boolean starActionBar;
private final static int version = Consts.SDKversion;

ArrayList<RadioButton> rbArray;
ArrayList<LinearLayout> lArray;
ArrayList<ImageView> ivArray;

int iRow;

SQLite info;
private String correctAnswer;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    info = new SQLite(getActivity());
    starActionBar = PreferenceManager.getDefaultSharedPreferences(
            getActivity()).getBoolean("star", true);
    setHasOptionsMenu(true);

}

@Override
public void onViewStateRestored(Bundle savedInstanceState) {
    super.onViewStateRestored(savedInstanceState);
    for (RadioButton r : rbArray) {
        if (r.isChecked()) {
            r.performClick();
        }
    }
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.activity_pm_fragment, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

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

    ViewGroup rootView = (ViewGroup) inflater.inflate(
            R.layout.activity_main, container, false);

    lArray = new ArrayList<LinearLayout>();
    rbArray = new ArrayList<RadioButton>();
    ivArray = new ArrayList<ImageView>();

    lArray.add((LinearLayout) rootView.findViewById(R.id.PM_LinLay0));
    lArray.add((LinearLayout) rootView.findViewById(R.id.PM_LinLay1));
    lArray.add((LinearLayout) rootView.findViewById(R.id.PM_LinLay2));
    lArray.add((LinearLayout) rootView.findViewById(R.id.PM_LinLay3));
    lArray.add((LinearLayout) rootView.findViewById(R.id.PM_LinLay4));

    for (LinearLayout l : lArray) {
        l.setOnTouchListener(PracticeFragment.this);
        l.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (((ViewGroup) v).getChildAt(0).isEnabled()) {
                    ((ViewGroup) v).getChildAt(0).performClick();
                }
            }
        });
    }

    rbArray.add((RadioButton) rootView.findViewById(R.id.radio0));
    rbArray.add((RadioButton) rootView.findViewById(R.id.radio1));
    rbArray.add((RadioButton) rootView.findViewById(R.id.radio2));
    rbArray.add((RadioButton) rootView.findViewById(R.id.radio3));
    rbArray.add((RadioButton) rootView.findViewById(R.id.radio4));

    ivArray.add((ImageView) rootView.findViewById(R.id.ivradio0));
    ivArray.add((ImageView) rootView.findViewById(R.id.ivradio1));
    ivArray.add((ImageView) rootView.findViewById(R.id.ivradio2));
    ivArray.add((ImageView) rootView.findViewById(R.id.ivradio3));
    ivArray.add((ImageView) rootView.findViewById(R.id.ivradio4));

    rootView.findViewById(R.id.bNext).setVisibility(View.GONE);
    rootView.findViewById(R.id.bPrevious).setVisibility(View.GONE);
    sv = (ScrollView) rootView.findViewById(R.id.svMain);

    info.open();
    iRow = Integer.valueOf(info.getEverything(getArguments(), getArguments().getInt("position"), "next"));
    Cursor c = info.getCursor(iRow);
    ((TextView) rootView.findViewById(R.id.tvQuestion))
            .setText((getArguments().getInt("position") + 1) + ") " + c.getString(2));

    explain = (TextView) rootView.findViewById(R.id.tvExplain);
    explain.setText(c.getString(9));
    explain.setVisibility(View.GONE);
    correctAnswer = c.getString(8);

    String[] aArray = { c.getString(3), c.getString(4), c.getString(5),
            c.getString(6), c.getString(7) };

    c.close();
    info.close();

    int o = 0;
    int pos = 0;
    for (String s : aArray) {
        LinearLayout l = lArray.get(pos);
        if (s.contentEquals("BLANK")) {
            l.setVisibility(View.GONE);
        } else {
            l.setVisibility(View.VISIBLE);
            rbArray.get(pos).setText(s);
            rbArray.get(pos).setOnClickListener(null);
            if (o % 2 == 0) {
                l.setBackgroundColor(Consts.colorAlt);
            }
            o++;
        }
        pos++;
    }

    return rootView;
}

}

However if I comment out everything but the viewgroup and return rootview - still the same problem.

A: initialize the getAll every time as a new object in getItem()
make your fragment class  static
and create one method in PracticeFragment
 static PracticeFragment newInstance(int num) {
        PracticeFragment f = new PracticeFragment();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);

        return f;
    }

and change  in adapter
     @Override
public Fragment getItem(int position) {
        return PracticeFragment.newInstance(position);
       }

A: Subclassing it fixed the problem!


Q: Most viewed product I am trying to find most viewed product as per user ID. If two products have been viewed for the same number of times then the most recent viewed product is to be selected.
I have the following coding:
#tabulating most viewed product by an user in the last 15 days
df_most_viewed_product= new_df.groupby('UserID')['ProductID'].apply(lambda x: x.value_counts().index[0]).reset_index()

Its finding the most viewed product for all the USER IDs except for those, where the USER has viewed two products for the same number of time.In such a scenario I need to get the output as the most recently viewed product.
        ProductID   UserID  Activity    OS      date        time
392281  Pr102405    U100040 PAGELOAD    Windows 2018-05-21  04:18:05.465000
764999  Pr102405    U100040 CLICK   Windows 2018-05-23  15:52:02.061000
1501633 Pr105055    U100040 PAGELOAD    Windows 2018-05-23  15:52:39.035000
1603959 Pr100283    U100040 PAGELOAD    Windows 2018-05-25  15:27:37.062000
2212636 Pr100513    U100040 PAGELOAD    Windows 2018-05-27  02:18:47.676000
3093767 Pr100513    U100040 PAGELOAD    Windows 2018-05-26  20:47:49.788000

The answer should be Pr100513 as it has been been viewed recently.

A: Systematically build it up as you describe

*

*get hits and last hit per UserID and ProductID

*select rows from this aggregated data frame that match max hits and max last_hit
import io
import pandas as pd
df = pd.read_csv(io.StringIO(''' ProductID UserID Activity OS date time
392281 Pr102405 U100040 PAGELOAD Windows 2018-05-21 04:18:05.465000
764999 Pr102405 U100040 CLICK Windows 2018-05-23 15:52:02.061000
1501633 Pr105055 U100040 PAGELOAD Windows 2018-05-23 15:52:39.035000
1603959 Pr100283 U100040 PAGELOAD Windows 2018-05-25 15:27:37.062000
2212636 Pr100513 U100040 PAGELOAD Windows 2018-05-27 02:18:47.676000
3093767 Pr100513 U100040 PAGELOAD Windows 2018-05-26 20:47:49.788000 '''), sep="\s", engine="python")

df["date"] = pd.to_datetime(df["date"] + " " + df["time"])

# count hits per user and product after sorting so last_hit works
dfh = df.sort_values(["UserID","date"]).groupby(["UserID","ProductID"]).agg(hits=("OS","size"),last_hit=("date","last"))
# select the row with max hits and last hit
dfh.loc[dfh["hits"].eq(dfh["hits"].max()) & dfh["last_hit"].eq(dfh["last_hit"].max())]

output
                   hits                last_hit
UserID  ProductID
U100040 Pr100513      2 2018-05-27 02:18:47.676


Q: Take and save screenshot with html javascript I'm trying to take a screenshot and save it in a specific folder in my local computer with an onclick in a button, using HTML and JavaScript (or JQuery).

A: There's no way to save DOM elements as an image (unless you just use Firefox or something), but you can convert the DOM elements into canvas and save the image from there.
See http://html2canvas.hertzen.com/
Then use canvas.toDataURL() to save the image.


Q: gcloud app deploy fails with only [ERROR] I've been running python 2.7 apps on GCP for about 5 years and deploying using the App Engine Launcher.
Now that AEL is deprecated I'm trying to deploy via gcloud and get "ERROR: (gcloud.app.deploy)"

*

*I can use gcloud to run the project locally so I have confidence that the project is setup correctly and in the right directory locally.

*I ran gcloud auth login to give myself permission to upload to the project.
But when I try to redeploy my app I get an error:
DEBUG: Running gcloud.app.deploy with Namespace(__calliope_internal_deepest_parser=ArgumentParser(prog='gcloud.app.deploy', usage=None, description='Deploy the local code and/or configuration of your app to App Engine.', version=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=False), account=None, authority_selector=None, authorization_token_file=None, bucket=None, calliope_command=<googlecloudsdk.calliope.backend.Command object at 0x037D1F90>, command_path=['gcloud', 'app', 'deploy'], configuration=None, credential_file_override=None, deployables=[], docker_build=None, document=None, flatten=None, format=None, h=None, help=None, http_timeout=None, ignore_bad_certs=False, image_url=None, log_http=None, project='MY_PROJECT', promote=None, quiet=None, server=None, skip_image_url_validation=False, skip_staging=False, stop_previous_version=None, trace_email=None, trace_log=None, trace_token=None, user_output_enabled=None, verbosity='debug', version=None).
DEBUG: API endpoint: [https://appengine.googleapis.com/], API version: [v1beta5]
You are creating an app for project [MY_PROJECT].
WARNING: Creating an app for a project is irreversible.

DEBUG: (gcloud.app.deploy)
Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\cli.py", line 740, in Execute
    resources = args.calliope_command.Run(cli=self, args=args)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\backend.py", line 1684, in Run
    resources = command_instance.Run(args)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\surface\app\deploy.py", line 53, in Run
    return deploy_util.RunDeploy(args)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\command_lib\app\deploy_util.py", line 374, in RunDeploy
    app = _PossiblyCreateApp(api_client, project)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\command_lib\app\deploy_util.py", line 507, in _PossiblyCreateApp
    create_util.CreateAppInteractively(api_client, project)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\command_lib\app\create_util.py", line 109, in CreateAppInteractively
    all_regions = sorted(set(api_client.ListRegions()))
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\app\appengine_api_client.py", line 415, in ListRegions
    self.client.apps_locations.List, request)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\app\api\requests.py", line 67, in MakeRequest
    raise err() if err else exc
NotFoundError
ERROR: (gcloud.app.deploy)

It doesn't give me much to go on. Wondering if it is a problem with app.yaml or some other basic issue.
gcloud info
Google Cloud SDK [138.0.0]

Platform: [Windows, x86_64]
Python Version: [2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]]
Python Location: [C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\bundledpython\python.exe]
Site Packages: [Disabled]

Installation Root: [C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk]
Installed Components:
  bundled-python: [2.7.10]
  app-engine-python: [1.9.49]
  bq-win: [2.0.24]
  core: [2016.12.09]
  core-win: [2016.11.07]
  gcloud: []
  windows-ssh-tools: [2016.05.13]
  app-engine-python-extras: [1.9.49]
  gsutil: [4.22]
  bq: [2.0.24]
  powershell: [1.0.0.1]
  gsutil-win: [4.20]
System PATH: [C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\bin\..\bin\sdk;C:\Users\Jay-swtchbk\Miniconda2\condabin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\bin;C:\WINDOWS\System32\OpenSSH\;C:\Users\Jay-swtchbk\AppData\Roaming\Dashlane\4.6.5.21982\bin\Firefox_Extension\{442718d9-475e-452a-b3e1-fb1ee16b8e9f}\components;C:\Users\Jay-swtchbk\AppData\Local\Microsoft\WindowsApps;C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin;C:\Program Files (x86)\Google\google_appengine\]
Cloud SDK on PATH: [True]
Kubectl on PATH: [False]

WARNING: There are old versions of the Google Cloud Platform tools on your system PATH.
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\gcloud.cmd
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\dev_appserver.py
  C:\Program Files (x86)\Google\google_appengine\dev_appserver.py
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\gsutil.cmd
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\git-credential-gcloud.cmd
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\bq.cmd
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\gcloud-ps.ps1
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\gsutil-ps.ps1
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\bq-ps.ps1
  C:\Program Files (x86)\Google\google_appengine\endpointscfg.py
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\endpointscfg.py

Installation Properties: [C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\properties]
User Config Directory: [C:\Users\Jay-swtchbk\AppData\Roaming\gcloud]
Active Configuration Name: [tvpub1]
Active Configuration Path: [C:\Users\Jay-swtchbk\AppData\Roaming\gcloud\configurations\config_tvpub1]

Account: [*******@gmail.com]
Project: [MY_PROJECT]

Current Properties:
  [core]
    project: [MY_PROJECT]
    account: [******@gmail.com]
    disable_usage_reporting: [False]

app.yaml contents:
runtime: python27
api_version: 1
threadsafe: false

libraries:
- name: jinja2
  version: latest

- name: webapp2
  version: latest

- name: lxml
  version: latest

- name: numpy
  version: "1.6.1"

builtins:
- remote_api: on

inbound_services:
- mail

handlers:
- url: /assets
  static_dir: assets

- url: /static
  static_dir: static

- url: /admin/.*
  script: MY_PROJECT.app
  login: admin

- url: /favicon\.ico
  static_files: assets/img/favicon.ico
  upload: assets/img/favicon\.ico

- url: /.*
  script: MY_PROJECT.app```

A: Solved, for those who having similar issues:
I Was using:

*

*gcloud app deploy --project=MY_PROJECT

But it works if you specify the version flag (which is optional according to Google's documentation)

*

*gcloud app deploy --project=MY_PROJECT --version=1