text:
Q: Connect to bluetooth device via Hands Free Profile programatically on Android We have a Bluegiga Bluetooth module that is set up to work as hands free device.
After initial pairing, I need my application to initiate connection to it via HFP programmatically. Can this be achieved in Android?

A: Using hidden api works for me!
// get default bluetooth adapter
BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
// get bounded device on Android
Set<BluetoothDevice> devices = mAdapter.getBondedDevices();
if (devices.size() > 0) {
    for (Iterator<BluetoothDevice> it = devices.iterator(); it.hasNext();) {
        BluetoothDevice device = it.next();
        // treat the device the default buletooth device you needed
        mCurrentDevice = device;
        // break;
    }
} else {
    return;
}

// another method to get headset(HFP) profile
mAdapter.getProfileProxy(mContext, new BluetoothProfile.ServiceListener() {
    @Override
    public void onServiceConnected(int profile, BluetoothProfile proxy) {
        Log.e("log", "headset proxy connected");
        try {
            BluetoothHeadset mCurrentHeadset = (BluetoothHeadset) proxy;
            // check whether or not current device hfp is connected or not, if not,
            // try to connect the channel between phone and device using hidden api
            if (mCurrentHeadset.getConnectionState(mCurrentDevice) != BluetoothHeadset.STATE_CONNECTED) {
                Method connectMethod = mCurrentHeadset.getClass().getMethod("connect", mCurrentDevice.getClass());
                connectMethod.setAccessible(true);
                Boolean returnValue = (Boolean) connectMethod.invoke(proxy, mCurrentDevice);
                Log.e("log", "headset proxy connected " + returnValue);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onServiceDisconnected(int profile) {
        Log.e(LogTag.TAG, "headset profile disconnected");
    }
}, BluetoothA2dp.HEADSET);


text:
Q: Backlinking Many-To-1 relation in Xamarin.Forms using Realm I'm building an app using Xamarin.Forms with Realm as local database and I'm struggling with the following.
The app is consuming an API giving a JSON response like this:
[
    {
        "id": "5bf7029c-1577-4739-b37a-845cee1ef70d",
        "name": "Test",
        "categories": [
            {
                "id": "16db7cef-2f6a-4405-a004-df15864d4dde",
                "name": "Category 1",
                "master_id": "5bf7029c-1577-4739-b37a-845cee1ef70d",
                "rooms": [
                    {
                        "id": "d9246c9f-e8bb-41a9-b9a5-e21f1838de19",
                        "category_id": "16db7cef-2f6a-4405-a004-df15864d4dde",
                        "name": "Room 1",
                    },
                    {
                        "id": "424a592d-8cb3-42a3-acbc-dc67d1ac8ddf",
                        "category_id": "16db7cef-2f6a-4405-a004-df15864d4dde",
                        "name": "Room 2",
                    }
                ]
            }
        ]
    }
]

I have used QuickType to generate C# classes for me:
public class Master : RealmObject
{
    [PrimaryKey]
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("categories")]
    public IList<Category> Categories { get; }

    [JsonProperty("name")]
    public string Name { get; set; }
}

public class Category : RealmObject
{
    [PrimaryKey]
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("master_id")]
    public string MasterId { get; set; }

    [JsonProperty("rooms")]
    public IList<Room> Rooms { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }
}

public class Room : RealmObject
{
    [PrimaryKey]
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("category_id")]
    public string CategoryId { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }
}

With the help of Newtonsoft I am parsing the incoming JSON directly to objects and the database with the following code:
IEnumerable<Master> masters = await Task.Run(() => JsonConvert.DeserializeObject<List<Master>>(json, new JsonSerializerSettings
{
    MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
    DateParseHandling = DateParseHandling.None

}));

realm.Write(() =>
{
    foreach (Master master in masters)
    {
        realm.Add(master);
    }
});

So far everything is working and the Master object including all child objects are created properly. However, I need to be able to access parent data easily. For instance, I want to be able to get the name of the Category when I only have a Room available using a statement like Room.Category.Name.
I have tried several way of achieving this but so far without success. I will elaborate on my attempts, because I have the feeling that I might be close.
My first attempt was by using the Realm Backlink property and added the following attribute to the Room class:
[Backlink(nameof(Category.Rooms))]
public Category Category { get; }

However, adding this property to the Room class results in this error:
Error CS0120: An object reference is required for the non-static field, method, or property 'Room.Category' (CS0120).
If I look at the examples given on the Realm website, I only see examples in which the Backlink is placed on the parent class in stead of the child class what I am trying now, so I'm not sure if this is even possible.
My second attempt was to have the relations populated by the JSON deserialization in reverse, so the Category would not contain a list of Rooms, but the Room would contain the Category (and I would be able to use the backlink as described in the examples that I found). However, only changing the C# models by adding the Category property to a Room and changing the Rooms property in the Category class to a backlink resulted in empty relations as the Category property was not populated at all. Maybe I should change the JsonSerializerSettings to 'enable' this feature, but I could not find any information if this is even possible.
My final attempt was to create a method that uses the CategoryId to give me the Category object from the Room object:
public Category Category
{
    get
    {
        return Realm.Find<Category>(CategoryId);
    }
}

While this seemed to work initially this approach is giving me errors when trying to use the Room.Category relation in queries to Realm (using Linq) as the relation cannot be processed by Realm. I also get a warning when building the app: Warning: Fody/RealmWeaver: Room.Category is not an automatic property but its type is a RealmObject which normally indicates a relationship.
Any help on this matter is highly appreciated.
Thank you in advance.

A: Backlink properties are always collections because nothing prevents you from adding the same room to two different categories. That is why in most examples they are placed on the "parent" class. Still, you could easily add one on the "child" class if you're certain it'll only belong to a single parent:
public class Room : RealmObject
{
    // Other properties

    // Notice that the collection may be private
    // to avoid polluting your public API
    [Backlink(nameof(Category.Rooms))]
    private IQueryable<Category> Categories { get; }

    // May also use FirstOrDefault if you can't guarantee
    // the room will be added to a single Category
    public Category Category => Categories.SingleOrDefault();
}

Keep in mind that you still won't be able to use Category in LINQ expressions because it's not a persisted property that Realm is aware of.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add an extra variable to login and authenticate it? I want to add an extra variable to my custom login and to authenticate it to then add it to an SQL database.
My custom login:
<?php
require('wp-load.php');
require('site_config.php');

function FilterMid() {
    $x = '

                Extra
                <input type="text" class="text" id="user_extra" name="user_extra" />

';
    return $x;
}

function validate_login_extra() {
    $ex = $_POST["user_extra"];
    db_insert("butikk_sjekk", "butikk", "$store"); //custom mysqli function
}
add_filter('wp_authenticate_user','validate_login_extra',10,2);

if ( ! is_user_logged_in() ) { // Display WordPress login form:
    add_filter( 'login_form_middle', 'FilterMid' );
    wp_login_form();
    exit;
}

The thing is. On my login form I can without problem see the extra field. But I cannot figure out how to capture the extra field, authenticate it, than store it. Tried searching the web, and reading the wordpress codex with no help.


text:
Q: Custom Menu for Team / User in MS CRM 2011 Online Does anyone know how to customize the menu in MS CRM 2011 (Cloud) so that certain options (e.g. Marketing) do not appear for some users / teams but continue to appear for the Administrators or Power Users?
Many thanks

A: For the sitemap, you'll want to use the "Privilege" rule.
Here's some documentation on the sitemap:
http://msdn.microsoft.com/en-us/library/gg334430.aspx
Here's an example of using the privilege rule to show/hide areas:
http://worldofdynamics.blogspot.com/2012/04/dynamics-crm-2011-restricthide-settings.html


text:
Q: How to use Twilio in my ASP.NET MVC application I have followed a walk-through on how to set up Twilio in my web application, but I am getting an "Argument cannot be null" error.
Walk-through: http://www.asp.net/mvc/overview/security/aspnet-mvc-5-app-with-sms-and-email-two-factor-authentication
Everything seems to be exactly as he put it, but I am getting an error. If anyone knows why I am getting this error or can spot a difference in my code that would be great.
My Code:
<appSettings>
   <add key="webpages:Enabled" value="false" />
   <add key="SMSAccountIdentification" value="My Identification" />
   <add key="SMSAccountPassword" value="My Password" />
   <add key="SMSAccountFrom" value="My Number" />
</appSettings>

.
public class SmsService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        var Twilio = new TwilioRestClient(
            System.Configuration.ConfigurationManager.AppSettings["SMSAccountIdentification"],
            System.Configuration.ConfigurationManager.AppSettings["SMSAccountPassword"]);
        var result = Twilio.SendMessage(
            System.Configuration.ConfigurationManager.AppSettings["SMSAccountFrom"],
            message.Destination, message.Body
        );
        Trace.TraceInformation(result.Status);
        return Task.FromResult(0);
    }
}

I removed my identification, password, and number but they are correct from Twilio. I simply copied and pasted them.
Also, the rest from the walk-through is exactly the same.
The error occurs on the following line:
var result = Twilio.SendMessage(System.Configuration.ConfigurationManager.AppSettings["SMSAccountFrom"],
            message.Destination, message.Body)

I have also confirmed that message is not null.

A: The error arose because all data coming from my web.config was null. I discovered this by hard-coding values in and it worked. Upon further investigation I discovered that I was using the wrong Web.Config file. I should have been using the global one, but instead I was accidentally using the one in Views.
In short, I was getting null values because I was using the incorrect web.config file.

A: From, destination, or body is null. The error is that an argument provided is null. You should check the values of what you are passing.


text:
Q: Skype Web SDK throwing a few 401 errors I have Skype for Business Online account and trying to configure skype into my web application using Skype for Web SDK.
I followed this tutorial
I am able to authenticate user and get access token from Azure AD. Get user presence and other details. But cannot initiate audio or video calls due to the following errors.

It must be due to some missing configuration. Can any one help me resolving it ?


text:
Q: How to add 5 random numbers which are less than 10? I've created two functions. One to create 5 random numbers to push them into an array. And another one to sum up the numbers. The random number generator is working and making an array perfectly. But the sum is not accurate. I'm unable to find where the problem is.

//Generates 5 random numbers smaller than 10

function pushIntoArray() {
    let arr = [];
    let number;
    for(let i = 0; i < 5; i++) {
        number = Math.floor(Math.random() * 11);
        arr.push(number);
    }
    return arr;
}
console.log(pushIntoArray());

//Adds the numbers in arr
function sumNum(arr) {
    let total = 0;
    for(let i = 0; i < arr.length; i++) {
        total += arr[i];
    }
    return total;
}
let arr = pushIntoArray();
console.log(sumNum(arr));

A: Because you are logging a different set of array values and checking the sum of different set of array values.
I have changed your console.log statement.

//Generates 5 random numbers smaller than 10

function pushIntoArray() {
    let arr = [];
    let number;
    for(let i = 0; i < 5; i++) {
        number = Math.floor(Math.random() * 11);
        arr.push(number);
    }
    return arr;
}

//Adds the numbers in arr
function sumNum(arr) {
    let total = 0;
    for(let i = 0; i < arr.length; i++) {
        total += arr[i];
    }
    return total;
}
let arr = pushIntoArray();
console.log(arr);
console.log(sumNum(arr));

A: You are not performing the sum on the array that you logged in the console. What you are logging is
console.log(pushIntoArray()); // This is displayed in the console

But then you are generating a ney array by calling
let arr = pushIntoArray();

BUT you are performing the sum on the arr array not the one that is displayed in the console.
console.log(sumNum(arr)); // you did not console.log(arr)

The function works correctly, you are just calling it on the wrong thing.

A: the function is working correctly but you are logging a different array of random numbers and calculating the sum of a different array.
//Generates 5 random numbers smaller than 10

function pushIntoArray() {
    let arr = [];
    let number;
    for(let i = 0; i < 5; i++) {
        number = Math.floor(Math.random() * 11);
        arr.push(number);
    }
    return arr;
}
// this array is different (this is not passed to the sumNum function)
console.log(pushIntoArray());

//Adds the numbers in arr
function sumNum(arr) {
    let total = 0;
    for(let i = 0; i < arr.length; i++) {
        total += arr[i];
    }
    return total;
}
// this array is different
let arr = pushIntoArray();
console.log("sum of array:", arr)
console.log(sumNum(arr));


text:
Q: SQLite-Net Extensions: How to get rid of relationship records? Let's say I have a many-to-many relationship like in the official sample:
public class Student
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    public string Name { get; set; }

    [ManyToMany(typeof(StudentSubject))]
    public List<Student> Students { get; set; }
}

public class Subject
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    public string Description { get; set; }

    [ManyToMany(typeof(StudentSubject))]
    public List<Subject> Subjects { get; set; }
}

public class StudentSubject
{
    [ForeignKey(typeof(Student))]
    public int StudentId { get; set; }

    [ForeignKey(typeof(Subject))]
    public int SubjectId { get; set; }
}

If I am now deleting a Student, the relationship record represented by the intermediate object does not get deleted, too. (And if I am enabling cascading deletion, the Subject gets deleted – what should not happen.)
Currently I am cleaning up manually by deleting the record with a custom query, but is there a better way with sqlite-net?

A: You can set to null or an empty list the Subjects property and call UpdateWithChildren on the student object.
student.Subjects = null;
conn.UpdateWithChildren(student);

It will update the student object and its relationships, deleting all the records for that student, which is equivalent to:
conn.Execute("DELETE FROM StudentSubject WHERE StudentId = ?", studentId);

The drawback is that you have one more 'update' statement executing in the database if you let SQLite-Net Extensions handle the relationship.


text:
Q: Custom popover for iPad/iPhone In the iBooks application, the brightness, font and search views subclass UIPopOverController but without border.
Is there any way to mimic those views?

A: The border may be from using a UINavigationController for the popup.  I'd try using a plain UIViewController instead.

A: Here is one https://github.com/werner77/WEPopover the arrow + bg are images, I guess we can replace that with transparent bg.
It can be used with iPhone as well.


text:
Q: What is the best practise for assigning an EC2 EIP after starting an instance? I would like to auto-assign an EIP to an instance when it is started. I know I can write a script to stop/start the instance and assign the EIP I want using the EC2 tools, but that depends on me stopping/starting the server. In the case of an EC2 outage or hardware failure where Amazon stops/starts my instance, the EIP would not be reassigned.
I asked someone this question before and they cryptically mentioned that it could be done via script from inside the box after boot. Then they went offline so I could not follow up.
Is there any way to tie an EIP to an instance at boot time?

A: You can do it with something like this, in the /etc/rc.local on the server in question:
ec2-associate-address --private-key /root/private_key.pem --cert /root/public_key.pem <eip-address> -i `curl http://169.254.169.254/latest/meta-data/instance-id

A: Use a VPC, then you won't have to worry about that problem.
Here is a bash i wrote to change EIP on any VPC Instance by using the friendly Name="tag", you can also specify a default region, or add it into the command.
#change vpc instance public IP address (EIP -> NIC|INSTANCE)
#usage "changeip [instance friendly tag=Name] [region]"
#example "changeip my.instnace us-west-1"
#dafault region is us-west-1 (you must include --region for $region default)
#for VPC instances only
function changeip {
    if [[ ! $1 ]]; then
        echo 'Error : You must provide tag name for instance'
        echo 'Example:  changeip [friendly name]'
        return
    fi
    if [[ $2 ]]; then
        region='--region '$2
        echo 'Using region '$2
    else
        region='--region us-west-1' #sets default region
        echo 'Using default '$region
    fi
    name=$1
    instance=$(ec2-describe-instances $region | grep Name | grep $name | cut -f3)
    if [[ ! $instance =~ ^('i-'[A-Za-z0-9]*)$ ]]; then
        echo 'Error : Getting the instance id'
        echo $instance
        return
    fi
    echo 'Applying to '$1 '=> '$instance
    echo 'Please wait....'
    ip_new=$(ec2-allocate-address $region -d vpc | cut -f2)
    if [[ ! $ip_new =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        echo 'Error : Getting a new IP address'
        echo $ip_new
        return
    fi
    new_idas=$(ec2-describe-addresses $region $ip_new | cut -f 5) >> /dev/null
    if [[ ! $new_idas =~ ^('eipalloc-'[A-Za-z0-9]*)$ ]]; then
        echo 'Error : Getting New IP allocation id eipalloc'
        echo $new_idas
        return
    fi
    ip_old=$(ec2-describe-addresses $region | grep $instance | cut -f2)
    if [[ ! $ip_old =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        echo 'Error : Getting old IP address'
        echo $ip_old
        return
    fi
    id_dis=$(ec2-describe-addresses $region $ip_old | cut -f 6)
    if [[ ! $id_dis  =~ ^('eipassoc-'[A-Za-z0-9]*)$ ]]; then
        echo 'Error : Dissasociating Old IP'
        echo $id_dis
        return
    fi
    id_release=$(ec2-describe-addresses $region $ip_old | cut -f 5) >> /dev/null
    if [[ ! $new_idas =~ ^('eipalloc-'[A-Za-z0-9]*)$ ]]; then
        echo 'Error : Release Old IP'
        echo $id_release
        return
    fi
    ec2-disassociate-address $region -a $id_dis  >> /dev/null
    sleep 8
    ec2-release-address $region -a $id_release >> /dev/null
    ec2-associate-address $region -i $instance -a $new_idas >> /dev/null
    echo 'SUCCESS!'
    echo 'Old = '$ip_old
    echo 'New = '$ip_new
}

A: Agree with Eric, that option is not wise in terms of security.
Another option would be to have another machine, with credentials in it, in charge of responding to requests from other machines.
E.g.: Machine with my credential is EC2-1.
You launch perhaps 2 machines to run your web servers, EC2-2 and EC2-3. When they bootstrap, they can "signal" this to EC2-1, which in turn will run the API call to associate EC2-2 and EC2-3 to two Elastic IPs. This way, you have to make EC2-1 VERY secure, and you are not at risk with the other machines.
Best,
Simone


text:
Q: Is there a way to test if an input is a number in C++? Question's all in the title.
I'm making a calculator and I obviously need input. I use the cin>> function but I was wondering if there is a way to test the input to find out if it's a number.
If I enter anything that isn't a number the program crashes. Is there a built in function/operator? Please help!

A: The input operator will only read to an integer if the input is a number. Otherwise it will leave the characters in the input buffer.
Try something like this
int i;
if (cin >> i)
{
    // input was a number
}
else
{
    // input failed
}

A: atoi and sscanf are your friends, or just compare if the entered charcode is within the "0"-"9" range


text:
Q: How do you define multiple query or mutation in GraphQLSchema I am new to GraphQL. Forgive me if this is obvious.
Beside using buildSchema, is there a way to define more than one query/mutation using new GraphQLSchema?
This is what I have right now.
const schema = new graphql.GraphQLSchema(
    {
        query: new graphql.GraphQLObjectType({
            name: 'RootQueryType',
            fields: {
                count: {
                    type: graphql.GraphQLInt,
                    resolve: function () {
                        return count;
                    }
                }
            }
        }),
        mutation: new graphql.GraphQLObjectType({
            name: 'RootMutationType',
            fields: {
                updateCount: {
                    type: graphql.GraphQLInt,
                    description: 'Updates the count',
                    resolve: function () {
                        count += 1;
                        return count;
                    }
                }
            }
        })
    });

A: Multiple "queries" are actually just multiple fields on one Query type. So just add more fields to that GraphQLObjectType, like so:
query: new graphql.GraphQLObjectType({
    name: 'RootQueryType',
    fields: {
        count: {
            type: graphql.GraphQLInt,
            resolve: function () {
                return count;
            }
        },
        myNewField: {
            type: graphql.String,
            resolve: function () {
                return 'Hello world!';
            }
        }
    }
}),


text:
Q: How do I pass a function (written externally) and allocate to a column in pandas python? def calc1(tentative_valuations, previous_buying_price):
  return tentative_valuations - previous_buying_price

#mortgage calculator
def calc2(loanper, previous_buying_price):
  return loanper * previous_buying_price

#indicative paid interest to date **REQUIRES ACCESSOR** ###################
calc3 = int(lookups((ym_between(b, a)[0]), (ym_between(b, a)[1]), 'Cum Interest Paid'))

# #net indicative capital gain today #######################################
calc4 = calc1(tentative_valuations, previous_buying_price) - calc3
#print(calc4)

# #to calculate psf before
def calc5(previous_buying_price, area):
  return previous_buying_price/area

# #to calculate psf after
def calc6(tentative_valuations, area):
  return tentative_valuations/area

#print(calc5(previous_buying_price,area))
#print(calc6(tentative_valuations, area))

# #annualised ##########################################
def calc7():
  return round((((calc6(tentative_valuations, area)/calc5(previous_buying_price, area))**(1/(ym_between(b,a)[0]+ ym_between(b,a)[1]/12))) - 1)*100,2)
#no problem
#print(calc7())

#indicative paid principal to date
calc8 = int(lookups((ym_between(b, a)[0]), (ym_between(b, a)[1]), 'Cumulative Paid Principal'))

#indicative balance
calc9 = (loanper * previous_buying_price) - calc8

  #create the dataframe.
    df2 = pd.DataFrame(columns=['Gross Indicative Capital Gain Today', 'Net Indicative Capital Gain Today','Indicative Average Gross Annual Capital Gain', 'Indicative Paid Principal to Date ', 'Indicative Paid Interest to Date',
                        'Indicative Balance'])
    df2['Gross Indicative Capital Gain Today'] = calc1(tentative_valuations, previous_buying_price)
    df2['Net Indicative Capital Gain Today'] = calc3
    df2['Indicative Average Gross Annual Capital Gain'] = calc7()
    df2['Indicative Paid Principal to Date'] = calc8
    df2['Indicative Paid Interest to Date'] = calc3
    df2['Indicative Balance'] = calc9
    df2.head()

when i call df2, nothing seems to appear only the headers? all the calc are either variables or functions that have output. Rather new to pandas (my 2nd day learning), would appreciate the help thank you guys :)

A: Calling df2 directly won't do anything.
Change the last line to this:
print(df2)

A: you cannot assign types like, int, bool to specific columns in a data frame like that you have surround it in an array like this:
df2['Indicative Paid Principal to Date'] = [calc8]

if you want to add values to a new row you can do this
new_values = [calc1(tentative_valuations, previous_buying_price), calc3, calc7, calc8, calc3, calc9]
df2.loc[0] = new_values


text:
Q: Spreedly Integration .Net Web App I'm thinking about integrating Spreedly into my webapp to handle the payments & subscriptions. It's a .Net MVC app, however I could do the payment form in .Net Web Forms if needs be.
I'm just looking through the Spreedly API documentation, and the examples appear to use curl commands which I am very unfamiliar with, e.g. example .
I've googled (and maybe I'm googling for the wrong thing) and while I get lots of websites giving me lots of different examples of curl commands, I am still unsure how to actually use them in the context of a .Net web page?
Any help/links/etc to enlighten me would be much appreciated :)

A: I've implemented a NuGet package that could help you....
You can also browse the code on GitHub to see how curl maps to HttpClient, for example...

A: Here's a question that discusses implementing a cURL request using a C# WebRequest -
cURL with user authentication in C#
Here's the .NET binding on the cURL website -
http://curl.haxx.se/libcurl/dotnet/
Finally, this Google search got me a sizable number of results, which seem to be relevant to what you're looking for -
http://www.google.com/search?hl=en&q=C%23+.NET+cURL


text:
Q: How many websockets can client receive per second? I have simple javascript websocket on client side
var ws = new WebSocket("ws://myhost:myport");
ws.onopen = function(e) {
    // handle sockets here
};

I am going to write C++ server that might send 10,000-100,000 sockets to client per second.
Question: is it good performance for websockets? Will it work fine without delays? What is the limit number of sockets I can send without delays?


text:
Q: Invoke python script from C# and pass parameters to a function dynamically How to call python code from C# dynamically and pass parameters dynamically.
Python script can accept 2 or 3 0r 4..parameters.
Wen I invoke function getting error says "str is not callable"
This is my python script
#this method can accept 2 or 3 or 4 or--parameters dynamically
 class AddTest:
  def CalcAdd(self, Numb1, Numb2):
    return Numb1 + Numb2;

This is my c# code
  var engine = Python.CreateEngine();
        var scope = engine.CreateScope();

        ObjectOperations ops = engine.CreateOperations();

        var compilerOptions = (PythonCompilerOptions)engine.GetCompilerOptions();
        //compilerOptions.Module = IronPython.Runtime.ModuleOptions.co
        //ErrorSink errorSink = null;
        //ErrorListener errorListener = new ErrorSinkProxyListener(errorSink);
        var scriptSource = engine.CreateScriptSourceFromFile(@"C:\Nidec\PythonScript\download_nrlist.py", Encoding.UTF8, Microsoft.Scripting.SourceCodeKind.File);
        try
        {
            var compiledCode = scriptSource.Compile();
            compiledCode.Execute(scope);
            var pyScope = engine.ExecuteFile(@"C:\Nidec\PythonScript\download_nrlist.py", scope);
            var variables = pyScope.GetVariableNames();
            var type = variables.ToList().Where(x => !x.Contains("_")).ToList().FirstOrDefault();
            var clsName = scope.GetVariable(type);
            var clsObje = ops.CreateInstance(clsName);
            var f = ops.GetMember(clsObje, "CalcAdd");
            var __func__ = ops.GetMember(f, "__func__");
            var t = __func__.GetType();
            PropertyInfo property = t.GetProperty("ArgNames", BindingFlags.Instance | BindingFlags.NonPublic);
            var arguments = property.GetValue(__func__, null) as string[];
            object[] obj = new object[arguments.Length-1] ;
           //int[] obj = new int[arguments.Length-1] ;
            for (int i = 0; i < arguments.Length-1; i++)
            {
                obj[i] = i + 1;
            }
            var ccResult = ops.Invoke("CalcAdd", obj);// error str is not callable
        }

A: object pythonClass = engine.Operations.Invoke(scope.GetVariable(clsName));

 var results = engine.Operations.InvokeMember(pythonClass, "CalcAdd", obj);


text:
Q: Makers google maps javascript. O que está errado? Estou criando um script para adicionar os valores de um vetor em um mapa (somente as posições 0 e 1), porem nada acontece. no console não há erros.
Script:
function marcar(){
  var marcacao = function(position){

    // Gravar dados da posição capturada em uma variável...
    var coords = position.coords;

    var pontos = [
      [-30.403.601, -56.744.400,  queimada],
      [-30.403.601, -56.744.400,  queimada],
      [-30.403.601, -56.744.400,  queimada],
      [-30.403.601, -56.744.400,  queimada],
      [33.475.201,  -98.228.699,  queimada],
      [32.294.300,  -97.525.497,  queimada],
      [32.294.300,  -97.525.497,  queimada],
      [32.294.300,  -97.525.497,  lixo urbano],
      [35.789.001,  -109.478.699, raios],
      [28.040.701,  -83.462.997,  falta de agua],
      [28.040.701,  -83.462.997,  falta de agua],
      [33.176.102,  -122.465.401, queimada],
      [-22.569.380, -44.964.485,  queimada],
      [33.176.102,  -122.465.401, raios],
      [21.985.701,  -95.394.997,  queimada],
      [21.985.701,  -95.394.997,  falta de agua],
      [20.675.800,  -109.457.497, raios],
      [20.675.800,  -109.457.497, queimada]
    ];

    for (var i = 0; i<pontos.length; i++){
      var ponto = pontos[i];
      // GOOGLE MAPS: Mostrar marcador no mapa...
      var map = new google.maps.Map(
        document.getElementById("map"),
        {
          center : new google.maps.LatLng( ponto[0], ponto[1] ),
          zoom : 5,
          mapTypeId : google.maps.MapTypeId.ROADMAP
        }
      );
      var image = 'images/ray001.png';
      var marker = new google.maps.Marker(
        {
          title : "VOCÊ ESTÁ AQUI: "+ponto[0]+", "+ponto[1],
          position : new google.maps.LatLng(ponto[0], ponto[1]),
          map: map,
          icon: image
        });
      marker.setMap(map);
    }
  }

  // Caso falhe na captura, faça isso...
  var fnFalhar = function(error){
    navigator.notification.alert("Erro ao capturar posição: "+error.message, "INFORMAÇÃO");
  }

  // Opções para acessar o GPS...
  var opcoes = { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true };

  // CAPTURAR POSIÇÃO: Chamada a API de Geolocalização (GPS) via Apache Cordova
  navigator.geolocation.getCurrentPosition(marcacao, fnFalhar, opcoes);
}
marcar();

A: Fiz um teste com seu código e o mesmo apresentou problemas na declaração dos valores do array, exceto isso, funcionou perfeitamente.
Segue um exemplo de como você deve declarar os valores.
var pontos = [
  [-30.403601, -56.744400,  'queimada']
];

Em sua declaração, [-30.403.601, -56.744.400,  queimada], o JavaScript não identifica -30.403.601 como um valor número e queimada como uma string.


text:
Q: Matching case words in strings python I'm trying to write a function that check if a word is in string OR the word has len(word)-1 chars in common with each word in the string.
For example:
word: match   string: There is a match   -> True
word: matck   string: There is a match   -> True

The output need to be True for both examples because matck-1=matc and match-1=matc
I have wrote the below code so far:
for idx, f in enumerate(files):
    for word in words:
        if term in f:
            numOfWord[idx] += 1
        else:
            file_words = f.split()
            for f_word in file_words:
                if word[:-1] == file_word[:-1]:
                    numOfWords[idx] += 1

But it's not good because I have a very big list of word and very big dir of long files so the run time is not realistic.

A: You can use Levenshtein distance to check that
def minimumEditDistance(s1,s2):
if len(s1) > len(s2):
    s1,s2 = s2,s1
distances = range(len(s1) + 1)
for index2,char2 in enumerate(s2):
    newDistances = [index2+1]
    for index1,char1 in enumerate(s1):
        if char1 == char2:
            newDistances.append(distances[index1])
        else:
            newDistances.append(1 + min((distances[index1],
                                         distances[index1+1],
                                         newDistances[-1])))
    distances = newDistances
return distances[-1]

print(minimumEditDistance("kitten","sitting"))
print(minimumEditDistance("rosettacode","raisethysword"))

https://rosettacode.org/wiki/Levenshtein_distance#Python


text:
Q: Is there a way to assign/edit String[i][j] value on runtime in dart? CODE
void main() {
  List<String> str = ["hello", "world"];
  for (int i = 0; i < str.length; i++) {
    for (int j = 0; j < str[i].length; j++) {
      if (str[i][j] == 'o') {
        str[i][j]='e';
        print('$i,$j');
      }
    }
  }
  print(str);
}

The Error I get
The operator '[]=' isn't defined for the class 'String'.
Try correcting the operator to an existing operator, or defining a '[]=' operator.
        str[i][j]='e';

If i comment this line //str[i][j]='e';  i get the location of the characters but i am unable to edit the string like we usually do in C++

A: String in Dart does not have a []= operator which means you cannot set a value on the String using the [] operator like you are trying to do.
This makes sense since String is immutable in Dart and calling the []= does not allow us to return anything, so we would not be able to get the modified String back.
We can instead call .replaceRange() on the String which allow us to replace a part of a String with some other String value. The method will return a new String with the change (since we are not allowed to change any existing String object).
With this, we can rewrite your example to:
void main() {
  List<String> str = ["hello", "world"];
  for (int i = 0; i < str.length; i++) {
    for (int j = 0; j < str[i].length; j++) {
      if (str[i][j] == 'o') {
        str[i] = str[i].replaceRange(j, j + 1, 'e');
        print('$i,$j');
      }
    }
  }
  print(str);
}

Which will output:
0,4
1,1
[helle, werld]

If the purpose is to replace all o with e, a more efficient solution would be to use the replaceAll() method:
void main() {
  List<String> str = ["hello", "world"];

  for (int i = 0; i < str.length; i++) {
    str[i] = str[i].replaceAll('o', 'e');
  }

  print(str); // [helle, werld]
}

A: Simple way: Map and replaceAll
 List<String> str = ["hello","world"];

    str = str.map((s)=>
       s.replaceAll("o", "e")
      ).toList();

    print(str);

Result


text:
Q: Unexpected end of file in shell script I have script:
#!/bin/sh
PSQLPATH=$1
USER=$2
if [ -z ${PSQLPATH} ]; then
   echo "incorrect path param"
   echo "Usage: $0 psqlpath username"
   exit 1
fi
if [ -z ${USER} ]; then
   echo "incorrect username param"
   echo "Usage: $0 psqlpath username"
   exit 1
fi
${PSQLPATH}/createdb -h localhost -U ${USER} highway2
${PSQLPATH}/psql -f createDatatable.sql -h localhost -d highway2 -U ${USER}
${PSQLPATH}/psql -f insertStatements.sql -h localhost -d highway2 -U ${USER}
echo "execute passed"
exit 0

When I am trying to execute it like ./script.sh I got an error line 19: unexpected end of file. What I am doing wrong?

A: Check your line endings. When I run your script (under Cygwin), with no arguments given, I get your error if I have Windows-style line endings (\r\n). When I use Unix-style line endings, by eliminating the \rs, the script runs, complaining about my not having given the correct parameters.


text:
Q: Combine Table Records per Day to Create 'Last Week' page I apologize if this has been asked before.. I'm very new to developing and although I've tried searching a lot, I'm not really sure what to look for.
Anyway so I have a table which counts records being entered per day. It looks something like this (each record is represented by a letter) (assume today's date is 27/01/2013):
RECORD | COUNT | DATE
------A-----|-----4-----|27/01/2013
------B-----|-----7-----|27/01/2013
------B-----|-----3-----|24/01/2013
------C-----|-----8-----|22/01/2013
------A-----|-----2-----|19/01/2013

Each new post is checked in the table and it updates the count if the record already exists on the current day, otherwise a new record is created.
For the page which prints the records which have been added 'TODAY', I have the MySQL query
SELECT * FROM `table` ORDER BY `date` DESC, `count` DESC LIMIT 1000

and use a php 'if' statement to only print the records where the date('Y-m-d') = date in the table. So only the records and the corresponding count which has been entered that day are printed.
- the table above would produce the result:
1. B 7
2. A 4

What I would like is a page which prints the records which have been entered in the last week. I know I can use DATE_SUB(now(),INTERVAL 1 WEEK) AND NOW(), to print the records from last week but I need to duplicate records to be combined and the counts added together.. so the result for this table would look like this:
1. B 10
2. C 8
3. A 4

How would I go about combining those duplicate records and have a list of records ordered by count? Is this the best method to get a 'last week' record count, or is there another table structure which would be better?
Again I'm sorry if this a silly question or if my explanation was long-winded, but just some simple pointers will be really appreciated.

A: Using GROUP BY will allow you group related records together
SELECT `record`
     , SUM(`count`) AS `count`
FROM `table`
WHERE `date` > `date` - INTERVAL 1 WEEK
GROUP BY `record`
ORDER BY `count` DESC
LIMIT 1000

A: Try this
SELECT `record`, SUM(`count`) AS `count`
  FROM `table`
 WHERE `date` > DATE_SUB(CURDATE(),INTERVAL 1 WEEK)
 GROUP BY `record`
 ORDER BY `count` DESC

And you can LIMIT 1000 grouped resultset if you need to


text:
Q: How Can I generate sequence No in SQL Query? Id  Desc     Sequenceno
-----------------------------
84  TEST         1
84  TEST2        2
84  TEST3        3
85  IPhone       1
85  IPhone1      2
87  Nokia        1
88  Vivo         1
88  Vivo1        2

I have Id and Desc Column. How can I get Sequenceno Column like above?
Thanks in Advance.

A: Use the ANSI-standard row_number() function:
select t.*, row_number() over (partition by id order by [desc]) as seqnum
from t;

A: Try this:
SELECT
  Id, [Desc],
  ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Id) AS Sequenceno
FROM #Temp;


text:
Q: cifs mounts with wrong uid, gid (buster -> bullseye) Context :
Existing debian buster acting as CIFS / SMB client
Problem :
After migration from buster to debian bullseye, mount point is still working but uid and gid option are ignored at the filesystem level (but are correct within the mount command's output)
cat /etc/fstab :
...
//192.168.0.1/data    /mnt/data    cifs    _netdev,nodev,nosuid,noexec,credentials=/etc/credentials,uid=myuser,gid=mygroup,file_mode=0660,dir_mode=0770,vers=1.0     0       0
...

mount : (uid 101 is myuser and gid 101 is mygroup so here values are correct)
...
//192.168.0.1/data on /mnt/data type cifs (rw,nosuid,nodev,noexec,relatime,vers=1.0,cache=strict,username=cifslogin,uid=101,forceuid,gid=101,forcegid,addr=192.168.0.1,soft,unix,posixpaths,serverino,mapposix,acl,rsize=1048576,wsize=1048576,bsize=1048576,echo_interval=60,actimeo=1,_netdev)
...

ls -la /mnt/data :
drwxr-xr-x 3 1100 users    0 Sep 13 00:01 .
...

A: After some trial and error I found out that there exist two options forceuid and forcegid that can be leveraged to ignore a samba server's unix extension.
cat /etc/fstab :
...
//192.168.0.1/data    /mnt/data    cifs    _netdev,nodev,nosuid,noexec,credentials=/etc/credentials,uid=myuser,forceuid,gid=mygroup,forcegid,file_mode=0660,dir_mode=0770,vers=1.0     0       0
...


text:
Q: Bootstrap Modal not closing on X or Close button, but does on ESC or clicking in the overlay Well, the title says it all. I have a default (copied from Bootstrap docs) modal which opens using $('#myModal').modal(); but under no circumstances the modal closes with the dismiss X or cancel button. Console doesn't log any errors. When I press ESC or at any point in the gray transparent overlay it does get closed.
For the sake of being sure I've disabled all other javascript code in my project. I've been staring at this for an hour now. What am I missing? Have done this many times before but I'm baffled with this behavior...

A: I've just found that with bootstrap 4 if you create a modal with javascript and add it to the document to display it it doesn't set any listener events for the data-dismiss action, so have had to do it myself:
$('#modalId').on('click', 'button.close', function (eventObject) {
    $('#modalId').modal('hide');
});

A: Check if you have data-dismiss attribute as follows
In X icon
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Close Button
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

If you have them, please copy and paste your code that might help to identify what is causing the problem

A: Does the close button have data-dismiss="modal" ?
From bootstrap:
<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

You could try to toggle or hide manually,
$('#myModal').modal('hide')

A: Well, after I was sure I'd ruled any external factor out I tried using the bootstrap javascript file from BootstrapCDN.com rather than my pulled in version using composer. You know what? There was a bug in my pulled in version causing this behavior...


text:
Q: how to make a jQuery event apply to all selected elements including the ones added as a consequence of the event? I want to create a function that adds a h1 for each h1 clicked, I have coded one that works, but it only works with the original h1, and the newly added h1s do not generate anything when clicked.
 $(document).ready(function(){
        $("h1").click(function(){
              $("body").after("
this is an added header
");
        });
  });

A: You're best using a delegated event for this:
$("body").on("click", "h1", function(event){
    $(this).after("
...
");
});

Basically, there's only one event handler on the body that's firing if a click event happens from within a h1 tag. It's inefficient to repeat the same listener multiple times across different elements, especially when you need future elements to trigger that behaviour too. That's precisely one of the reasons why delegated handlers exist.

A: Use event delegation
$(document).ready(function() {
  var body = $("body"); // cache selector
  $(this).on("click", "h1", function() {
    body.after("
this is an added header
");
  });
});


text:
Q: Parsing mathematical expressions in python So I'm currently working on a python program to parse mathematical expression strings and evaluate them. I currently have the following code:
def evaluate(string):
    expr = [a for a in string if a!=" "]
    for i,char in enumerate(expr):
        if char=="/":
            tmp = int(expr[i-1])/int(expr[i+1])
            expr[i+1] = tmp
            expr.pop(i)
            expr.pop(i-1)
        elif char=="*":
            tmp = int(expr[i-1])*int(expr[i+1])
            expr[i+1] = tmp
            expr.pop(i)
            expr.pop(i-1)
    for i,char in enumerate(expr):
        if char=="-":
            tmp = int(expr[i-1])-int(expr[i+1])
            expr[i+1] = tmp
            expr.pop(i)
            expr.pop(i-1)
        elif char=="+":
            tmp = int(expr[i-1])+int(expr[i+1])
            expr[i+1] = tmp
            expr.pop(i)
            expr.pop(i-1)
    return expr

I gave it the input 2 / 2 + 3 * 4 - 6 * 2 and it returned ["13", "-", "12"]. Some steps I took to diagnose the problem was:
1. I moved the return expression to between the two for loops. The program then returned ["1.0", "+", "12", "-", "12"], so I know that the second loop is only evaluating the +.
2. I thought it might be a problem with the - block of code, but when I changed the input to 2 / 2 + 3 * 4 + 6 * 2 it output ["13", "+", "12"]
3. I had it print out i in the second loop, and it printed out 0,1,2. So there's the problem, it is only iterating through the first 3 elements of the list.
I get the feeling the problem has to do with modifying the list in place, and that screws up enumerate somehow. But what is the issue such that the first for loop works fine and it breaks the second? Any help would be appreciated as I am very confused

A: Use this improved code:
def evaluate(string):
    expr = [a for a in string if a!=" "]
    while( ('*' in expr) or ('/' in expr) or ('+' in expr) or ('-' in expr) ):
        for i,char in enumerate(expr):
            if char=="/":
                expr[i+1] = int(expr[i-1])/int(expr[i+1])
                del expr[i]
                del expr[i-1]
            elif char=="*":
                expr[i+1] = int(expr[i-1])*int(expr[i+1])
                del expr[i]
                del expr[i-1]
        for i,char in enumerate(expr):
            if char=="-":
                expr[i+1] = int(expr[i-1])-int(expr[i+1])
                del expr[i]
                del expr[i-1]
            elif char=="+":
                expr[i+1] = int(expr[i-1])+int(expr[i+1])
                del expr[i]
                del expr[i-1]
    return expr


text:
Q: Loading properties in chrome extensions I am working in a project where I inherited a lot of code with some decisions that I have to live with, but some I have to change. One of them there are a lot of hardcoded values for hostnames. The project is a chrome extension.
I am trying to load properties, such as backend host names in my chrome extension. I know that there is a way to load a JSON file like this, however, this is async and I don't believe that it will work for me.
So I created a JS file that has the properties config.js in the form of an object like so:
const config = {
    "envs":{
        "dev": {
            "protocol": "https",
            ...
         }
     }
};
export {config as default};

But then I realized that I have some JS files that are modules and they can make user of import statements and others are not modules. So you can have background.html looking like this:
<script src="/libs/socket.io.js"></script>
<script src="/libs/paho-mqtt.js"></script>
<script type="module" src="myscript1.js"></script>
<script src="myscript2.js"></script>
<script src="myscript3.js"></script>

Imagine that myscript1.js above needs to grab a value from the config.js I mentioned. It will import config from "config.js". But then what if myscript2.js or myscript3.js need to read that same config, what do I do? 2 and 3 are classic scripts and therefore I can not use imports. I feel like I am missing something so obvious.
Any ideas? thank you in advance.


text:
Q: Selecting specific records in a column else all of them I am building a website in ASP.NET/ SQL Server 2012.
My question is, I have drop down boxes that contain the following strings as an example.
<asp:ListItem>Doesn't matter</asp:ListItem>
<asp:ListItem>I don't drink</asp:ListItem>
<asp:ListItem>Occasionally/Socially</asp:ListItem>
<asp:ListItem>I party hard</asp:ListItem>

What sort of SQL command do I need to in order to be able to use logic like this pseduo.
If SelectedItem is 'Doesn't Matter' return all rows in column
ELSE IF
Retrieve records in column where drinking_habit = ListItem.

I dont want to use a simple IF ELSE stored procedure because I have lots and lots of filtering options available and making else seems really badly designed.
Many thanks!

A: Use WHERE with OR:
SELECT IdCol, TextCol
FROM dbo.Table
WHERE @TextCol = 'Doesnt matter' OR TextCol = @TextCol

On this way TextCol will only be evaluated if the parameter is different than Doesn't matter.
Note that i've used the text value just for demonstration purposes. You should use the IdCol instead(text can change anyway).


text:
Q: which
* element was clicked? I have 5 (maybe more) li elements.

One

Two

Three

Four

Five

I want to get which elements was clicked(which row??). If random user clicks  Two I want to get $("li:eq(1)")(as typed).
How can I get this result?

A: You can use jQuery.index. Something like this:
$('ul > li').click(function() {
   alert($(this).index($(this).parent('li'));
});

A: $("#ulId li").click(function() {
   $(this).something(); //the clicked li is $(this), and you can invoke functions on it.
})

A: You can get the text node value of the clicked item with:
$('li').click(function(){
   var clicked = $(this).text();

  alert(clicked+" was clicked");
});

A: Working example: http://jsfiddle.net/tbugV/1/
$("#mylist li").each(function(index)
                     {
                         $(this).data("row", index);
                     }).
                click(function()
                      {
                        alert($(this).data("row"));
                      });

A: If you give your elements an id such as

One

Two

Three

Four

Five

Then you can use $(this).attr(id) in the click handler to determine the id of the clicked element. This will also allow to give non sequential ids to your elements, and will detach what's written in the
 from the actual value you get.
Also, you can encode multiple value in the id (for instance el_5_3) which can be useful sometimes.
$("#mylist li").click(function()
                      {
                      var id = $(this).attr("id").split("_");
                      alert("You clicked the element with id="+id[1]);
                      });

Working example:
http://jsfiddle.net/jFrdp/

A:  $('html').click(function() {
     var el = e.target;
     alert(el);
 });

A: As people just keep posting code, and no explanations, I will try the other way around...
The click event handler is called in the scope of the clicked element, so you can use the this keyword to access the element. You can use $(this) to get a jQuery object that contains the clicked element, so that you can use jQuery methods on it.
Example:
$(document).ready(function(){

  $('ul li').click(function({
    var text = $(this).text();
    alert('You clicked on the item with the text "' + text + '"');
  }));

});

A: $('li').click(function(){
alert($(this).html());
});

This code will alert one when user will click the one button.


text:
Q: overloading in inheritance c++ so I got this problem while trying to overload in c++:
I have those classes:
class Data
{
public:
    void virtual f(){cout<<"In data!"<<endl;}
};

class A: public Data
{
public:
    void f(int x){cout<<"Class A int is: "<<x<<endl;}

};

then I do:
Data *D=new A();
D->f(4);

I expect the Data's f() function to do to class A's f() function since I did it virtual, but it won't.
Any ways to make it work?

A: That's not the same function, the one in the derived class takes an int parameter.
That shouldn't even compile, because Data doesn't have a method called f(int).
For polymorphism to work, you need the same signature:
class Data
{
public:
    void virtual f(int){cout<<"In data!"<<endl;}
    //              |
    //        dummy parameter
};

class A: public Data
{
public:
    void f(int x){cout<<"Class A int is: "<<x<<endl;}
};

A: You need to have the same parameters when overloading. Your compiler sees doStuff(int a), doStuff(String a) and doStuff() as different functions. Be sure they all have the same parameters when you're overloading.

A: Overloading does not work across class boundaries.
Here is something you can do to be able to call both using an object of class A -
class Data
{
public:
    void virtual f(){cout<<"In data!"<<endl;}
    //              |
    //        dummy parameter
};

class A: public Data
{
    using Data::f;

public:
    void f(int x){cout<<"Class A int is: "<<x<<endl;}
};


text:
Q: Determine the number of records in an array of records using user input variables I have a code written in Pascal. I have a record type called recordPembeli and I have an array[1..x] of recordPembeli. The x in this array will be the length of the data which the user determines in the body of program readln(x).
Here is the program:
program iniSesiDua;
uses crt;

type
    recordPembeli = record
        nama : string[5];
        jumlahPembelian : integer;
    end;

var
    x : integer
    dataPembelian : array[1..x] of recordPembeli;

begin
    clrscr;

    write('Masukkan jumlah pembeli : ');readln(x);

    readln;

end.

I try it and it says :

Warning: Variable "x" does not seem to be initialized
Error: Can't evaluate constant expression

Can I even determine the length of the data by user input in array of record or is it forbidden?

A:
Can I even determine the length of the data by user input in array of records...?

Yes you can, but the array must be dynamic, which means that the number of elements is not defined at compile time, but at run time:
var
  x: integer;
  dataPembelian: array of recordPembeli; // dynamic array, no size

begin
  write('Masukkan jumlah pembeli : ');readln(x); // Get length from user
  SetLength(dataPembelian, x);                   // create the records in the array

Note that the indexing of the array elements starts from 0.

A: The bounds of an array (unless it is a dynamic array) must be a compile time constant.
You are using a variable, and one that hasn't been initialized at that.

A: The variable determining the length x and the array's declaration cannot be in the same block.
You will need to use a nested block like this:
program iniSesiDua(input, output);
    type
        recordPembeli = record
                nama: string(5);
                jumlahPembelian: integer;
            end;

    var
        x: integer;

    procedure readAndProcessPembelin;
    var
        dataPembelian: array[1..x] of recordPembeli;
    begin
        { You read and process data here. }
    end;

    { === MAIN =============================================== }
    begin
        write('Masukkan jumlah pembeli : ');
        readLn(x);
        readAndProcessPembelin
    end.

Non-constant subrange bounds are an extension of ISO standard 10206 "Extended Pascal".
Your error messages seem like to have been emitted by the FPC (Free Pascal Compiler).
This processor does not support Extended Pascal (yet).
There you are forced to use an alternative data type,
e. g. a linked list or more conveniently "dynamic" arrays.


text:
Q: Github Copilot Auto complete Quotes and Brackets i have an issue with github copilot's auto complete.
When coding C in vscode, the auto complete suggest me some code but without closing brackets and quotes. how to fix it?
Here is an example of code (just an example, don't care what is it :)), you can see that the suggestion doesn't have the closing quote and bracket.

I tried to change auto complete settings but nothing changed.


text:
Q: How to neatly align long equations one below each other I have seven different equations which I want to left align.
Below is the code I am using to align the equations:
\begin{equation}
\phi_{1} \; = \; n_{20} + n_{02}
\end{equation}

\begin{equation}
\phi_{2} \; = \; (n_{20} - n_{02})^2 + 4n_{11}^2
\end{equation}

\begin{equation}
\phi_{3} \; = \; n_{30} - n_{12}^2 + 3n_{21} - n_{03}^2
\end{equation}

\begin{equation}
\phi_{4} \; = \; n_{30} + n_{12}^2 + 3n_{21} + n_{03}^2
\end{equation}

\begin{multline}
\phi_{5} \; = \; (n_{30} - 3n_{12})(n_{30} + n_{12})[(n_{30} + n_{12}^2) -3(n_{30} + n_{12})^2] + (3n_{12} - n_{03})(n_{21} + n_{03})[3(n_{30} + n_ {12})^2 - (n_{21} + n_{03})^2]
\end{multline}

\begin{equation}
\phi_{6} \; = \; (n_{20} - n_{02})[(n_{30} + n_{12}^2) - (n_{21} + n_{03})^2] + 4n_{11}(n_{30} + n_{12})(n_{21} + n_{03})
\end{equation}

\begin{equation}
\phi_{7} \; = \; (3n_{21} - n_{03})(n_{30} + n_{12})[(n_{30} + n_{12})^2 - 3(n_{21} + n_{03})^2] + (3n_{12} - n_{30})(n_{21} + n_{03})[3(n_{30} + n_{12})^2 - (n_{21} + n_{03}^2)]
\end{equation}

I want the equations to be left align and evenly spaced on each line, i.e. if an equation is too long it should go on to the next line.

A: A single align environment seems right, plus additional line breaks for  equations 5, 6, and 7; the second halves of these equations are indented (by the amount of \quad) relative to the first halves. Note that I've performed alignment on the = symbols, not full left-alignment.

\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{align}
\phi_{1} &= n_{20} + n_{02}\\
\phi_{2} &= (n_{20} - n_{02})^2 + 4n_{11}^2\\
\phi_{3} &= n_{30} - n_{12}^2 + 3n_{21} - n_{03}^2\\
\phi_{4} &= n_{30} + n_{12}^2 + 3n_{21} + n_{03}^2\\
\phi_{5} &= (n_{30} - 3n_{12})(n_{30} + n_{12})[(n_{30} + n_{12}^2) -3(n_{30} + n_{12})^2] \notag\\
&\quad+ (3n_{12} - n_{03})(n_{21} + n_{03})[3(n_{30} + n_ {12})^2 - (n_{21} + n_{03})^2]\\
\phi_{6} &= (n_{20} - n_{02})[(n_{30} + n_{12}^2) - (n_{21} + n_{03})^2] \notag\\
&\quad+ 4n_{11}(n_{30} + n_{12})(n_{21} + n_{03})\\
\phi_{7} &= (3n_{21} - n_{03})(n_{30} + n_{12})[(n_{30} + n_{12})^2 - 3(n_{21} + n_{03})^2] \notag\\
&\quad+ (3n_{12} - n_{30})(n_{21} + n_{03})[3(n_{30} + n_{12})^2 - (n_{21} + n_{03}^2)]
\end{align}
\end{document}

A: You can use align and split:
\documentclass{article}
\usepackage{amsmath}

\begin{document}

\begin{align}
\phi_{1} &= n_{20} + n_{02}
\\
\phi_{2} &= (n_{20} - n_{02})^2 + 4n_{11}^2
\\
\phi_{3} &= n_{30} - n_{12}^2 + 3n_{21} - n_{03}^2
\\
\phi_{4} &= n_{30} + n_{12}^2 + 3n_{21} + n_{03}^2
\\
\begin{split}
\phi_{5} &= (n_{30} - 3n_{12})(n_{30} + n_{12})[(n_{30} + n_{12}^2) -3(n_{30} + n_{12})^2] \\
         &\qquad+ (3n_{12} - n_{03})(n_{21} + n_{03})[3(n_{30} + n_ {12})^2 - (n_{21} + n_{03})^2]
\end{split}
\\
\begin{split}
\phi_{6} &= (n_{20} - n_{02})[(n_{30} + n_{12}^2) - (n_{21} + n_{03})^2] \\
         &\qquad+ 4n_{11}(n_{30} + n_{12})(n_{21} + n_{03})
\end{split}
\\
\begin{split}
\phi_{7} &= (3n_{21} - n_{03})(n_{30} + n_{12})[(n_{30} + n_{12})^2 - 3(n_{21} + n_{03})^2] \\
         &\qquad+ (3n_{12} - n_{30})(n_{21} + n_{03})[3(n_{30} + n_{12})^2 - (n_{21} + n_{03}^2)]
\end{split}
\end{align}

\end{document}

What's the difference with just align and \notag? The equation number in a split is vertically centered (unless the tbtags option is passed to amsmath).


text:
Q: jQuery conflict between scripts I am using CakePHP and  am using 2 javascript scripts one of which relies on jQuery.
On one of these javascripts the $ variable is used which conflicts with jQuery and thus
I had to include the following bit of code in cakephp :
    <?php
    $this->Js->JqueryEngine->jQueryObject = '$j';
    print $this->Html->scriptBlock('var $j = jQuery.noConflict();', array('inline' => false));
 ?>

This made the javascript + jQuery inclusion work fine. I then wanted to add another javascript which requires jQuery - which I have however I get the following error:
Uncaught TypeError: Object function $(element) {  if (arguments.length > 1) {
for (var i = 0, elements = [], length = arguments.length; i < length; i++)
  elements.push($(arguments[i]));
return elements;  }  if (Object.isString(element))
element = document.getElementById(element);  return Element.extend(element);} has no method 'extend'

I am not a massive javascript buff. But this confuses me and obviously there is a conflict - please help me get this jQuery based script work.
Thanks,

A: You need to use the no conflict selector that you defined in the no-conflict section, i.e. $j instead of simply $.


text:
Q: Migrate Magento EE 1.14.3.1 to Magento CE 2.1.7 How to migrate Magento Enterprise Version 1.14.3.1 to Magento Community Version 2.1.7?
I am not getting perfect solution for migrate from M1 Enterprise to M2 Community.
Official Data-migration-tool is not providing solution for this so please help me to migrate Step-by-Step.

A: The Data-migration-tool does not come with such functionality out of the box (and I guess it won't ever have) for obvious reasons not to mention the advantages and features you will loose if you switch from EE to CE.
But leaving this aside and focusing on the technical question, if I were you I would try to extend the tool to do what I want.
How? you may ask.
The data migration tool transfers data from a source database to a destination database and it uses a set of config files where you can specify in what order, what data and how you want your data to be transferred. That is all it does.
By default it comes with 3 modes that need to be executed in order (if you are planning to do a full migration):

*

*Settings: Migrates the system configuration and website-related settings

*Data: Migrates database assets in bulk like catalog, customers, orders...

*Delta: Migrates incremental changes (for example, orders and inventory)
This said, I would start by creating the set of config files needed using the ones already there.

Then, I would first focus on migrate only settings.
Once I'm happy with the results, I would try to migrate data, commenting out the steps I don't need, for example <step title="Log Step"> or <step title="VisualMerchandiser Step"> (it does not exists in CE).
This does not pretend to be a step by step guide (I'm afraid, I don't even have an environment with a 1.14.3.1 database right now to try myself) and of course it will require a lot of trail and error until you get the expected result, but the good news is that is possible :)
Hope it helps.
Important: remember to backup your databases (specially source db) before you start, so you can perform as many tests you need with the confidence that you won't loose your information.
Further readings:

*

*How Migration Works

*Data Migration Tool Technical Specification


text:
Q: BLE RSSI real time value update Kotlin I need help with this project, i use BLE and connect it to smartphone and i can get the RSSI value by "ScanResult" in the ScannerFragment but its a static value in the recyclerview, i dont know what to do to make the RSSI value change in real time as i move my phone away/ closer to the BLE device, so it would jump for example from -50dBm to -60dBm as i move the smartphone away from the BLE device
ScannerFragment

import android.Manifest
import android.app.AlertDialog
import android.bluetooth.*
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import java.util.*
import kotlin.collections.HashSet

class ScannerFragment : Fragment() {

    private lateinit var startButton: Button
    private lateinit var stopButton: Button
    private lateinit var multilateration: TextView
    private lateinit var recyclerView: RecyclerView
    private lateinit var linearLayoutManager: LinearLayoutManager

    private var btManager: BluetoothManager? = null
    private var btAdapter: BluetoothAdapter? = null
    private var btScanner: BluetoothLeScanner? = null
    var beaconSet: HashSet<Beacon> = HashSet()
    var beaconAdapter: BeaconsAdapter? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_scanner, container, false)
        initViews(view)
        setUpBluetoothManager()
        return view

    }

    companion object {
        private const val REQUEST_ENABLE_BT = 1
        private const val PERMISSION_REQUEST_COARSE_LOCATION = 1
    }

    private fun initViews(view: View) {
        startButton = view.findViewById(R.id.startButton)
        stopButton = view.findViewById(R.id.stopButton)
        recyclerView = view.findViewById(R.id.recyclerView)
        startButton.setOnClickListener { onStartScannerButtonClick() }
        stopButton.setOnClickListener { onStopScannerButtonClick() }
        linearLayoutManager = LinearLayoutManager(context)
        recyclerView.layoutManager = linearLayoutManager
        beaconAdapter = BeaconsAdapter(beaconSet.toList())
        recyclerView.adapter = beaconAdapter
        multilateration = view.findViewById(R.id.multilateration)

    }

    private fun onStartScannerButtonClick() {
        startButton.setBackgroundColor(Color.GREEN)
        startButton.visibility = View.GONE
        stopButton.visibility = View.VISIBLE
        beaconSet.clear()
        btScanner?.startScan(leScanCallback)
    }

    private fun onStopScannerButtonClick() {
        stopButton.setBackgroundColor(Color.RED)
        stopButton.visibility = View.GONE
        startButton.visibility = View.VISIBLE
        //beaconAdapter?.beaconList?.clear()
        beaconSet.clear()
        btScanner?.stopScan(leScanCallback)
    }

    private fun setUpBluetoothManager() {
        btManager = activity?.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        btAdapter = btManager!!.adapter
        btScanner = btAdapter?.bluetoothLeScanner
        if (btAdapter != null && !btAdapter!!.isEnabled) {
            val enableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT)

        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkForLocationPermission()
        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private fun checkForLocationPermission() {
        // Make sure we have access coarse location enabled, if not, prompt the user to enable it
        if (requireActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            val builder = AlertDialog.Builder(activity)
            builder.setTitle("This app needs location access")
            builder.setMessage("Please grant location access so this app can detect the BLE.")
            builder.setPositiveButton(android.R.string.ok, null)
            builder.setOnDismissListener {
                requestPermissions(
                    arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
                    PERMISSION_REQUEST_COARSE_LOCATION
                )
            }
            builder.show()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>, grantResults: IntArray
    ) {
        when (requestCode) {
            PERMISSION_REQUEST_COARSE_LOCATION -> {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    println("coarse location permission granted")
                } else {
                    val builder = AlertDialog.Builder(activity)
                    builder.setTitle("Functionality limited")
                    builder.setMessage("Since location access has not been granted, this app will not be able to discover BLE beacons")
                    builder.setPositiveButton(android.R.string.ok, null)
                    builder.setOnDismissListener { }
                    builder.show()
                }
                return
            }
        }
    }

    private val leScanCallback: ScanCallback = object : ScanCallback() {
        @RequiresApi(Build.VERSION_CODES.O)
        override fun onScanResult(callbackType: Int, result: ScanResult) {

            val scanRecord = result.scanRecord
            val beacon = Beacon(result.rssi)
            beacon.manufacturer = result.device.name
            beacon.macAddress = result.device.address
            beacon.rssi = result.rssi

            if (scanRecord != null) {
                val iBeaconManufactureData = scanRecord.getManufacturerSpecificData(0X004c)
                if (iBeaconManufactureData != null && iBeaconManufactureData.size >= 23) {
                    val iBeaconUUID = Utility.toHexString(iBeaconManufactureData.copyOfRange(2, 18))
                    val major = Integer.parseInt(
                        Utility.toHexString(
                            iBeaconManufactureData.copyOfRange(
                                18,
                                20
                            )
                        ), 16
                    )
                    val minor = Integer.parseInt(
                        Utility.toHexString(
                            iBeaconManufactureData.copyOfRange(
                                20,
                                22
                            )
                        ), 16
                    )
                    beacon.type = Beacon.BeaconType.iBeacon
                    beacon.name = beacon.manufacturer
                    beacon.uuid = iBeaconUUID
                    beacon.major = major
                    beacon.txPower = result.txPower
                    beacon.minor = minor
                    Log.e("BeaconID", "iBeaconUUID:$iBeaconUUID major:$major minor:$minor")

                }
                if(beacon.name == "Beacon_1" || beacon.name == "Beacon_2" || beacon.name == "Beacon_3" || beacon.name == "Beacon_4" ) {
                    beaconSet.add(beacon)
                }
                (recyclerView.adapter as BeaconsAdapter).updateData(beaconSet.toList())

            }
        }
        override fun onScanFailed(errorCode: Int) {
            Log.e("Failed", errorCode.toString())
        }
    }

}

BeaconsAdapter

import android.os.Build
import android.support.annotation.RequiresApi
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import java.util.*

class BeaconsAdapter(beacons: List<Beacon>) :
    RecyclerView.Adapter<BeaconsAdapter.BeaconHolder>() {
    var beaconList: MutableList<Beacon> = beacons.toMutableList()
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BeaconHolder {
        val inflater = LayoutInflater.from(parent.context)
        return BeaconHolder(inflater, parent)

    }

    override fun onBindViewHolder(holder: BeaconHolder, pos: Int) {
        val beacon: Beacon = beaconList[pos]
        holder.bind(beacon)

    }

    override fun getItemCount() = beaconList.size

    @RequiresApi(Build.VERSION_CODES.N)
    fun updateData(data: List<Beacon>) {
        beaconList.clear()
        beaconList.addAll(data)
        notifyDataSetChanged()

    }

    class BeaconHolder(inflater: LayoutInflater, parent: ViewGroup) :
        RecyclerView.ViewHolder(inflater.inflate(R.layout.scan_result_items, parent, false)) {
        private var image: ImageView? = null
        private var mac: TextView? = null
        private var name: TextView? = null
        private var instanceMajorMinor: TextView? = null
        private var namespaceUUID: TextView? = null
        private var beaconRSSI: TextView? = null
        private val context = parent.context

        init {
            image = itemView.findViewById(R.id.beacon_image)
            mac = itemView.findViewById(R.id.beacon_mac)
            name = itemView.findViewById(R.id.beacon_name)
            instanceMajorMinor = itemView.findViewById(R.id.beacon_instance_major_minor)
            beaconRSSI = itemView.findViewById(R.id.beacon_rssi)
        }

        fun bind(beacon: Beacon) {
            mac?.text = String.format(
                context.getString(R.string.mac),
                beacon.macAddress
            )
            beaconRSSI?.text = String.format(
                context.getString(R.string.rssi),
                beacon.rssi
            )
            if (beacon.type == Beacon.BeaconType.iBeacon) {
                namespaceUUID?.text = String.format(context.getString(R.string.uuid), beacon.uuid)
                name?.text = String.format(context.getString(R.string.name), beacon.name)
                //namespace
                instanceMajorMinor?.text = String.format(
                    context.getString(R.string.major_minor),
                    beacon.major,
                    beacon.minor
                )
                image?.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ibeacon))
                instanceMajorMinor?.visibility = View.VISIBLE
                namespaceUUID?.visibility = View.VISIBLE

            }

        }

    }

}

Beacon

class Beacon(rssi: Int?) {
    enum class BeaconType {
        iBeacon
    }

    var macAddress : String? = null
    var manufacturer: String? = null
    var type: BeaconType = BeaconType.iBeacon
    var uuid: String? = null
    var name: String? = null
    var major: Int? = null
    var minor: Int? = null
    var txPower: Int? = null
    var rssi = rssi
    override fun equals(other: Any?): Boolean{
        if(this === other) return true
        if(other !is Beacon) return false
        if(macAddress != other.macAddress) return false

        return true
    }

    override fun hashCode(): Int {
        return macAddress?.hashCode() ?:0
    }

}


text:
Q: Netty 4.0 LengthFieldBasedFrameDecoder Not Working We have a socket client program written in c#, and I'm trying to rewrite it with Netty. The c# login method looks like this:
public bool login(String prefix, string username, string password)
    {
        Send(String.Format("{0}{1},{2}\n", prefix, username, password));

        try
        {
            var _4B = new byte[4];
            _socket.Receive(_4B, 4, SocketFlags.None);
            var len = ConvertToInteger(_4B);
            var b = new byte[len];
            _socket.Receive(b, len, SocketFlags.None);
            GZipStream stream = new GZipStream(new MemoryStream(b, 0, len), CompressionMode.Decompress);
            StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("GBK"));
            String line = sr.ReadToEnd();
            Window.MSG("Socket", "Feed login: " + line, MessageType.SystemMessage);
        }
        catch (SocketException e)
        {
            Window.MSG("Socket", "Socket Exception: " + e.Message, MessageType.Error);
            return false;
        }
        return true;
    }

The above code works fine, then I wrote a Netty client like below:
public void start() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(host, port))
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch)
                            throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast("lengthFieldBasedFrameDecoder",
                                new LengthFieldBasedFrameDecoder(
                                        Integer.MAX_VALUE, 0, 4, 0, 4));
                        /*
                        pipeline.addLast("gzipdeflater", ZlibCodecFactory
                                .newZlibDecoder(ZlibWrapper.GZIP)); */

                        pipeline.addLast("decoder", new StringDecoder(
                                Charset.forName("gbk")));
                        pipeline.addLast("encoder", new StringEncoder());
                        pipeline.addLast("handler", new FeedClientHandler());

                    }
                });
        ChannelFuture future = bootstrap.connect().sync();
        future.channel().writeAndFlush(login);
        Thread.sleep(600000); // todo
    } finally {
        group.shutdownGracefully();
    }
}

This netty client is not working, and can't get any output, I debugged and found the LengthFieldBasedFrameDecoder.decode(ChannelHandlerContext ctx, ByteBuf in) method returns null because in.readableBytes < frameLengthInt  (in.readableBytes = 1028, frameLengthInt = 1882716544).
I have no idea how to get it work, any suggestions? thanks in advance : )

A: Thanks to trustin and Suvitruf's comment, after setting the LengthFieldBasedFrameDecoder's ByteOrder as LITTLE_ENDIAN, the client works!
pipeline.addLast("lengthFieldBasedFrameDecoder", new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN, Integer.MAX_VALUE, 0, 4, 0, 4, true));


text:
Q: How can I access Documents folder of iOS App with C# I want to push a file from Windows (c#) to an iPad and get it back later. I have no Network connection so I need to do this via USB cable.
I have found Manzana but seems not to support iTunes FileSharing.
Any hints ? I googled a lot but couldn't find anything useful.
There are some functions like "AMDeviceStartHouseArrest" but I don't know how to use them to get my Files.

A: There is a way to get this done.
Thanks to a blogpost from Simon (http://blog.victornet.de/2011/04/10/c-manzana-iphoneipad-hausarrest/) and some Mails it finally worked.
I'm now using Manzana with the expansion from Simon:
MobileDevice.AMDeviceStartHouseArrestService(iPhoneHandle,
MobileDevice.CFStringMakeConstantString(bundleIdentifier), null, ref hService, 0);

Starting the 'Housearrest' for a specific App (by bundleIdentifier) makes its '/Documents' Folder accessible via the default Manzana methods. So there is no need for jailbreaking the iDevice. Finally I'm able to push files to the iDevice and read them back.
Thanks again to Simon for the great support!

A: Im not quite sure what you are asking. If you want to access standard files on an ipad, it can be set as a USB mass storage device. I believe the standard IO methods (System.IO) would then be able to read and write to the device, if you pass in the correct path. If you are talking about accessing an applications files, I do not believe this is possible due to security concerns with iOS (at least not in a standard, non-jailbroken way)


text:
Q: Closing JAX-RS StreamingOutput's OutputStream Should the StreamingOutput's OutputStream be closed by the implementing class?
The java-doc does not give any recommendations. I guess it just delegates to the underlying ServletOutputStream which means it should not be closed, but my guess might be wrong :) Also the javadoc makes a reference to the MessageBodyWriter interface where it's explicitly said that the output stream must not be closed.
https://docs.oracle.com/javaee/7/api/javax/ws/rs/core/StreamingOutput.html

A: Being unable to find a definitive answer I took a look at jersey's source being the reference implementation. In Jersey the StreamingOutput is processed by a MessageBodyWriter by simply calling streamingOutput.write(os) [1] where os is the OutputStream passed to the MessageBodyWriter. That's good because its javadoc is quite clear that this OutputStream must not be closed.
To summarize: The OutputStream passed to the StreamingOutput must not be closed.
[1] https://github.com/jersey/jersey/blob/master/core-common/src/main/java/org/glassfish/jersey/message/internal/StreamingOutputProvider.java


text:
Q: Deserialize JSON in Silverlight 4 I have a class MyItems in my namespace as
[DataContract]
public class MyItems    {
[DataMember]
public int LineNum { get; set; }
[DataMember]
public string ItemCode { get; set; }
[DataMember]
public string Priority { get; set; }
[DataMember]
public string Contact { get; set; }
[DataMember]
public string Message { get; set; }
}

and on an XAML I have a button and in its action listener, I am trying to deserialize the JSON string that is coming from a form and trying to update a DataGrid.
In the first step Inside the action listener, I am trying..
List<MyItems> myItems= JSONHelper.DeserializeToMyItems<myItems>(result);

and result (of type string ) has
{"MyItems":[{"LineNum":"1","ItemCode":"A00001","Contact":"5","Priority":"1","Message":"IBM Infoprint 1312"},            {"LineNum":"2","ItemCode":"A00002","Contact":"5","Priority":"1","Message":"IBM Infoprint 1222"},            {"LineNum":"3","ItemCode":"A00003","Contact":"5","Priority":"1","Message":"IBM Infoprint 1226"},            {"LineNum":"4","ItemCode":"A00004","Contact":"5","Priority":"1","Message":"HP Color Laser Jet 5"},            {"LineNum":"5","ItemCode":"A00005","Contact":"5","Priority":"1","Message":"HP Color Laser Jet 4"}]}

The JSONHelper.DeserializeToMyItems code looks like,
public static List<MyItems> DeserializeToMyItems<MyItems>(string jsonString)        {            MyItems data = Activator.CreateInstance<MyItems>();            using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))            {                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<MyItems>));                return (List<MyItems>)serializer.ReadObject(ms);            }        }

While running, I get an exception at the line   serializer.ReadObject(ms)
Unable to cast object of type 'System.Object' to type 'System.Collections.Generic.List`1[ServiceTicket.MyItems]'.

I am not sure how to do a type cast for and I am handling a List of type MyItems. Can anyone help me on this please ?. would be highly appreciated as I am new on Silverlight.
thanks
Denny

A: Try following, it should resolve your problem.
public class JsonHelper
{
    public static T Deserialize<T>(string json)
    {
        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            return (T)serializer.ReadObject(ms);
        }
    }
}

and use the above method like following:
List<MyItems> myItems = JsonHelper.Deserialize<List<MyItems>>(result);

Hope this helps!


text:
Q: NSDecimalNumber round long numbers I'm trying to get NSDecimalNumber to print out large numbers, 15 or more digits.  At 15 digits I see 111,111,111,111,111.  Above 15 digits I see 1,111,111,111,111,110 even though the number being formatted is 1111111111111111.
An example to illustrate my problem:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumSignificantDigits:25];
[formatter setUsesSignificantDigits:true];

NSDecimalNumber* test = [NSDecimalNumber decimalNumberWithString:@"12345678901234567890"];

NSString* output = [formatter stringFromNumber:test];
NSLog( @"num value: %@", test );
NSLog( @"str value: %@", output );

And the output looks like:
2010-09-16 09:24:16.783 SimpleCalc[739:207] num value: 12345678901234567890
2010-09-16 09:24:16.784 SimpleCalc[739:207] str value: 12,345,678,901,234,600,000

What silly thing have I missed?

A: The problem here is that NSNumberFormatter does not handle NSDecimalNumbers internally, they are converted to double and you are seeing the resulting loss in precision. From the docs:

The representation encompasses integers, floats, and doubles; floats and doubles can be formatted to a specified decimal position.

You should probably be taking a look at the - (NSString *)descriptionWithLocale:(NSDictionary *)locale method on NSDecimalNumber.

A: Or NSDecimalString(). Take your NSDecimalNumber (e.g. myDecimalNumber), extract the NSDecimal via decimalValue (NSDecimal decimal = [myDecimalNumber decimalValue]) and create an NSString with the NSString *myString = NSDecimalString(decimal) function.
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/index.html#//apple_ref/c/func/NSDecimalString


text:
Q: how to get user country name from user ip address in php how to get country name from user IP address
I have IP addresses of user i get the country name of user base on user IP address
how it is possible in php ?
function get_client_ip() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

A: Try this
function ip_details($IPaddress)
{
    $json       = file_get_contents("http://ipinfo.io/{$IPaddress}");
    $details    = json_decode($json);
    return $details;
}

$IPaddress  =  'Your ip address of user';

$details    =   ip_details("$IPaddress");

//echo $details->city;
 echo $details->country;
//echo $details->org;
//echo $details->hostname;

A: For getting IP address you can use the function given by you or simply you can use

$_SERVER['REMOTE_ADDR']

to get the IP address of the user use as follow:
$ip =  $_SERVER['REMOTE_ADDR'];   // ip = 8.8.8.8
$country = file_get_contents('http://ipinfo.io/8.8.8.8/country'); // for more info visit [enter link description here][1]
echo $country;  // output = US | UK | IN as per ip (just one country code)

A: Although this post has a correct answer, I have a small modification on it : using curl instead of file_get_contents because :

*

*ipinfo.io documents suggests that.

*file_get_contents doesn't have try catch pattern.

*You can set a timeout request easily to prevent script waiting long for response.

Note :
Without Token, you will reach the limitation soon, so to gain free 50.000 requests/month (currently) it's better to add token in end of url :
function ip_details($ip) //return country code based on ip
{
    if(empty($ip)) return "";

    $url="http://ipinfo.io/{$ip}?token=XXXXX";

    //trigger url
    $curl = curl_init();

    curl_setopt($curl, CURLOPT_TIMEOUT, 3); // wait 3 seconds to response
    curl_setopt($curl, CURLOPT_URL, $url);
    //curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    //curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
       'Content-Type: application/json',
    ));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

    $json = curl_exec($curl);

    if (curl_errno($curl)) {
       return "";
    }

    //curl_close($curl);

    $details    = json_decode($json);
    $country = (empty($details->country)) ? "" : $details->country;

    return $country;
}

A: You can do this, which includes currency:
<?
function resolveIP($ip) {
  $string = file_get_contents("https://ipsidekick.com/{$ip}");
  $json = json_decode($string);
  return $json;
}

$ip = '17.142.160.59';
$json = resolveIP($ip);

echo "Country name: {$json->country->name}\n";
echo "Currency name: {$json->currency->name}\n";
echo "Public holiday: {$json->currency->holiday}\n";
?>

A: Get Current country name and country lat long value :
$IPaddress = !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$details = $this->ip_details("$IPaddress");
$country_name = $details->country_name;

$geocode_stats = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?address=$country_name&sensor=false");
$output_deals = json_decode($geocode_stats);
$latLng = $output_deals->results[0]->geometry->location;
echo $lat = $latLng->lat;
echo $lng = $latLng->lng;


text:
Q: Cannot convert value of type '[RuntimeIntent]' to expected argument type '[Intent]' I am trying to implement Watson Conversation API in my iOS app. While passing response.intents and response.entitities to to issueCommand function, I get an error "Cannot convert value of type '[RuntimeIntent]' to expected argument type '[Intent]'". I tried to typecast both the arguments of issueCommand arguments but it wasn't useful. It will be great if someone can guide me in the right direction? Thanks!
The code is as follows:
func conversationRequestResponse(_ text: String) {
    let failure = { (error: Error) in print(error) }
    let request = MessageRequest(input: InputData.init(text: text), context: self.context)
    self.conversation?.message(workspaceID: Credentials.ConversationWorkspaceID,
                               request: request,
                               failure: failure) {
                                response in
                                print(response.output.text)
                                self.didReceiveConversationResponse(response.output.text)
                                self.context = response.context
                                 var entities: ConversationV1.RuntimeEntity

                                /// An array of name-confidence pairs for the user input. Include the intents from the previous response when they do not need to change and to prevent Watson from trying to identify them.
                                // issue command based on intents and entities
                                print("appl_action: \(response.context.json["appl_action"])")
                                self.issueCommand(intents: response.intents, entities: response.entities)
    }
}

func issueCommand(intents: [Intent], entities: [Entity]) {

    for intent in intents {
        print("intent: \(intent.intent), confidence: \(intent.confidence) ")
    }
    for entity in entities {
        print("entity: \(entity.entity), value: \(entity.value)")
    }

    for intent in intents {
        if intent.confidence > 0.9 {
            switch intent.intent {
            case "OnLight":
                let command = Command(action: "On", object: "Light", intent: intent.intent)
                sendToDevice(command, subtopic: "light")
            case "OffLight":
                let command = Command(action: "Off", object: "Light", intent: intent.intent)
                sendToDevice(command, subtopic: "light")
            case "TakePicture":
                let command = Command(action: "Take", object: "Picture", intent: intent.intent)
                sendToDevice(command, subtopic: "camera")
            default:
                print("No such command")
                return
            }
        }
    }
}

The errors can be seen in the image below:
enter image description here

A: Why not just change the signature of issueCommand to take RuntimeIntents and RuntimeEntities, like so:
func issueCommand(intents: [RuntimeIntent], entities: [RuntimeEntity]) {


text:
Q: read file in form with js codeigniter i need to create a form with two textarea and 1 file input that uploads a txt/csv file where there are 2 numbers in two row (1 row - 1 number) and popolate the 2 textarea with the two numbers using codeigniter and Javascript. thanks for the help
file:

     59.8
     42.8
     55.8
     51.1

html
<input type="file" id="id">

<textarea id="result1" cols="50"></textarea>
<textarea id="result2" cols="50"></textarea>
<textarea id="result3" cols="50"></textarea>
<textarea id="result4" cols="50"></textarea>

this is the js if there is 1 textarea where print the result but every row need to be print in a single textarea and doens't work
  $("#id").on('change', function(event){
        event.preventDefault();

        var selectedFile = event.target.files[0];
        var reader = new FileReader();

        var result = document.getElementById("param3");

        reader.onload = function(event) {
          result.innerHTML = event.target.result;
        };

        reader.readAsText(selectedFile);
    });

A: To achieve this you can use split() to convert the value read from the text file in to an array, with one element per line of text.
Then you can loop through that array and set the values within each textarea. Try this:
<input type="file" id="id">

<textarea class="result" id="result1" cols="50"></textarea>
<textarea class="result" id="result2" cols="50"></textarea>
<textarea class="result" id="result3" cols="50"></textarea>
<textarea class="result" id="result4" cols="50"></textarea>

let $results = $('.result');

$("#id").on('change', e => {
  e.preventDefault();

  var reader = new FileReader();
  reader.onload = e => {
    e.target.result.split(/\r\n/).forEach((text, i) => {
      $results.eq(i).val(text);
    });
  };
  reader.readAsText(e.target.files[0]);
});

Note that I applied the same class attribute to the textarea elements to make the logic much simpler. Generally speaking, incremental id attributes are an anti-pattern and should be avoided where possible.
Here's a working example in a jsFiddle (as SO snippets are sandboxed and cannot use FileReader). You'll need to create a text file yourself to see it in action.


text:
Q: Remove margins for some elements inside container I want to remove space  (only right and left) between .items container and items, but to keep the margin between each item.

.item {
  background-color: red;
  width:140px;
  height:180px;
  margin: 10px
}

.items {
  display:flex;
  flex-wrap:wrap;
  width:800px;
  border:1px solid red;
}

How to remove margin left and right between .items and the grid?

A: But the border on the outer container, and apply the negative amount of your .item margin, to the inner .items container.

.container {
  border: 1px solid red;
}

.items {
  display: flex;
  flex-wrap: wrap;
  width: 800px;
  margin: 0 -10px; /* or just -10px, if you want to eliminate the
                      top/bottom ones as well */
}

.item {
  background-color: red;
  width: 140px;
  height: 180px;
  margin: 10px
}

A: If you want to remove margin-left and margin-right, but save margin-top and margin-bottom, you can use following code:
.item {
  background-color: red;
  width:140px;
  height:180px;
  margin: 10px 0;  //First number is top and bottom, second is right and left
}